How to reference taxonomy used by other content type? I have two content types: Content A and Content B

Fields in Content A: Title, Location, Body

Fields in Content B: Title, Type, Location, Body

Location is a vocabulary (Au, Uk, Us, Ca, etc)

Type is an entity reference of Content A inside Content B node.

Content A has a node with information in order:
News X, Ca, This is the body of News X

Content B has a node with information in order:
John Doe, Content A, ????, This is about John Doe

In this question mark, I want to include Location but only that which is selected in that node of Content A.

Location can be multiple, that is, if Content A node has "location": Ca, Uk
then Content B node referenced to Content A will only enlist Ca, Uk out of all other terms in that vocabulary.

I have looked into google, found nothing. Please help.

For simple displaying of taxonomy term

Assuming your are using entityreference for Drupal 7 the module provides out of the box a field formatter that allows you to display the Rendered entity with a specific view mode

Thus you can display the referenced entity with the taxonomy term included.

Go to the manage display of your Content B and change the format to Rendered entity and choose teaser for the view mode

Go to the manage display of your Content A and modify the teaser view mode and add the taxonomy term field to be displayed.

For more advanced use cases

You might want to try any combination of the following

field_extractor to extract a specific field from a referenced entity
inline_entity_display similar to above
field_reference refer to specific field on the same node/entity or other node/entities


php include inside .tpl.php template file I have 2 template files where I want to use a common piece of template code. Is it ok to do an include of the chunk of template code I want to use?

Example model.tpl.php:

include('/path/to/template.php.tpl');
<!-- Other Template Code -->

Its better to modify the shared template inside hook_theme and use Drupal theme engine:

<?php print theme('your_shared_template_file', $args); ?>


How do I override the base URL for private files? Why in Drupal 8 is possible to override the base_url for public files using the file_public_base_url but not for private files?
There are scenenarios where Drupal is installed behind a reverse proxy. The private files point to the hostname where the backend server is, instead of pointing to the frontend server.

