title: Form submit to page with another Form

text:
# Question
Title: Form submit to page with another Form
I am trying to make a submission from one page that has a form to another dynamic page with a form. As you can see in my hook menu I'm using `drupal_get_form` as the callback and I would think this would normally work, since I am able to go to the 1st form just fine without any problems.

I do notice I get this error when I submit to the URL, the page is simply not rendering the 2nd form or the contents I have in the function that is suppose to display in the mark up of the 2nd form.

This is the error I get

```
Notice: Undefined index: listings_mini_form in drupal_retrieve_form() (line 764 of /home/domain/public_html/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'listings_mini_form' not found or invalid function name in drupal_retrieve_form() (line 799 of /home/domain/public_html/includes/form.inc)

```

This is not a multiform rather it is 2 different pages with their own forms.

Any suggestions?

```
/**
 * Implements hook_menu().
 */
function listings_menu() {
    $items = array();

    $items['site/listings'] = array(
        'title' => 'State Listings',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('listings_form'),
        'access arguments' => array('access content'),
    );

    $items['site/listings/%/%'] = array(
        'title' => 'Business Listings',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('listings_mini_form'),
        'access arguments' => array('access content')
    );

    return $items;

}

/*
 *  FIRST FORM
 */

function listings_form($form, &$form_state){

    $form['zipcode'] = array(
        '#title' => t('Zipcode'),
        '#type' => 'textfield',
        '#maxlength' => 5,
    );

    $form['form-wrapper']['form-wrapper-zip']['submit'] = array(
        '#type' => 'submit',
        '#value' =>  t('Submit')
    );

    return $form;
}

/*
 *  FIRST FORM SUBMIT FUNCTION
 */

function listings_form_submit($form, &$form_state){

    $zipcode = $form_state['values']['zipcode'];

    $form_state['redirect'] = 'site/listings/'.strtolower(listings_db_state($zipcode)).'/'.strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
}

/*
 *  2ND FORM ON PAGE IM CALLING
 */

function listings_mini_form($form, &$form_state){

    $form['mini-form'] =  array(
        '#title' => t('Enter your Zip Code for more listings.'),
        '#type' => 'textfield',
        '#maxlength' => 5,
    );

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

    if(isset($form_state['values'])){
        $form['page_output'] = array(
            '#markup' => listings_list_view($form, $form_state)
        );
    }

}

/*
 *  2ND FORM SUBMIT FUNCTION
 */

function listings_mini_form_submit($form, &$form_state){

    $zipcode = $form_state['values']['zipcode'];

    $form_state['redirect'] = 'site/listings/'.strtolower(listings_db_state($zipcode)).'/'.strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
}

/*
 *  FUNCTION WITH LISTINGS INSIDE OF IT
 */

function listings_list_view($form, &$form_state){

    global $base_url;

    $zipcode = isset($form_state['values']['zipcode']);
     dpr($zipcode);

     #blah blah blah
}

```

# Answer
> 1 votes
Use this code, your missing `$return $form` in the second form

```

    /**
     * Implements hook_menu().
     */
    function listings_menu() {
        $items = array();
        $items['site/listings'] = array(
            'title' => 'State Listings',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('listings_form'),
            'access arguments' => array('access content'),
        );

        $items['site/listings/%/%'] = array(
            'title' => 'Business Listings',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('listings_mini_form'),
            'access arguments' => array('access content')
        );

        return $items;
    }

    /*
     *  FIRST FORM
     */

    function listings_form($form, &$form_state) {

        $form['zipcode'] = array(
            '#title' => t('Zipcode'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

        $form['form-wrapper']['form-wrapper-zip']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit')
        );

        return $form;
    }

    /*
     *  FIRST FORM SUBMIT FUNCTION
     */

    function listings_form_submit($form, &$form_state) {

        $zipcode = $form_state['values']['zipcode'];

        $form_state['redirect'] = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
    }

    /*
     *  2ND FORM ON PAGE IM CALLING
     */

    function listings_mini_form($form, &$form_state) {

        $form['mini-form'] = array(
            '#title' => t('Enter your Zip Code for more listings.'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

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

        if (isset($form_state['values'])) {
            $form['page_output'] = array(
                '#markup' => listings_list_view($form, $form_state)
            );
        }
        return $form;
    }

    /*
     *  2ND FORM SUBMIT FUNCTION
     */

    function listings_mini_form_submit($form, &$form_state) {
        $zipcode = $form_state['values']['zipcode'];
        $form_state['redirect'] = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
    }

    /*
     *  FUNCTION WITH LISTINGS INSIDE OF IT
     */

    function listings_list_view($form, &$form_state) {
        global $base_url;
        $zipcode = isset($form_state['values']['zipcode']);
        dpr($zipcode);
        #blah blah blah
    }

```

I got output using this code

```

    /*
     *  FIRST FORM
     */

    function listings_form($form, &$form_state) {
        $form['zipcode'] = array(
            '#title' => t('Zipcode'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

        $form['form-wrapper']['form-wrapper-zip']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit')
        );

        return $form;
    }

    /*
     *  FIRST FORM SUBMIT FUNCTION
     */

    function listings_form_submit($form, &$form_state) {
        $zipcode = $form_state['values']['zipcode'];
        $form_state['redirect'] = 'site/listings/' . $zipcode . '/' . $zipcode;
    }

    /*
     *  2ND FORM ON PAGE IM CALLING
     */

    function listings_mini_form($form, &$form_state) {
        $form = array();
        $form['mini-form'] = array(
            '#title' => t('Enter your Zip Code for more listings.'),
            '#type' => 'textfield',
            '#maxlength' => 5,
        );

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

        if (isset($form_state['values'])) {
            $form['page_output'] = array(
                '#markup' => listings_list_view($form, $form_state)
            );
        }
        return $form;
    }

    /*
     *  2ND FORM SUBMIT FUNCTION
     */

    function listings_mini_form_submit($form, &$form_state) {
        $zipcode = $form_state['values']['zipcode'];
        $form_state['redirect'] = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));
    }

    /*
     *  FUNCTION WITH LISTINGS INSIDE OF IT
     */

    function listings_list_view($form, &$form_state) {
        $zipcode = isset($form_state['values']['zipcode']);
    }

```

# Answer
> 0 votes
After the redirect has happened, a new form will be built, hence `drupal_get_form` will render `listings_mini_form`. `$form_state` from the old form `listings_form` will be lost during the redirect, so it doesn't transfer over to the second form. The second form will get a new `$form_state` when `drupal_get_form` is called.

What you're probably after is a querystring redirect:

```
/*
 *  FIRST FORM SUBMIT FUNCTION
 */
function listings_form_submit($form, &$form_state) {
    $zipcode = $form_state['values']['zipcode'];

    $url = 'site/listings/' . strtolower(listings_db_state($zipcode)) . '/' . strtolower(str_replace(' ', '+', listing_db_city($zipcode)));

    $options = array(
      'query' => array(
        'zipcode' => $zipcode,
      ),
    );

    $form_state['redirect'] = array(
      $url,
      $options,
    );
}

```

Now you can get your zipcode in your second form:

```
/*
 *  2ND FORM ON PAGE IM CALLING
 */
function listings_mini_form($form, &$form_state){
  $form['mini-form'] =  array(
    '#title' => t('Enter your Zip Code for more listings.'),
    '#type' => 'textfield',
    '#maxlength' => 5,
  );

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

  $query = drupal_get_query_parameters();

  if (!empty($query['zipcode'])) {
    // Do whatever you want with $query['zipcode']
  }
}

```

---
Tags: 7, forms
---


# Question
Title: Special code for .htaccess and robots.txt files
My client was noticing that his site was extremely slow yesterday morning so he contacted his WiredTree host, who suggested that we add the following code in the .htaccess file:

```
Options +FollowSymlinks
RewriteBase /
SetEnvIfNoCase User-Agent "^SemrushBot" bad_user
SetEnvIfNoCase User-Agent "^DotBot" bad_user
SetEnvIfNoCase User-Agent "^AhrefsBot" bad_user
Deny from env=bad_user

```

`Options +FollowSymlinks` is already in the file and `RewriteBase /` is currently commented out and I'm not sure if I should uncomment it, not knowing what affect that would have. Then I would add the 3 set commands and the deny command below it. Is it OK to uncomment this line and add the extra commands?

# Answer
It looks like the most important bit they want you to put in .htaccess is this:

```
SetEnvIfNoCase User-Agent "^SemrushBot" bad_user
SetEnvIfNoCase User-Agent "^DotBot" bad_user
SetEnvIfNoCase User-Agent "^AhrefsBot" bad_user
Deny from env=bad_user

```

