title: insert json into db

text:
# Question
Title: insert json into db
I'm trying to store some JSON data as string into database, but db\_query change my JSON {} to table prefix.

So I have wrong JSON in DB as result.

How can I prevent such behavior?

# Answer
> 1 votes
You shouldn't be using db\_query for inserts (the docs specifically say you shouldn't) but that's not actually the source of this problem.

You should use db\_insert, and your data needs to be sent to the DB as a string.

```
// Mock json data -- notice it's stored as a string
$json_data = '[{
  "first_name": "Ralph",
  "last_name": "Wallace",
  "email": "test@example.com",
}]';

db_insert('my_table')
 ->fields(array(
  'fieldcontainingjson' => $json_data,
 ))->execute();

```

**Update in light of your comment stating that you can't use db\_insert:**

First, you should consider if db\_merge() will work for you. But we won't argue that point and will just try to get this to work with db\_query.

Make sure you're using placeholders correctly with db\_query(). This should work:

```
$json_data = '[{
 "first_name": "Ralph",
 "last_name": "Wallace",
 "email": "test@example.com",
}]';

db_query('INSERT INTO {my_table} (fieldcontainingjson) VALUES (:json)', array(':json' => $json_data));

```

In the future it's considered best practices to share your code that's not working for you.

---
Tags: 8, database
---


title: Views only used for not logged user

text:
# Question
Title: Views only used for not logged user
Is there a way to only display a view result for Not Logged user.

If yes, How I could perform this.

I'm using drupal 7

Thanks a lot

# Answer
In view's settings (Page settings/Block settings) find **Access**. Change **Permission** to **Role** and select appropriate role (*anonymouse*)
> 0 votes

---
Tags: views
---


title: File Upload to share storage

text:
# Question
Title: File Upload to share storage
I am trying to create a load balanced Drupal installation. My setup has a shared storage that all the webservers can read write to. At the moment I’m having trouble setting up the Drupal configuration at {mydomain}/admin/config/media/file-system/ to save our content to the correct file path.

The file path on the operating system that I’m trying to write content to is of the form:

\xx.xx.xx.xx\my\content\folder\

When I place this in the public file path I get the content written to the local path:

D:\myDrupalInstalation{mydomain}\sites\xx.xx.xx.xx\my\content\folder\

However I know the PHP has rights to write modify content on the shared storage because when I try the same path in private file path the content is written to the shared storage:

\xx.xx.xx.xx\my\content\folder\sites{mydomain}\allTheContent\

Which is what we require.

How can I configure the public file path to write to the same location?

P.S. I think it is something due to the fact that the Drupal config page itself specifies "*This directory must be relative to the Drupal installation directory and be accessible over the web.*" for public path and "\* It should be writable by Drupal and not accessible over the web.\*" for Private.

Thanks

# Answer
> 0 votes
In a Linux environment, this is done for NFS drives by creating a symbolic link under your Drupal webroot.

In the Windows environment, you can also create a symlink to a network drive path (e.g. *\xx.xx.xx.xx\my\content\folder* ).

---
Tags: files
---


# Question
Title: Is this way safe to bootstrap Drupal from an external PHP script?
I want to bootstrap Drupal from an external PHP file located in Drupal's root directory. The following code will do the job.

```
error_reporting(E_ALL);
ini_set("display_errors", 1);
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$html_1='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" version="XHTML+RDFa 1.0" dir="ltr"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:dc="http://purl.org/dc/terms/"
  xmlns:foaf="http://xmlns.com/foaf/0.1/"
  xmlns:og="http://ogp.me/ns#"
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
  xmlns:sioc="http://rdfs.org/sioc/ns#"
  xmlns:sioct="http://rdfs.org/sioc/types#"
  xmlns:skos="http://www.w3.org/2004/02/skos/core#"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema#">
<head profile="http://www.w3.org/1999/xhtml/vocab">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>HOW TO BOOTSTRAP DRUPAL FROM AN EXTERNAL PHP SCRIPT?</title>
</head>
<body>
';

$html_2 ='</body>
</html>';

global $user;

if ((user_is_logged_in()) && ($user->uid == 1)) {
    //only if this is the admin, do stuff. for example:
    print $html_1;

    print  t("  <h1>This User</h1>\n") ;

    print "  <p>Logged In</p>\n";
    print "  <p>User ID: ".$user->uid."</p>\n";

    print $html_2;

} else {
    drupal_access_denied();
    module_invoke_all('exit');
    drupal_exit();
}

```

Let's say I want to create a script that lets the admin export nodes of a certain content type. And let's assume I don't want to write a custom module or use views. I know that my way of doing that is the wrong way. I'm trying this in order to learn bootstraping Drupal from an external php script. If I put my script in Drupal's root directory, and I don't change anything in the .htaccess file, will the script cause any security issue?

So I want to know if this example safe, i.e. if the code doesn't have any security issues. So my question is about the security of the process.

# Answer
> 0 votes
Why not to use `drush` to handle Drupal boostrap as demonstrated below?

So the file can contain a minimum content like (no need to call Drupal bootstrap):

```
<?php
drupal_set_message('Foo');

```

then run it as:

```
$ drush scr foo.php
Foo

```

---
Tags: security, bootstrapping, external-scripts
---


# Question
Title: How to get the site url in views custom output
I want to print the site url in views field with a custom output, I tried \[site:url\] token, It doesn't work.
I already have entity token and entity\_token enabled in my site.
Is there a way to do that with or without tokens?

# Answer
Try to add field handler "custom text" and rewrite result as on the screenshot

but put there your field name instead of \[title\].
> 2 votes

---
Tags: views, tokens
---


# Question
Title: Required Modules by Translation Management Tool (tmgmt)
I read the description for the translation management tool (tmgmt) and I found it requires many other modules. I'm wondering what the modules do specifically to make the tmgmt work? I read their respective project page descriptions, but that doesn't really help me understand how exactly it integrates with the module. Those modules are:

Is there quick explanations or examples regarding how they support tmgmt?

# Answer
> 1 votes
A explanation on what these modules do

* Entity API: Provides API functions that makes working with entities easier (e.g. tokens for entity fields, CRUD functions, etc.). There's no visible functionality here.
* Views: Provides a way to select into data tables (e.g. users, nodes, etc.), filter them, and display the data in different modes (e.g. as page, block, RSS feed, etc.)
* CTools: A suite of API/utility functions to help with development tasks (e.g. creating modals, handle AJAX requests, etc.). The only visible functionality is Page Manager, a UI that allows you to override URLs paths with a different display).
* Views Bulk Operations: Adds an option to Views to select multiple items and perform an operation on them (e.g. bulk unpublishing selected nodes).
* Content Translation: A core Drupal module that enables the ability to translate node content into other languages.
* Locale: A core Drupal module that enables the ability to translate the interface (e.g. button & label names).
* Internationalization: A suite of UI tools that extends out Locale to provide more control with interface localization.
* Entity translation: Provides a UI for the Content Translation module.
* Rules: Provides UI and API for enforcing workflow. These enforcements are called Rules which has 3 parts: an *event* (something thing happened to your data), a *condition* (checks on the data to see it matches your scenario), & *action* (actions to take to enforce your workflow on your data).

There's much more to these modules than what a couple sentences can provide. Read the respective documentation pages for more information.

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


# Question
Title: How to dynamically populate select options?
I'm trying to build an admin form for a module, using `system_settings_form()`.

I want the users to be able to select sub-options, from a list that is dynamically generated depending on the main option.

For example

```
$main_options = array('foo','bar');
$sub_options['foo'] = array('foolish','football','foodstuff');
$sub_options['bar'] = array('barley','baroque','barbarian');

$form = array();

$form['main_option'] = array(
    '#type' => 'select',
    '#options' => $main_options,
);

$form['sub_option'] = array(
    '#type'  => 'select',
    '#options' => $sub_options[SOMEHOW USE THE SELECTED VALUE OF main_option AS INDEX],
);

return system_settings_form($form);

```

So I would expect sub\_option to be unpopulated the first time the form is called, and then populated as soon as the user populates main\_option.

Is this possible?

**Update**

Thanks for the advice re Ajax. I looked up https://www.drupal.org/node/752056 and this is what I've built: here the values in `olt_test` need to change based on the value selected for `olt_provider`.

```
  $form['olt_provider'] = array(
    '#type' => 'select',
    '#title' => t('Provider'),
    '#options' => variable_get('providers'),
    '#ajax' => array(
      'callback' => 'olt_provider_select_callback',
      'wrapper' => 'tests-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $form['olt_test'] = array(
    '#type' => 'select',
    '#title' => t('Test'),
    '#prefix' => '<div id="tests-div">',
    '#options' => array(''),
  );

```

and in `olt_provider_select_callback()` I have

```
  function olt_provider_select_callback($form, $form_state) {

  $new_options_value = [new value calculation snipped]

  $form['olt_test'] = array(
    '#type' => 'select',
    '#title' => t('Test'),
    '#prefix' => '<div id="tests-div">',
    '#options' => $new_options_value,
  );

  return $form['olt_test'];
}

```

~~The problem I'm now seeing is that the Ajax only fires on the first time the `olt_provider` select box is clicked - subsequent clicks don't fire. Any thoughts?~~

~~**The problem I'm now seeing** is that although the `olt_test` dropdown is correctly updated via Ajax, **this replacement value is not saved on form submission**. Any thoughts?~~

**Final Update** \- My form is working correctly now. The data was being saved on form submission, but I needed to add some more code to retrieve the saved data and display the default values when the form was loaded.