Perhaps a workaround is to use the mod_substitute module (http://httpd.apache.org/docs/2.4/mod/mod_substitute.html) but I don't know if it's the best on.

The private files point to the hostname where the backend server is,
  instead of pointing to the frontend server.

Private files are not directly served to the user. Public files are served directly to the user. With a public file, when a file is requested, PHP is never executed, and therefore Drupal is never executed. By virtue of the files being public, they do not require any access checks, and so there is no reason to bootstrap Drupal. Instead, the server (apache, windows etc) serves the files directly to the user. The proxy can then cache that response, since the response for that file will always be the same for everyone.

Private files on the other hand require access checks. By definition, they are meant to have access checks performed upon them before they are served to the user. With private files, the request for a file is made to a php script (index.php - from which every Drupal request begins). This script (which is Drupal) runs access checks on the requested files. If the the access checks are passed, Drupal reads the data from the actual file, then sends a binary file response to the browser (rather than an HTML response, which would be a webpage). This binary file response is the file, which the browser either then renders or offers to the user as a download, depending on the file type and their browser settings.

An analogy to these files systems is to consider public files to be like wanting a cola, and going to the fridge to get it, while private files are like wanting a beer, asking a server for it, who then checks your ID and if you are old enough, gets it from the fridge, and brings it to you.

So private files by their definition cannot be directly accessed, as a script (Drupal) first needs to check whether the user should have access. As such, private files cannot be cached by the proxy, as the proxy has no means of checking access. This is why the base URL cannot be overridden.


How can I do a cascading Entity Reference data entry or is it even possible? I am working on a system where we want users to be able to create a Project which will be made up of one or more Project Activities, each Project Activity being constituted of several Sub-Activities.

Each Project Activity can be one of several types, and the Sub-Activities also are typed. This means that when I assign a Project Activity to a Project, I should only assign Sub-Activities of the same corresponding type.

So, I have two fields in the Project content type, one is Project Activity, the other is Sub-Activity (which can have multiple values). Both these fields are Entity References to the corresponding Project Activity and Sub-Activity content types. What I want then, is when I enter the Project and choose Project Activity type A, I should only be able to select Sub-Activities of type A also.

I had thought to do this using the Views selection with a contextual filter, however this only seems to work with a static filter when mine needs to be dynamic.

Does anyone know a way round this, or a different approach which could solve the problem?

I've not used it yet myself. But, if you want an out of the box solution you can try the Hierarchial Select module:

  This module defines the "hierarchical_select" form element, which is a
  greatly enhanced way for letting the user select items in a hierarchy.

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!

See the project page for a Demo page.

Depending on how complex your criteria is you could also consider the #states Form API of Drupal 7, or a simple jquery Ajax callback on your select tags in the form.


Default value to drupal variable I have a piece of code that I want to have the default value be a variable, but I need to know how to set a default value if the variable is not set:

  $form['background_audio_height'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#default_value' => variable_get('background_audio_upload_path'),
'#size' => 5,
'#maxlength' => 3,
'#required' => TRUE,
);

How can I set a default value if background_audio_upload_path is not set?

You can pass a second variable to the variable_get() function, which is a default value.

example:

variable_get('background_audio_upload_path', 'path/to/foo.bar');


Ways to specify different versions of nodes? I'm creating a dev portal for a client's software, and they would like to have nodes pertaining to different versions of the software in the documentation.

Rather than have to make an entire new set of nodes for each version of the software, I would like to be able to add/edit a 'version' of the node that pertains to 1.x 2.x etc, within the node edit screen, and control what version the end user sees with a custom module and/or $_GET variable.

My first thought is to use the translation module since this is essentially the same thing, albeit with languages instead of software versions, but I was wondering if anyone had any ideas of what method I should go about doing this?

In this case, go with taxonomy terms. That way you can organize content around a taxonomy term, one for each version. You can even tag content that is applicable to multiple versions just by selecting taxonomy terms.

Then, you could create a view that says "give me all of the content related to version X" and you'd be able to see those. Plus if you ever wanted to do more than "just nodes" e.g. other entities or bundle types, you can just add the field to those bundles and go on your merry way. Plus, since taxonomy terms are entities, you can add fields and content to those terms and build pages that surround those terms.


How to set Rules event for "Content is viewed" from excluding Teaser view? I set up a Rule that will execute during the "Content is viewed" Event and the action was to show a system message.

It worked and was triggered when I viewed the node. However, when I went to the home page, it was triggered N times, where N is the number of nodes on the /node page.

How do I stop this from happening? The Rule should only fall through on content full view, and exclude the teaser view.

In your rule add a data comparison called "view-mode" and set it to "Full content".


To add a value entered in a field to select list I have a field and select list. When a value is entered in the field ,if that value is  not present in the select list then i want to append that value in the select list.
how can i acheive this?

Not exactly the workflow you're looking for but one of these two modules can help you:

Select or Other

  Provides a new Forms API element which is a select/radios/checkboxes
  element that has an 'other' option. When 'other' is selected a
  textfield appears for the user to provide a custom value.

Multiple Selects

  Rather than having a multi-select field, this modules allows you to
  have multiple select fields with the traditional FieldAPI 'Add another
  item' button.


"WHERE NOT IN ( SELECT... )" with SelectQuery? Is it possible to add a WHERE NOT IN (SELECT...) clause to a SelectQuery object? I was looking at SelectQuery::condition(), and it doesn't seem to allow for this syntax:

public SelectQuery::condition($field, $value = NULL, $operator = NULL)

It only seems to allow for value comparison expressions. Is there another method that provides this syntax?

I'm looking at conditions on the order of thousands of values, so it seems inefficient to have a bunch of AND value <> x conditions.

What you're looking for is SelectQuery::exists(), unfortunately it doesn't seems to work with "common way" to build such clause:
Normally in a EXISTS clause you put a JOIN on tables outside of your sub query like this:

SELECT n.nid
FROM node n
WHERE EXISTS (
  SELECT NULL
  FROM users u
  WHERE u.uid = n.uid
  AND u.status = 0)

This returns the nodes of blocked users (yes it can be built easily without the EXISTS but it's for teaching purposes ;).

The problem here is that the exists condition doesn't support "outside linking", the u.uid = n.uid part so you have to build a completely independent query which is not very efficient IMHO.
In Drupal you will write this:

$query = db_select('node', 'n')
  ->fields('n', array('nid'));
$subquery = db_select('node', 'n2')
  ->fields('n2', array('nid'))
  ->join('users', 'u', 'n2.uid = u.uid'
  ->condition('u.status', 0);
$query->condition('', $subquery, 'EXISTS');
$result = $query->execute();

You can also use db_query() like you used to do in Drupal 6 and of course SelectQuery::notExists() is available.


What to do when a theme doesn't show up in the enabled or disabled themes? I am moving from one server to another a Drupal 7 site. I have Drupal set up on the new server and modules installed. However, I would like to enable a theme (shoppica, in particular). I have followed the instructions in placing the files in ./sites/all/themese/shoppica, however it does not show up in the list of themes. What other steps am I missing in order to get this theme to show up?

I would double check that all the theme files crossed over. As long as there is a .info file in the theme folder, it should show up in your drupal site.


Using node reference question In Drupal-6 I have a content type called: Colors with the following fields: title, body and code.
Then I have another content type called: Material with the following fields: title, body and color. This color field is a node reference related to the Colors content type.

So far so good.

Now when I create a Material node I can select a color from a select list. And here is my issue: this select list shows the title of the colors nodes. Is there any way to show the code for the node instead of the title. Or better, show the title and the code.

You can use a view to show the nodes that can be referenced, have a look at the settings of the widget, it's been a while since I used D6, but if you select title and code inside your view it should be visible when you edit a Material node.


Is this the correct way of iterating through users and check if they have a determined permission? I'm developing a module where I need to retrieve all users of a website and check if they have a specific permission.

<?php
$reviewers = array();

$result = db_query('SELECT uid, name FROM {users} ORDER BY uid');

while ($record = db_fetch_object($result)) {

    if ($record->uid != 0) {
        if (user_access('review article', user_load($record->uid), TRUE)) {

            $reviewers[$record->uid] = (string) $record->name . '@domain.com';

        }
    }
}

I'm using this code and it works but it can become quite slow. I've tested in a site with 5.000 bogus users and it takes about 30 secs to complete.

That code works, but as you found out, it needs to load each user completely and is therefore very slow.

Unfortunately, the database schema of permissions/roles in D6 is really crappy. It stores all permissions of a role in a single role, separated with a comma.

But still, it should be possible to query that information directly. What you want to query is  which roles have a specific permission and then which users that have at least one of these roles.

Something like this:

db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {permission} p ON p.rid = ur.rid WHERE p.perm LIKE '%s'", '%, $permission_name_here,%');

There are a few special cases where this doesn't work/needs additional checks:

uid 1 does have all permissions
all users automatically have the authenticated user role (rid 2) but that is not stored in the users_roles table. So if a permission could possibly be assigned to that role, then you need to explicitly check that and if yes, return all users.
It is possible to dynamically assign roles to users based on some conditions. In this case, the query won't work for that...


Upgrading to  Drupal 7.7 produces a fatal error: What can I do? I have upgraded my local site to Drupal 7.7 from Drupal 7.4, following the instructions in How to upgrade Drupal 7 to Drupal 7.2.

Before I could use update.php, visiting my site got me this message on every page of the site:

  Fatal error: Class 'DatabaseConnection' not found in C:\Users\Developer\Documents\Sites\accountablog\includes\database\database.inc on line 17

Doing a database restore did nothing to alleviate the problem.
What can I do to fix the problem?

The database.inc file does contain the definition of the class DatabaseConnection.

/**
 * Base Database API class.
 *
 * This class provides a Drupal-specific extension of the PDO database
 * abstraction class in PHP. Every database driver implementation must provide a
 * concrete implementation of it to support special handling required by that
 * database.
 *
 * @see http://php.net/manual/en/book.pdo.php
 */
abstract class DatabaseConnection extends PDO {
  // …
}

It is probable the file was not correctly copied, or has been corrupted during the copy; that would explain why the class has not been found, but the class is effectively present in the file that comes with Drupal 7.


Views No Results: Show Block Instead? I have a view that is set up to report breaking news from a "breaking news" text field. But this field is often empty, and in the no results behaviour, we would like to show one of our special offer blocks instead.

I can see an option for "Entity:Rendered Entity" in no results behaviour, but this is only nodes or users, I cant see a way to display a pre existing block?

There is a module that exposes blocks to the view header/footer and no results. It's called the Views Block Area.

  This module exposes all available blocks as a views area. This way you
  can add any block inside a footer or header from your view.

  Blocks that are generated by views, can't be selected. These blocks
  can be inserted by views areas.

This is also only for Drupal 7


Site not responding while flushing cache I have a Drupal 7 site which requires flushing the cache from time to time. The problem is that whenever I flush the cache (~30 seconds) the site is non-responsive until the flush is over.

What could be the cause and how do I debug this?
Thanks

Using a MySQL frontend like phpMyAdmin run SHOW PROCESSLIST while your site is locked from the cache clear. That should show what is causing the issues for you. My guess is it will be a metadata lock. https://www.drupal.org/project/apdqc was built to prevent db locks in database caused by the cache.


Views filter: how to compare two fields? I have two content types "type1" and "type2" and one taxonomy. I have assigned the taxonomy to both of the content types. In type1 its name is "field_type1_test" and in type its name is "field_type2_test".

Now I want to fetch the title and body from the "type1" Where values of "field_type1_test" = "field_type2_test".

Is this possible?

If yes then how will I do this in views? Help please.

Not sure you are going to use it, but for those who may get here looking for the same:

Under the Filter Criteria, Search for "Globals: Fields Comparison".
For the record, the fields you want to compare should be among the fields you are loading in the current View.

So, if you want to compare to something you are not willing to show, you should add the fields to the View and check the Exclude from display.

Hope it helps!


Why is the "webform submission updated" hook not using the correct data? Created a function in respond to hook_webform_submission_update to generate a FillPdf.

function my_module_webform_submission_update($node, $submission) {

    if ($submission->nid == 43) {

        $uuid = ($submission->data['975'][0]);
        $sid = ($submission->sid);

        $f = "./sites/default/files/docs/mdx_lh_" . $uuid . "_" . $sid . ".pdf";

        if (file_exists($f)) unlink($f);

        $wf = array(array("nid" => 43, "sid" => $sid));

        fillpdf_merge_pdf(326,NULL,$wf);
    }
}

When the event is triggered, after pressing the save button, the FillPdf uses the old data.  Going over the webform a second time without changing anything, just clicking the save button, the FillPdf uses the correct data.

I thought the hook_webform_submission_presave was to change data (if needed) but it seems the event hook_webform_submission_update is triggered before data is actually saved.

Is there a way to force data save before calling fillpdf_merge_pdf, or is there another event to use?

For whatever reason querying the database give the correct data and yet the FillPdf sevice uses the older one, we moved the routine to the point where the results are showed, where its activated with a button. This option works fine.


Multiple rendering causing a ul more I had following code in template.php this is in function bartik_process_page(&$variables)

 $main_menu_tree = menu_tree_all_data('main-menu');
 $variables['main_menu_expanded'] = menu_tree_output($main_menu_tree);

and in page.tpl.php

<?php if ($main_menu): ?>

                        <?php print render($main_menu_expanded); ?>

        <?php endif; ?>
                          <?php if ($main_menu): ?>

                        <?php print render($main_menu_expanded); ?>

        <?php endif; ?>
                            <?php if ($main_menu): ?>

                        <?php print render($main_menu_expanded); ?>

        <?php endif; ?>

and output it is like this in bartik

1

Home

2. Now u can see i m getting
 extra

Home

Any idea how can i stop it

I have found the answer of it since in render variables are passed by reference https://api.drupal.org/api/drupal/includes!common.inc/function/render/7

so i was passing $main_menu_expanded multiple times in render which was culprit.

Fix is

$variables['main_menu_expanded'] = render(menu_tree_output($main_menu_tree));
<?php if ($main_menu): ?>

                        <?php print ($main_menu_expanded); ?>

<?php endif; ?>

<?php if ($main_menu): ?>

                        <?php print ($main_menu_expanded); ?>

<?php endif; ?>

Now i dont get extra ul


drupal_http_request with basic authorization receives 401 response I am trying to use drupal_http_request to connect to a remote rest-based webservice that uses http basic authorization. The following curl command works every time from a command line, and I'm trying to figure out how to do the same the "drupal 7 way".

    curl 'https://XXXXXXXX/login' -H 'Authorization: Basic XXXXXXXX==' \
      -H 'Content-Type: application/x-www-form-urlencoded' \
      --data 'username=XXXXXXXX&password=XXXXXXXX'

Here is the code I am using in Drupal

    class XXXXXX {
      function login($username='', $password='') {
        // construct url - returns https://XXXXXXXX/login
        $url = $this->constructLoginUrl();

        $data = array(
          'username' => $username,
          'password' => $password
        );

        $headers = array(
          'Authorization' => "Basic XXXXXXXX==",
          'Content-Type'  => "application/x-www-form-urlencoded"
        );

        $response = drupal_http_request( $url, $headers, 'POST', http_build_query( $data )

        return $response;
      }
    }

When I run the curl request, I get a json_encoded response. When I run the second bit of code, I get a 401 unauthorized error from the other server. So, my intent is to make the Drupal request work exactly the same as the curl request above. Is there something I should be doing differently?

If you're using Drupal 7, then I'm fairly certain you're supposed to put everything after the URL into a single options array instead of positional arguments. This was done so you can pass some arguments without passing all of the preceding ones.

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_http_request/7

drupal_http_request($url, array(
  'headers' => $headers,
  'method' => 'POST',
  'data' => http_build_query($data)
));

should work.


Batch operations: callback_batch_operation() not invoked I have a batch process where the callback_batch_operation() functions are never called, as showed when logging with some Devel dd() calls.

Here is the involved code fundamental parts (all this in the same multilang.admin.inc file):

function multilang_default_form_submit($form, &$form_state) {
  $operations = array();
  if ($categories = $form_state['values']['default']) {
    foreach ($categories as $category) {
      if ($category) {
        $operations[] = array('multilang_default_process', $category);
      }
    }
  }
  $batch = array(
    'title' => '...',
    'init_message' => '...',
    'operations' => $operations,
    'finished' => 'multilang_default_finished',
    'file' => drupal_get_path('module', 'multilang') . '/multilang.admin.inc',
  );
  dd($batch, '$batch'); ## log
  batch_set($batch);
}

function multilang_default_process($category, &$context) {
  dd(func_get_args(), 'default_process'); ## log
  // ...do the desired job...
}

function multilang_default_finished($success, $results, $operations) {
  dd(func_get_args(), 'multilang_default_finished() args'); ## log
  // ...send appropriate messages...
}

And here is the log result, in a case where only one operation was required:

$batch: Array
(
    [title] => Resetting Multilang configuration
    [operations] => Array
        (
            [0] => Array
                (
                    [0] => multilang_default_process
                    [1] => multilang_exclude_paths
                )

        )
    [finished] => multilang_default_finished
    [file] => sites/all/modules/multilang/multilang.admin.inc
)

default_finished: Array
(
    [0] => 1
    [1] => Array
        (
        )
    [2] => Array
        (
        )
    [3] => 0 sec
)

The above log shows that the multilang_default_process() function is not called, though correctly stated as callback_batch_operation in $batch.

Obviously the first suspicion after the function's correct spelling, goes to its localization through the file index in $batch.
But not only I multiple checked it, but also we can notice that the default_finished() function gets called, while it is localized through the same file index.
This is also ensured by the fact that, if I intentionally set file to another, incorrect value, then the default_finished() function is not called.

Another puzzling thing (at least at my eyes) is the default_finished() passed arguments: despite no callback_batch_operation was called, $success (index 0) is set to TRUE and (remaining to process) $operations (index 2) is empty.

Am I missing (like it happens too often :-) something stupidly obvious...?

Yes, it was stupidly obvious!

When bulding my $operations I wrote
$operations[] = array('multilang_default_process', $category);
while according to the batch_set() documentation it should be
$operations[] = array('multilang_default_process', array($category));

Sigh...


Converting Drupal Content Types What are the steps needed and modules required to convert a large number of nodes from one content type to another, both in Drupal 7. They are fairly simple. If you know of a good tutorial that would be great too.

All my searching seems to bring up migrate which I thought was from 6 to 7.

I've tried node convert but I'm not sure how to use actions or if it can do many nodes at once.

And would it be possible for the URL alias and the taxonomy selections to be transfered?

Have a look at the Node Convert module.

Node Convert adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability of converting the node from its current node type to another node type. Also it gives the ability of transfering all the custom CCK field values of the current node type to the destination CCK fields, or discard them. As of 5.x-1.4 you can bulk convert many nodes of the same type, to another one that can be accesed in Administer → Content → Convert Nodes.
The module has been tested on converting node types with the following CCK fields:

Text
Number
Image
Node reference
User reference
Link
Date
Datestamp
Email
Audio
Video

Here is the documentation for the module: https://drupal.org/node/291564


Have Views based Taxonomy Term page use term description for title I am using a view to replace the standard Taxonomy Term page (turned on the standard one in Drupal 8.x). I want the Title of the page to be changed from the Name of the term to the Description of the term everywhere it appears, in the Title attribute in the Header but more importantly in the Title that is rendered on the page. I have tried all sorts of tricks in a custom page--taxonomy.html.twig file to no avail.

There is an incompatibility to use Description as Title, at least if you use the default settings. Description is a long text field and it possibly contains HTML. Titles are supposed to be plain text only, they are usually "cleaned" against HTML in them.

That said, if you think you have a case where this makes sense, you can try to use the field tokens for the Taxonomy term Description field. But you'll have to make a lot of changes to the Views if you want to do it through the interface and not custom code.

"Taxonomy term" Views is of the "Content" type, not "Taxonomy term" type, so you don't get taxonomy term info out-of-box in there. You have to add a Relationship towards the term in order to get the term info to be available in Views.

So first add the Relationship for your Taxonomy reference field, it will be under "Content" Category, named something like "Taxonomy term referenced from field_tags". You'll probably want to Require it, to exclude all nodes that don't have that taxonomy tag.

Once you have the Relationship you will be able to add the Field "Description" to your views (change the Format to "Fields" if it's "Content"). You can Exclude it from display if you don't want it in the Views results. And recreate the "Content" Format with Fields, add the node Title field etc.

The Title in the "Taxonomy term" Views isn't coming from the Views Title field, it's coming from the Contextual filter "Override title" option. There is also the Header option rendering the Taxonomy term which shows the linked term name and its description below it.

So if you want to change how that behaves, that's where you'll have to make the changes. I don't think you'll be able to have the Description token work in the default "Has taxonomy term" Contextual. You'll have to remove it and add the Contextual for your tags field, possibly for the Description field (I haven't tried it). Then set the title override on that Contextual and adjust the Views Header option.

Since your Contextual is limited to one field, and no longer covers entire site's Taxonomy, you have to be careful to recreate other Taxonomy pages (for other Vocabularies) if you need them. It's always a good practice not to work on the original "Taxonomy term" Views, instead keep it intact and disabled for future reference, and Duplicate into a new Views and work on the Duplicate.


Logging URLs in the PHP-FPM Access Log - possible Clean URL Conflict I have set up an access log in PHP-FPM under pool.d/www.conf, and I noticed that the log usually constructs the URL as "index.php" with all query parameters, EXCEPT for 'q,' which is the URL. I know that this is removed by the server for clean URLs, so would anyone know how to collect this?

Looking at the access log format instructions, it seems like there should be a header specifying location. I'll see if I can find one in Charles Web Proxy.

Here are the relevant config file sections:

from NGINX site config:

location / {
    # try_files $uri @rewrite; # For Drupal <= 6
    try_files $uri /index.php?$query_string; # For Drupal >= 7
}

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

...

location ~ '\.php$|^/update.php' {
    fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
    # Security note: If you're running a version of PHP older than t$
    # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
    # See http://serverfault.com/q/627903/94922 for details.
    include fastcgi_params;
    # Block httpoxy attacks. See https://httpoxy.org/.
    fastcgi_param HTTP_PROXY "";
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_intercept_errors on;
    # PHP 5 socket location.
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    # PHP 7 socket location.
    #fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}

from /path-to-php5/fpm/pool.d/www.conf

; The access log file
; Default: not set
access.log = /var/log/php5-fpm/$pool.access.log

; The access log format.
; The following syntax is allowed
;  %%: the '%' character
;  %C: %CPU used by the request

...

;  %e: an environment variable (same as $_ENV or $_SERVER)
;      it must be associated with embraces to specify the name of the env
;      variable. Some exemples:
;      - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
;      - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e

...

;  %o: output header
;      it must be associated with embraces to specify the name of the header:
;      - %{Content-Type}o
;      - %{X-Powered-By}o
;      - %{Transfert-Encoding}o

;  %u: remote user
;
; Default: "%R - %u %t \"%m %r\" %s"
access.format = "%R|%u|%t|%m|%r%Q%q|%s|%f|%{mili}d|%{kilo}M|%C%%"

I am using

access.format = "[%t] %m %{REQUEST_SCHEME}e://%{HTTP_HOST}e%{REQUEST_URI}e %f pid:%p took:%ds mem:%{mega}Mmb cpu:%C%% status:%s {%{REMOTE_ADDR}e|%{HTTP_USER_AGENT}e}"

which logs lines like

[16/Nov/2018:23:54:13 +0100] GET https://realdomain.com/path?param /linux/path/file.php pid:1234 took:1.035s mem:2mb cpu:0.99% status:200 {192.168.1.10|Mozilla/5.0 (full User-Agent)}

More info: https://github.com/php/php-src/blob/master/sapi/fpm/www.conf.in#L257-L318


View with field collection and filters I want to make a profile for musicians. They should type their skills (reference to taxonomy) and levels (radiobuttons) like flute - beginner, piano - advanced,...
Then I need a view with the profile information and the skills and levels. There should be a possibility to search for the skills and levels.
I tried it with a field collection field in the profile but then there is only one exposed filter for the profile field, a textfield for both the skills and levels.
How can I do this? I am getting mad about it. Is there another way to make this work?

If you would like to look at an advanced application of someone doing something very similiar to you, have a look at the Recruiter installation profile for Drupal 7. Just download, install and then look at how the views, content types, taxonomy and fields are configured. Instead of musicians and skill it is configured to software developers with skills.


Webform 4 - More than one conditional hides or shows component - Confusing Is & Isn't Shown? I'm getting the following error: More than one conditional hides or shows component -- Once a user selects one option, it should hide other fields not pertaining to the selection. attached screenshot.

not sure what I'm doing wrong.

ok it works with this setting it seems. it seems that once u set it to "isn't shown" it will auto hide it by default. which is why its throwing an error as it cant do 2 conditions at once.


Maintaining order history when creating orders as admin I have learned that much of the sales tracking and order history is dependent on the sales being made through the use of commerce checkout. For my project, however, I was utilizing the Commerce Kickstarter distribution to create a system to manage business sales whereby the admin would create customer profiles and, subsequently, be able to select from existing customer profiles when an order is created.

That is to say, the admin is the only necessary user.

I soon found, however, that order histories for each Customer Profile remained unchanged after orders. To get around this, I created a rule to create a User Profile to match every Customer Profile whenever the latter is created. In order to associate ownership of the Customer Profile by the New User, I wrote an additional script and triggered it as part of the rule.

Although the Customer Profiles are now owner by their respective Users, the Order History remains unchanged for each user - new orders do not create any history. This is because the user associated with the orders is whichever user is logged in, rather than the user associated with the Customer Profile being chosen for the order. I would like to rectify this as it would allow me to enjoy the full benefits of Commerce Reporting.

My first intuition is to use function hook_commerce_order_presave -> but I have found no examples of this, and am unsure as to the specific structure of $order. Can anyone shed some light on this?

I was able to solve this issue:

RECAP

Problem: Keeping order history in situations where the admin creates orders on behalf of Customers.

Solution:
a) User profiles must exist for the customer profiles. If the admin is creating customer profiles, a Rule can be created to a create User Profile whenever a Customer Profile is saved. To do this, I created a field for Customer Profiles called "Username", and use that data to populate the name of the new User.

b) A script will need to be written to automatically associate ownership of the Customer Profile by the appropriate User Profile. I was unable to create a functioning Rule which doesn't use my own php code to handle this.

c) One more rule to change the data value of the Order before it is saved. Specifically, you want to change [commerce-order:owner] to the right value (which can also be supplied by my Customer Profile's "Username" field). You will need to ensure that your rule has a Condition of "entity has field -> username" or the appropriate token won't be available.

I hope this can be helpful to someone!


How do I specify a Forena PDO data source in settings.php? I would like to override my Forena data sources in a local settings file for development. I would also like them in settings.php on production for database independent deployment.

I have checked the documentation but a full example is not provided. Can anyone provide a full example?

A sample of what you are looking for can be found in Forena subfolder repos/sample/settings.php, it looks like so (and is for 7.x-4.x):

<?php
/*
 * Sample Repository configuration file
 */

/*
 * Security provider:  Specify the class name that is used to provide security
 */
$conf['access callback'] = 'user_access';

/*
 * Data provider:
 * Specify the class name that will be used to interpret data block files.
 * Note that data blocks in a repository
 *
 */
$conf['data provider'] = 'FrxPDO';

/*
 * URI:
 * The format of the uri depends on the type of data engine that's being used.
 * In database engines it might be the connection string to the db.  In the file
 * engine it would be the path to the directory containting the files
 */
$local_path = realpath(dirname(drupal_get_path('module','forena').'/forena.info'));
$conf['uri'] = 'sqlite:'. $local_path . '/repos/sample/sample.db';
$conf['debug'] = FALSE;
/**
 * Uncomment the following line to specify a particular path in which to save reports.
 * The default value would be controlled by Forena configuration page. If you'd like users
 * to be able to define their own reports in this repository then you need to make sure that this
 * is writable by the web user (e.g. apache).
 */
// $conf['report_path'] = 'sites/files/reports'

Disclosure: I'm a Forena co-maintainer.


How to reload Google chart on ajax submit? I have a simple Drupal form. I am using hook_theme() to draw a chart right under my form. I am using Google chart API. When the page loads first time, my chart appears with no problems. But when I submit my form I use ajax_command_replace() to replace my chart with another one (without page reload). The goal is to make it possible to send variables from my form right to my theme function and draw another chart according to them. The problem is when I push the submit button the old chart disappears (which is good) and the new chart doesn't appear (which is bad). What am I doing wrong?

The issue is already created on drupal.org for this and you can try  the code from the below mentioned url:
Ajax load of chart


How can I assign a block to a panel or mini-panel? I was reading the project description for Panels, and I noticed it was a way—using mini-panels—for me to rearrange the contents of my site.

So I just created a mini-panel with a two column layout. I want to add one block to the left and one block to the right. How can I do this?

Mini panels are blocks and you can add Mini Panels to Panels. You can't add blocks themselves to Panels, but usually most of the content that you can display in a block, you can actually display in Panels, content such as Activities, Menus, Mini panels themselves, Miscellaneous, Pages elements, Views, Widgets, Nodes, Custom content and more.

See Drupal - Blocks vs Context vs Panels.


Is it possible to show notification in MacOSX or Safari? I'm using Drupal latest version with lot of modules.
As you know, websites can Show notification in Notification center and/or Safari in Mac OSX.
I see that, Wordpress has a module for this.

Is it possible to do it for Drupal?

I dont know what the Wordpress module does.

But for the server running the website you can send notifications to the OS using Drush Notify (built into Drush version 6).

From the readme it has a few example functions:

drush_notify_send(): Send a message to notifications center and audio.
drush_notify_send_text(): Send a message to notification center.
drush_notify_send_audio(): Send a message to audio system.


Using blocks in multiple regions In one demo projects I have found that I need to place same block in two different regions.
I have the knowledge that one block can be placed to one region only.
Can anyone help me with this ?

Using the Context module you can achieve your required feature.

This module will help you to place all your blocks in multiple regions on same or multiple page.


How do I adjust autocomplete list width Has anyone been successful in adjusting autocomplete list width (entity reference tag style)? I have hard time grabbing the element in Inspector/Firebug.
The goal is to have the width wider than the field that it's bound to, so to accommodate entire item label.

As coded in autocomplete.js file inside misc folder, popup is wrapped inside

You can able to set width using above id. If you want to disable hide popup option for time being to style the popup results, then try commenting lines shown below in autocomplete.js file inside misc folder of your drupal root.

/**
 * Hides the autocomplete suggestions.
 */
Drupal.jsAC.prototype.hidePopup = function (keycode) {
  // Select item if the right key or mousebutton was pressed.
  if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) {
    this.input.value = $(this.selected).data('autocompleteValue');
  }
  // Hide popup.
  var popup = this.popup;
  if (popup) {
    this.popup = null;
    $(popup).fadeOut('fast', function () { $(popup).remove(); });
  }
  this.selected = false;
  $(this.ariaLive).empty();
};

NOTE: Remove commented code once styling is done. Clear the cache after making javascript changes and make sure changes are reflected in autocomplete.js file using firebug. Clear browser cache.

Hope it helps :-)


Trying to get a "Is between" date filter to work... it is returning an offset by + 1 days. Please see my website to see what i'm talking about: http://apollo.tbc.iit.edu/~spaceweather/sw_test/?q=download-cases-data#

Ive found some examples and posts on how to do this but even after following them i'm still having issues.

I'm trying to filter the results shown in a table. I want the dates in between the two specified dates a user might put in.

When I select 05/24/2013-05/26/2013 I get an offset of 05/25/2013-05/27/2013 for the results. Can anyone help with this?  I'm storing the date as a Unix time stamp.

Thank you for your help!

(*Note my website has been updated according to the suggestion below by @adem .)

The filter type must be "single filter",
operator must be "is between", as demonstrated in this screenshot:


Custom Install.php template In the process of developing a distribution, I'm stuck with the task to customize the install.php page. Can't find a way to change the tpl/layout of the installation process or which preprocess function to use.

I'd like to do the same as Commerce Kickstart did, in a certain way.

Any ideas how?

Here's the trick that Kickstart uses (from commerce_kickstart.install).
The actual styling is in the Shiny admin theme.

/**
 * Implements hook_install_tasks_alter().
 */
function commerce_kickstart_install_tasks_alter(&$tasks, $install_state) {
  _commerce_kickstart_set_theme('shiny');
}

/**
 * Force-set a theme at any point during the execution of the request.
 *
 * Drupal doesn't give us the option to set the theme during the installation
 * process and forces enable the maintenance theme too early in the request
 * for us to modify it in a clean way.
 */
function _commerce_kickstart_set_theme($target_theme) {
  if ($GLOBALS['theme'] != $target_theme) {
    unset($GLOBALS['theme']);

    drupal_static_reset();
    $GLOBALS['conf']['maintenance_theme'] = $target_theme;
    _drupal_maintenance_theme();
  }
}


I am looking for a friend's list  for the Organic Groups module I'm looking for a friend's list (kind of Google+ circles functionality) to work with the Organic Groups module.

I wish to allow users to add tags to users that are their friends, e.g. work or family, and then use these tags for activities like share, privacy, or mailing list.

I didn't find any, but the closest modules are:

Relationships; it is public to other users and has to be confirmed by the other user.
User roles; it is set by the admin
Mail lists; I didn't find any that tag/manage contacts by tags or lists. The Lists module doesn't work well.

You might give User Relationships module a try.

Basically, you can create one way and two way relationships, such as friends, manager.


Not too sure about template.php I'm primarily a designer and I've been working on Drupal themes for some time now. At this point, I'm comfortable enough converting my designs to Drupal themes reasonably quickly but I continue to have doubts about how to use the template.php file... I've read up about it quite a bit, but my understanding of its usefulness is theoretical at best.

Clearly it's not a required file since it's never stopped my themes from working in the past, but is it advisable to have one in all cases? Are there functions (or anything else for that matter) one would automatically include in template.php?

The template.php file should contain the presentation code; the "logic" code, such as the theme functions, or other code that computes the value of a variable, should be in the template.php file.

To make an example, code similar to the following one should not be in the template file, but it should be put in a function contained in the template.php file, and which return a value to the calling code, which then uses the returned code:

  if ($user->uid) {
    $class[] = 'authenticaded-user';

    if (user_access('administer content')) {
      $class[] =  'content-administrator';
    }
  }
  else {
    $class[] = 'anonymous-user';
    $class[] = 'anonymous-' . strtr(ip_address(), '.', '-');
  }

  if (isset($class)) {
    print ' class="' . implode(' ', $class) . '"';
  }

The code in the template file should just print (or render) values, but not compute those values; clearly, it's perfectly fine to use code similar to the following one (the code is taken from a Drupal 7 theme):

    <?php if ($logo || $site_title): ?>
      <?php if ($title): ?>

<a href="<?php print $front_page ?>">
        <?php if ($logo): ?>
          <img src="<?php print $logo ?>" alt="<?php print $site_name_and_slogan ?>" title="<?php print $site_name_and_slogan ?>" id="logo" />
        <?php endif; ?>
        <?php print $site_html ?>

      <?php else: /* Use h1 when the content title is empty */ ?>

<a href="<?php print $front_page ?>">
        <?php if ($logo): ?>
          <img src="<?php print $logo ?>" alt="<?php print $site_name_and_slogan ?>" title="<?php print $site_name_and_slogan ?>" id="logo" />
        <?php endif; ?>
        <?php print $site_html ?>

    <?php endif; ?>
    <?php endif; ?>

The difference is that, in this case, the code is verifying if the variable contains a useful value, and eventually avoid to output the markup, when it's not necessary.


Can we make template for contextual filter? Can we make template for contextual filter, because while I am writing php code in it, it is not supplying true values.
I am writing these code in php code of contextual filter:

<?php
   $children = array_keys(taxonomy_get_children($handler->argument, $vid=1));
   if(!empty($children)) $handler->argument .= '+' .implode('+', $children);
?>

I need to apply these code in template file so that get satisfactory result over there and can apply some custom code too.

There is no such template, but to override contextual filters you can follow the following approach:

In a custom module

you can use hook__views_pre_view to change contextual filter,
add children terms till depth to the contextual filter,
function taxonomy_get_children_all() defined below, will fetch all child terms till depth:
In view, don't forget to allow multiple value contextual filter for contextual filter.

function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
  $c = taxonomy_get_children($tid, $vid, $key);
  $result = array();
  foreach ($c as $t => $d){
    $result[$t] = $d;
    $below = taxonomy_get_children_all($t, $vid, $key);
    if (!empty($below)) {
       foreach ($below as $nt => $nd){
         $result[$nt] = $nd;
       }
    }
 }
 return $result;
 }

 function formalter_views_pre_view(&$view, &$display_id, &$args){
 if($view->name == "category_view") { // && $display_id == "page") {
   $vid = <Your vocabulary id>;

   $t = $args[0];

   $tt = taxonomy_get_children_all($t,$vid);
   foreach($tt as $k => $v) {
     $a = (string)$k;
     $args[0] = $args[0] . "+" . $a;
   }
 }
}