They should probably go inside the `<IfModule mod_rewrite.c>` block in your .htaccess file, just after `RewriteBase /` (whether it's commented out or not). This `RewriteBase /` line shouldn't cause any problems, if your drupal site is not in a subdirectory (e.g. your index.php file shouldn't be in a sub-folder of your webroot like http://domain.com/drupal/index.php)

The `Options +FollowSymLinks` shouldn't need to be included twice if it's already there.
> 2 votes

---
Tags: .htaccess
---


# Question
Title: The file names are not transliterated on upload
I am using Drupal 7 and have transliteration module enabled.

I have a file field and I want to have the names of the uploaded files to be transliterated on upload.

The url alias for the nodes are well transliterated. But the file names are not.

I checked the settings for file system. The current settings are:

* Transliterate file names during upload.(checked)
* Lowercase transliterated file names. (checked)

If I "Transliterate existing file names" (admin/config/media/file-system/transliteration) then the names of the files I have already uploaded are transliterated. But still, when I upload new files, the file names are not transliterated.

Any ideas why the names are not translated on upload?

# Answer
> 0 votes
File names are not URL aliases. Pathauto has never had any sort of integration with files at all.

# Answer
> 0 votes
Although this is an old question, you could add debug in

`transliteration_init`

To check the value of `$_FILES` and transliteration there.

for example, to test the var value, add

```
watchdog('debug', var_export($_FILES, 1));

```

---
Tags: 7, files, transliteration
---


# Question
Title: Views Block Caching issue for not logged in User
We are using Drupal inbuilt caching with Memcache. Our website home page has more than 5 blocks created using Views for which we have enabled Time based caching. But the contents are not getting listing in these views even after the query caching time. Following is the views cache settings:

Query Caching : 15 mins and Render Caching 6 days Block Caching : Do not Cache

Following is the Drupal cache settings:

Also, like to add one more point that the contents are published using Scheduler module.

# Answer
I have found out the issue. Views Query caching and Render Caching are not related. If we set render caching higher than query caching then Drupal will always fetch from Render cache and hence the result will remains. So its recommended to set both as same values. I modified the same to 15mins Query caching and 15mins Render caching.
> 0 votes

---
Tags: views, blocks, caching
---


# Question
Title: Why do taxonomy_get_tree() & entity_load('taxonomy_term', etc..) give different counts?
I'm finding that I am missing some terms in a vocabulary when I try to get them all with `taxonomy_get_tree($vid)`.

If I verify the count of terms in the vocabulary by getting the count of `entity_load('taxonomy_term', FALSE, array('vid' => $vid))` when I compare the counts they are different.

Can anyone tell me why the counts would be different?

I was hoping to use `taxonomy_get_tree()` as it's much faster for the number of terms I have (\> 10k) but it's useless if it's not going to deliver all terms.

Thanks for any info on this.

# Answer
After running some mysql queries on the taxonomy\_term\_data table it appears that the difference in counts is caused by differences in the terms language property.

When I count the terms in the taxonomy\_term\_data with the language set as 'und' it matches the total given by `taxonomy_get_tree($vid)`

When I count all terms in the taxonomy\_term\_data table regardless of language the total matches the the count given by `entity_load('taxonomy_term', FALSE, array('vid' => $vid))`

So if you only need terms in your current language go with taxonomy\_get\_tree($vid) otherwise you'll need entity\_load().
> 0 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: How can I override default theme_fieldset() function?
I am trying to override the theme\_fieldset function in a custom node edit form where the fieldset is added dynamically.

Here is what my code looks like:

```
function cms_content_edit(){
  $node = node_load(3089);
  module_load_include('inc', 'node', 'node.pages');
  $form = drupal_get_form('test_node_form', $node);
  $form['block1'] = array(
    '#type' => 'fieldset',
    '#title' => t('Block 1'),
    '#weight' => -50,
    '#collapsible' => true,
    '#collapsed' => true,
    '#attributes' => array('class' => array('portlet box blue-hoki')),
    '#theme' => 'fieldset_custom3',
  );
  $form['block1']['title'] = $form['title'];
  unset($form['title']);
  $form['block1']['body'] = $form['body'];
  unset($form['body']);
  $form['block1']['field_fichier'] = $form['field_fichier'];
  unset($form['field_fichier']);
  $output = drupal_render($form);
  return $output;
}

```

The custom function is defined this way in my .module file:

```
function theme_fieldset_custom3($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<div class="portlet-title">' . $element['#title'] . '</div>';
  }
  $output .= '<div class="fieldset-wrapper">';
  if (!empty($element['#description'])) {
    $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }
  $output .= '</div>';
  $output .= "</fieldset>\n";
  return $output;
}

```

Unfortunately my custom function is not called at all.

Did I do something wrong?

\******** EDIT \*********

Thanks to @kiamlaluno, after I added my custom function to hook\_theme(), my custom function was actually loaded.

```
function mymodule_theme() {
  return array(
    'fieldset_custom3' => array(
      'render element' => 'element',
    ),
  );
}

```

The problem now is that the .fieldset-wrapper div is empty. In my custom function, the $element\['#children'\] array is empty...

My fieldset is created dynamically, like that (in hook\_form\_alter()):

```
if(isset($form['#node_edit_form']) && $form['#node_edit_form']==TRUE && $form['nid']['#value']!=''){

       $form['block1'] = array(
          '#type' => 'fieldset',
          '#title' => t('Block 1'),
          '#weight' => -50,
          '#collapsible' => false,
          '#collapsed' => false,
        );
        $form['block1']['title'] = $form['title'];
        unset($form['title']);
        $form['block1']['body'] = $form['body'];
        unset($form['body']);
        $form['block1']['field_fichier'] = $form['field_fichier'];
        unset($form['field_fichier']);
        $form['block1']['#theme'] = 'fieldset_custom3';
        // $form['actions']['submit']['#submit']['0'] = 'node_form_submit_custom';
    }

```

I also tried this way (this is a custom page):

```
function cms_content_edit(){
  $node = node_load(3089);
  module_load_include('inc', 'node', 'node.pages');
  $form = drupal_get_form('test_node_form', $node);
  $form['block1'] = array(
    '#type' => 'fieldset',
    '#title' => t('Block 1'),
    '#weight' => -50,
    '#collapsible' => true,
    '#collapsed' => true,
    '#attributes' => array('class' => array('portlet box blue-hoki')),
    '#theme' => 'fieldset_custom3',
  );
  $form['block1']['title'] = $form['title'];
  unset($form['title']);
  $form['block1']['body'] = $form['body'];
  unset($form['body']);
  $form['block1']['field_fichier'] = $form['field_fichier'];
  unset($form['field_fichier']);
  $output = drupal_render($form);
  return $output;
}

```

But the problem is the same.

\******** EDIT 2 \*********

I also noticed that the issue also happens when I try to use the default theme\_fieldset() function as configuration:

```
$block1 = array(
        '#type' => 'fieldset',
        '#title' => t('Block 1'),
        '#weight' => -50,
        '#collapsible' => true,
        '#collapsed' => false,
        '#description' => t('Edit the welcome e-mail messages sent to new member accounts created by an administrator.'),
        '#tree' => TRUE,
        '#theme' => 'fieldset',
      );
      $form['block1'] = $block1;
      $form['block1']['body'] = $form['body'];

```

I double checked and the theme\_fieldset() function (/includes/form.inc) is actually well called, but the fieldset is not generated as expected. Apparently something is missing so Drupal can do the job. May be the $variables object.

Here is a screenshot of what my form looks like with this configuration.

When I don't use the "#theme" config, everything is perfect:

```
$block1 = array(
    '#type' => 'fieldset',
    '#title' => t('Block 1'),
    '#weight' => -50,
    '#collapsible' => true,
    '#collapsed' => false,
    '#description' => t('Edit the welcome e-mail messages sent to new member accounts created by an administrator.'),
    '#tree' => TRUE,
  );
  $form['block1'] = $block1;
  $form['block1']['body'] = $form['body'];

```

# Answer
> 1 votes
You cannot use a theme function if you don't make Drupal know about it first. To do that, you need to implement `hook_theme()`.

```
function mymodule_theme() {
  return array(
    'fieldset_custom3' => array(
      'render element' => 'element',
    ),
  );
}

```

---
Tags: theming, forms
---


title: How do I stop spam messages?

text:
# Question
Title: How do I stop spam messages?
In my site with Drupal 7 spammers create a new block. What can I do to stop this?

# Answer
> 3 votes
1. Update Drupal to the latest version withing the major. (Drupal 7.43 is the latest for 7 major. https://ftp.drupal.org/files/projects/drupal-7.43.tar.gz)
2. Delete the users that spam.
3. If admin (uid 1) account was used to spam, change password. Check if email has been hijacked. If a wrong email is specified for admin user (uid 1), change it to yours before changing password.
4. If your site allows other users (a social network), check user permissions if they are allowed too much.
5. If you conclude that your site has in fact been seriously hacked and none above works, bring in a specialist to handle your specific problem.

There is also a walkthrough "Your Drupal site got hacked, now what?" at Drupal.org: https://www.drupal.org/node/2365547

---
Tags: 7, advertising
---


# Question
Title: Views: group by content type in an arbitrary order
**Note:** I spend a lot of time in this question explaining, what I've been trying to do, but the end goal is to be able to sort by content type in an arbitrary order. I'm then grouping on content type, and getting headings in my results as desired. If you can show me how to do it without hook\_views\_query\_alter() I'd be just as happy, though why my solution isn't working is giving me an ulcer. I'd prefer to avoid creating a whole bunch of attachments since I'm dealing with about 20 types here, but I think that is the next thing I'll have to try if nobody can help me.

---

A few other answers here, have gotten me to where I feel I'm close, but I'm getting not results, hopefully someone here can see what I'm doing wrong.

My actual setup is more complex than this. Basically I have a variable in settings that gives me some details about the different content types I'm dealing with, including a weight value for each. I'm building my order by clause using those weight values, but that doesn't seem to be the problem, so here is the query taken to it's simplest form:

Given a view that loads a set of nodes of at least two different types, one of which (for the purposes of this function has a machine name of 'brief' and a human readable name of Briefs):

```
/**
 * Implements hook_views_query_alter().
 */
function MYMODULE_views_query_alter(&$view, &$query) {

    if ($view->name == "view_name" && $view->current_display == "display_block_name") {

        $caseclause = 'CASE node_type WHEN "brief" THEN 1 ELSE 2 END';
        array_unshift($view->query->orderby, array(
            'field' => $caseclause,
            'direction' => 'ASC'));
    }
}

```

I would expect this to give me the node listing with Briefs listed first, and other types listed afterward. Instead I get no results. If I remove the alteration to $view-\>query-\>orderby I get results. I've tried checking for "Briefs" instead of "brief". I got the column name, by adding it as a sort in the view and seeing what the view itself used, but just in case I've also tried node.type and type as the column name to put in the case statement. I tried doing all of this with the $query object too, just in case.

I tried adding the CASE clause as $query-\>addExpression, setting an alias of order\_col for the expression, intending to then order by that column, but the whole page stopped showing up. It is possible I did something wrong on that attempt, if you can make that work, please let me know.

So here's what I need: How can I make a CASE statement work in hook\_views\_query\_alter(), or failing that, how can I sort content type by an arbitrary order?

Here's a really brief section of the configuration variable that I have in settings.php that I'm trying to get the weight value from to do my sort.

```
$conf['pubtype_bundles'] = array(
    'brief' => array(
        'name' => 'Briefs',
        'weight' => 5,
        'description' => 'Issue Briefs, Policy Briefs, and Briefing Notes',
        'help' => '',
        'types' => array(
            'issue' => 'Issue Brief',
            'policy' => 'Policy Brief',
            'briefing' => 'Briefing Note',
        ),
        'typehelp' => '',
    ),
    'book' => array(
        'name' => 'Books',
        'weight' => 10,
        'description' => '',
        'help' => '',
        'types' => array(
            'book' => 'Book',
        ),
        'typehelp' => '',
    ),
);

```

# Answer
When you want to do arbitrary sort, U must be having your own sorting routine/algo/criteria? When you have that then you can add a "global php" field in sort criteria and then u can use a setup code(if required) and then you can write your sorting logic in "sort code".
> 1 votes

# Answer
Though I am not very clear with this

> Basically I have a variable in settings that gives me some details about the different content types

What I understood is, you have a settings defined somewhere which has weight and content type relation. Based on this one solution can be:

* Create a weight field / setting (assuming there is no configuration for it) in content types, and populate the weight from your settings.
* Use this weight field to sort nodes in views.
> -1 votes

---
Tags: 7, views
---


# Question
Title: Version control on Entity form type submissions
A project collecting data from multiple entity forms was handed over to me. My client requested the implementation of a review mechanism for the data that are stored in entity form submissions.

The reviewers should have the ability to edit the submissions while they are keeping the initial content intact. The features extend to comparison between the various versions of the submission along with comments that can be attached to each version explaining the scope of the changes.

Pretty much the exact functionality that Node revisions are covering at the moment.

Unfortunately I just discovered that revisions are not available for entityform submissions (Add revision support to submissions) leading me to a dead end.

So, I seek some experienced guidance if there is a workaround to this, that I'm unable to see.

* Could I create this versioning system somehow with the current data structure?
* Would it be able to migrate the data collected from form submissions to content type nodes so that I can use their revision framework (along with Diff and Node Compare modules)?

# Answer
> 0 votes
Trying to hack data out of an Entity form seems to make things unnecessarily more complicated, so I decided to redesign the whole form as a content type create form, while using entity reference fields to link the various instances.

---
Tags: nodes, entities, version-control
---


# Question
Title: qTips do not appear on content type create form
I have installed qTip (Stylish jQuery Tooltips) module `v7.x-2.0-rc3`, but I cant get it to work on a content type create form.

The steps I've followed are the following:

1. Install and enable qTip module along with Fields sub-module.
2. Create a new qTip instance with the default and simplest options.
3. Go to my content type and manage a Long text field with a text-area widget.
4. Enable the qTip Settings for it. Set it to Custom Text and fill in a sample text. Select my previously created qTip instance.
5. Press Save and clear all caches.

However when I go to the form (Content -\> Add Content -\> My\_content\_type) the qTips are nowhere to be seen. I've tried to hover over the label and the text editor. Nothing shows up.

On the other hand when I preview my instance the qTip appears normally:

Am I missing something here?

# Answer
> 0 votes
I found no solution why this was happening, so I had to switch to Form Tips which worked flawlessly along with some custom CSS theming.

---
Tags: forms, tooltips
---


# Question
Title: ckeditor - Two views with editable fields on the same page
I have put two identical pane views (an original display along with a clone) on the same page. I needed two copies because each view has its own set of exposed filters, so they can display different nodes side-by-side.

The views consist of multiple editable fields that seem to be identical comparing to the other view so they have even the same element IDs..

As a result, ckeditor which is the default wysiwyg editor only loads on the first view, giving me the following error on console:

```
Uncaught The editor instance "edit-field-e1-0-field-e1-und-0-value" is already attached to the provided element. ckeditor.js?o5iwm7:286

```

How can I prevent this? Is there a way to set different ids on cloned displays?

If I recreate the same display manually, would it be any difference? (its a huge display)

# Answer
> 0 votes
To counter this, I had to clone every field in the second display only to force Drupal to assign different element IDs to each one. Then I deleted the initial fields.

So

```
views-field views-field-field-e1

```

changed to

```
views-field views-field-field-e1-1

```

letting the Ckeditor to render the rich text editor on every instance.

---
Tags: views, wysiwyg
---


# Question
Title: Navigation links in a region rendering vertically
I am trying to place a block, that contains a navigation menu, within the Navigation region of a Bootstrap themed Drupal 7 site.

The menu is drawn vertically, I assume from the fact that it's a block within the region, and it's overwriting some of the CSS..

It also seems that the UL that is generated for the menu doesn't have the necessary "nav navbar-nav" classes.

Is my only option to override the region.tpl.php, block.tpl.php and the definition for UL (which I have yet to find)?

# Answer
> 1 votes
You can copy the responsible template file from bootstrap theme and put it in sub theme. I think you will find your template under Menu folder in tempaltes of bootstrap theme (parent theme) You will find these files and you have to modify one of these in order to achieve what you said.

1. menu-link.func.php
2. menu-local-action.func.php
3. menu-local-task.func.php
4. menu-local-tasks.func.php
5. menu-tree.func.php

Thanks

---
Tags: 7, theming
---


# Question
Title: How to limit direct access to URLs of nodes that are shown in a video gallery created with Views?
I have made a video gallery using **Views**. But I only want that the page accessible to public and prevent access to each of the videos individually.

The videos had to be created as a type of content, so all of them have accessible ULRs like `/content/video-1`, etc.

# Answer
Try content access module and prevent access to `video` content individually( or also you can set access to it for you desire `roles` )

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

Also you can use Node View Permissions module, but I suggest use `Content access module`.

(if you want work with drupal for future is better getting involve with this useful modules)
> 5 votes

# Answer
Install Node View Permissions module.

> Node view permissions module enables permissions "View own content" and "View any content" for each content type on permissions page as it was on Drupal 6.

Now goto permission page and remove **View any content** permission from video content type for **Anonymous user**.

In case you want only few of the videos from Video gallery to be accessible to the anonymous user, then install Deny Access module.
> 3 votes

# Answer
Just update your content type.

1. Add a numeric field like *display\_order* etc.
2. Set value of this field only for those videos you want to show.
3. Go to your view settings and set;

Use pager:Display a specified number of items | x items

where x is the no.of videos you want to show
4. Then apply sorting by *display-order*

Hope it will work.
> 1 votes

# Answer
I think the Rabbit Hole module does exactly what you're looking for. Here's an excerpt from the module's description page answering your need. Good luck.

> Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
>
> Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.
> 1 votes

# Answer
Go for rabbit hole module, it does exactly the same. All the content is accessible via views/code but when you try to access the detail page "content/\***" it is either access denied or you can set a redirect.
> 1 votes

# Answer
1) Create a *Boolean* value field in your content type.

2) If value is selected as true a unique class should be added to that video field, if value is selected as false the class should not be added to that video field.

3) Write some *CSS* to hide the videos where the class is not present.
> 0 votes

