How to create a single page using Drupal Commerce containing product, billing infor payment method? I'm trying to create a donation form as product, but I want the billing information/Account Information form and Payment method options to be in a single page together instead of having them on a different process page.

Is this possible?

Is there a way to configure this in Drupal Commerce or is there a programmatic way to do this?

The checkout flow uses panes, and there is nothing hindering you to put all of the panes in a single page and skip the review page if you wanted to. This can be setup in the checkout settings with a simple drag and drop interface. Should be fairly simple to setup the way you want to out of the box.


How to sell digital goods (redeem codes) using Drupal? I'm considering Drupal as a platform for a web project I'm working on.
I'm looking for a way to sell redeem codes using UberCart, Drupal Commerce or some other module.

The client will be able to buy a single code or several codes and receive it/them by email.

Redeem code format : 201504[variable_value],  eg : 201504846, 201504965, 201504347...

Any ideas on how to manage this? Will every code be considered as a product (unique SKU)?

I need to be able to import the codes into the Drupal store. How will I be able to achieve this? I buy the codes in bulk and get them in an Excel spreadsheet.

There's a UC solution called UC Product Keys out there for this particular use case, but you're better off avoiding it; the project has no 7.x version and is minimally maintained.

The Drupal Commerce equivalent is Commerce Product Key...

  This module lets sites implementing the Commerce module, attach
  product keys to orders. Product keys / Vouchers are strings of text
  that are used to unlock or activate a piece of software.

  Right now we have an entity that can be attached to a product and then
  assigned via a rule to a product once it has been bought. The required
  actions and rules events are fleshed out and simply require the wiring
  up of the rules to meet you scenario.

It probably won't do everything you need (e.g. import license keys), but it should be a good starting point to build your own product key solution off of.


After restoring, incorrect database credentials are used I am trying to get a local drupal environment up and running using an sql dump from a production environment. I am attempting to follow instructions from drupal's documentation.

So far, from our production server, I went ahead and ran drush sql-dump > prod_drupal_backup.sql. Then, I used scp to pull the prod_drupal_backup.sql file from the production server.

On my local machine, using MAMP, I created a database (prod_drupal, same as the database on the production server) and gave a user, admin, access to the database. I went ahead and pulled down the codebase and created a fresh Drupal instance. During this set up, I gave Drupal the admin credentials to connect to the database and had a fresh site up and running.

With a backup, I was ready to restore the database using the prod_drupal_backup.sql SQL dump file. So I went and ran /Applications/MAMP/Library/bin/mysql -uroot prod_drupal < ~/Desktop/db_backup.sql. After this completed, I checked the database via MAMP's localhost:8888/phpmyadmin. The prod_drupal database had the correct data in it. So then I went to the website (localhost:8888) and saw what I wanted, the login screen with all of our styling and everything. When I logged in using one of the accounts registered for the site, it thrown the The website encountered an unexpected error. Please try again later. error.

When I look at my MAMP sql error logs in mysql_error.log, I see errors like access denied for user 'mikesmith@localhost'. This makes zero sense because Drupal is supposed to be connecting to the database with admin, not mikesmith. The way Drupal is trying to connect to the database doesn't match what's in the settings.php file.

What am I doing wrong?

I am using MAMP Pro 5.5.1 and PHP 7.2.21, if this makes any difference.

Some possible solutions / debugging steps:

Check that your local settings.php file is correct by using drush status command.
 Do this when in the same directory as the settings.php file (or with a correctly set up site alias).  You should see information about the database and drupal version.  If you don't then something is wrong with your settings.

Next, Drupal uses the DB to cache things in the DB.  This cached information in an SQL dump can cause a local site to crash.  Some ways to possible ways to correct this are:

On the local site, try using the drush cc (assumed D7 per tag) on the command line.

(OR)

Prior to making the dump from production, clear cache (either via admin screen or drush cc).

(OR)

Remove the contents of any Cache_* table on the local site (keep the tables)

Another possibility is that the password encryption salt string is different between the sites. This is set in the settings.php file and should be the same on both sites.

Finally, you can always reset the local user password via drush.  Two useful drush commands are:

drush uli --name=xxx  (Gets a password reset URL.. may need to put the correct host name)
drush upwd [username] [new-password]


Unset a SQL condition with query builder I try to remove a where condition to a query statement. To resume, I build a query and add geographical coordinates condition to get POI in a specific area. I execute the query and if there is no result, I remove the condition to get all the POI. Here the script :

//Declare the statement
$statement = $this->connection->select('table', 't')
            ->fields(/*...*/)
            ->range(/*...*/);

//Add the condition
$statement->condition("lat", [$GPSbounds['lat_min'], $GPSbounds['lat_max']], "BETWEEN");
$statement->condition("lng", [$GPSbounds['lng_min'], $GPSbounds['lng_max']], "BETWEEN");

// launch the SQL query
$statementInterface = $statement->execute(); // Execute the statement
$results = $statementInterface->fetchAll(\PDO::FETCH_OBJ); // Get all the results

So, if there is no result, I do this :

if (sizeof($results) == 0) {

    //We remove the bounds conditions
    //=& is reference equality, changes applicated to $conditions are applicated to $statement->conditions();
    $where =& $statement->conditions();
    foreach ($statement->conditions() as $index => $condition) {
        if (array_key_exists('field', $condition)) {
            if ($condition['field'] == 'lat' || $condition['field'] == 'lng') {
                unset($where[$index]);
            }
        }
     }

     //dump $statement->conditions() : condition is removed
     $statementInterface = $statement->execute(); // Execute the statement
     //dump $statementInterface->getQueryString() : condition is in the query so the result are empty again (as the first execution)
     $results = $statementInterface->fetchAll(\PDO::FETCH_OBJ); // Get all the results
}

If I do a var_dump() of $statement->conditions() before execute(), the condition has been removed (not in the array). But after the execute(), if I dump the query string, the condition is present and the query result 0 result again (because of the condition restriction). What can I do ?

Executing the same query builder object twice is not supported.

Instead, build the query with everything except the the two conditions, clone it, add the two conditions, if you have nothing, execute the original (or the clone, depending on which object you picked to execute first).


need to print current row position number in block for most popular article I created a view mode named "small-sidebar" and here I need to print current row position number in this block...

I'm using this code :

        <?php echo $content['small_image']; ?>

        <?php echo $label; ?>

      <?php echo $content['title']; ?>

        <?php  echo $content['read_more_link']; ?>

    <?php render($node); ?>

but it not show the current position

in the div class lebel-no I need to print the current position

You can do this in two steps below,
STEP : 1
Add the views result counter under the fields option
Ex:
Fields
Global: View result counter
Content: Title
Content: Body

STEP : 2
If you want to theme it in your own way add the following tpl.php file in your theme folder,
views-view-field--custom-view-theming--counter.tpl.php
I have added the following html to theme it like a tab
<span style="margin-bottom: 20px;padding: 5px;border-radius: 3px;background: #479ED2;color:#fff;">
    View result counter:<?php print $output; ?>
</span>

Thats all about bringing a view counter in your block.


How to edit CCK form? How I change node edit form, which created by CCK module?

Now if the form is submitted, CCK update some field in mysql database. I need to change this, because in one form input contains three values, and this values need to be recorded in three fields in databse. How can I do this?

Jimmy Ko said, that I can retrieve the submitted value in $form_state['#values'], but I don’t know in what .php file I can do this?

For achieving this goal you have to implement hook_nodeapi

In presave operation you can get desired value.

Example code you can get from the D6 release of the Examples for Developers module.


dependent dropdowns via #ajax for unlimited option I have a commerce Product content type, which has a field collection field attached to it field_mycollection, which has 4 different fields field1, field2, field3 and field4 dependent on each other. Like field2 will be filled based on field1 selected, field3 will be filled based on field2 selected and field4 is dependent on field3. #ajax is used for this.

My Content
|_ field_mycollection
   |_ field_field1
   |_ field_field2
   |_ field_field3
   |_ field_field4

It is working fine for me for one set of field collection. But I have unlimited option enabled for field collection. It is not working for that.

How could I achieve this goal? I did it using hook_form_FORM_ID_alter().

How to manage edit form ?

My code is :

foreach ($form['field_part_details']['und'] as $key => $fc_mycollection) {
  if (is_numeric($key)) {
    $options_first = custom_get_first_dropdown_options();
    $year = isset($form_state['values']['field_part_details']['und'][$key]['field_year']['und'][$key]['tid']) ? $form_state['values']['field_part_details']['und'][$key]['field_year']['und'][$key]['tid'] : key($options_first);
    $make = isset($form_state['values']['field_part_details']['und'][$key]['field_make']['und'][$key]['tid']) ? $form_state['values']['field_part_details']['und'][$key]['field_make']['und'][$key]['tid'] : '';

    $html_id_first = drupal_html_id('dropdown-first-replace');
    $form['field_part_details']['und'][$key]['field_year']['und']['#ajax'] = array(
      'callback' => 'custom_dependent_dropdown_callback_year',
      'wrapper' => $html_id_first,
    );

    $form['field_part_details']['und'][$key]['field_make']['und']['#options'] = get_second_dropdown_options($year, 'year');
    $form['field_part_details']['und'][$key]['field_model']['und']['#options'] = get_second_dropdown_options($make, 'make');
    $form['field_part_details']['und'][$key]['field_make']['und']['#prefix'] = '
';
    $form['field_part_details']['und'][$key]['field_make']['und']['#suffix'] = '
';

  }
}

Callback Code is :

function custom_dependent_dropdown_callback_year($form, $form_state) {
  return $form['field_part_details']['und'][0]['field_make'];
}

Any help is appreciated.

Use drupal_html_id() to generate unique ids. That is:

$html_id_first = drupal_html_id('dropdown-first-replace');
$form['field_mycollection']['und'][$key]['field_field1']['und']['#ajax'] = array(
  'callback' => 'custom_dependent_dropdown_callback_year',
  'wrapper' => $html_id_first,
);
...
$form['field_mycollection']['und'][$key]['field_make']['und']['#prefix'] = '
';
$form['field_mycollection']['und'][$key]['field_make']['und']['#suffix'] = '
';


Restrict taxonomy terms when users edit content? I've implemented my site's structure by creating a taxonomy for "areas" and making a term for each area I want in my site (guest info, newbie, facilities, news, and admin). I've let the main menu show these terms as menu items, so that each item shows the content of the corresponding area. When I add content, I specify which area it's for, and this works quite well.

Now, though, I would like to introduce a content type for users to create (for a "user-to-user" area) and I want to hard-code this content type to a specific taxonomy term.

If I leave out the field for this taxonomy, no term will be assigned. :-/
If I include the field for this taxonomy, the user can choose a term (and put the page in any area). :-/
It doesn't look like term assignment is something that can be done with Actions and Triggers. :-/

Is there perhaps a module that provides control over what terms are available for a given situation (user/role/content type)? I've googled, but all I can find is acces control modules for users and nodes, not taxonomy terms.

Edit: To be clear, I'd like to EITHER programmatically set a particular term of a particular vocabulary every time a user of a particular role saves a node of a particular type (but without me having to do PHP programming); OR allow users of a particular role access to only a subset of a particular vocabulary.

Help! :-)

Taxonomy Access Control will let you set up the permissions at the term level.

  Access control for user roles based on taxonomy categories
  (vocabulary, terms).

  Automatically controls access to nodes (based on their taxonomy
  terms).
  Configuration page for each user role.
  Three node access permission types: View, Update, Delete.
  Two term access types: View tag, Add tag.


Drupal calendar issues I am having an issue with completing my event calendar. Everything is in place but the header is all jacked up. For every month, it gives the header as August 1, 2014, September 1, 2014. It is VERY frustrating. I went through everything (the calendar View) and some of the PHP but cannot find anywhere the issue!

Does anyone know how to fix this? I tried looking online and I cannot seem to find the solution anywhere! I even went into the settings for time/date and could not find a single thing.

I want to say that the current date is August 22. I could see if it was August 1 for it to display like that but it is not! I would like it to say AUGUST 2014 or just simply August! Not the WHOLE date typed out.

weekly view:

looks fine!

So if anyone out there can please help me fix this issue, I would so much appreciate it! I have been playing around for hours and to no avail! It must be something simple, right?

Thank you!

Here's the fix, the reference to it is here : click on this link and scroll down to item #20 : drupal.org/node/2294973 , however its pasted below just in case that link becomes broken...

Quick workaround for people unable to apply the patch:

STEP 1: Edit date_views/theme/theme.inc and go find line 165.

Change these two lines:

$format_with_year = variable_get('date_views_' . $granularity . 'format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . 'format_without_year', 'l, F j');

To these two lines:

$format_with_year = variable_get('date_views_' . $granularity . '_format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . '_format_without_year', 'l, F j');

Note: the only difference is one underscore character added to each line.

Upload the changed file back to your web server.

STEP 2: Go to (YOUR_WEBSITE)/admin/config/regional/date-time/date-views and click Save. If you get permissions errors, try clearing caches.


How can I print a field from a referenced entity in my theme? I'm trying to print a field from an entity reference field - but I don't have a clue how to do it!

A bit of background: I've got two content types - master and variation. Variation includes an entity reference field, pulling in fields from the referenced master. But they share an image field. When the variation's image field is empty, I need the master's to display in its place. On the other hand, if the variation's image-field is in use, the masters needs to be hidden. My first thought was to use a display mode, but as you can see I need a little more flexibility than that.

So the details.

A dpm($node) on a variation node gives me:

... (Object) stdClass

field_master_reference (Array, 1 element)

--und (Array, 1 element)

----0 (Array, 3 elements)

------target_id (String, 2 characters ) 11

------entity (Object) stdClass

--------(list of lots of strings which I'll leave out for concision)

--------field_country (Array, 1 element)

--------field_publisher (Array, 1 element)

--------field_catalog (Array, 1 element)

--------field_main_image (Array, 1 element)

----------und (Array, 1 element)

------------0 (Array, 13 elements)

--------------fid (String, 2 characters ) 10

--------------alt (String, 0 characters )

--------------title (String, 0 characters )

--------------width (String, 3 characters ) 518

--------------height (String, 3 characters ) 360

--------------uid (String, 1 characters ) 1

--------------filename (String, 21 characters ) testimage99_r1_c1.png

--------------uri (String, 38 characters ) public://masters/testimage99_r1_c1.png

--------------filemime (String, 9 characters ) image/png

--------------filesize (String, 4 characters ) 4627

--------------status (String, 1 characters ) 1

--------------timestamp (String, 10 characters ) 1366482521

--------------uuid (String, 36 characters ) 67gf4dbb-0a37-4ee9-893e-6g51e3et33c1

------access (Boolean) TRUE

(miscellaneous other fields which I leave out)

I've bolded the relevant structure. From it, how do I print field_main_image (as a fully rendered image)? Sincere thanks to anyone who can help me with something that has perplexed me since Wednesday.

You could do this using either of these:

hook_node_view() in your own custom module
hook_preprocess_node() in your theme template.php

Here's an example of both of these methods. The idea is the same as what rooby suggested earlier but you need to modify the content of the node, not the fields.

Example 1: hook_node_view(), can be used in a custom module.

    // Implements hook_preprocess_node();
    function mycustommodule_node_view($node, $view_mode, $langcode) {

      $field_name = 'field_main_image';

      // Check that the field exists in our node and that it has no content.
      // Alternatively we could check $node->type.
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {

        // Use entity metadata wrapper to gain easy access to referenced entities.
        // This method is more reliable than digging the field array.
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {

          // Get the referenced node object.
          $master = $node_wrapper->field_master_reference->value();

          // Use field_view_field to get the renderable content of the field.
          // Save this data in $node->content so that node template can output it.
          $node->content[$field_name] = field_view_field('node', $master, $field_name);
        }
      }
    }

Example 2: hook_preprocess_node(), can be used in theme template.php.

    // Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = field_view_field('node', $project, $field_name, array(
          'type' => 'image',
          'settings' => array(
            'image_style' => 'thumbnail',
            'image_link' => 'content',
          ),
        ));
        }
      }
    }


How do I load information for views programmatically? I have a view for a blog page that has the basic fields associated such as title, body, post-date, image, and author. What I need is a way to get access to the fields of the view to show on parts of the site with out creating a page or block. I just need the view to organize my information and will be using jQuery to parse the data.

Sounds like you could use views_get_view_result().

views_get_view_result($name, $display_id = NULL)
Get the result of a view.

Also take a look at this answer for a more complete solution.


Migrate theme settings between multisite installations I have set up a second site on a multisite development instance of Drupal 7. We're using a subtheme based on Adaptive Themes. Being that plans call for about a dozen sibling sites, I would like to copy this over theme settings from the first site to each subsequent sibling sites.

What tools would be recommended for this arena?

Someone suggested using Features. However, of the options I don't see a way to package up theme settings.

So far what I've been able to figure out, the answer is -- it depends. It depends on what you're moving between installations.

Features module has worked best for me to move configuration settings or for modules (and their dependents). Sometimes, you'll have to include the strong arm values inside the Feature export.

For user content, it's best to use Migrate (or Backup and Migrate).


Prevent replacing  with I am using Bootstrap 3 subtheme (7.x-3.1-beta2 ) on Drupal 7 for the administrative backend. It seems that the Bootstrap base theme replaces <input type="submit"> with a <button> element. That breaks the layout of the views backend.

I tried to change this by:

copying button.func.php into the subtheme
renaming the function according to the subtheme name
modifying the output to return <input> instead of <button>

Code in button.func.php

<?php
function bootstrap_subtheme_adl_admin_button($variables) {
  $element = $variables['element'];
  $value = $element['#value'];
   if (!empty($element['#icon'])) {
     if ($element['#icon_position'] === 'before') {
       $value = $element['#icon'] . ' ' . $value;
     }
   elseif ($element['#icon_position'] === 'after') {
     $value .= ' ' . $element['#icon'];
    }
  }

return '<input' . drupal_attributes($element['#attributes']) . '>\n';
}

However, this does not have any visible effect.
Any advise?

If I'm reading the question directly, you've copied button.func.php into your sub-theme, modified the code inside it, and then tried to see if your changes work?