How to attach a view display switch to a view? I am wondering how I can attach a switch/ link from one view display to another view display within the same view. I can only think of messing around in the template files and hardcoding this navigation.

What is the best solution/ is there a better solution for that?

Update: both displays shall have a own url this for caching and possibility to link to a specific display.

myview/(default: display-table)
myview/display-table
myview/display-list

Display Suite

A possible solution to this is probably utilizing display suite.

You could trigger a link using display suite & display suite extras to open different view mode. The drawback to this is that the user would have to load a different page.

Quicktabs

Another solution would be to load the two views as blocks and use quicktabs to display the two views in that tab format you require. The drawback to this solution is that you have two views loaded.

Views Header

At the top of your views, just add a header anchor to your other views page. This solution is best if you just have one view where this output is being displayed. Otherwise, it would be difficult to maintain duplicate views.


How do I create radio button for options on a Drupal Commerce product? I just need some radio buttons for adding on components in a drupal commerce product. The best example is Apple's build a customized MAC or laptop where you add on specific elements to the product but start with a base. I also need to know how I can do this with ajax.

Sounds like you're after either the Commerce Product Option module:

This module adds customizable product options to the "add to cart" form. The approach is generic, so all field types / widget can be used. This module is created only for the commerce module. For other systems you need different systems / approaches.
The module provides a field called option set. You can assign to your commerce product. Each option set consists of a list of fields. If a product is connected to a option set the add to cart form will be extended by the fields of the option sets.