# Answer
Using the Rules module you can implement a rule that looks similar to this:

```
{ "rules_disallow_accesss_to_selected_urls" : {
    "LABEL" : "Disallow access to selected URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "content\/video-1",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, access to URLs like [site:current-page:url] is not allowed ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

```

Anybody trying to access relative path `content/video-1` will be redirected to a page with path `no_access`, and a related error message will be shown (adapt this path to fit your own conventions, and review the message to be shown).

The above rule only restricts access to relative path `content/video-1` (as in your question). If you want to expand the rule to similar URLs, change `content\/video-1` to something like `content\/video-\\d+$`, or any variation that fits the naming convention of your paths.

The above rule does not (yet) take into account to only apply the Rules Action for users with selected roles only. But for anybody a bit familiar with the Rules module, that is a straight forward "Condition" to add ... eg: skip the rules action for users with a role like editor, administrator, etc. Which you can do by adding a Rules Condition like "user does NOT have role administrator (and/or editor)". That way those kinds of special users can still view such nodes anyway (without such extra condition they also cannot view such nodes anymore ...).

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function (available if Rules UI is enabled). Then further edit/refine to make it fit in your own environment (e.g the "Sorry, ..." message to be shown).

# Additional refinement

In one of the other answers you added a comment that includes this:

> ... I wanted to redirect to home page in some cases, 404 in others, etc., so I had better control ...

If that's what you also want to do, then you can further refine the above Rules Action by adding the Conditional Rules module also. With that, for each of your "some cases" you can then specify the appropriate URL to redirect to. Refer to my answer to "How to set the values of some fields depending on the value of a list box?" for an illustration of how to use this module within a Rules Action.
> 0 votes

---
Tags: views, nodes, users
---


# Question
Title: How can I embed the YouTube field module in a specific page?
Shifting from Wordpress, I'm quite a newbie at Drupal. So I want to embed the YouTube field module in a specific page, not just on the landing page (as it is shown in the setup video https://www.youtube.com/watch?v=SzvEEMO0\_Ug). But how can I do this? I somehow just can't figure out where I can select the page I want it to be on. Thanks a lot for any help

# Answer
> 2 votes
Fields are designed to be attached to pieces of content (entities), especially the main content entities (nodes). Using youtube field, would mean you can attach a different youtube video to every type of content. This likely results in a textfield on every node edit page (of that certain content type) where you enter a URL or something.

If that is what you want, proceed happily. If you go to the manage display section of your content type you can alter the `teaser` view mode (switch in the right top) and remove the field from display so it does not show on the front page.

If that is not what you want and you only want one block to appear in a sidebar or something, go to the blocks page, create a new block and just paste the embed code there. Make sure to set the content filter to `full-HTML` so it does not get sanitized. Each block allows you to specify the URL's on which it should be displayed. (There is no need for this module)