# Answer
> 4 votes
Ajax would be the better way to get precisely what you are asking. One important part of using the form ajax is if you dont tell it which part to rewrite, and which to return, it will rewrite the whole form. It is easy to cause an Inception style recursion problem. This is a pretty good explanation of the ajax.

An alternate, because I always like to provide them, is using form #states. Most straightforward use of states would be if you have one sub\_option select element for each of the main\_options, or perhaps whole fieldsets.

# Answer
> 5 votes
As said before you could make use of Form APIs `#states` to display one element only after a certain input to another form element has been made. In your case you'd maybe go with two additional select lists, both initially hidden. Check `form_examples_states_form()` for more information.

```
$form['main'] = array(
  '#type' => 'select',
  // ...
);
$form['sub_a'] = array(
  '#type' => 'select',
  // ...
  '#states' => array(
    'visible' => array(
      ':input[name="main"]' => array('value' => 'foo'),
    ),
  ),
);
$form['sub_b'] = array(
  '#type' => 'select',
  // ...
  '#states' => array(
    'visible' => array(
      ':input[name="main"]' => array('value' => 'bar'),
    ),
  ),
);

```

# Answer
> 3 votes
There is an example of dependent drop-down in the developer examples.

```
function ajax_example_dependent_dropdown($form, &$form_state) {
  // Get the list of options to populate the first dropdown.
  $options_first = _ajax_example_get_first_dropdown_options();
  // If we have a value for the first dropdown from $form_state['values'] we use
  // this both as the default value for the first dropdown and also as a
  // parameter to pass to the function that retrieves the options for the
  // second dropdown.
  $selected = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);

  $form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'Instrument Type',
    '#options' => $options_first,
    '#default_value' => $selected,

    // Bind an ajax callback to the change event (which is the default for the
    // select form type) of the first dropdown. It will replace the second
    // dropdown when rebuilt.
    '#ajax' => array(

      // When 'event' occurs, Drupal will perform an ajax request in the
      // background. Usually the default value is sufficient (eg. change for
      // select elements), but valid values include any jQuery event,
      // most notably 'mousedown', 'blur', and 'submit'.
      // 'event' => 'change',
      'callback' => 'ajax_example_dependent_dropdown_callback',
      'wrapper' => 'dropdown-second-replace',
    ),
  );

  $form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => $options_first[$selected] . ' ' . t('Instruments'),

    // The entire enclosing div created here gets replaced when dropdown_first
    // is changed.
    '#prefix' => '<div id="dropdown-second-replace">',
    '#suffix' => '</div>',

    // When the form is rebuilt during ajax processing, the $selected variable
    // will now have the new value and so the options will change.
    '#options' => _ajax_example_get_second_dropdown_options($selected),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function ajax_example_dependent_dropdown_callback($form, $form_state) {
  return $form['dropdown_second'];
}

```

The purpose of the code is clear: The second drop-down element is populated of values that depend from the value the user selects from the first drop-down, using the following function.

```
function _ajax_example_get_second_dropdown_options($key = '') {
  $options = array(
    t('String') => drupal_map_assoc(array(
      t('Violin'),
      t('Viola'),
      t('Cello'),
      t('Double Bass'),
    )),
    t('Woodwind') => drupal_map_assoc(array(
      t('Flute'),
      t('Clarinet'),
      t('Oboe'),
      t('Bassoon'),
    )),
    t('Brass') => drupal_map_assoc(array(
      t('Trumpet'),
      t('Trombone'),
      t('French Horn'),
      t('Euphonium'),
    )),
    t('Percussion') => drupal_map_assoc(array(
      t('Bass Drum'),
      t('Timpani'),
      t('Snare Drum'),
      t('Tambourine'),
    )),
  );
  if (isset($options[$key])) {
    return $options[$key];
  }
  else {
    return array();
  }
}

```

The main difference with your code is that the AJAX callback just returns the form element that is dynamically changed; it's the form builder that changes the drop-down options. The most common error is changing a form element in the AJAX callback, which is not what Drupal expects it to do.

A note about using #states: For more simple cases, like hidding one or more elements basing on the value of another element, that is the perfect use case. In your case, supposing that the first drop-down element has N different values, using #states would mean having N+1 drop-downs, with just two being visible.
Considering also that each drop-down should have a different element id, the submission handler would be a little complicated to write. Differently, the submission handler for the example I show would just check `$form_state['values']['dropdown_first']` and `$form_state['values']['dropdown_second']`. With the example given by leymannx, you should check the value of `$form_state['values']['main']` to understand which of the other drop-down elements would contain the selected value.

---
Tags: forms
---


# Question
Title: Terms not showing in programmatically added vocabulary
I've added a vocabulary(accommodation\_type) in my accommodation module and referenced it to a field that I created in a (accommodation)content type I also created programmatically.

The Content type, the vocabulary AND the referencing field are all created. But when I create a term in the newly found Vocabulary it's not showing up in the dropdown field when I try to add content.

The weird part is: If I manually add a field to the Accommodation content-type. Or switch the Vocabulary of the existing referencing field to a different vocabulary and switch back to the accommodation\_type vocabulary it works....

Howcome the terms I've added to my newly found Vocabulary are not showing up in the dropdown field of my content type?

Here's my complete module:

```
<?php
/**
 * Implements hook_install().
 */
function accommodation_install() {
    node_types_rebuild();
    $types = node_type_get_types();
    variable_set('comment_accommodation', '0');
    node_add_body_field($types['accommodation']);

    accommodation_add_vocabularies();
    accommodation_add_custom_fields();

    drupal_flush_all_caches();
}

function accommodation_add_vocabularies () {
    foreach(_accommodation_get_vocabularies() as $voc) {
        $vocabulary = (object) $voc;
        taxonomy_vocabulary_save($vocabulary);

        // Store the vid so we can delete the vocabulary later.
        // Storing the vid is also useful for when we want to programmatically insert terms.
        variable_set($vocabulary->machine_name . '_vid', $vocabulary->vid);
    }
}

function accommodation_uninstall() {
    $ournewtype = 'accommodation';
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
    $result = db_query($sql, array(':type' => $ournewtype));
    $nodeids = array();
    foreach ($result as $row) {
        $nodeids[] = $row->nid;
    }
    node_delete_multiple($nodeids);

    accommodation_delete_vocabularies();

    accommodation_delete_custom_fields();
    node_type_delete($ournewtype);
    field_purge_batch(500);
}

function _accommodation_get_vocabularies () {
    $t = get_t();
    return array(
        array(
            'name' => $t('Accommodation type'),
            'machine_name' => 'accommodation_type',
            'description' => t('For example: Villa, chalet etc...'),
            'module' => 'taxonomy',
        ),
    );
}

function _accommodation_installed_fields() {
    $t = get_t();
    return array(
        'accommodation_price' => array(
            'field_name' => 'accommodation_price',
            'label' => $t('Price of the accommodation'),
            'type' => 'text'
        ),

        'accommodation_type' => array(
            'field_name' => 'accommodation_type',
            'label' => $t('Accommodation type'),
            'type' => 'taxonomy_term_reference',
            'instance_settings' => array(
                'allowed_values' => array(
                    array(
                        'vocabulary' => 'accommodation_type'
                    ),
                ),
            )
        ),
    );
}

function _accommodation_installed_instances() {
    $t = get_t();
    return array(
        'accommodation_price' => array(
            'field_name' => 'accommodation_price',
            'type' => 'text',
            'label' => $t('Price of the accommodation'),
            'widget' => array(
                'type' => 'text_textfield'
            ),
            'display' => array(
                'example_node_list' => array(
                    'label' => $t('Price of the accommodation'),
                    'type' => 'text'
                )
            )
        ),
        'accommodation_type' => array(
            'field_name' => 'accommodation_type',
            'entity_type' => 'node',
            'label' => $t('Accommodation type'),
            'bundle' => 'accommodation',
            'required' => true,
            'widget' => array(
                'type' => 'options_select'
            )
        )
    );
}

function accommodation_add_custom_fields() {
    foreach (_accommodation_installed_fields() as $field) {
        field_create_field($field);
    }
    foreach (_accommodation_installed_instances() as $fieldinstance) {
        $fieldinstance['entity_type'] = 'node';
        $fieldinstance['bundle'] = 'accommodation';

        field_create_instance($fieldinstance);
    }
}

```

# Answer
You're missing the index settings. Try adding these as your term reference and re-install.

Install:

```
    'accommodation_type' => array(
        'field_name' => 'accommodation_type',
        'label' => $t('Accommodation type'),
        'type' => 'taxonomy_term_reference',
        'active' => 1,
        'cardinality' => 1,
        'deleted' => 0,
        'entity_types' => array(),
        'indexes' => array(
          'tid' => array(
            0 => 'tid',
          ),
        ),
        'locked' => 0,
        'module' => 'taxonomy',
        'settings' => array(
          'allowed_values' => array(
            0 => array(
              'vocabulary' => 'accommodation_type',
              'parent' => 0,
              'depth' => '',
            ),
          ),
        ),
        'translatable' => 0,
        'type' => 'taxonomy_term_reference',
    ),

```

Instance:

```
    'accommodation_type' => array(
        'field_name' => 'accommodation_type',
        'entity_type' => 'node',
        'label' => $t('Accommodation type'),
        'bundle' => 'accommodation',
        'required' => true,
        'settings' => array(
          'user_register_form' => FALSE,
        ),
        'widget' => array(
          'active' => 1,
          'module' => 'options',
          'type' => 'options_select',
        ),
        'display' => array(
            'default' => array(
                'label' => 'above',
                'module' => 'taxonomy',
                'settings' => array(
                  'empty_fields_emptyfieldtext_empty_text' => '',
                  'empty_fields_handler' => '',
                ),
                'type' => 'taxonomy_term_reference_link',
                'weight' => 1,
            ),
        ),
    ),

```

When creating taxonomy, Drupal needs the terms to be indexed for referencing. Take a look in your database's taxonomy\_index table for your tids. If they are missing, that's probably the root of the issue.

Personally, I prefer Entity References in lieu of Term References. They are essentially the same, but the field settings might be a little different. That said, the example I shared might not be the exact solution, but I'm sure that's your issue. If you are still having trouble with it, set up your content type so it works as intended and then export it using the Features module. The field include will show you what you are missing.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to load sliders on subsequent pages in GD Infinite Scroll?
Here is my Testcase. If you scroll down, the feed will automatically extend: It is an infinite scroll-feed. However, the slider images of subsequent pages are not being loaded. As soon as the page is being refreshed, all visible sliders are loaded.

In the scenario I use the following two Drupal modules:

1. GD Infinite Scroll
2. Zurb Orbit

How can I get sliders of subsequent pages to work properly? (Additionally: If the last page is being scrolled down, the infinite scroll would literally keep scrolling this very page infinitely. Is there a way to prevent it and just stop upon hitting the last post of the last page?)

# Answer
user *gooddesignusa* kindly showed me a solution:

scripts.js in the theme folder has to be like this (can also be created if no scripts.js is there):

```
(function ($, Drupal) {

  Drupal.behaviors.STARTER = {
    attach: function(context, settings) {
      // Get your Yeti started.
    }
  };

  //runs on document ready.
    $(function(){
    //checks for autopager function and checks if ID of view is on page
    if($.autopager && $('#gelaendespiele').length){
      //binds ajaxSuccess
      $(document).bind('ajaxSuccess.autopager',function(event, xhr, settings){
        //rerun function after ajax is done loading
        $(this).foundation('reflow');
      });
    }
  });

})(jQuery, Drupal);

```

Then I had to uncomment line 72 of my info file (make sure scripts.js is included)

Finally clear all caches.
> 1 votes

# Answer
The reason for this behavior is simple. Module uses ready-made JS libraries. It places them in the footer to make sure they will fire after elements meant to be affected are ready. But when other module dynamically adds elements, libraries are not fired again. This is a common problem with AJAX-loaded content and Drupal does have a solution for it.

The solution would be to wrap them in behaviors, as described in Managing JavaScript in Drupal 7. Not using behaviors actually can (and in my opinion should) be considered a bug against module compatibility. Sadly, doing it is too laborious task for Q&A format.
> 0 votes

---
Tags: feeds, javascript, views
---


# Question
Title: Is it possible to abort sending of the e-mail somewhere in the middle of sending procedure?
Mail sending is initiated in the depths of some third party module. There's a case when I need to intervenue and depending on some environment variables either let it through, or prevent it. How do I do that?

I've seen in the wild a weird technique of setting `$message['to']` to `+` (what's logic behind this by the way?). But this generates an error in server logs.

Any ideas?

# Answer
> 2 votes
As reported in the documentation for `hook_mail_alter()`, you can avoid a message is sent by setting `$message['send']` to `FALSE`.

> ### Parameters
>
> * `$message`: An array containing the message data. Keys in this array include:
>
> + 'id': The `drupal_mail()` id of the message. Look at module source code or `drupal_mail()` for possible id values.
>     + 'to': The address or addresses the message will be sent to. The formatting of this string will be validated with the PHP e-mail validation filter.
>     + 'from': The address the message will be marked as being from, which is either a custom address or the site-wide default email address.
>     + 'subject': Subject of the email to be sent. This must not contain any newline characters, or the email may not be sent properly.
>     + 'body': An array of strings containing the message text. The message body is created by concatenating the individual array strings into a single text string using "\n\n" as a separator.
>     + 'headers': Associative array containing mail headers, such as From, Sender, MIME-Version, Content-Type, etc.
>     + 'params': An array of optional parameters supplied by the caller of `drupal_mail()` that is used to build the message before `hook_mail_alter()` is invoked.
>     + 'language': The language object used to build the message before `hook_mail_alter()` is invoked.
>     + 'send': **Set to `FALSE` to abort sending this email message**.

At least, your code should check the value of `$message['id']` which is a concatenation of the short name of the module and the key assigned to the message from the module.

```
function mymodule_mail_alter(&$message) {
  if ($message['id'] == 'modulename_messagekey') {

    // Verify other conditions are true.

    $message['send'] = FALSE;
  }
}

```

# Answer
> 0 votes
This should do what you need:

```
function hook_mail_alter(&$message){

    // Some logic here to test if you want to abort the mail
    $message['send'] = false;
}

```

---
Tags: hooks, emails
---


# Question
Title: Comment permission by role and content type
I have different roles (e.g. A, B, C) and I have different contents in a menu (e.g. A, B, C).

I want that only the user A can post/edit comments on content A, and not on B and C.

So I don't know what module can help me with that.

# Answer
What you looking for is Comment Permission module.
**Some description of this module**

> The Comment Permissions module enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.
> 1 votes

# Answer
It sounds like Content Access will be flexible enough to do what you want.

> 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.

It has a per-node setting so you allow role-level access to each piece of content you want to restrict.
> 0 votes

---
Tags: 7, users, comments
---


title: How to get field Type from View

text:
# Question
Title: How to get field Type from View
I have a view that takes fields and combines them or compares them and then gives me results in a new field (views conditional, global text etc..) but I need the TYPE of data that is returned. How can I figure this out? I do not have Drush on my current setup or we'd be good to go... I looked in the DOM and see nothing special about the field for example...

# Answer
> 0 votes
Use Php views and in it use gettype, I think you can acheive it by `Php views` ( also you can achieve it with hook\_views\_pre\_render) and return data tye with `gettype`.

> gettype — Get the type of a variable Description
>
> string gettype (mixed $var )
>
> Returns the type of the PHP variable var.

# Answer
> 0 votes
You can install devel and use `<?php dsm($fields) ?>` inside views-view-fields.tpl.php which you need to place inside the templates folder of your theme.

This will give the results similar to var\_dump but in a much readable and organized format.

---
Tags: 7, entities
---


# Question
Title: How to add the Organic Group list in the user profile
Is there a way to add the Organic Group list in the user profile

The OG List appear in the Registration Form but not in the user profile

Not appear in this path /user/\[uid\]

# Answer
This question is slightly vague, however, I am going to answer in the two methods that I take away from it.

1. You want a list of all OG groups on a user page: Create a View for all of the different content you have related to groups (i.e. you have a content type called "Groups" that is an Organic Group).
2. You want a list of all OG groups that a user is a member of: Create a View (with a contextual link and/or relationship) between the UID in the current URL and get their appropriate group memberships.

You can create either of these Views as a block and place that on the /user page.
> 0 votes

---
Tags: organic-groups
---


# Question
Title: hook_file_dowload() randomly thinks user is anonymous
I have a custom module implementing hook\_file\_download() for both public and privately managed files. At the head of my hook implementation I have the typical declarations to access the $user global:

```
function contractor_file_download( $uri ) {
  $caller = 'contractor_file_download';
  global $user;

  devlog( $caller.': uri is "'.$uri.'", user is "'.$user->uid.'"' );
  devlog( $caller.': globals user is "'.print_r( $GLOBALS['user'], 1 ).'"' );
  ...
}

```

The problem I'm having is that $user contains the anonymous user *sometimes*, if that makes any sense. Although it makes no sense, when testing via an OSX machine, any browser, the $user is always the valid logged in user. But when testing via any flavor of Windows, about 70% of the time both $user and $GLOBALS\['user'\] both contain the anonymous user. Yet, in all instances, the "My Account" link can be clicked and the correct logged in user profile loads.

What could cause $user to contain the anonymous user even after the user has logged in?

Additional info: the files being accessed getting the anonymous user are all private managed files.

# Answer
> 1 votes
Solution is insuring all site urls use the same subdomain, either including the www before the domain or not including the www before the site domain. Plus within .htaccess forcing all user urls to reference the site via that same subdomain qualifier.

The problem was inconsistent use of www and nothing as the site's subdomain.

---
Tags: hooks, users, files
---


# Question
Title: Feeds import by http always imports even after deleting the source
I'm using Feeds to import an xml file. I'm using cron to do this every minute. I noticed that if I delete the source file, the import still succeds! It seems Feeds caches the data somewhere and there is no setting to disable this as far as I know.

This would not be a problem because I don't allow to have duplicate content but I need to have a different file with the same name to get different data but Feeds, recognizing a file with the same name, ignores it and imports the cached data.

Does anyone knows a good solution to prevent this from happening?

Thanks.

EDIT: I can't find any temp file in the system but in the db there is a '`cache_feeds_http`' table that has in fact the data from the file. I tried truncate the table and delete the source file but the behaviour is still the same. What's going on here?!?! Where is the data being pulled?

# Answer
> 0 votes
I solved my problem changing FeedsHTTPFetcher to FeedsFileFetcher in my module and changing the importers to file also. In this case, each import gets the file even if there's already one with the same name.

---
Tags: caching, feeds
---


# Question
Title: A view that displays content with taxonomy term of current user?
**The Setup:**