If that's what you did, the problem is that Drupal never sees the code. Fortunately (if that is the problem) the solution is simple: copy the code from that file into your sub-theme's template.php file and make whatever changes are required. Be sure the function is correctly named (i.e. to override theme_button, you'd need themename + button = themename_button()). In your example above, your sub-theme would have to be named 'bootstrap_subtheme_adl_admin' in order for your function to be called even if the code is in the correct file.

Incidentally, the reason the button.func.php file works in the base Bootstrap theme appears to be the theme's registry.inc file.

Basic sub-theme how-to with Bootstrap

Download Bootstrap sub theme into /sites/all/themes; don't bother to enable the theme
Copy bootstrap_subtheme from the /sites/all/themes/bootstrap/bootstrap_subtheme to /sites/all/themes/bootstrap_subtheme
Move /sites/all/themes/bootstrap_subtheme/bootstrap_subtheme.info.starterkit to /sites/all/themes/bootstrap_subtheme/bootstrap_subtheme.info
Enable bootstrap_subtheme

Overriding a theme function implemented by a parent theme

Set up parent and subtheme as described above
Never edit the parent theme in any way
Copy the theme function you want to modify from e.g. /sites/all/themes/bootstrap/theme/system/button.func.php into the file at /sites/all/themes/bootstrap_subtheme/template.php
Change the name of the function in /sites/all/themes/bootstrap_subtheme/template.php from bootstrap_button to bootstrap_subtheme_button


Good and basic solution for search page I'm starting in on drupal search engine and I am looking to create a search page. First I would like the search is on very specific fields of some content types. What can be done with the basic module "Search" Drupal and "Views"?

Here is a draw of the search page I would like :

Filter 1,2, 3 are checkboxes to filter on content-type after the search.

I have no idea where to start :(.

---------- I add some explanations

I installed the module and SearchAPI followed a tutorial at: http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages

This module is very powerful to index only the fields you want, thank you for this discovery. Being an intern student, I am not allowed to release details on what the project, but I'll offer you a similar example.

We have 5 different types of content: car, motorcycle, boat, Helicopter and plane. Each type has common fields and fields of its own.

Car: Name, Brand, Fuel, Transmission
Moto: Name, Brand, Fuel, Transmission, Max Speed
Boat: Name, Brand, Fuel, GPS
Helicopter: Name, Brand, Fuel, Number of propellers
Plane: Name, Brand, Fuel, Number of reactors

I want to index Name, Brand, Transmission, Number of propellers, and number of reactors. (I think it's doable quite easily with SearchAPI)

On the drawing on the filter tabs, I would like three tabs: Car, Motorcycle and Other which includes: Boat, Helicopter and Airplane.

By default, the validation of the text field reloads the page, such as a GET or POST form. It reload returns the results for the 5 types of content, so the 3 tabs are checked by default. After reloading, the user can check and uncheck the tabs to filter results by content type (Ajax or simple JS filter on CSS class, I do not know yet).

Another difficulty, my project manager wants the search results are like this:

Title of the node

Field corresponding to the search results. (Can be Name, Brand, Transmission, Number of propellers, or number of reactors)

I hope to enlighten you about my problem. I do not want a ready-made solution, but how to achieve it. Is it doable in the first place ...

You are correct. You could perfectly accomplish this with Views. A simple guide, just for illustration purposes, since we don't have the specifics in your question:

Create a View
In the FILTER CRITERIA section, add the desired filters (make sure to check the "Expose this filter to visitors..." checkbox) by doing that, you are indicating that you want it to be visible in the search page, so your users can change them.
In the OTHER area, mark "Use ajax" as "Yes" to submit the form asynchronously.
In the EXPOSED FORM area, go to "Exposed Form Style" > "Settings" and check the
"Autosubmit" checkbox (if you wish to automatically submit the form once an element is changed).

Additionally, you could use the Better Exposed Filters module for advanced cool stuff (E.g. hiding the "Send" button, showing filters as checkboxes, etc).


Prevent node from being saved So, this seems like a rather simple task but I've been stuck on it for a while.

I need either in hook_node_presave or in hook_node_submit (but NOT in hook_node_validate) to check for a field value in a node and according to that value choose whether or not to cancel the node saving procedure.

How do I do that? (The canceling part, not the checking part ;) )

I've found that the best way is to just thrown an error during presave. Here's a simple example:

function mymodule_node_presave($node){
  if(empty($node->title)){
    throw new Exception('Error saving node: Title cannot be empty');
  }
}

The node_save() function has a try...catch block wrapping the presave step that will catch the exception.

The advantage of this over drupal_goto() is that, if you're importing multiple nodes, it will skip the current node and proceeed to the next one. This is great if you're using something like the Feeds module. In contrast drupal_goto() will exit immediately and may interfere with other steps in the request or cron, which will break importing multiple nodes.


Drupal 7 Form AJAX button to return javascript script I am trying to create a form that allows a user to type in an address and click submit. In return the button makes an AJAX callback that builds the javascript link for a user to copy and paste into their site. Once a user inserts the javascript into their site it will display a map from my site. The problem I am having is when the user creates their custom map using my form I want to return a sample map of what it should look like. I need this javascript to be printed to the browser.

But when it is returned nothing is displayed. Here is my form & callback function.

function d3vo_widget_builder_form($form, &$form_state) {
    $form['city'] = array(
      '#title' =>   t('City'),
      '#type' =>    'textfield',
      '#required' => TRUE,
      '#description' => t('Find your city'),
    );

    $form['height'] = array(
      '#title' =>   t('Widget Height'),
      '#type' =>    'textfield',
      '#size' => 5,
      '#description' => t('Set the widget height'),
      '#element_validate' => array('_validate_field_is_numeric'),
    );

    $form['map-area'] = array(
      '#type' => 'markup',
      '#prefix' => '
',
      '#suffix' => '
',
      );

    $form['submit'] = array(
      '#type' =>    'button',
      '#value' =>   'Get Widget',
      '#ajax' => array(
        'callback' => 'd3vo_widget_map_ajax_callback',
        'wrapper' => 'mapsample-div',
        'method' => 'html',
        'effect' => 'fade',
        //'progress' => array('type' => 'none'),
    ),
    );

    return $form;

function d3vo_widget_map_ajax_callback($form, $form_state){
       $point = geocoder('google',$form_state['values']['city']);
       $lng = $point->coords[0];
       $lat = $point->coords[1];
       if($form_state['values']['height'] == NULL){
           $height = 500;
       } else {
       $height = $form_state['values']['height'];
       }
       $widgetScript = '';

        $form['script'] = array(
         '#value' => $widgetScript,
         '#type' => 'textfield',
         '#attributes' => array('readonly' => 'readonly'),
         );

        $form['map'] = array(
          '#type' => 'markup',
          '#markup' => $widgetScript,
        );

        return array($form['script'], $form['map']);
    }

Im not very familiar with using Javascript in Drupal. I have searched and tried many different ways but I can not get the map area to show. Any help would be greatly appreciated.

The AJAX callback is only used to tell Drupal's AJAX engine what part of form to update. All actual work of building the form elements is supposed to happen in form's hook, in code wrapped in a control statement like the following.

if (!empty($form_state['values'])) {
  // ...
}


Load webform submission How can I load a webform submission programmatically ?

I've tried : $webform_submission = WebformSubmission::load($sid);

but it return null.

I do this in a custom module call by an handler after webform submission.

I think you have to load sid like below

// Load submission using sid.
/** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);


Taxonomy hierarchy in filter block of views isotope? How can I set the filter block to show a hierarchical taxonomy? As far as I can see there is only a flat list being built by default. How can I change this and apply the hierarchy of a taxonomy?

This is the link of the module, of course do not answer if you do not know what is views isotope Module.

First, I'm confused about what you mean by views isotope?

But if you're asking to build a hierarchical taxonomy in view select, there's Simple hierarchical select module.

  Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.


Form #after_build is not working for PHP 7x I'm using #after_build in one of my custom module form like follows

  $form['profile_image'] = array (
    '#type' => 'managed_file',
     '#after_build' => array("change_pic"),
  );

and the function is

function change_pic($element, &$form_state, $form) {
  if($form_state['values']['profile_image']['fid'] != 0){
    // my code goes here..
    return $element;
  }
}

It's working fine in PHP 5x version. but throws the following error in PHP 7x version.

  ArgumentCountError: Too few arguments to function change_pic(), 2 passed
  How can we handle this in PHP 7?

Any inputs would be helpful.

There are only 2 args to an after build method, the element and the form state.

Just remove the extra one and it’ll work:

function change_pic($element, &$form_state)


How to render a block provided by a contrib module in a node template I installed Better Social Sharing Buttons and I can not understand how to programmatically display the block of this module in node.html.twig. I display the blocks created by me like this:

function MYTHEME_preprocess_node(&$variables) {
  $block_entity = Drupal\block_content\Entity\BlockContent::load(6);
  $block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'foo bar');
  $variables['MyCustomBlock'] = $block_view;
}

and then {{ MyCustomBlock }} in node.html.twig.

How to display the block created by the Better Social Sharing Buttons module?

Go for Twig Tweak.

  Twig Tweak is a small module which provides a Twig extension with some
  useful functions and filters that can improve development experience.

Then it's just

{{ drupal_block('better_social_sharing_buttons_block') }}

Read the docs about Rendering blocks with Twig Tweak.

  This subject is rather confusing because too many things in Drupal are
  referred to as "Blocks". So it is essential to understand what kind of
  block you are going to render. This guide covers three main cases you
  may deal when rendering blocks in a Twig template.


How to handle DB updates when my Drupal source is in git? I've put my Drupal installation in Git so that it is easier to replicate the production site on my development system.  Then I discovered drush and I think it's way cool.  But then it occurred to me:  If I use drush on my development box to update a module, then the source code changes will be in git and will end up in production by way of git.

But what about the database changes?  How do I apply those in production?  Is it sufficient to run drush updatedb in production (after using git to transfer the code)?

I'm not sure the version numbers are relevant for this question.  Anyhow, running Drupal 6 currently, planning to upgrade to Drupal 7.

Yes, if you update the files on the production site, all you have to do is to run the update.php or drush updatedb additionally.
For migrating functionality from staging to production site, you might be interested in Features. It allows you to export various "pieces" of functionality and transfer them to another installation; this can include content types, fields, views and image styles, to name a few.

Hope this helps!


Drupal Lightbox2 fails W3C validation because of rel="lightbox[field_image][]" attribute I am using the latest Lightbox2 module for Drupal which works great but for my field images it adds a rel="lightbox[field_image][]" which fails W3C validation.

Is there a way to work around this so it passes validation? I have been reading somewhere to change the "rel" to "data-rel", but how would you apply this? Any ideas?

You can copy the lightbox2-insert-image.tpl.php file into your own theme and change it there - but this will break the functionality of the module as javascript uses rel attribute multiple times.

You could refactor the javascript, change all occurrences where it accesses rel and change it to data-rel and create patch and submit it to drupal.org to the author of the issue as a request (or just submit issue now requesting this and wait if/until the maintainer does it).

On a personal note - why do you need it to pass W3C validation? Is it a project MUST requirement? If not, I would not waste any time on this as valid HTML is not that important any more, not even for SEO and indexing.

Edit: http://google.com is not passing W3C validation, I think that sends a message. (http://validator.w3.org/check?uri=google.com&charset=%28detect+automatically%29&doctype=Inline&group=0)


Change date format in Advanced Forum I have changed date formats in Views and in Drupal core Date settings, but I'm still seeing wrong date format on forum (for example in node where conversation is) at class .forum-posted-on.

In template file advanced-forum.myforumtemplate.post.tpl.php:

<?php print $date ?>

How to change date format?

You need to alter the date through template_preprocess_node() and template_preprocess_comment() in your theme. The first preprocess is used for the forum nodes (initial forum post) and the latter for comments (replies).

Add the following code to your theme's template.php file:

function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['node']->type=='forum') {
    // Custom date.
    $variables['date'] = format_date($variables['node']->created, 'custom', 'M d Y, H:i:s');
    // Use date format provided by Drupal:
    // $variables['date'] = format_date($variables['node']->created, 'short');
  }
}

function YOUR_THEME_preprocess_comment(&$variables) {
  if ($variables['node']->type=='forum') {
    // Custom date.
    $variables['date'] = format_date($variables['node']->created, 'custom', 'M d Y, H:i:s');
    // Use date format provided by Drupal:
    // $variables['date'] = format_date($variables['node']->created, 'short');
  }
}


How can I sort entity type query results with pseudo values? Is it possible to use the D8 EntityQuery condition and sort functionality to filter/sort based on the outcome of multiple fields (and possible external/3th party value) calculations?

Example with condition:

I want to filter the results based on the average of 5 numeric fields.
So i need to add them up and divide them by 5 and if that outcome < 8 i do not want to use the entity.

Example sort with external API value:

I want to sort the results based on a calculation with an external API value.
So lets say i have a numeric field in my entity with the value of 10. The external API gives me a value of 30. The calculation would be 30 - 10 = 20.

Now for my second entity the numeric field value equals 5 and the API sais 20. The calculation would be 20-5=15.

Now i want to sort the results from highest to lowest. So in this case the first entity should be first because the outcome of the calculation was 20 and for the second entity it was 15 so it should come second.

Some thoughts...

You should be able to do aggregation in your queries; try looking at QueryAggregateInterface and ConditionAggregateInterface. However this interface does seem to be pretty simple. The Views plugin implements full 'having' and 'group by' functionality, but probably in a way that's difficult to access outside views.

You might investigate using the Symfony Doctrine class or plain PDO to do it the 'old way'.

I am pretty sure you won't be able to calculate based on an external API; the database needs all the values to hand, either in a table or as query-provided data. Some databases do support advanced functionality like REST queries, but any code doing this won't be portable and so won't be available as standard in the Drupal interfaces.

You could possibly do the API lookups in advance (in e.g. php) and then pass them to a temporary table for the DB to check.


Allow user to filter View by Month only using a D/M/Y date field I have a simple date (birthday) field in my View, and I have added that field as an exposed filter. I want to be able to filter by just the month, so that the View can return a list of users whose birthdays are in the month of July, for example. Currently, the exposed filter also requires that I choose a year, which makes the filter un-usable. How can I filer based on just the month and nothing else?

Thanks!

You can use Computed field and create other field on your content type, there Month will stored (calculated as PHP code: return date('m', {Date Field Value});, so you can easily filter by months in Views by this field...


Having two types of view for one path I need a view for taxonomy terms that shows both any child terms as links and a table of product nodes tagged with the term, but I can only work out how to apply one or the other.

Any help appreciated!

edit for clarity: For the path taxonomy/term/%, I need to show the child terms of parent terms, or for a child term a table of all products (nodes) that are associated with that term. I have assumed it would be easiest to combine these two into one view somehow.

By the sounds of it are you trying to display two different views on one page? if so have a look at panels, or you can do it manually by loading the views pragmatically in the template.
if not, please clarify.


skip processing html and page From a module, I want to output "hello world" simply as a string as efficiently as possible when i call /mymodule/helloworld.

ofcourse, using hook_preprocess_html and hook_preprocess_page i can assign nearly empty templates. the html template should contain <?php print $page; ?> and the page template <?php print render($page['content']); ?>, and the content could be the string 'hello world'.

however, drupal will still go through all the processes of generating $css in html or $page['sidebar_first'] in the page. Even if I override template_process_html it seems $variables['page']['page_top'] has already been populated.

How can I skip all the content processing and go straight for the output ?

[EDIT] had some usefull comments here, but still not what I want. I forgot to mention, I do want to use a template to print 'hello world'. So as I can override it in a theme, for example.

Yes, I can change the delivery callback (either in hook_menu or in
hook_page_delivery_callback_alter), but what the callback method
receives is a render array. I do want to use a node template to render
the content as html. I'd have to write my own delivery callback, I guess
Yes, I can print out the html and call drupal_exit(), but then I wouldnt have
the luxury of using a node template either

So, still looking.

*-pike

based on comments above and my own edits, i came up with this

function my_page_callback() {
    $output =  array(
        'template' => array(
            'data'      => array('dummy'=>true),
            '#theme'    => 'my_theme'
        )
    );
    print drupal_render($output);
    drupal_exit();
}

that goes straight for the beef: print the output. it does however use the templating system to create that output. it does not, i think, do all the preprocessing that would otherwise happen.


Are configurations written and read directly to/from .yaml files or still to the database? Background

Drupal 7 and previous versions have attracted criticism for Drupal web site admin configuration being stored in the MySQL database, the criticism being that being in a database means that it cannot be directly managed in git together with the PHP code based development for a Drupal site (custom modules, themes etc.).

Secondly with configuration being in the database along with content, transporting configuration between development, test, staging and live servers as part of development activity is complicated, though Features module (and related) can help.

Reading through:
https://www.drupal.org/documentation/administer/config

...I'm getting the impression that, in Drupal 8, the database is still used to store the config, when for example a site builder creates a new content type, rather than this being written to a .yaml file which is used directly.

So actually it seems that the role of the yaml file(s) is a much more purer (than Features) vehicle for the configuration. Whereas with Features it was PHP code which was harder to read what the configuration was, including if doing diffs between commits where config had been updated resulting in a new version of the Features-based config export. By that I mean not that PHP itself is hard to read, as I'm familiar enough with it, having written custom modules, hooks, themes. What I mean is that to express a configuration in PHP is perhaps not the most legible way to do it. So I can see the rationale of using yaml. The difference is that yaml will be read by a parser to apply a config. The complexity of applying the config is in the parser, which most folks need not concern themselves with most of the time, so the yaml can more cleanly describe the config. whereas in Features, there is no parser / yaml (or other script) separation. The descripton of the config and the means to apply it are necessarily in the same place as PHP code which is executed directly, so it's bound to be a bit harder to read the config, particularly if doing git commit diffs.

So there's the rationale for yaml, a Declarative Programming approach to storing configuration management in Git, contrasted with Features which is an Imperative Programming approach. And next what I need to know is this the case that Drupal 8 does still store config in the database does still and yaml files are the means for transporting config (replacing what Features did in D7 and before)?

(By the way I am a big fan of Drupal and spend most of my time at work, working with it for the sites that my organisation produces and maintained and am also involved in the community. So this question is not a stealth campaign against Drupal in favour of other platforms. It is a genuine question to try to dispel the apparent mystique around Drupal 8 and the new config management system)

Update
@Berdir's answer (accepted) is a great definitive summary as to the state of Drupal 8 regarding configuration management.

I recently discovered that using yaml for config in Drupal 8 is a concept that has been developed for Drupal 7 with the Patterns module, also read a FAQ on it which includes comparing features.

Update

Change default active config from file storage to DB storage Is a definitive answer about making config active from DB storage, which corroborates with @Berdir's answer.

Yes and no. (I am not sure if this will be too technical).

The configuration is stored in configuration objects. Drupal has by default an active and a staging storage for those configuration objects.

The default active storage is in the database, yes, for performance and easier backup/restore, among other reasons. But that is an implementation detail. It used to be read directly from files, but that was pretty slow, even with caching.

The staging storage is yaml files in the staging folder in your file system. Those are the files you manage in git.

You can export to staging and import again from staging through the click of a button in the UI or with drush. Unlike Features in Drupal 7, which uses custom processing to transform configuration between feature files and the actual drupal site, the configuration object structure is always the same. Serialized to yaml for the file storage, as serialized php arrays in the database storage. Drupal does not care (for the most part, but that is too technical). If you want to, you could write a configuration storage that stores it encoded in pictures, as long as Drupal can get the standardized array structure out of it again that it put into the storage.

So, yes, the configuration is by default still stored in the database, but not in the way you were used to in Drupal 7.


CKEditor crashes when switching text format for specific content types drupal 7.38

wysiwyg 7.x-2.2+63-dev

CKEditor 4.5.1.a513a92

If I create an article, switch text formats, everything is fine.

If I create a basic page, switch text formats, the ckeditor toolbar crashes and none of the buttons are clickable.

The crash also occurs if I create a new content type.

Here is a copy of the console log:

  Uncaught TypeError: Cannot read property 'sas' of undefined
  js_ALIKtebL-PsIulJhUegpZmaxTRnPdAyakIc8kMeoL-4.js:382 Uncaught
  TypeError: Cannot read property 'sas' of
  undefinedDrupal.wysiwyg.plugins.sas.attach @
  js_ALIKtebL-PsIulJhUegpZmaxTRnPdAyakIc8kMeoL-4.js:382(anonymous
  function) @
  js_ALIKtebL-PsIulJhUegpZmaxTRnPdAyakIc8kMeoL-4.js:103CKEDITOR.tools.createClass.proto.setData
  @ ckeditor.js?nstvdm:780(anonymous function) @ ckeditor.js?nstvdm:349j
  @ ckeditor.js?nstvdm:10CKEDITOR.event.CKEDITOR.event.fire @
  ckeditor.js?nstvdm:12CKEDITOR.editor.CKEDITOR.editor.fire @
  ckeditor.js?nstvdm:13CKEDITOR.tools.extend.setData @
  ckeditor.js?nstvdm:251b @ ckeditor.js?nstvdm:775(anonymous function) @
  ckeditor.js?nstvdm:777CKEDITOR.editor.setMode @
  ckeditor.js?nstvdm:328(anonymous function) @ ckeditor.js?nstvdm:323j @
  ckeditor.js?nstvdm:10CKEDITOR.event.CKEDITOR.event.fire @
  ckeditor.js?nstvdm:12CKEDITOR.editor.CKEDITOR.editor.fire @
  ckeditor.js?nstvdm:13CKEDITOR.event.CKEDITOR.event.fireOnce @
  ckeditor.js?nstvdm:12CKEDITOR.editor.CKEDITOR.editor.fireOnce @
  ckeditor.js?nstvdm:13(anonymous function) @
  ckeditor.js?nstvdm:246CKEDITOR.scriptLoader.load.g @
  ckeditor.js?nstvdm:226CKEDITOR.scriptLoader.load @
  ckeditor.js?nstvdm:226(anonymous function) @
  ckeditor.js?nstvdm:245(anonymous function) @
  ckeditor.js?nstvdm:233(anonymous function) @
  ckeditor.js?nstvdm:231CKEDITOR.scriptLoader.load.g @
  ckeditor.js?nstvdm:226CKEDITOR.scriptLoader.load.B @
  ckeditor.js?nstvdm:226CKEDITOR.scriptLoader.load.s @
  ckeditor.js?nstvdm:226(anonymous function) @ ckeditor.js?nstvdm:227

I would "downgrade" to the stable WYSIWYG 7.x-2.2 version of the WYSIWYG module, and to the 3.6.x version of CKEditor (such as CKEditor version 3.6.6.1.7696), since the WYSIWYG module does not support the 4.x version yet ...).

Another option is to switch to the CKeditor module (which is in core in D8 now ...), and no longer use the WYSIWYG module in combination with the CKEditor library.


Access to referencing entity field from referenced entity template in Drupal 8 I'm building a custom block type with referenced nodes, on the "view" of the block type I configured to show the full node instead just links. And I want to access from the node--type.html.twig to some of the fields of the parent block (when the block is rendered). How we can do that?? is there any other good approach to doing this??

When you are inside the children node, you don't see what is around you. The children node is build and cached on its own. The entity reference is a n:m relationship. There can be more than one parent. So from the data modelling there is no easy solution. Better look for a solution from parent to children, not backwards.


Ways to sync outlook calendar? I need to display the outlook calendar in the same calendar format in a page. I need to add events to the calendar and synchronize it with Outlook.

What module should I prefer to both synchronize with Outlook and display as calendar?

Try to use Add to Cal module. I hope this module solve your query.

  A field formatter providing a widget for exporting events to:

  Google Calendar
  Yahoo! Calendar
  iCal
  Outlook

  The field formatter provides a button next to the field that shows a drop-down menu. This
  menu contains links to the supported formats, and includes basic
  styling that can be easily modified through CSS.


Decoupled Drupal - Security: files structure I am running a Drupal 8.9.2 site as a content repository accessed via an Angular 8 app. So there is one administrator who uses the Drupal interface to write content / upload files eccc.... and anonymous users view that content via the Angular app.
I have set up some views with REST Export display and have been able to pull the content in my Angular app running both backend and frontend on localhost, but when I deployed to the server problems have arisen...
all my calls fail or get canceled, this was the configuration on localhost: the Drupal website was in a folder in XAMPP/htdocs/example the views rest endpoints were like: http://localhost/example/web/api/content the Angular app was in a folder on the desktop and was served at http://localhost:4200/home
now I put all the files for both backend and frontend on the root folder on the server, I also have commented this line ErrorDocument 404 /index.php in the htaccess file found in the web folder so that non existent urls are managed by the Angular app.
So the question is: What is the correct files structure in order to have the frontend at example.com/home and my Drupal site at example.com/web/admin/eccc..... (if it is possible, otherwise please suggest a better option).

I solved my problem, the calls were failing due to a wrong version of PHP (you need 7.2 or higher).
As for the files structure I just put all the files in the root folder, both for Drupal and Angular, it works having my Drupal site in the web folder, I don't know for other configurations.


Adding options to View filter settings I want to add new option "Own Company" into "Options" select in View filter settings form:

This is filter of entityreference field.
Also I want to have opportunity alter views query with this value.

I tried with form_alter but I can't save chosen value.

Also I wanted to write own views child class that will handle entityreference filter settings. But I can't find dafault handler in hook_views_data_alter.

Also saw that views filter select in entityreference module is made with ctools plugins system. Filter settings form might be plugable but I can't manage to do it.

Has anybody altered views filter settings form?

1) Add new custom views filter handler that extends views_handler_filter_in_operator

class MY_MODULE_own_company_filter_handler extends views_handler_filter_in_operator {

  public function get_value_options() {
    $options = parent::get_value_options();
    $options['own'] = 'Own Company';
    $this->value_options = $options;

    return $this->value_options;
  }

  /**
   * Replaces "Own Company" value with real value.
   * Do query alter here or in query() function.
   */
  function pre_query() {
    parent::pre_query();

    // Check if "Own Company" was chosen.
    if (!empty($this->value['own'])) {

      // Unset "Own Company" 'own' value.
      unset($this->value['own']);

      // Get current "Own Company" value the way you like.
      $company_id = 100500; // Example value.

      // Set current "Own Company" value.
      $this->value[$company_id] = $company_id;
    }
  }

}

2) Implement hook_views_data_alter() and add custom handler to all entityreference field filters

/**
 * Implements hook_views_data_alter().
 */
function MY_MODULE_views_data_alter(&$data) {
  // Loop all field filters.
  foreach ($data as $data_key => $data_field) {
    if (strpos($data_key, 'field_data_') !== FALSE) {

      // Get field name
      $field_name = str_replace('field_data_', '', $data_key);

      // Check if field filter is entity reference
      if (isset($data_field[$field_name . '_target_id']['filter']['handler'])) {
        if ($data_field[$field_name . '_target_id']['filter']['handler'] == 'views_handler_filter_in_operator') {

          // Name of custom handler class
          $custom = 'MY_MODULE_own_company_filter_handler';
          // Add custom handler
          $data[$data_key][$field_name . '_target_id']['filter']['handler'] = $custom;

        }
      }
    }
  }
}


drupal_http_request with proxy I'm working on proxy based machine where I've configured my proxy settings at settings.php and its working fine.

When I'm trying to access a URL the data is getting displayed perfectly, for instance, https://maps.googleapis.com/maps/api/geocode/json?address=California but when I'm doing the same thing at my devel/php

$maps_url = 'https://maps.googleapis.com/maps/api/geocode/json?address=California';
$maps_json = drupal_http_request($maps_url);
dsm($maps_json);

it's returning me this:

I've confirmed 2 settings in my php.ini:

allow_url_fopen
allow_url_include

Where else should I look so that this issue will get fixed?

Found this module cURL HTTP Request via this thread and it worked like charm. The issue was with HTTPS hence the HTTP proxy module wasn't able to help me on this.


cannot update Drupal core with drush Why can't Drush find the Drupal core module?

root@hostname:/var/www/html/sites/example.org# drush pm-update core

...
Wysiwyg (wysiwyg)                        7.x-2.2         7.x-2.2         Up to date
core                                     Unknown         Unknown         Specified project not found

So then I tried:

root@hostname:/var/www/html/sites/example.org# drush -r /var/www/html -l example.org pm-update core
...
Wysiwyg (wysiwyg)                        7.x-2.2         7.x-2.2         Up to date
core                                     Unknown         Unknown         Specified project not found

I have used both these commands in the past to update other Drupal modules and it has always worked, until I have to update the Drupal core module.  Can Drush not handle this or is this a bug?

To update core on its own try

drush pm-update drupal

A plain

drush pm-update

will update all modules, and then core.

Note that it doesn't backup .htaccess, robots.txt, or any other files that you may have modified.  I have gotten in the habit of doing a full drush archive-dump before core updates, and/or using Backup and Migrate in combination with having everything under git control.


Users logouts from time to time I only want users to logout if they visit the "logout" page. For this I set this in my settings file:

ini_set('session.gc_maxlifetime', 0);
ini_set('session.cookie_lifetime', 0);

But users are still disconnecting from site from time to time and I don't know why.
Is there a better way to tell site to not log out users? What is causing users to be disconnected?

EDIT: I have users that launch site from browser and that launch site through mobile application by rest service(services module). Both types of users are disconnects. I not sure but sometimes when I save some views user is logging out and I recieve message that you have no access.

UPDATE: this part of code ini_set('session.gc_maxlifetime', 0); logs out user. I thought that if it set to 0 it means that user has never been loging out until he not push on logout.

Is there a better way to control user's login sessions? Yes.
There's a great module (beta since 2012, 1,000+ active sites used it as of October 1, 2014): https://www.drupal.org/project/persistent_login
From the module page:

The Persistent Login module provides the familiar "Remember Me" option in the user login
form. Additional security is provided by using two tokens (one long-running, one per
access) that allow the detection of unauthorized token use.
Persistent Login is independent of the PHP session settings and is more secure (and
user-friendly) than simply setting a long PHP session lifetime. For a detailed
discussion of the design and security of Persistent Login, see Improved Persistent Login
Cookie Best Practice.

What is causing the users to be disconnected? Depends.
As Mołot pointed out, there are literally dozens of things that could be happening. For example, we could be talking about multiple browsers, multiple devices, or someone who regularly clears out their cookies and internet history. Most of these situations are out of your control. The standard Drupal session cookie usually keeps me logged in over the course of a day or two without having to re-login. If someone is getting logged off in the same 24 hours span, something is happening.


How to check if an entity bundle has a field? How can I check if a bundle has a field? I know I can use $entity->hasField() if I have a specific entity (as is defined in this post), but how can I get this info with just the entity_type and bundle info?

I'm assuming I could just create an entity of the type and bundle (and never save it), and check against that, but that seems gross.

Woops, this is closely related to Get all fields defined in a bundle, but since that gets all fields, I'll post this.

Use the EntityFieldManager (entity_field.manager) service, specifically the getFieldDefinitions method, to get all field definitions, and then check for your specific field.

function doesBundleHaveField($entity_type = 'node', $bundle = 'page', $field_name = 'field_paragraphs') {
  $all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_type, $bundle);
  return isset($all_bundle_fields[$field_name]);
}