# Answer
> 1 votes
In the video, he creates a content type called "Youtube Field". (This is a confusing name, if you ask me. Maybe he should've named the content type "Youtube Pages"

**You do not have to** do this (**create a new content type**).

> But how can I do this? I somehow just can't figure out where I can select the page I want it to be on. Thanks a lot for any help

Sounds like you already have a content type on which you created Pages (called `nodes` in Drupal).

So all you have to do is add the youtube field to your Article content type (the Article content type comes by default when you install Drupal) **Assuming that you used Article content type to create your pages. Maybe you used Basic Page? or Maybe you created a new content type? let's assume it is Article for the rest of this answer**

you need to MANAGE FIELDS of your article content type (`/admin/structure/types/article/display`) and add a new field:

Label: Example \>\> Field Type: Youtube video.

Now when you add a new article / or **in your case edit your nodes**, you will have your Example field where you just paste the youtube url.

---
Tags: files
---


# Question
Title: Fatal error during add a field to a content type with a custom Field Type
I'm working on Drupal 8 and I create a custom field type so

When I tried to add a field to a content type Drupal give me this error

> Fatal error: Cannot redeclare class Drupal\any\_to\_show\Plugin\Field\FieldType\AnyToShowItem in /var/www/public/sites/all/modules/something/src/Plugin/Field/FieldType/AnyToShowItem.php on line 105

I'm confused because it suppose that the file is the definition and it says that I'm redeclaring the class, I search whole site but nothing.

I was grateful if somebody can help me. thanks in advance

# Answer
> 1 votes
This happened to me, and the solution was making sure that the file name matches the class name defined within, so in your case, the class name MUST be `AnyToShowItem`.

This is because the PSR-4 auto-loader would be trying to load `.../sites/all/modules/something/src/Plugin/Field/FieldType/AnyToShowItem.php` if the class `AnyToShowItem` doesn't exist. But if the class defined within doesn't match the filename, then `AnyToShowItem` will still be undefined but the class that IS contained in the file will be. So the next time the `AnyToShowItem` class is attempted to be constructed, the file is loaded again in a futile attempt to define the class, but the class within will already have been defined, and thus the redefinition error will be thrown

---
Tags: entities
---


# Question
Title: What is the difference between the Workbench and Workflow modules?
I use the Revisioning module to manage revisions of nodes on my Drupal 7 site. I had been updating the site by myself, so Revisioning was sufficient; now, however, I will be adding some content editors to the project so I need to set up a more complex workflow.

I used to use the Workflow module on Drupal 6 and the Drupal 7 version has integration with Revisioning. However, Workbench has been getting a lot of good press recently.

What are the significant differences between these two modules, Workbench and Workflow?

# Answer
**Workbench** gives you an intuitive and friendly user interface to control content (nodes)transitions on a previously defined states on a role based access control means that every transition to the node from a state to a state for the role authorized to perform that transition, with the ability to create new transitions and states.

You won't get that feature unless you enabled the workbench moderation module.

Workbench access module allows you set sections, editors, roles (defined using a menu items or taxonomy terms) to work on the description above based upon the permission given for the role to work on workbench functionality which gives you a generic out of the box role based access control to previously define workflow to manage content publishing process.

Workbench media provides integration between media and the Workbench suite. It simplifies the pages content administrators need to visit in order to add media which makes workbench files module useless and becomes depricated.

**Workflow** seems to be more powerful and provides you with one form to create and define workflows and manage states, transitions, assign roles, set labels for transitions and how states will be listed and logged read that awesome article

Besides have integration with many helpful modules may be used in your project in the future like og, rules, views and search\_api due to the dependency on drupal entity system allows to set workflows defined to other entity types not limited to nodes.

Actions on each transition could be tied and notification created for users in concern like group members and admins or high level managers.

**At the end** each of the two modules have very good functionality that deserves showing respect to maintainers, **Workbench** focus on content closely to E-magazines and online news portals or forums, **Workflow** pay attention on the process thinking of workflows as business rules required and may be helpful in ERP, CRM and E-commerce like systems some how.

**Finally close to scope** of that question I found a very simple module provides ability to add custom publishing states with integration to rules and views, specify defined roles to transition nodes between states.

I hope that review helps you determine what is the best module for your project.
> 21 votes

# Answer
**Workbench** is the module for Drupal 7. It's easier to use and more intuitive, but from my latest experience revisioning support (ref) is still a feature request.

**Workflow** is older and has more features, including revisioning support, but is more cumbersome to use.
> 8 votes

# Answer
Both these modules are basically used for the same purpose but their architecture is what differentiates them. Cant exactly compare which one is better out of them but based on the requirement i choose the one which will make my life simpler. Some of the key highlighter for both of them are:

1. Workbench: relatively simple, preferred if the number of steps and number of workflows are less, provides dashboard.
2. Workflow: workflow field which references the workflow, multiple workflows are kept completely separate, simple for a site maintainer to alter the workflow.
> 2 votes

# Answer
The Workbench module can achieve what the Workflow module does; plus it has a very powerful backend. I think this is the main difference.

If you need a complete backend for a workflow administration, it is better to use the Workbench module; if you need just a workflow use the Workflow module.
> -2 votes

---
Tags: 7, workflows
---


title: 404 Error report getting refreshed?

text:
# Question
Title: 404 Error report getting refreshed?
For some reason CRON seems to be deleting all 404 errors reported at

```
admin/reports/page-not-found

```

Is there any way to disable the deleting of the 404 errors?

# Answer
Watchdog entries are deleted by `dblog_cron()`, if the `dblog_row_limit` variable is greater than 0.

To stop them being deleted, set the `dblog_row_limit` variable to `0`.
> 1 votes

---
Tags: 7, log-messages
---


# Question
Title: Using drupal behaviors for a Bootstrap carousel
I created a custom front page using page--front.tpl.php, and I added a Bootstrap carousel on it which works fine, but the javascript I have (carou.js which is in mysubtheme'/js/carou.js') is not called. This is the Drupal behavior code.

```
(function ($) {
Drupal.behaviors.carou = {
    attach: function(context, settings) {
        $('#myCarousel').carousel({
            pause: false,
            interval: 3000,
        });
    }
}
})(jQuery);

```

I added it using the following code in the template.php file.

```
function bootstrap_subtheme_preprocess_page($vars) {
  if (drupal_is_front_page()) {
     drupal_add_css(drupal_get_path('theme', 'bootstrap_subtheme') . "/css/frontpage.css");
   //adding carou.js to front page
     drupal_add_js(drupal_get_path('theme', 'bootstrap_subtheme') . '/js/carou.js', 'file');
   }
}

```

I want to control the carousel options of `pause: false` `interval:3000` but I was not able to do so. This makes me think the JavaScript code is not being called, and I don't know what is not right in the code. I am not also very well versed with Drupal behaviors.

What is wrong in my code?

# Answer
> 0 votes
Finally fixed it. I modified the code this way

```
drupal_add_js(drupal_get_path('theme', 'bootstrap_subtheme') . '/js/carou.js', array(
                                                                                'type' => 'file',
                                                                                'group' => JS_LIBRARY,
                                                                                'weight' => -1));

```

I added group and weight to it then then drupal.behaviors code had some few errors in the structure. The last line was`})(jQuery);`But i fixed it to `}(jQuery));`

---
Tags: javascript
---


title: Multi level menu?

text:
# Question
Title: Multi level menu?
I've created a multi-level main menu in Drupal 8, all levels need to show by default (they are revealed on hover/tap).

Unfortunately when adding this menu as a block, Drupal states:

> The menu will only be visible if the menu item for the current page is at or below the selected starting level. Select level 1 to always keep this menu visible.

Which is exactly what I don't want, all items need to be visible by default regardless of the current menu item.

I can't see any obvious way around this, is there something obvious I'm missing?

# Answer
> 4 votes
All links in that menu have to have the "expanded" option checked. So you have to manually edit all of them and enable this option.

# Answer
> 1 votes
I solved that by a custom block:

```
namespace Drupal\MY_MODULE\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class MainMenuBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $menu_name = 'main';
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

    $parameters->expandedParents = []; // HERE HAPPENS THE MAGICK

    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);

    return $menu_tree->build($tree);
  }
}

```

Found this idea on http://mks.pp.ua/content/drupal-8/snippet-render-menu-drupal-8-programtically.

If you don't know how to get your own block programmatically follow the instructions on https://www.drupal.org/node/2101565.

If you did that, you can add your custom block to any region of your theme.

---
Tags: theming, 8
---


# Question
Title: Exposed filter selectbox dropdown for a textfield
I have a textfield for one of my content types and there are many unique results for it. I am trying to create a View of this content type of this textfield as an Exposed Filter with a list of all the unique results from this textfield. Views by default only gives you a textbox for you to search through these results, but if you don't know what to look for, it doesn't work too well.

* How would I expose this textfield of all the unique results in a selectbox in a view?

# Answer
> 1 votes
I had the same issue sometime ago and finally the only way to display all the values from a field in a dropdown filter seems to be the Drupal taxonomy. The Grouped flters option is fine but you need to enter all the values manually in the table (Label/value) and I think this is not what you are looking for.

If you can clone your Text field in a Term reference field (Taxonomy vocabulary), you should be able to create a dropdown filter in Views, based on this new Taxonomy field, with autocomplete or dropdown option for filter display. Then, each time a new term is created in the vocabulary, it will be suggested in the dropdown menu.

It was my option but maybe someone can suggest a way to display all field values in a filter, even if it is not a vocabulary. I would be really interested in that solution, anyway.

Hope this helps.

# Answer
> 2 votes
You can use **Grouped filters** of exposed filters to set unique results for select box in a views. Please see the screenshot given below:

# Answer
> 0 votes
In my case I had to filter my view with a bunch of offices, but these offices were in a custom made field formatted in json. I had to clean up the field by running it through views\_php with preg\_replace() to get it ready for processing.

Once my data is formatted correctly for js consumption. I concatenate all of these offices together into a gigantic array. From there I run through this array to detect duplicates and end up with a results array of unique results.

Then I add these unique results into an appended

```
//If needed run the field through a views_php field to prepare it for processing. Separate each entry with a comma so you can split it via js.

a = jQuery(".views-field-php em").text();
b = a.split(',');

var results = []; //Create an empty results array variable to be filled

jQuery.each(b, function(index, value) { //Run through "each" value and put it into results array

  if ((jQuery.inArray(value, results) == -1) && value != '') { //Does the value exist in the results array? If not do the following
    results.push(value); //Adds the value to the results array
  }

});

results = results.sort(); //Sort all the arrays alphabetically

//Add in the <select element into the page
jQuery("#edit-field-role-offices-wrapper").append('<select id="filter-off"><option>Filter by Office</option></select>');

//Add the <option elements according to EACH array value in results
results.forEach(function(z) {
  jQuery("#filter-off").append('<option value="' +z+ '">' +z+ '</option>');
});

//When selecting an item, copy that value into the textfield above and then hit the submit button
jQuery("#filter-off").live("change", function() {
  jQuery("#edit-field-role-offices").val(this.value);
  jQuery("#edit-submit-yearbook").click();
});

```

---
Tags: 7, views
---


title: How do I use absolute URLs?

text:
# Question
Title: How do I use absolute URLs?
I created a view for node titles only. I have inserted this view in simplenews newsletter using the *Insert view* module. The node title in newsletter emails are relative and broken. How do I configure my view so that absolute URls are used?

>

# Answer
**1. Add `Content: Link to Content` field to your View** . Your view fields will look as shown below.

---

**2. Make sure that your Title field is outputted as plain text.** In the `Content:Title` field settings uncheck the checkbox "Link to the Content". This is done because you'll use plain title text as a token for the link text. `Exclude Title field from display`, as it will be displayed later as an absolute link text.

---

**3. Create settings for the absolute link output in `Content: Link to Content` field settings.**

Open REWRITE RESULTS fieldset in `Content: Link to Content` field settings and check the following boxes:

Override the output of this field with custom text (set `{{ title }}` as text)
Output this field as a custom link
Use absolute path
> 9 votes

---
Tags: views, 8, uri, emails
---


title: Convert path alias to ID

text:
# Question
Title: Convert path alias to ID
How can I get the ID of a taxonomy term with only a path alias, using PHP?

I have a vocabulary with some taxonomy terms with a path alias like \[vocabulary\]/\[term\] (e.g. car/model) and I have repeated model terms. (So I think that using titles is not an option.)

I created a view with a path (car/%); if I want to make another view with an extra argument and car/%/% as path, I can't get the content unless I use the taxonomy ID like car/123/1 instead of car/model/cat.

Is there a way to make this?

# Answer
I solved the problem with this:

e.g. i have the path alias car/ilx-0 and i can get the tid easily, but what if i want to pass only the ilx-0 to another path view, like: products/ilx-0, the path alias doesn't match anymore so it's not easy to get the tid, to achieve that i used the following code on products/% view:

```
    <?php
    $pa=drupal_get_normal_path('car/'. arg(1, request_uri())); /* get the ilx-0 from products/ilx-0 and transform to taxonomy/term/tid */
    list($t1, $t2, $t3) = explode("/", $pa); /* Explode taxonomy/term/tid */
    /* $t1 = taxonomy */
    /* $t2 = term */
    return $t3; /* tid, return this value to get tid and pass to context filter*/
    ?>

```
> 1 votes

---
Tags: views, commerce, taxonomy-terms, path-aliases
---


title: Add styles to panes in Panels module

text:
# Question
Title: Add styles to panes in Panels module
I'm using Panels in page manager to create unique pages with different blocks and panes. I'd like to be able to add settings to each individual pane such as adding a class or style. For example when I edit a block or pane, I receive this window

I'd like to be able to add settings here but I'm not sure where to start. In Drupal 7 adding styles to individual panes was clear and I'm not sure it even has that functionality in 8 yet.

# Answer
I managed to create what I was after by using the Plugin Api I created module with the file structure

```
mymodule
   -src
      -Plugin
          -Block
           Block.php

```

In block PHP I used the following

```
<?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Block\Basic.
 */

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 *
 * @Block(
 *   id = "basic_text",
 *   admin_label = @Translation("Basic MyModule Block (basic_text)")
 * )
 */

class Basic extends BlockBase {

    /**
     * {@inheritdoc}
     */
    public function defaultConfiguration() {
        return array(
            'mymodule_string' => $this->t('Enter text here'),
            );
    }

    /**
     * {@inheritdoc}
     */
    public function blockForm($form, FormStateInterface $form_state){
        $form['mymodule_string_text'] = array(
          '#type' => 'textarea',
          '#title' => $this->t('Block contents'),
          '#description' => $this->t('This text will appear in the block.'),
          '#default_value' => $this->configuration['mymodule_string'],
        );
        $form['mymodule_style_selected'] = array(
            '#type' => 'select',
            '#title' => t('Style'),
            '#options' => array(
                0 => t('default'),
                1 => t('black'),
                2 => t('white'),
            ),
            '#default_value' => $this->configuration['mymodule_style'],
        );
        return $form;
    }
    /**
     * {@inheritdoc}
     */
    public function blockSubmit($form, FormStateInterface $form_state) {
        $this->configuration['mymodule_string']
         = $form_state->getValue('mymodule_string_text');
    }
    /**
     * {@inheritdoc}
     */
    public function build(){
        return array(
            '#type' => 'markup',
            '#markup' => $this->configuration['mymodule_string'],
        );
    }
}

```

I haven't implemented the logic handling the style options but I can now place a pane using the IPE and configure the style pane by pane.
> 0 votes

---
Tags: 8, panels
---


title: filter criteria: current users role

text:
# Question
Title: filter criteria: current users role
I am using views to show some published content. I would like to give users with the role `preview` the ability to see all content within the view – published and unpublished. So they can preview how the page would look like after publishing content. My thoughts: I need to add a filter-criteria:

> Published (=Yes)
>
> OR
>
> Current-User-Role (=preview)

Ideas?

---

edit #1: to make it easier, I could also allow to see the content for all authenticated users.

---

edit #2: I have about **15 views** where I need the preview functionality. they have different structure (filter criteria, viewmode, context etc) that means I need to keep it **flexible**. means probably that I need to define a filter and validate the data in the `template.php`

# Answer
> 2 votes
As said in the comment: If you want to give user access to unpublished content you can have a look at view\_unpublished

You can also try to use this in combination with the 'Content: Published or admin' filter, but I didn't have a change to try it.

A filter like you're describing can be a good addition to views, consider creating an issue for it.

# Answer
> 1 votes
If I understand well your question, I think that you can use the Access \> Permissions \> Access restrictions settings in your view, to limit view results to only users inside respective role.

**Update:** If your are needing allow to the same view shows only content of views according user's roles, you can install Content Access module http://drupal.org/project/content\_access. Then the same View will only show to the user the content that he can see, according settings in each `Content Type` \> `Access Control` tab. (Note: Maybe the module will require rebuilding content access permissions before you see changes)

Maybe will be useful see other alternative of module to control access to content, like ACL http://drupal.org/project/acl, but I have no experience with that module.

I hope information be useful.

# Answer
> 0 votes
You could do one thing for a temporary fix quick. Create two views separately and use some logic while rendering it at the theme layer. I could help here if you are interested in the hack.

# Answer
> 0 votes
Views has a filter option for `Content: Published or admin`. It will show unpublished content to users that have permissions to see it. Choosing that as the filter rather than `Content: Published` should automatically show unpublished content in line with the published as long as the user has the permissions to view the unpublished content.

# Answer
> 0 votes
The View Published or Roles module does just that.

# Answer
> -1 votes
You could write a custom module to implement

1. a new permission *view unpublished content*
2. check if the connected user has the permission to view the content if unpublished when processing the view

In your CUSTOM.module file :

```
/**
 * Implements hook_permission().
 */
function CUSTOM_permission() {
    return array(
    'view unpublish content' => array(
    'title' => t('View unpublished content'),
    ),
  );
}

/**
 * Implement hook_preprocess().
 */
function CUSTOM_preprocess(&$variables, $hook) {
    global $user;
    if ($hook == 'views_view_unformatted') {
        $view = $variables['view'];
        if ($view->name == 'THE_MACHINE_NAME_OF_YOUR_VIEW'){
            foreach ($variables['rows'] as $key => $row) {
                $result = $view->result[$key];
                $node = node_load($result->node_nid);
                if ( $node->status == '1' || ( user_access('view unpublish content') && $node->status == '0' ) ){
                    $variables['rows'][$key] = render(node_view($node, 'teaser')); // or render it full if you prefer
                }else{
                    unset($variables['rows'][$key]);
                }
            }
        }
    }
}

```

You install your CUSTOM module Then you give this permission to your specific role And set the view to display content without filter on node status

Hope that helps :)