A Taxonomy Vocabulary called "School" - During registration, users can choose multiple "Schools" from the taxonomy list to associate themselves with.

A content type called "Lesson" - Each lesson can choose a school from the taxonomy list to associate itself with.

**The Challenge:**

I would like to construct a view where the logged in user sees a list of lessons from schools they have associated themselves with.

I'm struggling to understand the relationships and (presumably) the contextual filters that I'll need to have in place to make this happen. Help!

# Answer
> 9 votes
You have the right idea!

You'll start with a View of "**Lesson**" content.

You'll then add a Relationship from the "**Lesson**" to the "**School**" taxonomy term, using the taxonomy term reference field configured on the "Lesson" content type.

Next, you'll add another Relationship from the "**School**" taxonomy term to the **User** entity type, using the taxonomy term reference field on the User entity. This is a reverse relationship; in the Views interface, it will be labeled something like "Taxonomy term: User using \[name of reference field\]". (My suspicion is that this is the part you're missing.)

Finally, you'll add a Contextual Filter "**User: Uid**", configured to provide a default value of type "User ID from logged in user". There will be a configuration option here to select the Relationship to use for this contextual filter, but at this point it should already be selecting the only User Relationship that is currently configured.

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


# Question
Title: How to get alternative text on image hover
How to display image's alternative text when an user `hovers` on that image.

I have come across few posts that displays `popups` and `views`, but not the `alternative text` of the corresponding images. Some of the modules like qTip and Beautytips looks relevant but I suppose those modules doesn't deliver my requirements. If I'm wrong, please let me know how to use those modules to get the `alternative text` displayed on `hover`.

Are there any suggestions regarding how to get alternative text on image hover (possibly without views)

Here, I've created a basic page and in the body I've added an image using advanced text editor.

# Answer
> 0 votes
There might be different ways to address this issue, but based on my problem statement and requirements I found this solution is quite easy.

I'm injecting `jQuery` code and modifying the `CSS` to get the `hover` effect. My idea is firstly to insert `hover text` as a span through jQuery injection. Secondly, modify the `CSS` in such a way that the text span appears only on hover.

Refer JS FIDDLE for the example code.

I've used JSInjector module for injecting jQuery code and modified `reset.css` file

# Answer
> 1 votes
In the field settings for the image, make sure to 'Enable Title field' - this will present a text input for each content under the upload button. You can include the title here, and it will show on mouse over.

# Answer
> 0 votes
I think what you are trying to do is in conflict with accessibility best practices. My understanding is that the alt attribute is only meant to be used for contexts where the image does not appear, and is not meant to be used as a compliment to the display of the image itself (as a tooltip or a description). In other words, I think the display of the alt text and the image are intended to be mutually exclusive.

Of course that does not mean that it's technically not possible to use the alt text as a tooltip (some ideas around that are discussed in this post), it's just discouraged.

Perhaps it would be best to refactor your content so that your hover text (that's intended to be used as a tooltip) is moved to the title attribute. This way you will be in-step with accessibility best practices and will automatically get native tooltip support from browsers.

I suppose that does not *directly* address your question, but it seems like the right note to start with.

---
Tags: media
---


# Question
Title: Problem with overlay in custom webform extension (D7)
I'm doing my first drupal module (webform extension) and I have a problem with the overlay when editing a webform.

I added the "Factors" tab in my *hook\_menu()*:

```
$items['node/%webform_menu/webform-factors'] = array(
    'title' => 'Factors',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('forms_grade_factors_create_factor'),
    'access callback' => 'user_access',
    'access arguments' => array('access administration pages'),
    'weight' => 5,
    'type' => MENU_LOCAL_TASK,
  );

```

But when I click on this Factor tab, the overlay **disappears**:

I don't know if it's important, but when I click on the other webform tabs, their urls are something like this:

drupal.dev/node/12#overlay=node/12/grant

And my module:

drupal.dev/node/12/webform-factors#overlay-context=node/12

How can I keep the overlay layer? Thanks a lot!

**EDIT:**

I also implemented *hook\_admin\_paths*:

```
function webform_factors_admin_paths() {
  return array(
    'node/*/webform-factors' => TRUE,
    'node/*/webform-factors/*' => TRUE,
  );
}

```

# Answer
The overlay automatically applies to paths that Drupal recognizes as being 'administrative'. That's always the case for paths that start with "admin", for example.

For custom node tabs, however, you'll need to implement hook\_admin\_paths() to register your custom path pattern:

```
<?php
function hook_admin_paths() {
  $paths = array(
    'node/*/webform-factors' => TRUE,
  );
  return $paths;
}
?>

```
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How to create a drop down menu for monthly archives?
I'd like to be able to display a block on the right sidebar with a drop-down menu for the monthly archives ("blog post" content type). Exactly as shown in the following screenshot taken from http://curbed.com/

Can anybody please advise me on how to do this with Drupal 7? Thanks!

# Answer
> -2 votes
with views and date modules' and an exposed form (in advanced) you'll be able to do something like that.

# Answer
> 2 votes
I have create a new content type name with blog which have default fields(node title and body) Steps are given below.

**First create a view(jump menu) for monthly archive.**

Select post date of node one for drop-down text and second for link. All settings are given in screenshot.

Settings for jump menu

Settings for post date(first)

Settings for post date(Second)

---

**Now add a page where display list of node based on drop-down value selection**

Follow Page settings

Contextual filter settings for year

Contextual filter settings for year

Select a region for your monthly archive block. Here I am adding views export code that will help you better.

---

---

**Views export code**

```
$view = new view();
$view->name = 'monthly_archives';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Monthly Archives';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Monthly Archives';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'jump_menu';
$handler->display->display_options['style_options']['hide'] = TRUE;
$handler->display->display_options['style_options']['path'] = 'created_1';
$handler->display->display_options['style_options']['choose'] = 'Select Month';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'blog' => 'blog',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'jump_menu';
$handler->display->display_options['style_options']['hide'] = TRUE;
$handler->display->display_options['style_options']['path'] = 'created_1';
$handler->display->display_options['style_options']['choose'] = 'Select Month';
$handler->display->display_options['style_options']['default_value'] = TRUE;
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = '';
$handler->display->display_options['fields']['created']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['created']['alter']['text'] = '<a href="archive/[created_1]">[created]</a>';
$handler->display->display_options['fields']['created']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created']['date_format'] = 'custom';
$handler->display->display_options['fields']['created']['custom_date_format'] = 'F Y';
/* Field: Content: Post date */
$handler->display->display_options['fields']['created_1']['id'] = 'created_1';
$handler->display->display_options['fields']['created_1']['table'] = 'node';
$handler->display->display_options['fields']['created_1']['field'] = 'created';
$handler->display->display_options['fields']['created_1']['label'] = 'link path';
$handler->display->display_options['fields']['created_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['created_1']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['created_1']['alter']['text'] = 'archive/[created_1]';
$handler->display->display_options['fields']['created_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created_1']['date_format'] = 'custom';
$handler->display->display_options['fields']['created_1']['custom_date_format'] = 'Y/m';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Monthly Archives';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = '';
$handler->display->display_options['fields']['body']['element_label_colon'] = FALSE;
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Content: Created year */
$handler->display->display_options['arguments']['created_year']['id'] = 'created_year';
$handler->display->display_options['arguments']['created_year']['table'] = 'node';
$handler->display->display_options['arguments']['created_year']['field'] = 'created_year';
$handler->display->display_options['arguments']['created_year']['default_action'] = 'default';
$handler->display->display_options['arguments']['created_year']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['created_year']['default_argument_options']['index'] = '1';
$handler->display->display_options['arguments']['created_year']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['created_year']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['created_year']['summary_options']['items_per_page'] = '25';
/* Contextual filter: Content: Created month */
$handler->display->display_options['arguments']['created_month']['id'] = 'created_month';
$handler->display->display_options['arguments']['created_month']['table'] = 'node';
$handler->display->display_options['arguments']['created_month']['field'] = 'created_month';
$handler->display->display_options['arguments']['created_month']['default_action'] = 'default';
$handler->display->display_options['arguments']['created_month']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['created_month']['default_argument_options']['index'] = '0';
$handler->display->display_options['arguments']['created_month']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['created_month']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['created_month']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['path'] = 'archive/%/%';

```

# Answer
> 0 votes
The non-intuitive part of creating a jump menu like this is that there is a setting within the contextual filters "Display a summary" section for format - it's necessary to select "Jump menu" here, rather than in the main view format.

---
Tags: 7, views, blocks
---


# Question
Title: Set author to the node automatically whenever the new user registered and also automatically authenticate the user
I have a Drupal site with content type `people`. In that content type I have a field that contains an email id.

What I want to do is, whenever the new user is registered, I want to compare the user's email with the email field of all the nodes with `people` as the content type. If these 2 fields match, then set the user as the author of that node.

I don't know how to execute this process.

Can anyone give me a solution?

# Answer
Create a custom module and Use below logic hope it will work.

```
function hook_user_insert(&$edit, $account, $category) {
  $email = $account->email;
  $uid = $account->uid;

  $query = db_select('field_email', 'e');
  $query->addField('e', 'entity_id');
  $query->condition('e.field_email_data', $email, '=');
  $nids = $query->execute();

  foreach($nids as $nid){

    //Update node user
    $node = node_load($nid); // ...where $nid is the node id
    $node->uid    = $uid;
    node_save($node);

   //Add role to user
   $role_name = 'member';
   if ($role = user_role_load_by_name($role_name)) {
     user_multiple_role_edit(array($uid), 'add_role', $role->rid);
   }

  }

}

```
> 2 votes

# Answer
Here is a summary of what you'll need to get it to work using the Rules module:

1. Create a rules component (= **Rule 1**, of type "component") with these parameters:

* node id.
    * user id.
    * eMail id.

Here is what the specs are for this Rules component:

* **Condition**: If the eMail id of the user id (indicated in the parameter `userid id`) matches the eMail id indicated in the parameter `eMail id`.
    * **Action**: Update author id of the node (indicated in the parameter `node id`) to the user id indicated in the parameter `userid id`.
2. Create a rule (= **Rule 2**) containing a *Loop* that should be triggered (= **Event**) after a new user account is created. The goal of this rule is to loop over each of the nodes of content type "*People*". In each iteration of that loop you use an action which is to invoke the Rule Component as detailed in Step 1 (and which passes the required parameters for it). By using a Rules Component, you'll be able to add any "Conditions" you might need inside the "Loop" (in this case: check that the eMail Ids match).

# Bonus features

1. In the Rules component, if needed/appropriate, you might also do things like:

* add additional conditions (e.g. because of changing requirements later on).
    * add additional actions (e.g. grant access to 1 or more roles for this user).
2. You only need site building skills to implement this solution (could be interesting for somebody new to Drupal).

# Video tutorials

If you're not familiar (enough/yet) with using *Loops* in rules, then watch the video about List and loops.

For a video that is fairly similar to what's needed in step 1 and step 2, refer to the 2nd video (= Solution video) about Creating multiple back links. Some more details about how your scenario slightly differs from what is shown in that solution video:

* You are creating an entity reference **to** nodes also, but **from** a user (not a node).
* You need 3 parameters in your Rules component (instead of 2).
> 1 votes

---
Tags: rules, emails
---


# Question
Title: does indexing tables have a bad effect on drupal?
I have one or two views which has a lot of fields to show and all of this fields are in filter criteria as exposed filter. now the problem is acting in low speed.

the solution I am now thinking about is to index some fields which are more in use as filter criteria. But I don't know if it has any bad effect on performance or not. Or does it effect views automatically or I should rebuild all views to see the indexing result.

please let me know more about indexing tables in drupal or if you know any better solution let me know!

# Answer
> 0 votes
The gains far outweigh any drawbacks; I'd add the index.

# Answer
> 0 votes
In drupal 7 and in Drupal 8 now in views you must use entity render + views\_modes instead of field on by one ( in format collum ) for use totaly the system cache. In views already you can configure the cache for accelerate you request time significantly.

---
Tags: views, performance
---


# Question
Title: How can I set a reminder for a specific user to be triggered on a specific date?
How can I set a **reminder for a specific user to be triggered on a specific date** (in a Drupal 7 site)?

Example: I want to remind the user regarding particular event such as hepB vaccination day.

Any suggestions?

# Answer
> 3 votes
# Rules module

Use the Rules module together with `Rules Scheduler` (a sub-module of it), as explained in the 3 steps below. These steps are based on a date field which is added to the user profile, so that for each user you can indicate an appropriate date.

### Step 1: Create a field to store the appointment date

Add a field to the "user" entity with machine name (say) `field_next_appointment`. Allow only 1 date (to store the "next" appointment), but don't make it required.

### Step 2: Create a Rules "Component"

Here is the Rules **Component** to be created (in Rules export format, just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at `admin/config/workflow/rules`):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Friendly reminder about your upcoming event",
          "message" : "This is a reminder about the upcoming event that you have an upcoming event on [user-to-notify:field_next_appointment] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Obviously, the ***Subject*** and ***Content*** of the eMail may need review / tuning, while you might also want to use some other ***From*** eMail ID.

### Step 3: Create a "Rule" using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at `admin/config/workflow/rules`):

```
{ "rules_on_new_user_event_registration" : {
    "LABEL" : "On new user event registration",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_appointment" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_email_notification",
          "task" : "[account:name]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-appointment",
            "date_offset" : { "value" : 259200 }
          },
          "identifier" : "[account:name]",
          "param_user_to_notify" : [ "account" ]
        }
      }
    ]
  }
}

```

Note that the above rule refers to the *Rules Component* from the previous step.

Also note the machine name of `field_next_appointment` in this rule, which is the field's machine name created in Step 1 (if in step 1 you used another machine name, then also replace the machine name `field_next_appointment` in this rule with the machine name of the field created in Step 1 (if you don't have such field yet, or the field names don't match, then the import of the above rule might not work).

The `schedule_delete` that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).