Or the Commerce Product Attribute module:

This module provides some enhancements to the Drupal Commerce attribute handling.
The improvement contains:
Attribute field for line itemEdit option for attributes

I'd advise installing both of those and seeing which fits your use case better. You'll have to handle the AJAX functionality yourself as I don't think it's built in to either.


Private file folder outside document root I am setting up a private files folder outside of www. I have set the permissions to allow access to the folder by www-data to read and write but not execute, however, my drupal 8 site is now showing an error:

  PRIVATE FILES DIRECTORY Not fully protected See
  https://www.drupal.org/SA-CORE-2013-003 for information about the
  recommended .htaccess file which should be added to the
  /var/drupal_data directory to help protect against arbitrary code
  execution.

That link is to an advisory and fixes regarding Drupal 6 and 7. There is no mention of of Drupal 8 and it appears reasonably out of date:

  20 Nov 2013

I didn't think apache could even utilise htaccess outside of the www folder in such a way.

Is there some other configuration or permission I need to be changing?

Up until now, for testing, I have had a private folder within the public files directory. I wish to move the private files directory outside the root directory as I am lead to believe it is better for security.

While many guides discuss the best practice of moving this folder outside the root directory few go in to much detail about either why that is beneficial or how that changes the site setup. If there are good recent explanations for this practice I would appreciate being directed to them.