# Answer
> -1 votes
In Drupal 7 (any Views 3.x?) you can and/or filters together.

\[my filters\] AND user has this role OR node is published

otherwise I wonder if something like Workflow could cut it.

---
Tags: 7, views, users
---


# Question
Title: What is an alternative to hook_node_view()?
When a node is rendered in a panel pane, `hook_node_view()` is not invoked. (I use Panels 7.x-3.4.) Is there any alternative to change rendered node content in any other hook?

I have tried with `hook_ctools_render_alter()`, but the HTML output of the node is presented as one large string. I need to change node content in one particular field, so I need to access a `$node` variable as an array, as it happens with `hook_node_view()`. I need to execute custom PHP for changing the output of one of the fields.

# Answer
> 0 votes
If you are just editing one field you can use `template_preprocess_field()`, `hook_field_display_alter()`, or `hook_field_display_ENTITY_TYPE_alter()`. Those should also fire in other contexts if you use that field outside the panel pane in the future (which may be a good or bad side-effect depending on your context).

---
Tags: 7, nodes, hooks, panels
---


# Question
Title: Change permission on Content Overview page
I have granted an admin 'Administer Content' permission under People-\>Permissions. This gives him the ability to publish/unpublish nodes. But I don't want him to be able to go to the Content overview page where he can delete and unpublish in bulk. This is because I have setup certain workflow rules with node\_validate which only let him delete or unpublish nodes under certain conditions within the node edit screen. If he goes to the Content overview page, he can circumvent the workflow logic.