### Step 4: Further tuning and enhancements

* The ***date\_offset*** (=259200) in the above rule corresponds to "3 days in advance", which may need review / tuning.
* If needed, you could also use the Field Permissions module to set field-level permissions to edit, view and create fields on any entity.
* Instead of just sending an eMail (as in the Rules Component), you could replace that by a more advanced option using the Message module (which has great integrations with the Rules module also). Here is an quote about that module (from its project page):

> ... enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

**Note**: Using Rules to send an email X days after a user registers also contains quite some details that may help you.

# Date Reminder module

There is also the Date Reminder module. Here is a quote about this module (from its project page, bold markup added here):

> ... allows a registered **user to request an email** reminder to be sent at a specified time before an event. Generally these would be calendar events, but any **node** type that has a CCK datetime can support reminders.

However I think that module is **not** going to answer your question, because:

* it's the ***user*** who has to ***request*** such reminder (in your question ***you*** want to ***set*** a reminder to a specific user).
* these reminders are related to some ***node***, while your question is related to a ***user***. You might possibly work around this by creating some extra node type (like "Appointment"?), though that seems like overhead.

# Answer
> 2 votes
Using the Date Reminder module will be helpful for you. Some details about it (from its project page):

> * When reminders are enabled for a node, registered users (with the appropriate privilege) can request reminders to be sent before each occurrence of the date/time. The user specifies how long before the date/time to send the reminder.
> * When reminders are enabled for a node type, anyone who can edit the node can enable or disable reminders for that node.
> * Reminders are sent using the Messaging system. The usual reminder method is email, but other messaging transports should work. (Well, not Drupal 7. The Drupal 7 version just uses straight email.)
> * System administrator can control:
>     + Which node types allow reminders, and which date field (if there are several) in a type to use as the basis of reminders.
>     + Which (registered) users can request reminders.
>     + Which users can request reminders to arbitrary email addresses instead of their own.
>     + Which users can see or administer other users' reminders.
>     + Content of reminder messages.
>     + If and how long reminders should be kept after last date occurrence.
>     + The list of allowed lead times for reminders from which users can select.
>
> An effort is under way to move much of the documentation here to the Date Reminder section of the Site Builders Guide. Currently that document is very incomplete, but watch there. Information on this module page will gradually be moving there.

# Answer
> 0 votes
You can create a cron job to execute a specific task at a scheduled time, as explained also in the article Managing Cron Jobs with PHP.

---
Tags: 7, datetime, emails, rules
---


# Question
Title: How do I enable recording option in the BigBlueButton module?
I am using the BigBlueButton module for conference in Drupal 6. I also installed the server.