How does Drupal Commerce use the commerce_line_items field? I have been trying for some time to figure out how Drupal Commerce uses the commerce_line_items field.  It looks to me like this is the field that provides the link between  a commerce line item and the order to which it is attached, so that if all you had was the order_id, you wouldn't have to query the entire commerce_line_items table, but could just look at this field.  However, I cannot figure out how or where this field is defined, and where its values are set.  If anybody can get me pointed in the right direction, I will happily write some documentation so that others may understand what is going on.

This answer refers to the Drupal 7 version, but I assume it's similar for D8.

The commerce_line_items field is a field of type commerce_line_item_reference (basically a reference field) that is defined and instantiated inside the function commerce_order_configure_order_type, in the file commerce_order.module.

This field of unlimited cardinality stores references to each of the line items in an order. Think of the line items as basically each of the "lines" in an order or invoice that reference a specific product, its quantity, price, and total price etc.

The values of the commerce_line_items field are initially set in the commerce_cart.module file, inside the commerce_cart_product_add function (basically when you add a product to the cart), in line 1377.

All of this information can be glanced by studying these files.

[EDIT]

I'm not sure I'm understanding where you are going with this question, but given your recent edition, yes, you can access the values of the line items by using, for example, an entity_metadata_wrapper, which will allow you to navigate the relationship to each line item and all its fields and properties. See this tutorial for entity_metadata_wrapper