So how do I programmatically take 'Administer Content' permission away when he goes to the Content overview page? I still want him to be able to see the Content overview, but I don't want him to be able to unpublish, delete, or do any of the other bulk operations.

Any thoughts would be appreciated.

# Answer
This is such an old question, but I had the same question and hiding it in css is not the answer.

The correct answer IS to enable the Actions permissions (VBO) (actions\_permissions) module. That will allow you to set which roles can perform bulk operations.
> 1 votes

# Answer
I am pretty sure there isn't a way to accomplish this.

Maybe you could use css and hide the Edit Options field set like this:

```
#edit-options {
  display: none;
}

```

That would hide it, but if he was malicious he could edit the CSS in his browser and then use it.
> -1 votes

---
Tags: users
---


# Question
Title: Creating entity in Rules causes PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
My application based on CRM-Core. I am using several rules which launch on the event "After saving a new crm core contact" and each has a crm\_core\_activity entity created as the rule's action.

Is it possible that the rules happen simultaneously which causes SQL error - trying to set same activity\_id (which is primary key)?

Here is the error:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '879' for key 'PRIMARY': INSERT INTO {crm_core_activity} (activity_id, revision_id, uid, type, title, created, changed, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => 879 [:db_insert_placeholder_1] => 1552 [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => email [:db_insert_placeholder_4] => תודה שפנית אלינו! [:db_insert_placeholder_5] => 1465830228 [:db_insert_placeholder_6] => 1465830228 [:db_insert_placeholder_7] => 4e87b796-fc8d-49f4-85f4-9ac944563576 ) in drupal_write_record() (line 7316 of /home/roi/sites/staging/0108-ormil/drupal-7.38/includes/common.inc).

```

The error happens randomly which makes me think this is a timing issue between multiple rules on the same trigger.

# Answer
The problem was that I created an entity using code (implementing hook\_rules\_action\_info()). In the hook I created a new entity and also saved it. In the rule I both called this hook implementation (create+save an entity) and also explicitly saved it is a rules action.
> 0 votes

# Answer
Have a look at issue # 430274, which explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg after only a few secs or mins later on ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the entity is for sure saved ... (so that can't be the reason anymore then why things don't work as expected ...).

**Note**: it's tough (virtually impossible) to pinpoint what exactly is causing your issue without knowing what exactly those rules look like. Adding a copy of your exported rules to the question may possibly help, but still. However, I'd recommend you to do some Rules debugging, using any of the techniques I described in my answer to How can I display the value of a variable inside a condition?
> 0 votes

---
Tags: entities, rules
---


# Question
Title: How to set kint() to be closed by default?
I find that when expanding Kint widgets, if the object is sufficiently large, the loading time can be quite slow. It appears, when you expand the root level, it also expands child objects. I would prefer that it keeps all children closed until I decide to expand; although I'm not sure if this will have any impact on performance.

Where can I configure Kint for Drupal?

# Answer
I know this is an old question, but I just figured this out and this question comes up first on google.

The option is already there. What you need to do is click *next* to the plus sign (the text next to it) not the actual plus sign itself. Clicking the plus sign will expand everything, clicking the title, path or array key will just expand the immediate node below it.

I went through almost a whole project thinking Kint() unusable when it's really just a confusing UI choice.
> 5 votes

---
Tags: 8, debugging
---


# Question
Title: How do I change the content text programmatically?
I have enabled the anonymous comment setting. And its E-mail form appears as shown below.

Now, I want to change the text ***"The content of this field is kept private and will not be shown publicly."*** to ***"E-mail address will not be shown publicly."***

How can I change this programmatically.

For information the HTML part I have copied through fire-bug which is as below.

```
<div class="form-item form-type-textfield form-item-mail">
     <label for="edit-mail">E-mail <span class="form-required" title="This field is required.">*</span></label>
     <input id="edit-mail" name="mail" value="" size="30" maxlength="64" class="form-text required" type="text">
     <div class="description">The content of this field is kept private and will not be shown publicly.</div>
</div>

```

# Answer
> 2 votes
This value is defined in the comment\_form function. More specifically, it is the description in this section:

```
  // Add author e-mail and homepage fields depending on the current user.
  $form['author']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail'),
    '#default_value' => $comment->mail,
    '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
    '#maxlength' => 64,
    '#size' => 30,
    '#description' => t('The content of this field is kept private and will not be shown publicly.'),
    '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  );

```

You could create a custom module and implement hook\_form\_FORM\_ID\_alter. Your custom module file would contain below lines in a .module file and a basic .info file.

```
<?php

function MODULENAME_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $form['author']['mail']['#description'] = t('E-mail address will not be shown publicly.');
}

```

Alternatively there are some options for overriding strings outlined here: Drupal 6 & 7 - Change default strings (text) without using full translation system

---
Tags: 7
---


# Question
Title: How to create custom ECK entity class (per bundle)
With ECK I created Entity type Vehicle, and added 2 bundles, Car and Truck

Goal is to have a class `Car` so I can use `Car::create()` and similar entity functions, and also implement my own functions.

As far as I came is creating `Vehicle` class, and it's working, but I'm struggling with bundles.

# Answer
> 2 votes
I guess it is impossible to do what you want. A bundle is not a sub-class of an entity as you seem to be assuming.

Classes are always defined in code and are always provided by a module. ECK uses a workaround but in fact only defines one entity type: `EckEntity`, it then performs some tricks to let Drupal see this as different entity types.

Creating entities for every bundle dynamically (since a user can add / remove bundles) would be difficult and appears to be only possible using dirty tricks like this:

```
// With a property
$myclassname = "anewclassname";
$myproperty = "newproperty";
eval("class {$myclassname} { protected \${$myproperty}; }";

```

From: https://stackoverflow.com/a/15579465/1293725

I am pretty sure Drupal does not support this (luckily).

Bundles are stored as properties on the entity, often (always?) as the `type` property, have a look at this example:

```
// Create node object with attached file.
$node = Node::create([
  'type'        => 'article', // < - this is the bundle
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
    'alt' => 'Hello world',
    'title' => 'Goodbye world'
  ],
]);
$node->save();

```

From: https://drupal.stackexchange.com/a/189095/9921

So in your case, you would need to do this:

```
$car = Vehicle::create([
  'type'        => 'car',
   ...
]);

```

Or define a new class for your bundles, but you would need to either use the eval method above to create a class for all your bundles, or define them in code and loose flexibility. Then in that class extend the Vehicle class and in the constructor provide the `type` or something. For the sake of readability of your code I guess it would be best to just follow conventions and not create classes for bundles.

---
Tags: 8, entities
---


# Question
Title: Create a non admin area form to update user form
I'm trying to see if there's an example of a form that isn’t in the admin area and is used to update user details.

Is it possible to create this type of form? Where can I find such an example?

# Answer
> 2 votes
Look at the Drupal core user module, is generates the forms for account editing. Specifically, `user_profile_form()`, `user_account_form()`, & `user_profile_form_submit()` will give you an example of an user-accessible form that updates a user account.

---
Tags: 7, forms, users
---


# Question
Title: How to ignore the first argument in view contextual filters?
I am having path aliases of the form

```
path/val1/val2/data

```

that are created with `pathauto`. I want to create a view that will be use a contextual filter and that will read only section 3 of the URL. When I set the view path to:

```
path/%/%/data

```

then I need to specify a contextual filter for section 3 (`val2`) that cannot filter my data properly.

My configuration looks like:

**Filter configuration:**

So I need the CELEX content filter to match *section 3* of the URL. Can I entirely skip %2 and just filter based on %3? Alternatively, can I declare the second section to be a wildcard in the view path?

When I attempt to `Provide default value` as Bryan Jones suggested, then it seems that default value doesn't work because the context filter actually DOES match the URL section, whereas the default value is provided **when the filter value is NOT in the URL**

What I see after previewing the view is

**Context values:**

**Query:** (Notice the value that I wanted to be `val2`)

# Answer
There is a specific contextual filter called "Global: Null" that you can employ to ignore a path part and leave the query unchanged. You will have to reorder the filters so that Null is in the right position (in your case, the first, since you want to ignore the first % of the path). See the screenshot:
> 2 votes

# Answer
you can use 'all' to get all values of 'val1'

Exp: path/all/val2/data

to get all values of 'val1', 'val2'

Exp: path/all/all/data
> 2 votes

# Answer
In the contextual filter you can select "Provide default value" From there you can select "Raw value from URL". You then choose the path component.

I hope that helps!
> 0 votes

---
Tags: 7, views, path-aliases
---


# Question
Title: Add a subquery in a WHERE condition, using hook_views_query_alter()
I tried to add a subquery like this:

```
function mymodule_views_query_alter(&$view) {
  $view->query->where[1]['conditions'][] = array(
    'field' => 'node.nid',
    'value' => 'SELECT SUBSTRING(source, 6) FROM {url_alias} WHERE alias LIKE "pros/%"',
    'operator' => 'in',
  );
}

```

I have a specific case where nodes are created with aliases starting with `pros/` or not, and I want to get only them.

In a simple raw SQL query, I'd go with this:

```
SELECT *
FROM node node
WHERE node.nid IN (SELECT SUBSTRING(source, 6)
                   FROM {url_alias}
                   WHERE alias LIKE "pros/%")

```

But I can't find out how to do this using `hook_views_query_alter()`.

# Answer
> 3 votes
Ideally I think its right to use views\_join\_subquery. But the subquery you are using is with `IN` keyword is always slow and will produce same result as using a `LEFT JOIN` joining with `node.nid` field.

You can try creating a views\_join and adding the `url_alias` table by add\_field method while the node table will be the left table.

I don't have the code at the moment but you can have a look at the below links.
https://stackoverflow.com/questions/6851945/add-table-join-where-and-order-by-to-views-query-in-views-query-alter
http://www.wordpressecoder.com/2014/01/how-to-alter-views-query-with-multiple.html
http://www.yellowpencil.com/blog/last-ditch-fix-programmatically-changing-drupal-7-view

# Answer
> 3 votes
In the end, I went through `hook_views_pre_execute()` and using a `LEFT JOIN`..

```
function mymodule_views_pre_execute($view) {
  $query = $view->build_info['query'];
  $query->leftJoin('url_alias', 'u', 'node.nid = substr(u.source, 6)');
  $query->where("u.alias LIKE 'pros/%'");
}