The demo code (http://demo.bigbluebutton.org/demo/demo10.jsp) is properly executed. I passed `record=true` in my API.

How do I enable recording option in the BigBlueButton module?

# Answer
> 1 votes
My problem is resolved. I have pass `record=true` in setting array of `bbb.module` file. Please see below code

```
function bbb_init_meeting($node = NULL, $params = array()) {
  $welcome     = variable_get('bbb_content_type_welcome_'     . $node->type, '');
  $dialNumber  = variable_get('bbb_content_type_dialNumber_'  . $node->type, '');
  $moderatorPW = variable_get('bbb_content_type_moderatorPW_' . $node->type, '');
  $attendeePW  = variable_get('bbb_content_type_attendeePW_'  . $node->type, '');
  $logoutURL   = variable_get('bbb_content_type_logoutURL_'   . $node->type, '');
  $settings = array(
    'nid'          => $node->nid,
    'name'         => $node->title,
    'meetingID'    => bbb_create_meeting_id($node->nid),
    'attendeePW'   => !empty($attendeePW) ? $attendeePW : user_password(),
    'moderatorPW'  => !empty($moderatorPW) ? $moderatorPW : user_password(),
    'welcome'      => !empty($welcome) ? $welcome : t('Welcome to @title', array('@title' => $node->title)),
    'dialNumber'   => $dialNumber  ? $dialNumber  : NULL,
    // TODO: This is limited to 90000 voice bridges and may
    // collide sooner, as rand() may return x twice in a row
    'voiceBridge'  => rand(10000, 99999),
    'logoutURL'    => $logoutURL, //TODO: make absolute, as soon as supported
    'initialized'  => 0,
    'created'      => time(),
    'record' => 'true',
    'duration' => '10',
  );
  $params = array_merge($params, $settings);
  return $params;
}

```

---
Tags: 6
---


# Question
Title: How to create a new field collection+fields in a programmatically added content type
I'm very new to creating modules and I'm creating a content type for the first time programmatically.

Creating the content type works fine, I've even added some fields. But now I'd like to create a new field in that content type which is a field collection.

I can't find a good spot on the internet that explains how I can add a new field collection to a new content type. All programmatically in one run.

Can anyone help me out how to achieve this?

It involves this contributed module.

# Answer
> 4 votes
I googled \_create field\_collection programmatically\_ and this example was from my first search result.

> Thought I would post my solution for programmatically creating a field collection, along with an attached field, during a module install. The example is specific to my use, but easily modified to add the field types you need. Of course, if there is an easier way please feel free to add your thoughts. This works with the current 7.x-1.x-dev branch.
>
> ```
> /**
>  * Create a Field Collection field and attach collection node reference
>  */
> function _create_field_collection() {
>   $t = get_t();
>
>   $fields_array = array(
>     array(
>       'field' => array(
>         'field_name' => 'bir_collection',
>         'label' => $t('BIR Collection Nodes'),
>         'cardinality' => -1,
>         'type' => 'field_collection',
>       ),
>       'instance' => array(
>         'field_name' => 'bir_collection',
>         'entity_type' => 'node',
>         'bundle' => 'article',
>         'label' => $t('BIR Collection Nodes'),
>         'description' => '',
>         'widget' => array('type' => 'field_collection_embed'),
>         'required' => 1,
>       ),
>     ),
>     array(
>       'field' => array(
>         'field_name' => 'bir_collection_node',
>         'type' => 'node_reference',
>         'label' => '',
>         'cardinality' => 1,
>         'settings' => array(
>           'referenceable_types' => array(
>             'bir_specimen' => 'bir_specimen',
>             'bir_image' => 'bir_image',
>             'bir_locality' => 'bir_locality',
>             'bir_view' => 'bir_view',
>           ),
>         ),
>       ),
>       'instance' => array(
>         'field_name' => 'bir_collection_node',
>         'entity_type' => 'field_collection_item',
>         'bundle' => 'bir_collection',
>         'label' => '',
>         'cardinality' => 1,
>         'description' => '',
>         'widget' => array('type' => 'node_reference_autocomplete'),
>         'display' => array('default' => array('type' => 'node_reference_default')),
>       )
>     ),
>   );
>
>   // Loop through fields array and create field and instance
>   foreach ($fields_array as $field) {
>     // Check if field already exists
>     if (!field_info_field($field['field']['field_name'])) {
>       field_create_field($field['field']);
>     }
>
>     // Check if instance exists
>     if (!field_info_instance($field['instance']['entity_type'], $field['instance']['field_name'], $field['instance']['bundle'])) {
>       field_create_instance($field['instance']);
>     }
>   }
> }
>
> ```

First field in the `$fields_array` array is the `field_collection` type field that you add to your `node` entity. (field\_name: bir\_collection)

The second field in the array is the field which is added to your `field_collection_item` entity (Notice the bundle in the instance is same as your field\_name on node: bir\_collection. This is how the connection is made). In this particular example, it's a `node_reference` type field, but this can be any other field type that's available to your Drupal instance.

The order has to be in this sequence, since you need to add the `field_collection` type field to your node to create the `field_collection_item` entity, then you add the fields to your `field_collection_item` entity.

---
Tags: entities
---


# Question
Title: Are there any hooks for the event when an user navigates the verification URL?
I'm looking for a way to modify an event (from my own module) when an user navigates to the account activation URL that they get in their mails. Are there any such hooks ready for me to use?

Also I would potentially need the `$account-> mail` variable if it's passed as an argument by any chance.

I've used this but it doesn't work as intended -

```
function my_module_form_alter(&$form, &$form_state, $form_id)
{
    // Trigger when at password reset form
    if ($form_id == 'user_pass_reset') {}
}

```

But the problem is I cannot seem to access the `$account` variable that way. What should I do?

# Answer
> 0 votes
Finally figured it out.

```
function my_module_lists_form_alter(&$form, &$form_state, $form_id)
{
    // Trigger when at password reset form
    if ($form_id == 'user_pass_reset')
    {
        // If $account has not been defined, define it from $user
        if (empty($account))
        {
            // Loads the user using the user id argument
            $account = user_load($form_state['build_info']['args'][0]);
        }

        // Log something
        watchdog('DEBUG MESSAGE:', 'We are there, user : ('.$account->mail.')!');
    }
}

```

If anybody has a better method, please do share.

# Answer
> 0 votes
Not sure if you are using the User Verification module. If yes, then you can try the hook they provide

```
hook_user_verify_verified

```

Hope this helps...

---
Tags: 7, hooks, users
---


# Question
Title: How to change Drupal's default "Unable to send e-mail." message?
I wanted to override/change the text message that appears while sending Drupal mail.

This is the text "Unable to send e-mail. Please contact the site administrator if the problem persists."

What are the ways to change this message into my own custom message ?

# Answer
You can use String Overrides modules for overriding any string that passed through t().

Here are some details about this module from its project page:

> Provides a quick and easy way to replace any text on the site.
>
> Features:
>
> * Easily replace anything that's passed through t()
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
> 2 votes

# Answer
Write some custom code in which you use a variation of the approach as explained in Hook into and Preprocess Drupal Messages? Here is a quote from it:

> The following example hides all error/warning messages from anonymous users and user's who don't have the 'administer nodes' permission. You can easily add your own conditions to filter out which message types should be displayed to who.

```
function mytheme_status_messages ($display = NULL) {

  $output = '';
  foreach (drupal_get_messages($display) as $type => $messages) {

    // skip all error/warning messages for anonymous users
    if (!user_is_logged_in() && ($type == "error" || $type == "warning")) { continue; }

    // skip error/warning messages for users who don't have the 'administer nodes' permission
    else if (!user_access('administer nodes') && ($type == "error" || $type == "warning")) { continue; }

    ...

```
> 1 votes

---
Tags: 7, i18n-l10n, emails, status-messages
---


# Question
Title: add js by #attached - hook_page_alter in theme's template.php
I am trying to add js by #attached, as I understand it's better from a caching perspective then drupal\_add\_js(). I try to use `hook_page_alter()` in `template.php`.
I have the following code:

```
function mytheme_page_alter(&$page) {
 $theme_path = drupal_get_path('theme', 'mytheme' );

  if (!isset($page['content']['#attached']))
    {
      $page['content']['#attached'] = array
      (
        'js' => array(),
      );
    }

  $page['content']['#attached']['js'][] = array($theme_path . '/test.js');
}

```

(this is adapted from http://www.jaypan.com/tutorial/including-javascript-or-css-files-every-page-load-module-drupal-7, I first tried to attach \[#attached\] directly to $page by means of `$page['#attached'] = array...` , but as I faced the problem described below I tried to test some code suggested by other people).

The problem is that the elements of the js are not properly set. After the `'js' => array(),` The Aptana Debugger shows what I'd expect :

After `$page['content']['#attached']['js'][] = array($theme_path . '/test.js');` , however, the array values are not set:
Still the value of `array($theme_path . '/test.js')`is what it 'should' be:

It's as if the ascription did not go through.
What did I do wrong?

# Answer
> 1 votes
I think your problem is you're trying to use a `hook` from a `theme` template.php? (Assuming because you have `mytheme_page_alter` as your function name for `hook_page_alter`). If you're not getting the JS included, it's specifically because you can't use hooks in template.php files. You need to create a new module.

---
Tags: javascript, theming
---


# Question
Title: Mixed content issue while running updates.php in Drupal 6.37
We are facing this issue again for Drupal version 6.37. We do not have jquery update module installed.

In our case the progress bar just hangs but the functionality is accomplished.The Drupal core and modules do get updated. When we run the update.php since ours is a https site, we get the Mixed content error

Mixed Content: The page at 'https://example.com/update.php?op=start&id=14' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://example.com/update.php?id=14&op=do'. This request has been blocked; the content must be served over HTTPS.

Any help will be appreciated.

# Answer
> 0 votes
Sorry, but I doubt this can be debugged from here. You need to:

1. inspect which elements, exactly, was served over HTTP instead of https.
2. Then, identify what created them (we may or may not be able to help)
3. Fix the reason - most common I know is hardcoding URLs in templates, but it might not be the case for you.

Last but not least, I find it to be much stable to use drush for updates.

---
Tags: updating, security
---


# Question
Title: How to change a node's term reference value, dependant on date
I have a content type "Page" and one of its fields is a term reference to the taxonomy term "Page Type"

Another field is "Expiry Date"

The page type starts off as "Open Consultation", but I need it to automatically change the term reference to "Closed Consultation" if the "Expiry Date" has passed.

I've been a developer for years, but I'm still quite new to Drupal (7)... I know the GUI, but not php or which files to override (if that is the answer)

So, I need a basic explanation of how to achieve this. Thanks !

# Answer
Take a look at the Computed Field Module, I'm not sure if can handle the date field type or not. on the other hand if Computed Field didn't do what you want you could do a hook\_form\_alter hook in your custom module. and code your logic there.
> 0 votes

---
Tags: nodes, taxonomy-terms
---


title: ajax form submit multiple times

text:
# Question
Title: ajax form submit multiple times
I have a form which consists of one submit button (Add to cart). I made it submit via AJAX but the problem is that when I press the button the second or third (and so on) times, the submit handler doesn't execute. I think this happens because the **form\_build\_id** and **form\_token** fields should be rebuilt.

Do you have any idea on how I can achieve this functionality?

This is the code I am using.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['submit']['#ajax'] = array(
      'callback' => 'mymodule_ajax_form_callback',
      'wrapper' => 'my_form_wrapper',
    );

    $form['#prefix'] = '<div id="my_form_wrapper">';
    $form['#suffix'] = '</div>';
  }
}

function mymodule_ajax_form_callback($form, &$form_state){
  return $form;
}