Block drush rsync command when specific alias is set as destination I already have policy.drush.inc inside my Drupal drush directory at sites/all/drush.  Also, I have a policy set to prevent sql-sync if the @staging alias is set.  Thus,

drush sql-sync @dev @staging

will fail with the output Per sites/all/policy.drush.inc, you may never overwrite the staging database.

This was done with

function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
  if ($destination == '@staging') {
    return drush_set_error('POLICY_DENY', dt('Per sites/all/policy.drush.inc, you may never overwrite the staging database.'));
  }
}

This function is working, and I want to do the same for the rsync command, so basically duplicated the function and replaced sql_sync with core_rsync as in

function drush_policy_core_rsync_validate($source = NULL, $destination = NULL){
  if ($destination == "@staging") {
    return drush_set_error("POLICY_DENY", dt("Per sites/all/policy.drush.inc, you may not sync external files to staging"));
  }
}

However, I still get the 'You will destroy data from $remote and replace with data from $local` warning when executing

drush rsync @dev:%files @staging:%files

How can I block drush rsync from executing and why does this function work for sql-sync but not `core-rsync'?

In the case of rsync, $destination is equal to @staging:%files, which is different than @staging.  drush_sitealias_evaluate_path is not called until after the validate function, and calling it twice would be slow.  You could test to see if $destination is @staging OR if it begins with @staging:.  That should work well enough for your purposes.

If you wanted your policy to depend on values set in your @staging alias, then it would be best to make Drush call drush_sitealias_evaluate_path before the validate function.  That would be a feature request, and should be done by posting an issue (or better yet, a PR) on the Drush project on GitHub.


How can I override the HTML of options on the user edit page so that they do not appear as collapsible fieldsets? In Drupal 7, several modules on the user edit page provide options in collapsible fieldsets (I think this is the right word-- you can click the title above the option and the area containing the option will "collapse" and fold up).

For example,
* timezone (Core)
* whether to receive e-mail notifications upon receipt of messages from other members (privatemsg)
* disable HTML mail (mimemail)

However, I would prefer to have the titles of these options to be regular titles (i.e., even if you click them, they don't collapse; nothing happens).  How can I override this behavior?

I tried the following code based on this question:

function mymodule_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    $form['timezone']['#collapsible'] = FALSE;
}

However, after clearing my cache, the timezone field is still collapsible on the user edit page.

EDIT: I had accidentally called form_user_profile_form_alter twice.  Consolidating the two overrides fixed my problem.

The easier way is to set the #collapsible property to FALSE.
As far as I know, when #collapsible is set to FALSE, #collapsed is not used anymore, which means the fieldsets are shown as visible; if that is not the case, then set also #collapsed to FALSE.

Clearly, this works only for fieldsets; for other form fields, those properties are not used.

As side note, on Drupal 8 collapsible fieldsets are implemented using "details" as form field (at least from the Drupal core code); if you are going to loop through the elements of a form to check for which ones the property should be set, the code should be similar to the following one, for Drupal 8.

foreach (element_children($form) as $id) {
  if (!empty($form[$id]) && ($form[$id]['#type'] == 'details' || $form[$id]['#type'] == 'fieldset')) {
    $form[$id]['#collapsible'] = FALSE;
    $form[$id]['#collapsed'] = FALSE;
  }
}


Allow user A to grant view permission of their node to user B My website users will have the ability to post pictures in a private photo gallery. I would like for those users to be able to grant "view" permissions for their private gallery to other users.

Bob (an authenticated user, not an admin) has a private photo gallery
He wants Dave (another authenticated user, also not an admin) to be able to view his private photo gallery
Bob grants permission to Dave, allowing Dave to view that gallery
Bob can revoke permission from Dave at any time

Is there a module/configuration that will this type of user-controlled granting of permissions?

Thanks!

Perhaps consider using Organic Groups which allow users to create and control groups of users and curate content for them.

There is also Node Access User Reference which is slightly more specific.

Both should work together but I think you will only need one of them for your stated needs.


Multisite setup on local development environment I've been around the block with this one. and I'm back at my front door!

I am trying to setup a multisite configuration on my local dev server, which currently looks like this.
I'm using Xampp in a windows environment so my root is "Xampp\htdocs\"; then any site I'm working on is created under a folder here.

This gives me the follwing Drupal stucture.

  \sites\all\themes\devsite

In my browser, I can go to http://localhost/devsite, and it launches my Drupal site without problems; If I go to http://localhost, I get redirected to XAMPPS installation page.

So now I embark on the multisite config.

First, my hosts file is altered to include these two entries.

127.0.0.1 devsite.com
127.0.0.1 m.devsite.com

Browsing to the following URLs launch my site.

http://devsite.com/devsite
http://m.devsite.com/devsite

I now copy my \devsite\sites\all structure to a \devsite\sites\m.devsite.com folder and setup a \devsite\sites\sites.php file with these entries.

$sites = array(
    'devsite.com' => 'all',
    'm.devsite.com' => 'm.devsite.com',
);

If I browse to either hostname, both load the site configuration which is in All. I can't seem to get it to load anything within m.devsite.com? I've tried copying the settings.php file into each stucture which produces an error message. I've tried renaming All to devsite in folder and sites.php but then I get a blank page when browsing.

Do you have any idea on what is wrong?

Not sure what exactly you want to do.

Multi-site is usually used to create separate drupal installation from the same drupal folder. To create one, you need to copy default/default.settings.php to yoursite.com/settings.php, make it writable and then visit the site, which should present you with the installer.

You only need to something with sites.php if you want to override the default domain mapping and e.g. also server siteB.com from sites/siteA.com. Also, Drupal doesn't search for a settings.php in 'all' but 'default'.

Your naming scheme sounds more like you want a mobile version of your site, which usually just implies that a different theme is used and some other mobile specific things. There are modules which can automatically changing the theme when the site is requested by a mobile browser.


Commerce: query products and product variations I have a view with a custom template and I need to query my products using some conditions. I'm running a videogame store, so I have a Content Type and Production Variation called "Games", and those games have a plataform assigned (Content Type field). So now I'm creating a custom PS3 categorie view and I need to query only PS3 games.

This is what I have currently:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_product')
    ->propertyCondition('status', 1)
    ->propertyCondition('type', 'games')
    ->fieldOrderBy('commerce_price', 'amount', 'ASC');
$result = $query->execute();

That query returns a list of "games", but I need to filter them by plataform.

PS: I don't know if any one can share information about querying products in Commerce. I have to say that Commerce API is very poorly explained.

Commerce Products are entities, so you can query them exactly like any other entity (like you're already doing). You may consider the commerce API docs for entities to be poor, but that's simply because there aren't any - you can apply standard Drupal entity logic.

It seems the only thing you're missing is the platform filter that you mention; that's just a matter of adding a field condition to the EntityFieldQuery:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_product')
  ->propertyCondition('status', 1)
  ->propertyCondition('type', 'games')
  ->fieldCondition('field_platform', 'value', 'PS3')
  ->fieldOrderBy('commerce_price', 'amount', 'ASC');
$result = $query->execute();

Your mileage may vary if field_platform isn't a text field. For example, if it's a taxonomy term reference, you'll need to find the ID of the taxonomy term and use something like

  ->fieldCondition('field_platform', 'tid', 123)

Or if it's an entity reference field you'll need the entity ID and to use something like this

  ->fieldCondition('field_platform', 'target_id', 123)


Behat and custom login pages I'm trying to use Behat and Drupal for BDD, but I'm running into some authentication issues. Simple steps like:

Given I am logged in as a user with the "administrator" role

Fail because I'm using Drupal's CAS module, which essentially customizing the /user/login page. Any idea on how I can get past custom login pages with Behat?

You can test login form in this way:

When I visit 'user/login'
And I fill in "username" for "name"
And I fill in "userpass" for "pass"
And I press the "Log in" button
Then I should see the text "some text"


Custom database connection What is the best way to connect to a remote database through drupal? Would the correct method be to use the settings.php with the database in there, and use the built in db_select, db_query() etc functions to access the remote database?

I have a system that has a bunch of entities, which are different 'servers'. Each server may or may not have a different database for up to 4 different services. Currently, I am storing the database connection details inside of the entity fields, and calling them using entity_load() as needed. In doing this, I am having to write my own SQL library and queries to retrieve data from the external databases.

I am wondering; if instead of writing the values to the entity fields, if I wrote them to maybe an external .php file (maybe dbconfig.php) or something, if there was a way I could still use the built in database functions and methods to access it, or if Drupal only reads from the settings.php for database connections.

I also question if using it on a table that doesn't use the same structure as drupal would even work. (It's a completely different service with it's own tables and structures).

What's the best way to handle this type of situation? I really would like to get away from writing my own library to use for remote connections, as being able to do pagination and all that using the built in methods is extremely helpful and already been tested and hardened.

Just trying to find the best way to get access to the drupal database methods/functions and still be able to update/edit/add new databases when they are needed without risking security, and without having to manually change permissions on the settings.php before making new changes. (The servers currently are automatically added as new entities by scanning a single remote db for new entries then using entity_create() to add them).

Is it possible for me to put an include('databases.settings.php'); inside of settings.php, and use $databases['database_name']['default'] = $info_array; inside of that file (and keep it writable) to store the new database values?

You don't have to re-invent the database abstraction layer to access external databases. You can switch the database connection dynamically.

Using Database::addConnectionInfo() you can add your database connection information dynamically. Then use Database::setActiveConnection() and Database::getConnection() with your respective target database identifiers for doing your queries with.

Entity (field) queries won't work obviously, if the external database doesn't have entity tables. But static and dynamic queries will. The latter allow for including the core pagination, if desired.

After you queried your external database, use Database::setActiveConnection() without parameters to reset the connection to the defaults. This is important for Drupal to being able to access its own tables after your queries.

Check the Database API documentation and the database class for more in-depth information. (This will also work in Drupal 7 and its database class.)


How to theme a radio button field on node edit form? The standard way the radio buttons field is rendered on a node add/edit form is that there is a wrapper div with classes:

form-item form-type-radio form-item-mymodule-imglayout-und

and inside there are input and label elements. Where to hook to change this? I would like the wrapper div to have classes:

form-item form-type-radio form-item-mymodule-imglayout-und mycustomclass

And the custom class should be dependent on the option the button represents, or just be sequential: first, second, third, ...etc

Additional info:

My point is to be able to add a distinct big background image to each radio button, depending on the option it represents. Like below - note that each radio button has an associated image, representing its option visually.

I think what you need to do is just altering the form array. You can accomplish this in your own hook_form_alter implementation.

For example:

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'YOUR_CONTENT_TYPE_node_form') {
        $form['YOUR_ELEMENT_NAME']['#attributes']['class'][] = 'your-custom-class';
    }
}


Change a Node Reference field value with VBO I'm having trouble setting a Node Reference field using VBO. If I select Integer as the parameter type it doesn't change the field value, and if I set it to Node Reference it has a "Data selector *" field for the input and no value seems to satisfy it.

Any suggestions?

Ok what worked out was having 2 parameters. One the node I'm altering, the other an integer field to input the node ID. Then I set up a "Fetch entity by id" action using the integer parameter. I use the entity variable provided by the fetch action to set the node reference field.


Get a list of services programatically I've recently started working with Drupal 8. I'm looking for a way to programatically(no drupal console or other CLI thing) get a list of all the services available.

Since it's built on top of Symfony I figured that the container should have a list of all the available services. Well, I was wrong.

I've searched around and I can't find any specific answers, other than the CLI option, which is not what I'm looking for.

If anybody can point me in the right direction here, I'd be grateful.

You can get all services from the container by using the kernel method getCachedContainerDefinition():

$container = \Drupal::getContainer();
$kernel = $container->get('kernel');
$services = $kernel->getCachedContainerDefinition()['services'];
foreach ($services as $service_id => $value) {
  $service_definition = unserialize($value);
}

Now you can output a list, for example containing the service id and the class name in $service_definition['class'].


How to customize user edit page drupal 7? I need to change the order in which things are on the user edit page in Drupal 7.  I have tried modifying page-user-edit.tpl.php and user-profile-edit.tpl.php, but it doesn't seem to ever get there. What can I do?

It's a little different for Drupal 7... The structure of the file name would be page--user--edit.tpl.php (for D7) as opposed to page-user-edit.tpl.php (for D6).

Also, remember to clear the cache after you make any such changes so that they're recognized.

Hope that helps... :)


Adding jQuery Tabs via template.php How do you add jQuery tabs in a "template.php" file?
I'm trying to add it with drupal_add_library('system', 'jQuery.tabs') or drupal_add_js('/misc/ui/jquery.ui.tabs.min.js'), but I'm not having any luck.

Here's my full snippet:

function custom_theme(&$existing, $type, $theme, $path) {
  $hooks = array();
  drupal_add_library('system', 'ui.tabs');
  // custom.js will call jQuery.tabs!
  drupal_add_js( path_to_theme() .'/js/custom.js', array('weight' => 9));

  return $hooks;
}

hook_theme() is a hook that must returns the list of theme functions implemented by a module, or a theme.

Calling drupal_add_library() or drupal_add_js() inside hook_theme() is not the way to add a JavaScript file to a page.

As reported in Structure of the .info file, a theme can use the scripts directive to declare the JavaScript files that it uses.

scripts[] = js/custom.js

Alternatively, a theme can use drupal_add_js() inside a theme function, or use the following snipped inside page.tpl.php, or any alternative page template Drupal would use.

drupal_add_js($path_to_script);
$scripts = drupal_get_js();


Different placement/alignment for image (field) in teaser and Full content view i have created a content type 'Article' which has a image field.
Both the teaser and Full view use the image field.(Default Drupal views for content)
Now the problem is this image field has the same CSS class.
So both the teaser view and full view get the same properties.
But i want the image in teaser view to align/float to left of teaser content, but to show in the top center region in the full view.
Since the CSS class is same for both view i can not achieve my goal ( point 5)

So please suggest me a way to achieve  point 5 without creating a new home page view in 'Views'

Just pick the field with right parent

on node teaser view - you will find class as "node-teaser"

and on full node view - you will find class as "node-full"

so its just matter of picking field with parent while applying the css.
OR also you can have a separate template for your node-teaser view, check this link


Basic Auth working but simple auth not working for create user I am totally stuck here in Drupal 8 REST API, any help is very appriciate.

Problem:

I am using Drupal 8.3.x, simple_auth module to generate Auth token for REST. When I try to create user by Authorization Bearer then its not working but when I try to create by Basic Auth then it works fine. I also enabled permission for user REST.

See Permission for user resource: URL: admin/config/services/rest/resource/entity%3Auser/edit

Postman Data:

Request header:
Authorization:Bearer token_value
Content-Type:application/hal+json
X-CSRF-TOKEN:OWp4RVNjlQbdjq-s6CMjNRIcfNiYsHp1L7Of87vJH2w

In Error Log:
League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request. in League\OAuth2\Server\Exception\OAuthServerException::accessDenied() (line 165 of /var/www/html/d8/drupal-8-composer/vendor/league/oauth2-server/src/Exception/OAuthServerException.php).

I resolved my problem by giving user creation permission to anonymous user.
"Access POST on User registration resource"


Form and Textcontent in Block I'm having problems with adding a form and text-content into a block. To get both, form and text, into my block, I use render() on my form, but I read, this isn't the best way to do, but don't found another way. Anyone knows how to get both into the content without using render()?

function commerce_bulk_invoice_block_view($block_name = '') {
    $block = array();
    if ($block_name == 'showinvoiceoptions') {
        $block['content'] = '
';
        if(!isset($_SESSION['selected_entities'])) {
            $block['content'] .= 'select a product first';
        } else {
            $block['content'] .= '
SESSION Variables:
';
            foreach($entity_array as $book) {
                $block['content'] .= '
';
                $block['content'] .= print_r( $book, true );
                $block['content'] .= '
';
            }
        }
        $block['content'] .= '
';

        $form = drupal_get_form('commerce_bulk_invoice_form');
        $block['content'] .= render($form);
    }
    return $block;
}

Try the following code

function commerce_bulk_invoice_block_view($block_name = '') {
  $block = array();
  if ($block_name == 'showinvoiceoptions') {
    $content = '
';
    if(!isset($_SESSION['selected_entities'])) {
        $content .= 'select a product first';
    } else {
        $content .= '
SESSION Variables:
';
        foreach($entity_array as $book) {
            $content .= '
';
            $content .= print_r( $book, true );
            $content .= '
';
        }
    }

    $content .= '
';

    $build['content']=array('#markup' => $content);
    $build['form']=drupal_get_form('commerce_bulk_invoice_form');

    $block['content'] = $build;
 }
 return $block;
}


How to Determine a View Row's Content Type I'm putting together a view with multiple content types. In my my_theme.theme file I want to set the template suggestion based on the item's content type (e.g. Content-Type-A gets Template-A.twig and Content-Type-B gets Template-B.twig). Digging through the $variables[] array I can't find if or where there is an element that specifies the content type for the current view row.

Does any know how I may determine the content type of view row in the $variables[] array? If it's not in there what's the best way of adding it?

Thanks!

Create a new display mode and use this display mode on the view. then each of this display mode can be altered in admin or custom template can be made.


Do I need to install Drupal using Drush in order to use Drush? I installed Drush and then I installed Drupal using the regular installer/method.

When I type drush cc all on my terminal I get this message:

  No Drupal site found, only 'drush' cache was cleared.

No, you do not need to install Drupal using Drush in order to use Drush. All you need is to make sure that while running drush cc all, you are in the Drupal directory.

For example, if your Drupal lies under /var/www/Projects with root name as drupal then first you need to move inside /var/www/Projects/drupal and then run the drush cc all command.

The reason being, Drush can be executed inside a Drupal environment only.


How can I link a gallery made with views to another gallery made in views? I am trying to do a gallery with a page of preview of the pics, I got how to do it with views and tags for the full size pictures and with image styles; I got the preview gallery (btw for this one I am using Nodequeues).
Now I don't know how to link the galleries from the previews to the full size ones, I did try with the output linking in the override section of the view, I tried creating a new field with the URL and nothing, it always links to content/node but not to /photos/node

Btw this is the website http://www.nellens.com/home/

Thank you.

If you are looking for using a view into another as a field then you can use Views Field View to achieve this.

Module page describe :

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


Do you really need SSL on local dev environments? If a Drupal site is running on production with https, is there any reason why this should be done also on local dev like xampp? Just wondered about so many people desperately trying to run SSL on localhost (independently of Drupal).

It depends on the site.

Some third party tech, services, etc require SSL to be enabled and working for basic functionality. Meaning for those cases any/all development/staging environments would need to be running SSL for development and quality assurance.

In all cases the closer your development environments are to the live environment the better quality assurance can be.


What are some reasons unpublished content is visible to anonymous users? The anonymous user role has no permissions to view/edit unpublished content. I'm wondering what kind of tests I can use to locate the bug, there is one module calling hook_node_access, but it returns AccessResult::allowed(); on update operations $op == 'update' so it should not be affecting view operations. I'm stumped.

The issue was a bug in node_view_permissions, updating to 8.x-1.2 solved the problem.


Is there any log or receipt or anything that message was sent to someone? I'm in a situation where I'm supposed to testify (= proof) that a message (confirmation) was sent from our site (using Drupal 7).

Is it possible to see it from anywhere? Does it register into hosting provider or something like that?

I tried looking at the log files on the server, but they didn't include anything regarding this message; the Drupal system log was one month ahead that time when the message was sent.

A custom message (confirmation) is sent with Rules when user makes an order and registers as user (of which all is done via customized "Add node" form).

It won't help to go back in time, but for similar requests in the future I recommend you to have a look at the Message module, which is part of the Message Stack. Read on for more details ...

Create a Message archive (audit trail)

By using the Message module, you automagically also create an archive of all Messages. Which is very handy in cases such as when a user claims to never have received some eMail. In such cases, think about how you'd proof that some eMail was mailed somewhere in the past ... as compared to using Message and just bring up that message again ...

A typical scenario (as in the question here) that would be prevented by using the Message module:

  I tried to look at the log files at server but they didn't include anything regardins this message. Also the Drupal system log was one month ahead that time when the message was sent.

Message stack

These are the basic components and dependencies of it:

For this question only the Message module would be needed (not the other Message-related modules). But first, to explain the above picture, some more details about the Message-related modules (=quotes are from the module's project page):

Message:

  The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

  This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

  With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Distributions / modules using Messages

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.

A great sample of this can be found in Commerce Kickstart, which uses the Commerce Message module, to create such "Events logging". In that case in the format of an Order History, as shown in this screenprint (from this module's project page).

If you'd rather look at an existing module as an example, then checkout the 7.x-4.x version of the Answers module (disclosure: I'm a co-maintainer) and its Answers Notification sub-module. This sub-module allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

Combining Rules and Message

Moreover, by using the technique of Replacement tokens, it's possible to create your own Message-"tokens" using ... Rules! If these Replacement Tokens don't mean anything to you (ie you don't understand what they are really about), then head over to the answer to What's the purpose of "Replacement tokens" of a Message type? for (way) more details on that.

As an example, here is a (rather basic) custom rule:

a Rules Event like "Before saving a new node", of "After updating an existing node" (or variations of these events).
a Rules Action to "Create a message" (of a selected Message type).

That's really it ...

A really interesting facility of the Message module is its perfect integration with the Rules module. Have a look at the answer to "How to implement a follow author (or user) function?" for way more details on that.

Yet another sample that could be a perfect fit (= a quote from the question ...):

  I'm using Drupal 7 and custom message(confirmation) is sent with Rules when user has made an order and registered as user (of which all is done via customized "Add node" form).

You might be lucky

The prior quote got added to the question afterwards. And possibly explains also why you tagged your question with the drupal-commerce tag (removed in revision 3 by a mod).

So if you're lucky your site might already use the Commerce Message module, in which case you already might have such audit trail (which you don't know about). Just use Views to search what you're looking for.

If you don't use that module yet, then hurry to get it enabled for similar requests in the future.

Possible alternative for syslog

The Message module is also a possible alternative for the Syslog module (included in Drupal core). For example in situations like this one (= quote from "Syslog module overview"):

  It is not suitable for shared hosting environments.

More info about the Message module

The Message module is an amazing module, it is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and Rules.

Though there is not a lot of documentation about it (which is what makes it a hidden D7 gem ...). A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to have a look at the answers to:

How to create a basic message - notifications system displaying a real time message counter badge?
How to show message view containing own and following activity?
How to integrate messaging into a custom module?
Is there a simple way to notify users about new posts on the site?

Tutorials:

What is Drupal's Message Stack and how do its modules work together?
How to allow users to manage their own Message Stack messages?


Nest a Field Widget's primary field in a Fieldset array I'm porting over some logic that's working on a custom form to a new field widget; however, due to some javascript logic the custom form needs the end field to be nested within other elements, but when I try to nest the element in the widget, the value is not sent through the form.
Forcing a name attribute like I do below doesn't seem to help.

$element['filter']['client_selector'] = array(
    '#title'=>'Your Clients',
    '#type'=>'fieldset',
    '#theme'=>'mymodule_option_selector',
    '#list'=>$client_selector
);
$element['filter']['client_selector']['tid'] = array(
    '#type' => 'hidden',
    '#default_value' => $selected_client,
    '#attributes'=>array('class'=>array('hidden-value'),
        'name'=>$instance['field_name'] . '[' . $langcode . '][' . $delta . '][tid]'),
);

This works to send the value, but not with the selector system

$element['tid'] = array(
    '#type' => 'hidden',
    '#default_value' => $selected_client,
    '#attributes'=>array('class'=>array('hidden-value')),
);

Thanks!

I ended-up just adding a submit and validation callback that re-aligned the index.

In the hook_field_widget_form

function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
//  widget form logic....

//  Add a custom submit handler to realign the values
    $form['#submit'][] = 'mymodule_option_selector_submit_validate';
    $form['#validate'][] = 'mymodule_option_selector_submit_validate';

//  Tell the form what field uses the option selector so it knows which fields to relign
    if(!isset($form['#option_selector_fields']))
        $form['#option_selector_fields'] = array();
    $form['#option_selector_fields'][] = array(
        'field_name'=>$instance['field_name'],
        'langcode'=>$langcode,
        'delta'=>$delta,
        'columns'=>$element['#columns'],
    );

    return $element;

}

function mymodule_option_selector_submit_validate($form, &$form_state){
    if(isset($form['#option_selector_fields'])){
        foreach($form['#option_selector_fields'] as $field_data){
            foreach($field_data['columns'] as $column)
                $form_state['values'][$field_data['field_name']][$field_data['langcode']][$field_data['delta']][$column] =
                        $form_state['values'][$field_data['field_name']][$field_data['langcode']][$field_data['delta']]['filter']['client_selector'][$column];
        }
    }
}

Still would be nice to know if there is some kind of toggle in the widget form system to accommodate this.


Why are anonymous visitors logged in when they visit /user/[uid] page? This seems to be a massive security floor in Drupal. I have the following display suite code in a Block which is added as a custom field to the User account display:-

    <?php
global $user;
$uid = arg(1);
$user = user_load($uid);
$roles = $user->roles;

if (in_array('RoleName1', array_values($roles))) {
 print "";
}
if (in_array('RoleName2', array_values($roles))) {
 print "";
}

?>

It checks for a couple of Roles and shows an image if they have a particular Role.

When an anonymous user now loads a user account page, they are logged in as that user! Visiting "/user/1" means they are logged in as the admin user!!!

This is no security hole, it's the custom code you shared.

// When you load the global user object ...
global $user;
// ... and then assign another user object to the global $user object ...
$user = user_load(<any_uid>);
// ... Drupal basically changes the context of the current user.
// It's kind of a hacky login by code.
// Hacky because, till this code executes
// there's no log about the user login, until drupal writes the current session into the database.

Typically $account is advised to prevent accidents like this.

$account = user_load(<any_uid>);