```

Something that tripped me up was that I had to use simple quotes around the `LIKE`, it didn't work with double quotes.

# Answer
> 3 votes
There is a great example of how to do subqueries in the Taxonomy Views integration. You can see it in views\_handler\_argument\_term\_node\_tid\_depth::query().

Ultimately though, the trick is that you build an entire sub-query using `db_select()`, and then just add that entire resulting object into the Views query object using the add\_where() method.

```
function mymodule_views_query_alter(&$view) {
  $sub_query = db_select('foo', 'f')
    ->fields('f', array('nid'))
    ->condition('f.bar', 'baz');
  $view->query->add_where(0, 'node.nid', $subquery, 'IN');
}

```

This ability to use a select subquery is documented in the Views add\_where() documentation (but unfortunately due to the rendering on api.drupal.org, it doesn't show the example).

You could also probably manually add the where to the `$view->query->where[1]['conditions']` array, but using the method instead of manipulating the array directly is recommended.

---
Tags: views
---


# Question
Title: Trying to theme my user login/registration/password reset pages in Drupal 7, going bonkers
What seems like it should be a very, very simple task -- theming the user login, registration, and password pages in Drupal 7 -- is turning out to be a Kafka-esque nightmare. I can't figure out what I'm doing wrong, and am wondering if I'm slowly regressing into a newt in the process.

So there's a ka-billion how-to posts all over the place about how to do this (all of the posts I've read seem to be derived from this page here), and a ka-trillion success stories, but sadly, I'm not one of them. Here's what I've done, and tell me, please, I beg of you, what idiotic thing I'm doing wrong:

**Step 1:**

I added the following code to my template.php file, making sure to replace "yourtheme" with the name of my theme:

```
<?php
function yourtheme_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'yourtheme_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_pass'
    ),
  );
  return $items;
}
?>

```

**Step #2:**

Then, below that code in the template.php file, I inserted this code, again, making sure to replace "yourtheme" with the name of my theme:

```
<?php
function yourtheme_preprocess_user_login(&$vars) {
  $vars['intro_text'] = t('This is my awesome login form');
}

function yourtheme_preprocess_user_register_form(&$vars) {
  $vars['intro_text'] = t('This is my super awesome reg form');
}

function yourtheme_preprocess_user_pass(&$vars) {
  $vars['intro_text'] = t('This is my super awesome request new password form');
}
?>

```

**Step #3:**

I created three new template files called user-login.tpl.php, user-register-form.tpl.php, and user-pass.tpl.php

**Step #4:**

I pasted the following code into each new template file:

```
<p><?php print render($intro_text); ?></p>
<div class="yourtheme-user-login-form-wrapper">
  <?php print drupal_render_children($form) ?>
</div>

```

**I'm slightly confused by this:**

"Save your template.php file to the theme's main directory. Save your .tpl.php files in the same place for the D6 examples, or, in the case of the D7 examples, to the directory you specify in the 'path' element of the $items array."

But that just means that I should save the .tpl.php files in my theme directory, correct? If so, I did this correctly.

**Step #5:**

Cleared the cache, moved around some elements...and...

Nothing. Is there anything I'm doing wrong? Thanks in advance for your help.

# Answer
The template.php file goes into your main theme directory (yourtheme in this instance.) The .tpl.php files go into the templates subdirectory (yourtheme/templates.) If you do not have the subdirectory, create it.

Hope this helps.
> 0 votes

# Answer
It is a simple module for Customize Drupal Login, Password and Register pages with background images. https://www.drupal.org/project/simplelogin
> 1 votes

---
Tags: theming, users
---


title: Returns 403 error after user login

text:
# Question
Title: Returns 403 error after user login
My site was copied from production to test server. It works on Drupal 7 + Nginx + PostgreSQL. On production, user login works fine, but on test server I receive a 403 error on users/admin (or user/1) where I'm redirected after login.

What I've already checked/done:

1. Database tables cache\_\* and sessions are empty.
2. User *admin* in the database has: uid = 1, status = 1, roles = 2 (authorized), 3 (administrator), 10 (site admin)
3. Try to open in IE, Chrome, Firefox. All history (cache and cookies) were deleted.
4. In file sites/default/settings.php there are the variables `$base_url = "http://mytest.domain.com"`, and `$cookie_domain = "mytest.domain.com"`
5. nginx.conf contains such rules for 403 error:

```
location ~ \..*/.*\.php$ {
    return 403;
}

location ~ ^/sites/.*/private/ {
  return 403;
}

location ~ (^|/)\. {
  return 403;
}

```

Also all *fastcgi\_cache* options are commented out.
6. Permissions on server: sites/default - 775 (folders), 644 (files); sites/default/files - 775 (folders), 644 (files).
7. Also I see that *login* field in the *users* table is updated when I login, but the *watchdog* table and *sessions* table don't contain rows about the session being open.
8. php.ini: opcache.enable = 0

How can I fix the 403 error?

# Answer
I've found a problem. As I said, I'm new to this project and recently I've found that it uses a Memcache module to save sessions. But both *memcached* and *php5-memcached* were not installed on my test server.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: page--user--login.tpl.php is not recognized
drupal isn't recognising the page--user--login.tpl.php file. Tried clearing the cache. Still not working. I've never themed the user login page before. Any idea's?

I am running Drupal 7 and I want to theme the whole page. The other page template is being picked up. There isn't any other page--user--login.tpl.php in my theme directory

the page--user.tpl.php is being recognised but the page--user-login-tpl.php is not. bummer because i want the login page to be considerably different to the user page.

# Answer
> 5 votes
This question is similar to https://stackoverflow.com/questions/8712061/style-drupal-7-log-in-page

It looks like you need to also have:

* a page.tpl.php in your theme for page--anything-else.tpl.php to work
* a page--user.tpl.php in your theme

You should also always clear the theme cache after adding/removing template files.

# Answer
> 1 votes
```
 function themename_theme(&$existing, $type, $theme, $path) {
$hooks['user-login'] = array(
    'template' => 'templates/user-login',
    'render element' => 'form',
 );
  return $hooks;
}

```

Add this code to your template.php file. Then you can create user-login.tpl.php.

Note: Don't forget to clear the cache

---
Tags: theming, users
---


# Question
Title: How do I define a template file for a specific node ID?
I'm trying to define a custom template file for a specific node, using the node ID. I read a lot of topics saying to create a node--X.tpl.php file in the templates folder.

That's what I did; unfortunately, even after flushing the theme cache many times, nothing changes.

Is there anything more I have to do?

# Answer
> 1 votes
A *page-node-{nid}.tpl.php* template file inside the theme directory would also work.

You should instead use *node-{nid}.tpl.php*.

(Replace *{nid}* with the node ID value.)

# Answer
> 10 votes
In Drupal 7, node--\[node-id\].tpl.php is used as template file for nodes, as well as node--\[node-type\].tpl.php. Nothing else needs to be done, except, as Clive wrote in his comment, you also need to have node.tpl.php in the directory containing the template files used by your theme.

Notice there is a difference between node--\[node-id\].tpl.php, and page--node--\[node-id\].tpl: The latter is also used for pages at node/\[node-id\]/edit, or node/\[node-nid\]/delete. See the comment at the beginning of theme\_get\_suggestions().

> Build a list of suggested theme hooks or body classes in order of specificity. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, for `$base = 'page'`, http://www.example.com/node/1/edit would result in the following suggestions and body classes:
>
> ```
>  page__node              page-node
>  page__node__%           page-node-%
>  page__node__1           page-node-1
>  page__node__edit        page-node-edit
>
> ```

# Answer
> 0 votes
a simple method to know the good name to use for your override is drush.

Open a command line go to sites/default in your drupal and type this line :

drush vset theme\_debug 1

to remove drush vset theme\_debug 0..

after that reload your node and look at the code source of it. You will see all possibles drupal's propositions for everything in your page (block, region, html.tpl.php, page.tpl.php ....)

---
Tags: 7, nodes
---


# Question
Title: Create a custom form in Drupal CMS for editors
I need to create a form for our Drupal Editors. The form must allow them to add records to database.

I see next steps to do:

1. I add action in place I want.
2. User clicks on action and modal form appears (that's I do not know how to do in Drupal way).
3. User submits form and record is added to database.
4. If possible refresh current page so user can see new record.

Could somebody please point me in the right direction?

So far I'm looking on: CTools Auto-modal and CTools Auto-modal Admin Interface. However I'm not sure if that is right direction.

# Answer
> 0 votes
Maybe just use a regular content type, add whatever fields you'd need, and let your Drupal editors edit regular nodes.

As a variation, use the ECK module so that you have custom entities (instead of nodes). And then let Drupal take care of storing the data in an appropriate table in the database. With such approach you get all sorts of extra facilities (integrations with other modules), out-of-the-Drupal-box ... Views, Rules, Group, Flag, you name it.

Another approach could be like I described in my answer to "How to implement a multi step approval with webforms/entityforms based on form components?".

---
Tags: 7, forms
---


title: How to export users with passwords?

text:
# Question
Title: How to export users with passwords?
How to export users with passwords? The Users export module cannot help, it export without passwords.

# Answer
> 8 votes
User passwords are stored using a one-way hashing algorithm and cannot be converted to plaintext. In addition, each Drupal site uses a unique cryptographic salt, so that the same plaintext password on two Drupal sites will not result in the same hashed password.

In other words, there is no way to generate a list of usernames and plaintext passwords.

# Answer
> 3 votes
As @MPD says, you can't do this, however you can export all the users and import with a random password and use this ways to set the password:

**Reference**

Generate new password for users periodically and notify user of new password

# Answer
> 2 votes
In very limited use cases, you really might be in need to allow certain users seeing other user's passwords. You can use the AES module.

However, for exporting these passwords you will have to write a custom module using AES module's decryption mechanisms (as the passwords won't be stored as plain text as well).

**A note of warning:** I strongly suggest checking, whether you really need to have users see other user's passwords. This implies a huge security impact on your site, and - as many users still use the same passwords on different web sites - on the security of your user's other profiles around the web.

**Edit:** After you provided some more insights on your requirements, a way to change the passwords in another application when a Drupal user sets a new password, without having to store it unhashed.

You will need to create a custom module. Implement the following hooks (replace MYMODULE with your module name):

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Alter all forms that allow editing the password:
  switch ($form_id) {
    case 'user_register_form':
    case 'user_profile_form':
      // Add an own submit handler to the user forms.
      $form['#submit'][] = 'MYMODULE_set_password_submit';
      break;
  }
}

/**
 * Submit handler setting the password in the third-party application.
 */
function MYMODULE_set_password_submit($form, &$form_state) {
  // Whether the password was changed.
  if (!empty($form_state['values']['pass'])) {
    // Get the password.
    $password = $form_state['values']['pass'];

    // And now you can use the contents of $password to call
    // your other applications API for resetting passwords or
    // hashing / setting the password using direct database
    // access.

  }
}

```