```

# Answer
> 2 votes
As reported on drupalcommerce.org, the trick is to clear the form and form state caches in your AJAX callback.

The following is a working code example taken from that post:

```
function ajax_cart_form_alter(&$form, &$form_state, $form_id) {
  // Add ajax property to Add to Cart button
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['submit'] = array(
      '#value' => t('Add to Cart'),
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => 'ajax_cart_form',
        'wrapper' => 'block-commerce-cart-cart',
        'effect' => 'fade',
        'progress' => array('type' => 'throbber', 'message' => ''),
      ),
    );
  }
}

function ajax_cart_form($form, &$form_state){
  global $user;
  $order_id = commerce_cart_order_id($user->uid);
  $cart =  commerce_embed_view('commerce_cart_block', 'default', array($order_id));
  $commands = array();

  // The next line allows different quantities
  // to be submitted each time
  unset($form['quantity']['#value']);

  // Clear form and form state cache
  $form_state = form_state_defaults();
  $form_build_id = $_POST['form_build_id'];
  form_set_cache($form_build_id, $form, $form_state);

  $commands[] = ajax_command_replace('#block-commerce-cart-cart .view-commerce-cart-block', $cart);
  $commands[] = ajax_command_replace('#block-commerce-cart-cart .cart-empty-block', $cart);
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> 0 votes
First of all, a clean form will work correctly. So, the problem is with altering your form.
Try to play with params `#ajax_processed`, `#processed`, `#executes_submit_callback`.
This code can be helpful in some cases:

```
// Make AJAX to work
unset($form['submit']['#ajax_processed']);

```

## Commerce cart

As I see tag on your question, I have tested your AJAX on standard commerce cart form:

```
/**
 * Implements hook_form_FORM_BASE_ID_alter().
 */
function mymodule_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $form['submit']['#ajax'] = array(
    'callback' => 'mymodule_ajax_form_callback',
    'wrapper' => 'my_form_wrapper',
  );

  $form['#prefix'] = '<div id="my_form_wrapper">';
  $form['#suffix'] = '</div>';
  $form['#submit'][] = 'mymodule_form_commerce_cart_add_to_cart_form_submit';
}

function mymodule_ajax_form_callback($form, &$form_state) {
  return $form;
}

function mymodule_form_commerce_cart_add_to_cart_form_submit(&$form, &$form_state) {
  // Ask to rebuild form
  $form_state['rebuild'] = TRUE;
}

```

AJAX callback is working correctly in this case, but submission of the form are processed only once. So we can rebuild a form to work with the same form again.
Note that standard message “Product added to your cart.” is shown by default Commerce Rules configuration on event “After adding a product to the cart”.

# Answer
> 0 votes
The following command replaces the form with a fresh one on every ajax submit and it works great for us:

```
function mymodule_commerce_ajax_cart_callback($form, &$form_state){
  $form = drupal_rebuild_form($form['#form_id'], $form_state, $form);
  ...
  $commands[] = ajax_command_replace('.' . drupal_html_class($form['#form_id']), drupal_render($form));
  ...
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> -1 votes
I would suggest using AHAH. It resubmits the entire form when adding the new element so you don't run into the problem you describe above.

# Answer
> -1 votes
Instead of using AJAX on the form I would instead add a Quantity field into the Add to cart form so that the user can both add multiple items and also keep track of how many they add. I believe e-cmmerce solutions may prevent you from clicking the Add to cart multiple times to prevent people accidentally adding more than one product as money is involved, though not sure if this is your problem.

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


title: Convert node data to pdf via Rules

text:
# Question
Title: Convert node data to pdf via Rules
I have a project plan content type. I would like to be able to change the "start date" field value to the current date, and set the "deadline date" field value to 2 weeks after. Then I would like to convert this data into a file (eg. pdf) which I can then attach to another entity.

The majority of this can be achieved using the Set Data Value action in Rules module; except of course for converting the data into a file. The module FillPDF comes quite close although it only allows for converting Webform data to pdf and not node data.

The following modules are able to convert nodes to pdf, however they do not have Rules integration: PDF using mPDF, Printer, email, PDF versions

What is the best way to achieve this?

# Answer
It appears that this module is the answer: PDF Archive

The only issue with this module is that it only converts the text of the node. Any images are not outputted to the pdf.

**PDF Archive:**

> The PDF Archive module provides the ability to generate PDF archives of any entity triggered by Rules actions. Both the entity view mode and role of the simulated user used for rendering the entity can be set per rule. An example feature is included to demonstrate the configuration of this module.
> 0 votes

# Answer
rules download module will definitely working with your requirement. This was previously discussed on drupal issue.

**Rules Download:**

Exposes some Rules actions to download files from the internet using HTTP and use them within rules.

This module exposes the following actions:

* Download a file from the internet.

There's a possibility, if you fetches an URL from the site that triggered the rule, that, depending on your configuration, it triggers the same rule again. To prevent that, each file that is downloaded is appended with a special URL parameter (drupal\_rules\_download=1) that prevent the action to be run again.

Downloaded files are stored within the Drupal files system, so they can then be used to set file fields on entities and other drupal actions in which a file field item is expected. For adding it to a single File field use "Set a data value" and for a multiple File field use "Add an item to a list".

This module started of as an attempt to create PDF with the print module and use it in Rules, but because of how Print module works, it was safer to do it as a separate request and then, the module involved into something more general and flexible.
> 0 votes

---
Tags: nodes, rules, files
---


# Question
Title: Internationalization and pay.nl does not seem to work properly together, any idea how to fix that one?
I am working on a website with four languages.

We use `Ubercart` with external payment facilities. We have `Paypal` and the following specific to Netherlands: `eBanking`, `iDEAL`, `MisterCash`. That works fine.

Now we are trying to get `pay.nl` to work. This one offers more methods of payments.

The request uses `/nl/` as expected with a path that looks like this:

```
http://www.example.com/nl/order/paynl/notify/?...snip...

```

But the i18n module seems to change that to `/en/` instead:

```
http://www.example.com/en/order/paynl/notify/?...snip...

```

And that prevents the payment from being accepted.

Any idea what could be happening? Would there be a way to prevent translations from happening when hitting `/order`?

# Answer
> 1 votes
Your problem might be because of the "Language negotiation" configuration.

So check this configuration, which in D6 you can find via `/admin/settings/language/configure/language`. Experiment with the 4 available options in the Language negotiation selection list, to see if any of these options solve your issue.

---
Tags: 6, ubercart, redirection, i18n-l10n
---


# Question
Title: How to create links which pass arguments to a page?
I am making a website which displays table from a database. For every row of the table I want to provide a link(or button) which will be placed in the last column and will redirect to a page displaying records from another table associated with that row. Is there a way to create such link which would pass an argument (row id) to another page so it could display apropriate records? Thanks

# Answer
> 3 votes
You can use l() function, Like

Suppose You are showing some data in table format as you mention in your question and using some query you get some data from databse in $result variable,

> $header = array(t('Approved By'), t('Role'), t('Points'), t('View More'));
>
> foreach ($result as $row) {
>
> $rows\[\] = array($row\['user\_name'\], $row\['user\_role'\], $row\['date'\], l(t('View'), 'node/' . $row\['row\_id'\]));
>
> }
>
> return theme('table', array('header' =\> $header, 'rows' =\> $rows));

Now above code create a page showing table

```
**Approved By**    **Role**                    **Points**    **View More**
Eve            content writer          94        View    -> url: my-page/1

John           content manager         80        View    -> url: my-page/2

Adam           manager                 67        View    -> url: my-page/3

Jill           admin                   50        View    -> url: my-page/4

```

> function my\_module\_menu() {
> $item\['my-page/%'\] = array(
> 'title' =\> 'my page',
> 'page\_callback' =\> array()
> 'page callback' =\> 'my\_page\_callback',
> 'page arguments' =\> array(1),
> 'access arguments' =\> array('access content overview')
> );
>
> return $item; }
>
> function my\_page\_callback($row\_id) {
> // Get some data from database using $row\_id
> // show in table
> }

---
Tags: navigation
---


# Question
Title: Image preview not generated on node edit page
My content type has field type "Image" and using "Media selector" to upload images.

Images are uploaded properly but not previewed at the same time on node add/edit page. I can check that preview is generated with firebug.

If I go to library then again preview not displayed but after saving node it is displaying.

What could be the issue?

# Answer
> 0 votes
There should not be any blank line before opening or after closing php tags. The chances of having it with index.php, template.php,settings.php etc. files

---
Tags: media
---


# Question
Title: Translation showing up in backend but not on display or user registration
I translated some fields, everything looks fine in the back end. String are successfully translated to French.

However they don't show up for user registration/profile modification, they don't show up on exposed filters or views.

Everything looks fine and translated, but not working...must be a setting? I have tried the language detection, views setting for user language, refreshed strings, updated, cleared cache...

# Answer
do you also use the i18n module ?

**tmgmt is not enough !!** this module is meant to help the translators and to use external translations servives.

probably you need to enable more translation modules from i18n like field translations, entity translation (seperate module) etc.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How to create a page with all the nodes of a specific user?
My users' profile pages contain a View with their 4 latest nodes. I would now like to add a "more" link underneath that View that redirects visitors to a page with all the nodes of that user.

I can easily create a View with all nodes of a specific user, but I don't know how to generalize this and create a page for every user. Am I making things too complicated? Maybe this is a triviality, but I can't find a solution on the internet...

# Answer
Nope, that's totally fine. What you are looking for is the power of Views' built-in contextual filters. With that you can pass arguments from an URL to a view.

> The classic example of how contextual filter values are provided to views is by the view path. If a view has the path example.com/my-view, the URL example.com/my-view/story/22 will call the view along with two values for contextual filters (in this case story and 22). But there are more ways of providing contextual filter values.

Just a rough outline so you can get the idea:

1. Build a Views page with a path that contains a wildcard. Let's say it's `usersnodes/%`
2. Build the "more" link on the user's profile page then to dynamically hold the user's uid. So that would be `usersnodes/123` for example.
3. In the view you created in step one now set the contextual filter (I think it's on the very right in the UI). There you have to possibility to grab an argument (or two, or three ...) from the URL and pass it as a contextual filter to the view to only get the nodes of the user whose uid was in the URL.
> 3 votes

# Answer
Presuming, your existing view is a block display on the user profile page, it sounds like you're looking for the **More link**. Under the **Pager** setting in the Views UI there's an option add a more link below the pager.

If your view has a page display, the more link will link to it. That page display can have it's own display setting separate from other displays (e.g. all nodes instead 4 latest nodes).
> 0 votes

# Answer
Although @leymannx's answer works fine, I've figured out a slightly different solution, since I'm working with Panels and Views pages aren't considered as Panel pages. This is what I came up with:

1. Build a View *All nodes* that displays all nodes of a user. I've done this by adding a new block to my View that showes a user's 4 latest nodes.
2. Make sure the **More link** under the **Pager** setting of the View is set to `yes`. Change the **Link display** under the **Advanced** settings to, say, `allnodes/!1`.

We'll now create a page with this path.

3. Add a new page *All nodes* and provide a placeholder `%user` in the path. For example: `/allnodes/%user`. Our created View and page don't necessarily need the same name; only an identical path is needed.
4. Select your favorite Panel lay-out for the page and add the *All nodes* view to it.
5. When users now click the More link in the View *All nodes*, they will be redirected to the appropriate *All nodes* page.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to display only Duplicate values with a view
**Background**

My site is very large already and its only in its infancy. The content title table has 14000+ values in it. To make sure there are no duplicate values in the table I am creating a view that will display all of the institutions with the same title and the same address. At the current time I am just checking title to keep things simple.

**Problem**

The sizeable amount of data means that to return values is very slow.

**Logic and Code**

I am creating a view with address, type & title in a table with the requirement that the only institutes that come in have the same name.

My thoughts were that on every row I would take the `$row->node_title` and put it into a query against every other value in title like

```
$query= db_query("SELECT node.title
                  FROM node
                  WHERE ((node.status = '1')
                  AND (node.type IN ('institution'))
                  AND (node.title=".$row->node_title."))")->rowCount();

```

This should return a number, if the number is 1 then i want to exclude it with the following statement

```
if($query == 1){
  return true
}

```

**Question**

This is taking so long to calculate I thought there must be a faster way. I'm not even sure if the result from this is returning correctly because I've been waiting so long, Is there a faster way to get a list of all the duplicate values in a table with drupal?

# Answer
> 1 votes
Try using Remove Duplicates

> This module helps the administrator to easily remove duplicate nodes according to one of the node fields.

---
Tags: views, database
---


title: Views escapes HTML tags in node body

text:
# Question
Title: Views escapes HTML tags in node body
I'm creating a view that displays a few fields from a specific content type. Among the fields is the trimmed nody body. The problem is that the HTML tags in the body are escaped and are visible as source in the view.

So instead of

> Lorem ipsum dolor sit amet, in dolores propriae sapientem vim. Per no autem minimum iudicabit, ad numquam eloquentiam ius. Quas iusto ea vis. Mea quaestio gloriatur mediocritatem et. Mei rebum postea ne, his malorum necessitatibus ei. Ea pro animal mandamus, ad pri postea eripuit.

I get the following:

> \<p\>Lorem ipsum dolor sit amet, in dolores propriae sapientem vim. Per no autem minimum iudicabit, ad numquam eloquentiam ius. Quas iusto ea vis. Mea quaestio gloriatur mediocritatem et. Mei rebum postea ne, his malorum necessitatibus ei. Ea pro animal mandamus, ad pri postea eripuit.\</p\>

From what I understand Drupal 8 escapes everything by default, so I suspect this has something to do with my problem. I looked at every setting I could find in Views, but I couldn't find anything that would change the escaping of HTML tags.

How can I output the body of a node unescaped in a Drupal 8 view?

# Answer
> 0 votes
I'd recommend against accepting this right away even if it works for you because I suspect it isn't the best answer, but I ran into this same problem and I ended up just overriding the template with raw HTML like so:

1. Copy core/modules/views/templates/views-view-fields.html.twig to the appropriate location in your own theme (e.g. themes/custom/mytheme/templates/views/views-view-fields.html.twig for me)
2. For each variable output in the loop add the `raw` filter, e.g. `{{ field.content | raw }}`
3. Clear your caches and refresh the page to see the result

I think this should be okay since any HTML that comes from the views fields should already be filtered of anything harmful (and I believe this is more or less how it used to be done - take a look at the old PHP views templates) but if someone knows better please do correct me in the comments.

EDIT: I noticed one of the related questions (Drupal 8: HTML isn't rendering, HTML tags are being printed) has a link to this issue: https://www.drupal.org/node/2363423 which I believe is related, so this workaround may soon no longer be necessary.

---
Tags: views, 8
---


# Question
Title: How do I loop over result rows and return calculated values?
I cannot get proper results from View PHP field.

I've set up a Flipped Table view of entity form submission of which I'm trying to calculate "results" (sum and count(for avg)) with following code

```
$results = array(); // For results
$static = get_object_vars($row);
dsm($static);
foreach($static as $key => $value) {
    if(strpos($key,'field_') !== FALSE){
        if($value !== NULL){
            $results[$static['entityform_id']]['count']++; // Count no. of fields
            $results[$static['entityform_id']]['sum']= $results[$static['entityform_id']]['sum']+$value; // Count sum of field values
        }
    }
}
return json_encode($results[$static['entityform_id']]);

```

which results:

```
{"count":55,"sum":55}   {"count":55,"sum":110}  {"count":55,"sum":165}  {"count":55,"sum":220}

```

At this point I do not understand that why sum is always row index * sum? Eg.1 =55, 2=110, 3=165... All the submissions have the same fields and field values (clones) which explaines sums but I can't figure out that where this multiplication "logic" happens?

It seems like it is looping/counting all four result rows every time.

# Answer
> 0 votes
This is because $results\[$static\['entityform\_id'\]\]\['sum'\] already contains the sum result from previous loop result. Thus it adds 55 for every row iteration. Try adding the current array index to $results inside foreach loop.

---
Tags: views
---


# Question
Title: Change a block programatically, accesing to the Views results
I have a Views block, which prints a list of products, in unformatted text. I would like to wrap each of these items with a custom href string, which is somehow convoluted and so it is difficult to set in the Views options. I have managed to do so, by retrieving the Views results with **hook\_views\_pre\_render** and

```
foreach($view->result ...

```

and then print the results directly to screen. If I use, instead,

**block\_view\_VIEWS\_MY\_VIEW\_BLOCK\_alter** and

```
$data["content"]["#markup"]

```

I have the problem that the data is in raw form and cannot achieve my initial goal. What method should I do for this apparently simple goal? I want the block to be finally printed by Drupal, even if modified with the href added programatically, but the rest of properties (pager, etc.) remaining untouched. Thanks!

# Answer
Reading from some sources and experimenting a little, I have been able to reply to my question. In your template, you must put the views-view-unformatted.tpl.php file (from themes folder), and there you can modify each of the rows based in some logic (though logic should be constrained to template.php y from there populate a variable in this tpl). The output of the view must be unformatted text, and the "auxiliary" data must be added, but hidden from view.

```
<?php

/**
* @file
* Default simple view template to display a list of rows.
*
* @ingroup views_templates
*/
?>
<?php if (!empty($title)): ?>
<h3><?php print $title; ?></h3>
<?php endif; $i = 0;?>
<?php foreach ($rows as $id => $row): ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php

if($view->result[$id]->taxonomy_term_data_description != ""){
 // Here I use a logic to show only the item name surrounded by dots.
  print ".." . $row . "..";
}else{
 // Here I use opposite logic to show the link
     print "<a href='" . $view->result[$id]->taxonomy_term_data_description . "'>" . $row . "</a>";
} // if
$i++;
 ?>

```
> 0 votes

---
Tags: views
---


# Question
Title: How to map fields from content type to user Profile
I am using a content type named `application`

There are some fields I like to map to the users profile to use them with panels.

For example there are fields called:

* name --\>textfield
* nickman--\>textfield
* birthday--\> date
* about--\>text with summery
* etc

Now I would like to map the content of these fields to the same fields used in the users profile to display the information the users had entered in their applications.

How could I do that? Where to start to find more about field mappings?

Thank you guys and gals!

# Answer
> 1 votes
If you want the content of the fields in `application` to be saved in the user entity, I can think of a couple of approaches:

1. Use Rules module to copy the values to the user entity when the `application` content is saved.
2. Write a custom module and use hook\_node\_update() to add the values to the user entity.

---
Tags: entities
---


# Question
Title: Addressfield entries not showing up when entityform sends an email
I have an Entityform that uses the Address Field module. Viewing a submission in the interface is fine. However, when the admin email goes out, only labels are shown; the address fields are empty. Has anyone had this problem?

# Answer
> 0 votes
This was addressed in an issue on Drupal.org. Which version of Entity2Text are you using? The fix was added to 7.x-1.0-alpha2.

---
Tags: emails, entities
---