Looking at the code in system.install that raises this error it just checks if private://.htaccess exists:

$htaccess_files['private://.htaccess'] = [
    'title' => t('Private files directory'),
    'directory' => drupal_realpath('private://'),
];

...

foreach ($htaccess_files as $htaccess_file => $info) {
  // Check for the string which was added to the recommended .htaccess file
  // in the latest security update.
  if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
    $url = 'https://www.drupal.org/SA-CORE-2013-003';
    $requirements[$htaccess_file] = [
      'title' => $info['title'],
      'value' => t('Not fully protected'),
      'severity' => REQUIREMENT_ERROR,
      'description' => t('See @url for information about the recommended .htaccess file which should be added to the %directory directory to help protect against arbitrary code execution.', [':url' => $url, '@url' => $url, '%directory' => $info['directory']]),
    ];
  }
}

At no point does it check if your private file directly is actually inside webroot or not.

This means in your case it's a false warning and you can ignore it, as your right in saying there is no point putting an .htacess file to deny access in a folder outside of webroot.


How to hide empty blocks supplied by the User Relationship module? I am trying to hide a module supplied block (User Relationships action block) from appearing on nodes posted by the logged in user. The block shows as empty on those pages.

I have tried php in the block visibility rule, I have tried the Context module, I have tried a template, to no avail except that with a template the block no longer shows anywhere regardless of the template having code inside it or not.

Otherwise, the visibility rules work if I limit visibility to specific paths.

It also looks like I am having problems hiding other module supplied blocks like the search block.

Interestingly enough, when I enable the Devel Themer module, the action block no longer shows on posts by the logged in user as it should but appears on others (this is the result I am trying to achieve.) Unfortunately, this module has other serious issues and I cannot leave it enabled permanently.

Combined with the fact that I haven't found any other complaint about this situation, this leads me to believe that the UR action block, by design, should not appear on the logged in user's posts and that I should not be facing this problem.

Does this mean I have a broken database somewhere?

Can anyone guide me on the diagnosis and possible repair of this situation --like, maybe, going into the database for a manual fix?

P.S.: In the database, the action block shows a size of NULL and a sort of NULL. Is this normal?

Rules block visibility

Have a look at the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

  Need to show a block only for users registered more than a month ago?
  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules check situations such as "is this a node posted by the logged in user" (so that the block is not to be shown).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".

Advanced debugging options

To futher investigate the "The website encountered an unexpected error, please try again later" (as in your comment to this answer), keep in mind that such errors originate from some PHP exception that occured somewhere. To get more details about such error, check your 'Recent log messages' (within "Reports", located at /admin/reports/dblog), which is available if the Database logging module is enabled.


Using hierarchical select to display a particular section of content I have a content type called "Results" that displays the results of a particular game.  I am using the Hierarchical select module for my taxonomy terms that include Year, Game and League.

My goal is to create a view that only displays a Result content type that matches the terms selected in the exposed Hierarchical Select module.  I currently have the view working, but it is displaying all the Results content type.

As far as drupal 6 views 6.x is concerned. You need to ensure you are saving the taxonomy heirarchy as additional terms in the database. Ensure also you are saving the entire lineage from the view. Finally Add a filter with Taxonomy: Term ID and leave this using default values.

(1) Ensuring you are saving the taxonomy heirarchy as additional terms:

-edit your "Results" content type, go to manage fields and edit the heirarchical field. Somewhere on this page you will see 'Save values additionally to the core taxonomy system (into the 'term_node' table).'

(2) Ensure you are saving the entire lineage:

-on the same page as above follow the link to oonfigure this heirarchical select on a separate window.. 'Due to limitations of CCK, there is a separate form to configure this Hierarchical Select widget's settings'

(3) Go back to views and add that filter I mentioned above.


Drupal views contextual filters I have set up a Drupal View (as a block) listing a number of books in my left sidebar (an unformatted list of fields, title, image etc.), in the main area the individual book is displayed as you click on the image in the left sidebar. Is it possible to use the contextual filters to disable that particular book from my view in that left sidebar?
I'm relatively new to Drupal! Many thanks if anyone can help!

Yes, you can use a contextual filter on a node nid.  For its value, select a default argument (since a block won't have it) and then select node id from url.  Then also click on exclude the argument.  This will create a contextual filter that excludes the node on the page from the View.


Making a block's content's all show in one row I have a block that is made up of 3 subblocks: an image block, a menu block and a views block.  I combine the three blocks programmatically like this:

function inflatable_icons_menu_combo_block_content() {
    $block = block_load('views', 'icon_views-block_5');
    $block2 = block_load('menu', 'menu-facebook-menu');
    $block3 = block_load('imageblock', '1');
    $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block3, $block, $block2))));
    return ($output);
}

Now this block shows up with all three blocks and looks like this:

But I need the image to show up on the same row as the other two blocks.  What would be a good way to make it all show up on one line?

This appears to be a stylesheet issue. Everything should 'float:left'. If this has already been done, then your first block is too wide and is forcing the other blocks to displace down.

Experiment with maxwidh on your first block to leave room for the other two.


How to change the author and date of a new comment before posting it? I am copying the content from my old non-CMS (Weebly) website to my new Drupal website by manually filling in node forms and comment forms. I would like to recreate all the original authors and posting times on the new website. As a first step, I have created a user account for all the people who contributed to the old website.

Adding nodes works perfectly: as an administrator, I can post new nodes as another user and change the posting time before publishing.

Now, I would also like to add new comments, and change the author and date before posting. I know that one can administrate a comment after posting it, as shown in the screenshot below.