# Answer
> 0 votes
you just export data only (not structure and data) from users table of old database and import this to the new database. All users with password can be export this way too

---
Tags: 7, users, importing-exporting
---


# Question
Title: Why does max_allowed_packet need to be increased?
Strange problem on the production server. After restarting the container assembly (which had the unintended side-effect of re-initialising the MySQL server with default settings), some memory-intensive pages (specifically the Views-enabled All Content page) wouldn't load. I couldn't import an SQL snapshot into a dev server for testing because MySQL kept on complaining about max\_allowed\_packet. After increasing max\_allowed\_packet, the import was successful and the troublesome pages loaded fine. I increased the setting on the production server and the problem went away as well. Why did max\_allowed\_packet need increasing unexpectedly? Is increasing it by a factor of 10 likely to avoid further problems, or will it cause more problems further down the line?

# Answer
> 2 votes
> Why does max\_allowed\_packet need to be increased?

When your server is processing big queries, then you have to increase the value of the `max_allowed_packet` (or to shorten your queries if possible ?).

Big queries makes me think of Views. One way to find those queries is, to enable the "Show the SQL query" under `admin/structure/views/settings` edit a view and see how big its query is.

It is possible that if your content has been increased, your queries will have been increased as well (will return a large result row).

You can increase the `max_allowed_packet`, if needed, as MySQL says:

> It is safe to increase the value of this variable because the extra memory is allocated only when needed.

---
Tags: views
---


title: How to override entity:link() function?

text:
# Question
Title: How to override entity:link() function?
I have an entity with `entitylisthandler`.

In entitylisthandler, i have a function to build row like:

```
public function buildRow(EntityInterface $entity) {

    /* @var $entity \Drupal\mymodule\Entity\xyz*/
    $row['id'] = $entity->id();
    $row['config_name'] = $entity->link();
    //$row['first_name'] = $entity->first_name->value;
    $row['ctype'] = $entity->ctype->value;
    return $row + parent::buildRow($entity);
  }

```

In @line 3:

```
$row['config_name'] = $entity->link();

```

I'm calling link function here which calls entity `canonical` link.

**How to change this default value 'canonical' to some other link like 'delete-form'?**

This is the Drupal core link function which I'm trying to override in `entitylistbuilder` file.

```
public function link($text = NULL, $rel = 'delete-form', array $options = []) {
  return $this->toLink($text, $rel, $options)->toString();
  }

```

I have changed its argument from 'canonical' to 'delete-form', but it won't work.

# Answer
You should not change the core function. What core does, if $rel is not set, it uses 'canonical'. If you want to use 'delete-form' instead, put this as an argument when using the link function:

```
$row['config_name'] = $entity->link(NULL, 'delete-form');

```

BTW, link() is deprecated, so use toLink() instead.
> 5 votes

---
Tags: 8, navigation, entities
---


# Question
Title: How do I link drush to my drupal site thats hosted via localhost?
I have installed drush via terminal, but how do I link it to my 2 local drupal sites? When I do drush status I get this:

PHP configuration : /etc/php/7.0/cli/php.ini PHP OS : Linux
Drush script : /usr/local/bin/drush
Drush version : 8.1.2
Drush temp directory : /tmp
Drush configuration :
Drush alias files :

So how do I now link the drush to my two virtual host drupal sites? I looked online for a tutorial or guide, but I don't quite understand the ones I found on how to link them.

# Answer
There are several ways to tell Drush which Drupal site you would like it to operate on.

1. Run Drush from the directory that contains the Drupal site's settings.php file. `$ cd /path/to/drupal_root/sites/default
$ drush status`
2. Pass `--root` and `--uri` options that identify the site: `$ drush --root=/path/to/drupal_root --uri=http://mysite.dev status`
3. Create a site alias, and use that `$ drush @mysite status` In order to use the last option, you must define the `mysite` alias as described in the example aliases file.

**UPDATE:**

The --uri option is used (a) to select which settings.php to use, and (b) to set the $\_SERVER superglobal. If your settings.php file is in the `default` directory, then --uri is not necessary to bootstrap. However, some modules will expect the URI to be set up correctly; in some instances, you will not get the correct results if this setting is omitted.
> 2 votes

---
Tags: 7, drush
---


# Question
Title: How to create a slideshow of different views?
I am trying to create a slideshow of different Views.

I am thinking that the "view field" might work with "views slide show" \- possibly sending the "view result counter" through as an argument. I am struggling though as I'm not sure this is a readable contextual filter when it reaches the "view field" view.

Can anyone point me in the right direction? If the "view result counter" is readable, what contextual filter should I add in the "view field" view.

# Answer
Your current approach will not work because View Fields View will insert the **same** view for each and every row/slide.

---

Here is what you need to do. For example: You want 4 slides.

Create a Slideshow View of Articles or something that has 4 or more content. Then set the view results to 4, so it only shows 4.

Now add a **Global: View Result Counter** and exclude from display.

Add a **Global: Custom Text** and for text put:

```
[counter]

```

In your view preview you should see numbers

```
1
2
3
4

```

Now we are going to override these (the custom text), and replace them with views in **template.php** (located in `/sites/all/themes/yourtheme/`) add the following code:

```
function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_slideshow_name" && $vars['fields']['nothing']->content == 1) {
    $vars['fields']['nothing']->content = views_embed_view('view_name', 'block_1');
  }
  else if ($vars['view']->name == "view_slideshow_name" && $vars['fields']['nothing']->content == 2) {
    $vars['fields']['nothing']->content = views_embed_view('view_name', 'block_2');
  }
  else if ($vars['view']->name == "view_slideshow_name" && $vars['fields']['nothing']->content == 3) {
    $vars['fields']['nothing']->content = views_embed_view('view_name', 'block_3');
  }
  else if ($vars['view']->name == "view_slideshow_name" && $vars['fields']['nothing']->content == 4) {
    $vars['fields']['nothing']->content = views_embed_view('view_name', 'block_4');
  }
}

```
* replace **yourtheme** with the actual name of your theme
* replace **view\_slideshow\_name** with the name of your view slideshow.
* replace **view\_name** with the name of the view that you want to show
* replace **block\_1** with the machine name of your view

Lastly, in Drupal, clear/flush your Cache to see the changes.

> **Note:** The changes will show up when you see the slideshow in your page and not in the view preview.

---

## Forgot to mention that you need to uncheck provide/add wrappers and classes.

## Also, for both of your fields, do as below

> It seems odd that you have to list the block name of the view you want to insert but not the block name of the view you are overriding.

That's because in my case I did not plan to add more blocks or pages to my view. When you do not specify, it affects all pages or blocks that are from your view.

But if you want to be specific here is how:

```
function bartik_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "rotator" && $view->current_display == 'block_1' && $vars['fields']['nothing']->content == 1) {

    $vars['fields']['nothing']->content = views_embed_view('checking_home', 'block_1');
    }

  else if ($vars['view']->name == "rotator" && $view->current_display == 'block_1' && $vars['fields']['nothing']->content == 2) {

    $vars['fields']['nothing']->content = views_embed_view('home_outstanding_issues', 'block');
    }

}

```
> 3 votes

---
Tags: 7, views
---


title: Sending a value to JavaScript

text:
# Question
Title: Sending a value to JavaScript
I have set theme handler for a form in Drupal and this handler has a template file. What is the easiest way to send a value from PHP to JavaScript in that include file?

# Answer
> 14 votes
The standard way to do this in Drupal is with drupal\_add\_js, using the "setting" type:

```
drupal_add_js(array('variableName' => 'value'), 'setting');

```

That will make the variable available on the JS side at Drupal.settings.variableName.

# Answer
> 1 votes
Few more examples on drupal\_add\_js,

It's better to specify your module name while adding JS variable to avoid any issues,

```
drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

```

In case you want to execute some JS code after the DOM is initialized,

```
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');

```

# Answer
> 1 votes
Also, the `#attached` key to a form can be used for sending php variable to js.

```
  $my_variable = 'My custom value';
  $form['some-element']['#attached']['js'] = array(
    array(
     'data' => drupal_get_path('module', 'my_module') . '/js/script.js',
    ),
    array(
      'data' => array(
        'variable' => $my_variable,
       ),
      'type' => 'setting',
    ),
  );

```

This can be used in `hook_form_alter` for example.

# Answer
> -10 votes
Easiest way is just to echo it out into a script tag:

```
<script type="text/javascript">
   var variableName = <?php echo $variable ?>;
</script>

```

If Drupal uses a templating language, you need to replace the `<?php echo... ?>` with the relevent output method...

---
Tags: javascript, theming
---