However, it is vital that the desired changes are made before posting comments, since publishing triggers multiple Rules, related to User Points, Flags etc. Otherwise, the wrong users are rewarded User Points, for example.

How can I do that?

Author
For changing the author (not the date), you might be able to use the Masquerade module for this. Some details from its project page:

The Masquerade module allows site administrators (or anyone with enough permissions) to switch users and surf the site as that user (no password required). That person can switch back to their own user account at any time.
This is helpful for site developers when trying to determine what a client, logged in as themselves, might see when logged into the site.
The masquerade module is designed as a tool for site designers and site administrators. While masquerading, a field is set on the $user object, and a menu item appears allowing the user to switch back. Database log (watchdog) entries are made any time a user masquerades or stops masquerading as another user.

So just switch to the appropriate user before filling in your forms, that should do what you're trying to achieve.
PS: works for any currently supported release of Drupal.
Date
Not sure (yet) about how to do this, but I'd try to use the Rules module for this. Here is a prototype of a rule that you may want to look at and experiment with:
{ "rules_update_comment_post_date" : {
    "LABEL" : "Update comment post date",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_presave" : [] },
    "DO" : [
      { "data_set" : { "data" : [ "comment:created" ], "value" : "-1 day" } }
    ]
  }
}

This rule should set the actual comment date to "current date - 1 day". Just as a sample. Adapt the value to fit your needs (before posting each comment, sorry ...), or try to think of an enhanced version of it to somehow retrieve the comment date as part of this rule.


User register and login functions are called from hook_form_alter, but user isn't logged in Background

I'm attaching the user register form, to the node create form with hook_form_alter. that way I create a node and user at once.

In order to validate and register the user, in hook_form_alter I add the relevant functions to my node form submit and validation calls.

function mymodule_form_alter form_alter(&$form, &$form_state, $form_id) {
   ....

    $form['#validate'][] = 'user_account_form_validate';
    $form['#submit'][] = 'user_register_submit';

Problem

The node is created and the user is created but the user isn't logged in.

Why isn't the user logged in?

The user register and login code seems to be running ok (see below), I can only think somehow the node creation is logging the user out? I have no idea how to continue debugging this.

Debugging

Thanks to Felix, I was able to debug by logging dpm (because it doesn't appear on the page) and the code is running correctly.

user_login_submit is called from user_register_submit

function user_login_submit($form, &$form_state) {
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;
  user_login_finalize($form_state);
}

And then user_login_finalize is called.

function user_login_finalize(&$edit = array()) {
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')
    ->fields(array('login' => $user->login))
    ->condition('uid', $user->uid)
    ->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);
}

I printed out $edit and $user and $edit is $form_state and $user is the newly created user. I can't see anything going wrong. The session opening is logged by watchdog, however perhaps it's never assigned?

How else could I continue to debug this? Could drupal_session_regenerate() be logging me out?

EDIT: I switched the user_register_submit to logintoboggan_user_register_submit, which worked on my dev environment but then broke on production with the same problem as above.

It doesn't appear to be a code problem, but something to do with the database or a setting. I dropped my production front end in front of my dev backend and it works fine, so it's some sort of database setting (which could of course effect the front end code).

If a redirect is happening after print('x') then it will be lost. dmp() should show up however I prefer using Devel Debug Log in these instances so you know if then code is running then it will output to the log.

You can use the function ddl('log message') or ddl($array) and then check the report of what has been output once your code has run.

I realise this isn't actually answering your question but may make debugging easier...


Drupal 6 / No access to admin There's a Drupal6 website I need to work on for a cliente. However, client does not have access to the admin. They don't remember their user/password.

What's the best way for me to retrieve the admin access besides the "remember password" feature?

Thanks a lot!

Johann

You can reset it directly in the db, if you have access to it?

UPDATE users SET PASS = md5('new_pass') WHERE uid = 1


The right way to validate fields via hook_node_validate Rather than creating a new field via the Field API, and as a quick workaround, I've added a simple text field to a content type that I'm now attempting to validate via hook_node_validate(). Unlike previous versions of Drupal, the value for this field is not simply available as $node->field_name or $form['field_name'], but instead as a nested array containing a variety of other information.

My question then is this: what is the 'correct' and therefore most future proof way to retrieve the value for this field? Am I supposed to be using the likes of field_view_value() or field_view_field(), or is it acceptable to simply reference $node->field_name['und'][0]['value'] for example.

field_get_items() is the one you're looking for:

$items = field_get_items('node', $node, 'field_FIELD_NAME');
$first_value = $items[0]['value'];

It also takes care of language selection for you, so no need to worry about that one any more.


How to create regular (monthly) reports from users? There are several users with a customized role - Sales managers, who need to provide monthly reports on sales. A Content Type - Sales Report was configured in the system.

The users will need to login and if the report is not yet provided for the last month, they need to have an option to create a new one and submit it, if the report was provided - they need to have the option to edit the report.

After the report is submited, a user with the role Department Manager will have to approve the report or send it back to Sales managers to be update.

How do I organize/configure this with Drupal?

This seems like a perfect usecase for the Forena module. Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports (and/or charts). Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links, and experiment a bit with some of its demo samples.

Have a look at the "Northwind database" demo videos, which is similar to what you're looking for. Such as these videos:

How to create a report/graph about Shipping summary (fast forward to about 4:15 if you're not interested in the SQL query prototyping part of it).
How to create Crosstab Tables and (related) charts (fast forward to about 2:15 if you're not interested in the SQL query prototyping part of it).
Various other Video demos and tutorials created in an earlier (7.x-3.x) release of Forena (which are mostly still accurate, but only using outdated Forena screens that have been enhanced in the 7.x-4.x version).

Below are some more suggestions to map the various features you're asking for to Forena equivalents ...

  There are several users with a customized role - Sales managers, who need to provide monthly reports on sales.

Forena comes with various types of permissions, such as:

Who is allowed to build the SQL statements (data blocks) that will be used in the reports that visualize these data?
Who can browse specific reports?

Especially for "sensitive data" (commissions, salaries, ...) this is important.

  A Content Type - Sales Report was configured in the system.

Forena doesn't really need a content type to show its reports/graphs. And using the BEAN integration of it you can also create blocks that display Forena reports. For the actual look-and-feel of the report, anything that can be expressed in XHTML is supported by Forena.

  The users will need to login and if the report is not yet provided for the last month, they need to have an option to create a new one and submit it.

That sounds like anonymous users are to be excluded from Forena reports (a matter of permissions). If the site somewhere shows a menu item or some link to "a" (monthly?) report, these users just have to use that link.  And specifying the actual month for which the report is to be shown, is typically implemented as a "report parameter", typically a pull down selection list near the top of the report.

Because of all the options that Forena offers to specify report parameters, there are various ways you could implement the selection of the actual month to be reported about.

  If the report was provided - they need to have the option to edit the report.

That's what you typically do using the WYSIWYG report editor. Though somebody who's familiar with XHTML might rather want to directly edit the (so called) .frx files.

  After the report is submited, a user with the role Department Manager will have to approve the report or send it back to Sales managers to be update.

That sounds like a workflow issue. Not sure if it is the only (or most elegant) way to implement this, but here is a possible approach:

Somebody authorized to do so, should create a report for the "new" month, by cloning the report from the "prior" month. Probably only changing the parameter list (by adding the new month to it).
Grant access to this new report to (only) role Department Manager, so that such users can look at the new report.
Continue improving the "new" report (as in step 1.) until it gets approved by the Department Manager.
After the "new" report is approved, grant access to anybody else who is now also allowed to browse it.
Build a special Forena report that can be used (by an authorized user ...) to send a notification eMail to all users that might be interested in being notified that the "new" report is available. To do so, you just build a report of such users, and enable "eMail" as on of the allowed "document formats" (= formats that a report can be exported to, such as CSV, XLS, PDF, eMail, etc).

  How do I organize/configure this with Drupal?

As detailed above: there's a module for it, i.e. Forena

PS: nowhere in your questions it says anything about "Charts" (sales people often "need" them also) ... But creating charts is a bonus that comes with Forena also ...

Disclosure: I'm a co-maintainer of Forena.


Different commerce payment paypal settings on dev and live sites The problem is similar like here:
How to force rules configuration to load

I planned to use hook_default_rules_configuration_alter(), but after this:

  if (isset($configs['commerce_payment_paypal_ec'])) {
    foreach ($configs['commerce_payment_paypal_ec']->actions() as $action) {
      dsm($action);
    }
  }

I don't see any $settings['settings'] array:

How can I change the saved commerce_payment_paypal_ec rule's settings by code?

This is a question that has came in different shapes, I'd recommend reading https://drupal.stackexchange.com/a/118316/2322 answer to get a better understanding on how drupal commerce and rules store this information. I don't know how to access the UI form the action itself.

Instead of trying to modify specific values, what I'd do is to try to replace the whole rule object with the one you want using entity_import of the rules_config object, something like:

if (isset($configs['commerce_payment_paypal_ec'])) {
    $configs['commerce_payment_paypal_ec'] = entity_import('rules_config', '{ "commerce_payment_paypal_ec" : {
        "LABEL" : "PayPal Express Checkout",
        "PLUGIN" : "reaction rule",
        "OWNER" : "rules",
        "TAGS" : [ "Commerce Payment" ],
        "REQUIRES" : [ "commerce_payment" ],
        "ON" : { "commerce_payment_methods" : [] },
        "DO" : [
          { "commerce_payment_enable_paypal_ec" : {
              "commerce_order" : [ "commerce-order" ],
              "payment_method" : { "value" : {
                  "method_id" : "paypal_ec",
                  "settings" : {
                    "api_username" : "1",
                    "api_password" : "",
                    "api_signature" : "",
                    "server" : "sandbox",
                    "currency_code" : "EUR",
                    "allow_supported_currencies" : 0,
                    "txn_type" : "auth_capture",
                    "ec_mode" : "Mark",
                    "shipping_prompt" : "0",
                    "log" : { "request" : 0, "response" : 0 },
                    "ipn_logging" : "notification",
                    "receiver_emails" : "",
                    "reference_transactions" : 0,
                    "ba_desc" : "",
                    "show_payment_instructions" : 0,
                    "update_billing_profiles" : 1,
                    "enable_bml" : 0
                  }
                }
              }
            }
          }
        ]
      }
    }');
  }


Can't run drush from within website folder configured with IIS on Windows Server 2012 I am trying to setup Drupal 8 on Windows Server 2012 on IIS. I have installed PHP7.0 and Composer. Using Composer I then installed Drush globally using composer global require drush/drush:8.*. Drush was installed at C:\Users\Myusername\AppData\Roaming\Composer\vendor\drush\drush. I have set the Path variable for the user 'Myusername' to include C:\Users\Myusername\AppData\Roaming\Composer\vendor\bin.

The problem I have is that if I cd into the website folder as configured in IIS, and then run drush version, I receive the following error:

"C:\\inetpub\\wwwroot\\mysite\\vendor\\bin\\drush.php.bat" is not recognized as an internal or external command, operable program or batch file.

If I run the same command outside of the site folder as configured in IIS, then drush version executes successfully.

It seems that when run from within the web site folder it is trying to run drush from within the website project instead of using the globally installed drush.

Any suggestions on how to get Drush running for the site?

Updated:

After some experimenting it seems that when I run Drush it looks for the closest vendor\bin directory. If it is not in the current directory, it works its way up the parent directories until it finds it. If it can’t find it, it uses the globally set one. For example, if I run drush from either C:\\inetpub, C:\\inetpub\\wwwroot then will get this error:

`"C:\inetpub\vendor\bin\drush.php.bat" is not recognized as an internal or external command, operable program or batch file.

If I run drush version from outsite of C:\\inetpub directory then it works correctly.

Drush Launcher solved the issue for me.

Step 1 Download drush.phar and put it in project root folder

Step 2 Create drush.bat file in project root folder and put following content (it will run phar in window)

@echo off
php "%~dp0\drush.phar" %*

Now it will use local drush.


Content type errors - "The Byline text" error I'm having trouble creating a content type. I can't seem to figure out to fix these validation errors. I'm not user what they mean.

The Byline text - Full content view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Teaser view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - RSS view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Search index view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Search result highlighting input view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Colorbox view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Revision comparison view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Tokens view mode is using the following invalid tokens: [node:author], [node:created].

I found the issue. Event though I had unchecked 'Display author and date information.' under 'Display settings', I still needed to empty the text fields or at least remove the tokens from them.


Is there a Drupal way to loop over Webform fields in form alter function? Since $form['submitted'] array has also other keys than just field names e.g. #tree, what is the correct way to loop over this array?

I need to add a #prefix and #suffix for each field and for now I've just created condition !is_numeric(strpos($fName,"#"))
This tells if it just a field name or if it holds render array properties or whatever they are called.

For D7 use element_children:

Identifies the children of an element array, optionally sorted by weight.
The children of a element array are those key/value pairs whose key does not start with a '#'. See drupal_render() for details.

E.g.
foreach (element_children($form['submitted'] as $key) {
    $form['submitted'][$key]['#prefix'] => 'foo',
}

For D8, use the equivalent Element::children in the same manner.


How can I modify the Quick Edit Module to have a better UX for end-users? For a current project I'm working on we're trying to leverage the "In Place Editor" functionality provided by the Quick Edit module.

Our main goals are to:

Have a module that allows us to perform Create Update and Delete options in-line on only fields that needs the functionality.
Make it so that there is a single visible button which says "Edit" on some content that is always used to enter the "In Place Editing" mode.

Instead, the Quick Edit module provides us with:

Quickedit on any and all fields that are editable by the user.

This works really well for site and content adminstrators, but, our target audience is the end-user of the site.

A contextual link (a pencil icon by default) which you must first click. This link then shows a menu for options "Quick Edit", "Edit", "Delete" (and any others that have been placed by modules hooking into the Contextual module).

Clicking "Quick Edit" then simply enables the ability to edit in line. At which point, you still have to click on a field within the context in order to get the field to appear as an editable form input (and it's not immediately obvious that's an available option).

What is the best way to go about achieving a slightly more stream-lined, end-user oriented, in place editing system in drupal 8?

tl;dr

Drupal gives me this:

I'd like this instead:

You can check https://www.drupal.org/project/simpler_quickedit to do exactly what you need


Background of CKEditor is black for authenticated user I am using the CorporateClean theme for Drupal 7.15, and I have an issue using CKEditor with this theme.

When an authenticated user writes some content, the background of the CKEditor text editor (the area where the user can enter and format text) turns black. I do not have this problem when login as the admin. I also do not have this problem if I remove CKEditor.

How can I change this background?

Do you have Firebug installed (extension for Firefox) ?
With Firebug you can inspect element and see what css definition makes it black.
Then, in your theme css file you can override that settings by writting your own definition to make it white. like

.ckebackground {
background-color:#ffffff;
}

where ckebackground is "problematic" class that makes it black.


Connecting views to another Drupal database I have a need to display views using an old Drupal database.  These views are already created, so I exported them and dropped the export code into a custom module hook_views_default_view, put in the necessary return, changed the view name, updated the paths, etc.  So, now I have two Views showing exactly the same dataset.

I need the newly created one to query against an old database; both databases have exactly the same structure. I have the old database setup in settings.php and, I thought, all I needed to do was add $view->database = "oldlife". That's not working - I'm getting the exact same data in both views (two different paths).

This is the code, minus all the handlers and unnecessary stuff:

function lwg_old_db_views_api() {
    return array(
            'api' => 3,
            'path' => drupal_get_path('module', 'lwg_old_db'),
    );
}

function lwg_old_db_views_default_views() {
    $view = new view();
    $view->name = 'commerce_vbo_views_orders_oldlife';
    $view->description = 'Display a list of orders for the store admin.';
    $view->tag = 'commerce';
    $view->database = 'oldlife';
    $view->base_table = 'commerce_order';
    $view->human_name = 'Orders';
    $view->core = 0;
    $view->api_version = '3.0';
    $view->disabled = FALSE;
    /**
      * many lines of $handler-> stuff
      */
    $handler = $view->new_display('page', 'Page', 'page_1');
   $handler->display->display_options['path'] = 'list-all-nodes';
   $views[$view->name] = $view;
   return $views;
}

Have a look at this module, it can do the job for you.

https://www.drupal.org/project/web_widgets


Book module versus Taxonomy module The Book and the Taxonomy modules are very similar for organising content in a hierarchy structure.

Both modules:

Allow Multi level hierarchies
Can be accessed by Views
All custom theming via node.tpl.php files
Offer the means for promoting or demoting content within a hierarchy, or moving it to another hierarchy

The Book module has the added advantage of creating navigation system (Although you could probably recreate this with taxonomy and Views).

My question is this: Which is the better to use for organising content in a hierarchical structure? Does one have any disadvantages or advantages over the other?

It seems odd to me that two similar modules exist in core. Why aren't they just combined into one?

The difference is that the Book module defines a content type ("Book page") that can be used to create books. The Book module allows also to create a hierarchical structure, and it shows:

the list of the child pages associated with the current book you are visualizing
a menu that allows to pass from a page to the next one, the previous one, and the top one
a link that allows you to create a new child page
a link that allows you to see a printable version of the current book page

The Taxonomy module is used to categorize the content of a site, but when you click on the link of a taxonomy term used by a node, the page you see shows all the nodes using that taxonomy term, without allowing you to pass from a node to the successive, or the one hierarchically on the top.

Said in sort, the Taxonomy module handles an attribute (in Drupal terminology is a field, handled with the field API) that can be associated with nodes, but also to users, while the Book module defines a content type that can be used to create books, and allows to handle that content type in a hierarchical way.


How to store your own key-value pairs in Redis using PhpRedis with D7 Redis module We have the D7 Redis module installed, which is being used as the cache mechanism for D7 caching. That module uses PhpRedis as the underlying library.

I would like to use that same Redis instance to cache a large amount of non-Drupal data that is retrieved from an external API, then will be rendered on a specific Drupal page. I'm wondering how I can get ahold of the Redis object instance that Drupal is already using, so I can use PhpRedis functions like $redis->set(key,value)?

Once configured/initialized, the module has a wrapper class/interface Redis_Client
 that contains the library object. It can be retrieved with the getClient() method:

$redis = Redis_Client::getClient()


How do I pass a string from a PHP field to the PHP filter? Is there any way to pass a string from php field to php filter?

on the PHP FIELD I can tell if a product has discount or not ( i think because the field formatter render the field_price in a way that triggers the discount rules) and if there is a discount I can set a variable on/off based on the output of this formatter.

This custom discount variable created with PHP FIELD I need to pass it to the PHP FILTER to control if a product must needs to be shown or not (sorry for my bad English)

PHP FIELD CODE

<?php

// $var1 will take value 0.00E or -94.99E (the last value is an example)
$var1 = strip_tags($data->field_commerce_price[0][rendered]);

// $var2 will take value 0 or -
$var2 = mb_substr($var1, 0, 1, 'utf-8');

// set $static = 0 or 1, if PHP FILTER can see this then can filter discount products
if ($var2=="-") { $static = "1"; echo "DISCOUNT!"; } else {$static = "0"; }

?>

PHP FILTER CODE

// all 4 variables gives output nothing
dpm($row->_field_data['nid']['entity']->field_commerce_price[0][rendered]);
dpm($data->_field_data['nid']['entity']->field_commerce_price[0][rendered]);
dpm($data->field_commerce_price[0][rendered]);
dpm($static);

if ($static=="1") { return FALSE; } else { return TRUE;}

So how PHP field send a string to PHP FILTER??? OR
Is there any to create a filter function using the PHP FIELD?

You can copy the code from the php field and add some logic to it to return false or true depending on the result but no there is no current way to transfer it.

EDIT: This may seem a bit backwards, though if you made a $_SESSION variable as an Array() you could maybe do something with that. Maybe not very helpful. views_php has always been entirely buggy for me and it comes in handy sparingly.


Modify apachesolr's 'did you mean?' suggestions to provide better alternatives Has anyone modified the default apachesolr 'did you mean?' suggestions that is returned out of the box with the apachesolr module?

For instance, a search for 'diabetes' currently returns 'did you mean: rates' http://www.health.govt.nz/search/results/diabetes

Is there a way to add some form of control over this, or is the solution simply adding more nodes to the index in the hopes of making it a better spell checker?

I found setting:
<str name="spellcheck.onlyMorePopular">false</str>

(instead of true) in solrconfig.xml dramatically improved the quality of the spelling suggestions.


Display Rate module results via Panels So many of us know that the Rate module does not smoothly integrate with Panels.

I discovered out a way to get the voting widget to show using a custom content with the following PHP code:

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
   print rate_embed($node, 'bias', RATE_FULL);
}
?>

Has anyone had any luck with doing something similar to display only the vote results (i.e. display total percent of that vote)?

I'm not a PHP wizard, but I think there is way by doing something like the following.

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
   print get_rate_resluts($node, 'bias', RATE_FULL);
}
?>

But end up getting either blank pages or some fatal database errors. Thoughts?

Update:
I think I figured out that I need to create a custom content to print the output after reading it here. Tried this:

$block['content'] = rate_get_results('bias', $nid, $widget_id) $output['rating'];

But it looks like it does not do anything which is better then seeing a blank page.

print rate_embed($node, 'NAME', RATE_FULL);

Replace NAME with the machine name of the widget; the view mode can be RATE_FULL, RATE_COMPACT, RATE_DISABLED, RATE_CLOSED, RATE_COMPACT_DISABLED.


Quick tabs: Passing current nid to a view I have a content type called products. The url is products/[node:title], i.e. /products/pear, products/banana, etc.

On the node page itself many of the fields of that node are hidden, because I want them displayed in tabs, along with content from associated nodes (via Entity References). So I am using Quicktabs and views to display this content. However, I can't work out how to pass the NID to a view if it doesn't appear in the URL. Since I just want to pass the NID of the page I am on, this seems like it should be a simple issue, but I can't work it out.

Ok I've worked it out. The URL that QuickTabs references is the System URL, so the NID is there and can be referenced just by %1.

I knew there would be a simple answer! Hopefully this will help someone else.


Foreign key for content type I have a content type named 'products' and every product have a unique vendor, so I want to add a field to the content type 'products' that allow me to chose the appropriate vendor from a list.

Is this possible without creating a custom module ?
Can I create another content type 'vendors' and join the two content type ?

Thanks.

It is possible to reference content types from one another but not with the core field system. There are currently 3 modules that offer this functionality:

References
Entity Reference
Relation

I'll let you read the module pages yourself to decide which one is best for your use case.

Each of the modules provides a field type that you can attach to one content type to reference another. The fields behave just like any others in the system and so can have a static or unlimited cardinality.


How to set a new taxonomy term without overwriting an existing one when using Rules? I'm using the Rules Action Set Data Value to set a taxonomy term for a specific user (uid= 75). The tag field exists in the user entity, and is set to "Unlimited".

There's nothing complicated about the rule, which looks like so:

{ "rules_invited_user" : {
    "LABEL" : "Invited user",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [ { "data_is" : { "data" : [ "account:uid" ], "value" : "75" } } ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-user-tag" ], "value" : "27608" } }
    ]
  }
}

I can set the term, but if there's another term set already for that user, it's overwritten.

How can I set a new term without overwriting an existing one?

The Rules Action Set a data value that your Rule uses, can only set 1 value, while you're trying to update something that is a list (or to use your own words: "...  set a new term without overwriting an existing one").

So try to replace your Rules Action (ie with the data_set) with an action "Add an item to a list". When doing so, you probably also want to set "ENFORCE UNIQUENESS" to true, so that you "only add the item to the list if it is not yet contained". Even though for your case it may not make a difference, IMO that is a kind of safety-belt when using this action.

For way more details about this, refer to "How to set multiple values to an unlimited Term Refence field with Rules". While reviewing this, also pay attention to the "Fetch entity by ID" (within the Rules loop): I wouldn't be surprised if you'd also need to add a similar "Fetch entity by ID".

Ps: I'm assuming this question is about D7 ...


How do I use a contextual filter? I have two content types: Medical Records and Resident Profile. Each Medical Records node is associated to a Resident Profile through an Associated Resident entity reference field added to the first content type.

In the node display page for the Resident Profile nodes, I want to have a block on the side that displays all the associated Medical Records nodes.

I know I have to do something with the contextual filters and relationships settings of a view, but I am not sure how to proceed.

How can I achieve what I described?

After creating a view, you can follow these steps to accomplish what you need:

Add a contextual filter, Search for nid - So you will have Content: Nid.

In When the filter value is NOT available:

Select Provide default value -> Type -> Content ID from URL.
Apply

Add a relationship in your view:

Search for field_associated_resident (your machine name), if there are two things come up. choose the one which says something like this: A bridge to the Content entity that is referencing Content via field_associated_resident (Language can differ).
Check Require this relationship.
Apply

Now go to your field selection, for example, you may want to display title. Add a field title and choose the relation you just created and Save.

To test this, you can use the nid of the Resident profile where you want to display it in the view itself. You should get your expected results there itself.


How do you validate against empty form fields in D7? In D6, the method I used was to store the value of form fields into a variable and then setting an error message of the variable == null.

Is this still possible in D7, or is there a better way to handle this?  The fields I'm trying to apply custom validation to are select lists so I imagine there must be a different technique.

I figured it out on my own: The process is the same as in Drupal 6. The arrays have just changed a bit. To use a custom validation with hook_form_alter() and a custom validation function, you would load your form_state values as follows (example based on fields from profile2):

function example_validate($form, &$form_state) {
  // Store our field values to validate against.
  $fieldname = $form_state['values']['profile']['field_name']['und'][0]['value'];

  if ($fieldname == null) {
    form_set_error('profile][field_name', t('Error Message'));
  }
}

The actual value for our fields is now found in the 'und' array. Since the #parent property of these profile fields is an array, use 'foo][foo2' format to specify the element for which to show the validation error. See form_set_error().


How to display/hide a field only if has a certain value? I am working on an event content type.
It contains a date field that lets users input the date in which their event will take place.
But sometimes the date of the event isn't known at the time the node is created. Users just need to create the event and discuss with other users (in the comments section) then decide when to organize it and add the date then.
So the date field has no default value and I created another boolean field that controls whether the date field is displayed or not using the conditional fields module.

The boolean field has two values, TRUE = « I know the date of my event ».
FALSE = « I will pick a date later »
The field is set to TRUE « I know the date of my event » by default.
If the user picks False « I don't know the date of my event yet », then the date field is hidden and no value is input.

The problems i'm facing are :
When displaying the event as a node and when listing all the events in a view :

If the user knows and inputs the date of the event :
- How to only display the date and hide the TRUE/I know the date of my event label/value of the boolean field

If the user chooses to pick a date later :
- How to display a « Date to Be Determined » message and hide the empty date field.

If you have ideas or a better way to handle this, you're welcome

Hope youre feeling better! You should be able to achieve this by:

exclude the Date field from view.
in the Later Date field, under "rewrite results" check "Rewrite the output of this field. at the bottom of that fieldset expand Replacement patterns to see all the tokens available.  You should see somethine like [Date] to indicate the content from the Date field. Enter that into your text.
In the "no results behavior" section, enter "Date to Be Determined" in the "No results text" box. check Count the number 0 as empty (so when the box isn't checked it will show your "Later" message) and check "Hide rewriting if empty"
Save view and refresh caches


How to render field HTML from tpl file I am trying to create a custom field widget and change the HTML of the field through a .tpl file or a theme function. The idea is my field will store some integer value (it will be updated by another form) and show the value in the from of a progresbar. My question is how can I change the HTML of the field. Same question is asked here also. Please help if anyone have any clue.

After a long research I got the answer how to do this.

/**
 * Implements hook_theme().
 */
function mymodule_theme() {

return array(
'my_field' => array(
  'render element' => 'element',
  //  'template' => 'field--field-progress',
  //  'variables' => array('element' => NULL, 'field' => NULL),
   ),
  );
 }

Than render the field as below_

function theme_progressbar_field($vars){
  $element = $vars['element'];
  $output = '';
  $output .= '
';
  $output .=' ';
  $output .='
';
  $output .=''.$element['myfield']['#value'].'%     ';
  $output .='
';
  $output .='
';
  $output .='

';
  $output .='
';
  $output .='' ;
  $output .= '
';
  return $output;
}