Why do D7 form builders have a $form parameter?

At least for D7 there is one scenario where the passed-in $form parameter does make a difference.

With hook_forms(), it is possible to define a 'wrapper_callback' for a form definition for a specific form id.

From the hook documentation https://git.drupalcode.org/project/drupal/-/blob/7.69/modules/system/system.api.php#L1821:

/**
 [..]
 *   - wrapper_callback: (optional) Any callable to invoke before the form
 *     builder defined in 'callback' is invoked. This wrapper callback may
 *     prepopulate the $form array with form elements, which will then be
 *     already contained in the $form that is passed on to the form builder
 *     defined in 'callback'. For example, a wrapper callback could setup
 *     wizard-like form buttons that are the same for a variety of forms that
 *     belong to the wizard, which all share the same wrapper callback.
 */

So if a wrapper callback was defined, then the $form array passed as a parameter may already be prepopulated.

I found some contrib modules where this is being used (simply grep for 'wrapper_callback'):

ctools does not set the wrapper callback in hook_forms(), instead it sets $form_state['wrapper_callback'] directly.
entity uses hook_forms() to set a wrapper callback to a form definition, but also sets it in $form_state['wrapper_callback'] directly.
media_bulk_upload does use hook_forms() to specify a wrapper callback.


Recently I had a slightly different but similar issue with answers in commons. When a user answers a question it was by default visible to trusted contacts of that user but not visible to group members and there was no way to change that even as an admin.
After spending quite some time, I tried disabling the commons feature "Commons Trusted Contacts" which solved the problem.

So, one thing is clear it is this feature/module which is overriding. If you don't need trusted contacts functionality, you can just disable this. Otherwise, Commons trusted contacts is the right place to look into to solve the actual cause.


How do I update a node via a custom form?

You need to use hook_menu() to register the path and callback function, like so:

<?php
function hook_menu() {
  $items['some-path/%node'] = array( // %node will use the node_load() function that's already provided by node.module.
    'type' => MENU_CALLBACK // This is just a callback item, it will not appear in any "menus"
    'page callback' => 'drupal_get_form'
    'page arguments' => array('the_form_function_name', 1) // Where 1 = the %node wildcard
    'access callback' => 'node_access',
    'access arguments' => array('update', 1), // The user must be able to update the node
  );
  return $items;
}
?>

Then build a simple form that provides fields to alter on the node, and run node_save() in the submit handler to save any modifications you make to the node.

<?php
function the_form_function_name($form, &$form_state, $node) {
  drupal_set_title('Now editing node ' . check_plain($node->title));

  // Just store the entire $node object in a custom form property. Easy.
  $form['#node'] = $node;

  // An example form field that we'll use to update the node's title.
  $form['new_title'] = array(
    '#title' => 'Title',
    '#type' => 'textfield',
    '#default_value' => $node->title,
  );

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

  return $form;
}

function the_form_function_name_submit(&$form, &$form_state) {
  $form['#node']->title = $form_state['values']['new_title'];
  // Save the modified node object (http://api.drupal.org/node_save)
  if (node_save($form['#node'])) {
    drupal_set_message('Updated the node.');
  } else {
    drupal_set_message('Could not update the node.', 'error');
  }
}
?>

This is just sample code – I have not tested, but it should work barring any typos.

You would hit this via: http://example.com/some-path/123 where 123 is the node ID of the node you want to edit.


Drupal 8 Theme Header Background Image Upload

I suggest you look at ThemeSettingsForm, which is where the code lives for the logo and favicon. Doing something similar there would work.

Note that it doesn't save the file, it just uses the file entity that it gets from the widget and puts it in a permanent place using file_unmanaged_copy().

Make sure to keep the conditional, so that you don't get a fatal error when not providing an image (I assume that's the problem with @dmouse's code example).


How do I attach CSS styles to all the pages?

Please try using below code
info.yml :

name: mysub-theme
type: theme
description: 'my sub-theme Commissions'
core: 8.x
base theme: businessplus_lite

libraries:
  - mysub-theme/my-sub-theme-style

mysub-theme.libraries.yml :

my-sub-theme-style:
  version: 1.x
  css:
    theme:
      css/style.css: {}


Hook not firing for custom entity -- how to set theme suggestions?

The theme system doesn't know about entity types by default. You need to implement hook_theme() yourself at the moment. You likely also need a preprocess function to define a few standard things.

The console project generates this when creating a new entity type through it, you could try that to see how it looks. Otherwise look at what node module does in node_theme() and template_preprocess_node().


You need to implement a route subscriber and an access handler. Assuming that that should be able to see the nodes via HTML but not via json. If they shouldn't be able to see via HTML either, swap out the node access controller by implementing an alter hook to modify the entity type info. If they should be able to see HTML, go the route subscriber path and alter the rest resource routes to add a new access requirement. Then implement your logic in an the access handler.


Excerpt from modules/comment/comment.module inside function comment_node_view($node, $view_mode):

// Only append comments when we are building a node on its own node detail
// page. We compare $node and $page_node to ensure that comments are not
// appended to other nodes shown on the page, for example a node_reference
// displayed in 'full' view mode within another node.
if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  $node->content['comments'] = comment_node_page_additions($node);
}

commenting for the node must be turned on
The node must be shown in the full-view_mode (normally this is node/<nid>)
node_is_page(): Whether the current page is the full page view of the passed-in node.
It must not be an edited preview of this node.

If you still feel like showing the comments on the frontpage for a specific node, try this:

$frontpage_commenting_node = node_load( **1** );
print render(comment_node_page_additions($frontpage_commenting_node));

Note:
 - You need to change the parameter of node_load to the effective node id in your system.
 - This is for Drupal 7


How can I have the table headers repeat throughout the view results for every X results?

Assuming that you are using the display style type of table in your view, you can set the checkbox for: Enable Drupal style "sticky" table headers (Javascript)

This will freeze the headers and allow the table data to scroll.


Load an AJAX submission enabled webform using another AJAX call

Try to create ajax links with this module Ajaxify Drupal with JQuery Ajax.

It will load all ajax behaviour of loaded content(if loaded content contains ajax enabled form then that also)

  Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.


Problems getting Default Content module to work with Features

Figured this out.

After you enable the Default Content Module, there will be a new setting for each Node by where you can select Revision information, URL path settings, Comment settings, etc.

This new setting is Machine Name.  You make a machine name for the node of the default content.

Then when you make a new feature (I guess it is best practice to have all of the default content nodes in one feature so when you deactivate the feature all of the default content will turn off and the features will still work) there will be a new component "Content Item".

This will have all of the machine names that you made while creating/editing nodes.

Hopefully someone will find this useful so they don't bang their heads against the wall like I did.


How to add title of the image in manage display section or display it in node view page

Custom Formatters

Try the Custom Formatters module to create a custom formatter, Tokens may help. There are some examples for inspiration: Custom Formatter Examples.

Or implement through your own custom solution in a module or a theme: Create a custom field formatter.

Views Block

Another way of doing it is hiding the Image field on Manage Display, and creating a Views Block instead with a contextual node ID filter that outputs that image field along with the title. If you don't see the title available as a field in content views out of the box you can add a Relationship to that field to get it.


Drupal 7 context module fails to load on front page

Figured it out. I had another reaction added that was causing the issue. I removed the reaction and it seems to work now.


configuration error directories not present

You can define it in settings.php like so:

$config_directories[CONFIG_SYNC_DIRECTORY] = '/../config/sync';

This sets the default sync directory outside my webroot.

CONFIG_SYNC_DIRECTORY is a constant defined for 'sync'.


How would I print out the first instance of a paragraph bundle in a node template?

TWIG

In twig you can check for the paragraph bundle in the items loop of a field template and only print the first item found:

field--node--field-paragraph--content-type.html.twig

  <div{{ attributes }}>
    {% for item in items if item.content['#paragraph'].bundle == 'paragraph_type' %}
      {% if loop.index == 1 %}
        <div{{ item.attributes }}>{{ item.content }}</div>
      {% endif %}
    {% endfor %}
  </div>

And then print this field in the node template:

{{ content.field_paragraph }}

UI

For a UI solution you need a field formatter like Paragraphs summary formatter, which in the moment only exists in a sandbox version, see https://www.drupal.org/project/paragraphs_summary/issues/2803859#comment-11804075


How to access individual items in $form_state['values'] post-submit

You can access $form_state['values'] of a field in like

$variable = $form_state['values']['your_field_name'];

After saving you can access like this

$variable = $form['your_field_name']['und'][0]['value'];

For more information please check

$form_state keys
What is $form_state used for ?

Hope this will help you.


This would have to be done using a custom module. I do not know of a contributed module that would perform this. Probably because a module like this could be seen as a huge copyright infringement lawsuit waiting to happen.

But if I were to do this I would use GuzzleHttp as the engine to pull down the content. Then take that content and create a new entity using entity_create(). Where you have to focus your efforts will be sanitizing the information you "guzzle" off the web so that you do not create security issues in your site from XSS, SQLi, or other vulnerabilities. The process would be triggered on node-save.

This is just the basic idea, I cannot explain how to write the entire module as that would be pages of content.


Drupal only sets node/nid as public when you give anonymous users permission to "access content". Additionally, you can use modules like http://drupal.org/project/content_access to specify what roles can access specific content types. Lastly, you can use http://drupal.org/project/field_permissions to specify what roles have access to specific fields on your nodes.

To answer your other questions, I don't think you need to write any custom modules to cover these needs and using Drupal to provide content only to privileged members is a very common use case.


Mixed content issue while running updates.php in Drupal 6.37

Sorry, but I doubt this can be debugged from here. You need to:

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

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


Add body class to Node Display (to distinguish it from Node/Edit or Node/add view)

arg(2) will return NULL on node pages (like node/1).

  if (arg(0)=='node' && is_numeric(arg(1)) && !arg(2)) {
    $variables['classes_array'][] = 'node-view-page';
  }


How can I dynamically change the display format?

You can do that printing directly the entityreference field in the node.tpl.php. First you need to check if the image field exists and then display the entity reference, so you can do something like this:

if(!$content['field_image']){
   //Load default image
}else{
   print 'Your custom label.';
}

You have to remember to set the format to hidden in the display section.


Can i populate the empty sites/default/files/ with files from a local installation?

If your two Drupal installs are exactly the same, it is possible. Your biggest problem will be figuring out the name of the files, since they will have some hash value generated by Drupal. I don't know exactly how this is generated, but yes it is possible.

Now while this is possible, it's not a long term solution. If you had a live site, and something was failing to generate the aggregated css and js files, it could be a quick short term solution until the real problem was found and fixed.

I believe that you have asked about this already and received answers about file permissions etc, some of this which doesn't belong here, since it's about setting up a server and not Drupal itself. I would advise against pursuing this path, and instead try to resolve the real issue. If you want to upload files, use image cache and a lot of other modules and features you need to resolve this anyways. Making a hacky unstable solution will do you no good.


IN views, just include a NODE/node last updated date field in your row.  For nodes, take the advice of MPD and those commenting in Showing the date of the latest edit, instead of node's posting date about creating the very simple preprocess() and/or view() hooks.


Getting the $user object of a logged out user based on a username and setting its status

What is wrong in your code is that the implementation of hook_menu() is gathering the arguments for the callback, when that hook is only called in specific moments (as I reported in my previous answer).

Rather than doing as you do, I would rather use the following code:

function mymodule_menu() {
  $items['auth/%user'] = array(
    'page callback' => 'mymodule_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_page($account) {
  user_save($account, array('status' => 1));
  drupal_goto('<front>');
}

In this way, Drupal will automatically get the user ID, and pass to the page callback the user object for that user. drupal_goto() is necessary as the page callback is not showing any output; you can redirect the user to any pages you want. (I chose "<front>" because it's a path that is always defined, in Drupal).
If you need to use a username, then you need to use a loader function that loads a user object knowing the username. As in Drupal there cannot be two users with the same username, it should avoid the user being acted upon is not the desired one.

function mymodule_menu() {
  $items['auth/%mymodule_username'] = array(
    'page callback' => 'mymodule_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_page($account) {
  user_save($account, array('status' => 1));
  drupal_goto('<front>');
}

function mymodule_username_load($name) {
  return user_load(array('name' => $name));
}

The code defines a new wildcard argument; if "%wildcard" is the name of the wildcard, then Drupal will look for the wildcard() function that needs to return FALSE in case of error; in that case, Drupal will return the "page not found" error (404).

Important I used the same value you used for "access callback," but it is not something that should be done, in this very specific case.
The reason is that the menu callback alters a user account; imagine what should happen if a user with a blocked account could do if he knows of this URL: He could enable his own account very easily. This is because the entry "access callback" you are using is saying "everybody can access this menu callback," which also means that Google, or any other search engine could enable a user just visiting the URL the search engine has found in some way.
In general, the rule is to restrict the access to a menu callback that alter some data, which includes also the case the menu callback deletes data.


How can I hide nodes from view, but open access to JSON:API at the same time?

If you're working with unauthenticated consumers, the Rabbit Hole module has the means to disable node/* routes without using the user role/permission system.

The Rabbit Hole module has a sub-module Rabbit Hole nodes that, when enabled, will let you disable node/* routes. This should leave open your jsonapi/* endpoints to anonymous consumers.


What is the best way to migrate and optimize 300 GB database to drupal?

The answer is Yes.
First - because you are asking on Drupal Answers site.
I would recommend you using configuration like this:

0 Load balancer managing several servers
1 Varnish (proxy cache)
2 Nginx (php-fpm)
3 Drupal
4 MySQL (Master+Slave)

Also memcache can be used. The main problem will be when you will try to update/insert new record in DB. All read queries will be managed by caching-proxying systems.
If you need text search - use ApacheSolr.
Try to not views or panels, with such DB size you can have perfomance issues.


Can I recommend not doing it with PHP?

I would suggest making a page (via Admin->Content->Add Content), this assumes that you have the node module installed.

And then set that page as your "Default 404 (not found) page" in Admin->Configuration->System->Site Information

And then you can use that page's path in the block set up, but list under "Only the listed pages"


How to set and use direct files folder path in a multisite installation

In /.htaccess, above other rewrite rules, use something like this example for foo.bar.com:

RewriteCond %{HTTP_HOST} ^foo\.bar\.com
RewriteRule ^files/(.*)$ sites/foo.bar.com/files/$1 [NC,L]


Adding the contextual link render element

First of, usually you want to handle the contextual links in your preprocess theme function so you don't have to handle it every time you need to render the thing.

The actual contual links is added to title_suffix, so you need to do {{ title_suffix }} somewhere in your template to actual render the contextual links. You also need to render the attributes or make sure your wrapper html tag has the contextual-region class.

In Drupal 8, most of contexual links are used with relationship to an entity. If you have something you can view and edit most likely it should be an entity, meaning you should use the entity view builder to render it etc. Might also make it easier for you to do contextual links, as there are many examples of how this is done in core and contrib, like the node module, user module taxonomy module etc.


User registration without email address OR registration with pseudo-email address

I think you need an email address, but I could be wrong about this.

You can definitely provide a fake email address though.

For example, you can use hook_form_alter() to modify the registration form:

function MYMODULE_form_user_register_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  // Hide the mail form
  $form['account']['mail']['#access'] = FALSE;
  // Set the email address to minor+UID@mydomain.com
  // You need to write this code yourself...

Make sure you set the email address to include the UID or something similar that will ensure the email is unique; Drupal has to have a unique email for each account.

Then, use hook_mail_alter to check the user's role and, if the user is a minor, query the parent's email address and send the parent an email instead.


Check out the flag API. There are examples for creatig flags, flagging a node and more. Here the example for the flag-creation:

$flag = flag_flag::factory_by_content_type('node');

// Absolutely required, will break your site if not added properties.
$flag->name = 'my_flag_name';
$flag->title = 'My Title';

// Properties required by the UI.
$flag->roles = array(2); // An array of role IDs. 2 is for "authenticated users".
$flag->types = array('story', 'page'); // An array of node types.
$flag->flag_short = 'Flag this';
$flag->unflag_short = 'Unflag this';

// Optional properties, defaults are defined for these (and more).
// Use a print_r() or dsm() to see all the available flag properties.
$flag->global = TRUE;
$flag->flag_long = '';
$flag->flag_message = '';
$flag->show_on_form = TRUE;
$flag->show_on_node = TRUE;
$flag->show_on_teaser = TRUE;
$flag->link_type = 'toggle'; // For JS link. Other options: 'normal' and 'confirm'.

// Save the flag.
$flag->save();


EntityQuery on nodes related by ERR and paragraphs

Newer versions of Drupal (tested with v8.6.2) can also resolve Paragraphs (Entity Reference Revisions) if you explicitly name the target entity type using dot notation:

$nids = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'publication')
    ->condition('field_mention.entity:paragraph.field_project.target_id', \Drupal::routeMatch()->getRawParameter('node'))
    ->execute();

Note the .entity:paragraph. instead of .entity. in the referenced field condition


Get this jQuery Youtube Playlist working?

In Drupal, you can't just call jQuery quite like that. The reason is mostly because there my be other JavaScript libraries in use so jQuery is not aliased as $() in Drupal. For more details on that you can view the Drupal Docs about JavaScript compatibility, or the specific issue in the queue.

The solution is to wrap your jQuery code as described in the Drupal docs page linked to above. In your case it would look something like this...

(function ($) {
  $("ul.demo1").ytplaylist();
})(jQuery);


Commerce Kickstart Review Overrides Error

Are you sure those modules are compatible with PHP 7? We haven't tested nor do we recommend running Commerce Kickstart 2.x in PHP 7 as far as I know.


Show news articles only by the year selected

You could create a view using Views and allowing an exposed filter on the year to the user to select the year or dates.  That would then submit the request to the server and reload the page with only the selected year.  It wouldn't be pretty like using Javascript, but it would do the job.


common header and footer for all pages in drupal7

The most common is to structure your header and footer using the core block system. Another solution would be to place the structure in the page.tpl.php. If you have a lot of page.tpl.php files and still want to use templates, then it might be better to place the header and footer in the html.tpl.php template.

Personally I would recommend using the blocks system.


How do I give the permission to add points, but not to moderate them?

In Drupal 6, there is no easy way to do that. It might work if you implement hook_menu_alter() in a custom module and add a different permission in access arguments that the default.

It might not help you at this point, but I have taken over that module for Drupal 7 and we have improved it a lot. Among many other things, it now has separate add/edit and moderate permissions which allow for fine-grained access control. So if you are just starting your site, you might want to consider using Drupal 7 instead.


This works

/* Implementation of hook_form_alter*/

function login_auth_form_alter(&$form, $form_state, $form_id) {

if ($form_id == 'user_login') {

        $form['#validate'][] = 'ea_login';
    }
}

/* implementation of hook_form_validate */
function ea_login($form, &$form_state) {

        $response = "SUCCESS message";

      rules_invoke_component('rules_display_a_message',$response);

}


Content Template admin interface for custom content type not displaying

It was PHP file size limit. Weird. It was increased and everything went back to normal.


Finally i got the answer. In order to alter Drupal 8 webform we can use code like this

$form['elements']['field_name']['#title'] = t('Your Name');

I think same method can follow to alter other field attribute.


Ajax callback values not saved on submit

So, product_id was rendered but its value not passed to the commerce_cart_add_to_cart_form. This is how I solved it.

Add to Cart Form Alter

if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {

  $form['product_id']['#type']='hidden';
  $form['product_id']['#prefix']='
';
  $form['product_id']['#suffix']='
';
  //...

Ajax callback

$form['product_id']['#value'] = array(
  $pid,
);
$commands[] = ajax_command_replace('#liberte_pid', drupal_render($form['product_id']));

It's quite simple once you know it : before calling ajax_command_replace() you don't need to rebuild the full form element, just set the wanted attribute, and drupal_render($form['form_elt'])) will do the magic :)


Too many redirects error with https and domain access module

Just in case anyone stumbles upon this (or perhaps for my future self). The issue ultimately ended up being Cloudflare. If you use Cloudflare for any of your domains don't forget to include it in the stack of things you're looking at when debugging (like I did).

If you use Cloudflare, there is a section under the "Crypto" menu for "SSL". I believe the default setting is "Flexible", if you leave this setting you can end up in a situation where you're bouncing between your load balancer and Cloudflare.
The setting you want is "Full" once it is set to "Full" you shouldn't keep getting bounced around.

This also explains why our .com was not getting the redirect error. Our .com is the only domain not on Cloudflare b/c that DNS is out of my control


After upgrading, the autoloader is not working

It sounds like the changes that composer made to your local environment weren't carried over. Without knowing any of the details of what might be different, you'll have to do some introspection. You can test the autoloader in both your dev/staging environment to tease out what's occurring differently in each environment.

There a few things you can do to test the autoloader:

Within index.php you can use the statement var_dump($autoloader) to dump the autoloader; it should have a classMap property which should have a keyed array that maps classes to PHP files. It should include a value for Drupal\Core\Site\Settings.
Within vendor/composer/autoload_real.php is the logic that registers the autoloader and includes other autoload_*.php used to build the autoloader object. You can various var_dump() statements to follow the path of execution to make sure the autoloader is being built correctly.
Within vendor/composer/ClassLoader.php you use the var_dump($class) statement in the ClassLoader::loadClass($class) method to have PHP spit out classes as the autoloader is including them.


How to display a view within a template only if there is something to display

Instead of embedding a view in a template, please consider having your view output a block display, which you can place on your site using the Block System, Panels or Context.


Want to generate csv of a view programmatically in drupal 7

Views data export

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV
  Microsoft XLS
  Microsoft DOC
  Basic TXT
  XML

You should created a Views with CSV display. And then created a bottom that point to that page.


From the point of view of the Boost module, it should be safe as well. Make sure you also regenerate the .htaccess for your site.


How to modify taxonomy term path in the page render array?

This question makes perfect sense if photo/% and video/% are views.  It might be even better to map taxonomy/term/% to topic/%, and then make a single view with a path topic/%/%, where one argument is the content type and the other is the taxonomy term. However, you may also use the paths you suggest by building two views (or two pages in one view), each with its own path.

On to your main question, though. Changing items in the render array is easy, but it can sometimes be hard to figure out what needs to change and when. It is a general problem with render arrays that sometimes there are shadow copies of info that are available for your reference. Changing these copies does not affect the rendering of the page, because they are only copies of the item that is used to build the actual page.  The problem with the code in your question is that it was altering a copy of the target link; the master information that you need to change to affect page rendering appears somewhere else in the data structure.  You need to adjust the copy that appears inside the 'content' item.

Here is some code that works for a similar content type:

function MYTHEME_preprocess_node(&$vars) {
  if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $tid = $info['tid'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $tid;
        }
      }
  }
}

From here, you can use pathauto to map photos/% to a pleasing URL to your photos + taxonomy term view.


You can either use Views and Aggregation to Sum the number of references to show on a list.

But, I recommend using the Computed Field module to write some PHP code that is run on save to store an integer value that is the count of references. This value can be cached by drupal and used within Views and other modules.

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!


How to write EntityQuery so that it checks user's access to nodes?

Entity queries by default consider the node grants system, you actually have to opt out of that to get everything when using node grants.

The problem is that drupal core doesn't actually implement that API for the status, that only becomes relevant when using modules that do.

So unfortunately, the only way to simulate "admin or published" is to do it yourself. Check the permission, if the user doesn't have it, add the status = 1 condition. Note that views uses "administer nodes" but technically, that's actuallly wrong, "bypass node access" would make more sense, that would be consistent with what is being checked when trying to access node/ID of an unpublished node. But in your own code, you can use whatever makes sense for you, including a custom permission.

Alternatively, you could use a module like https://www.drupal.org/project/view_unpublished, which does populate grant records and your entity query will just work. In fact, I just closed a bug report where someone reported the behavior you want as a bug when using that module: https://www.drupal.org/project/view_unpublished/issues/2871272.


Hide Webform Message "You are viewing this form as..."

Doh! I didn't realise this was a configuration option in another module - Webform CiviCRM.


How to redirect according to URL parameter after form submission

The issue with ?destination= is that it provides no mechanism for setting external => TRUE for the options in drupal_goto(), which Drupal needs to redirect to an off-site location.

I think the easiest way to get what you're looking for is to implement hook_form_alter() for the user login form, save the URL parameter if it's available, and then manually redirect in the submit handler.

Something like this:

function MYMODULE_form_user_login_alter(&$form, &$form_state, $form_id) {
  if (isset($_GET['redir'])) {
    $form['redir'] = array(
      '#type' => 'value',
      '#value' => $_GET['redir']
    );

    $form['#submit'][] = 'MYMODULE_user_login_redirect';
  }
}

function MYMODULE_user_login_redirect(&$form, &$form_state) {
  $form_state['redirect'] = array($form_state['values']['redir'], array('external' => TRUE));
}


Turns out that his site was moved to another server.

The FTP that I was seeing was from the old server. When I installed the simplenews it got installed in the new server.


Create nested paragraphs programmatically

save() returns the status of the save operation, not the entity. And you probably don't need to save the paragraphs, saving the node should save new paragraphs automatically.

So you can try this version:

$questions = [];

foreach($data['questions'] as $question) {
    $answers = [];
    foreach($question['answers'] as $answer) {
        $correct = $answer['field_correct'] === 'Yes' ? 1 : 0;

        $answers[] = Paragraph::create([
            'type' => 'quiz_answers',
            'field_answer' => $answer['field_answer'],
            'field_correct' => $correct,
        ]);
    }

    $questions[] = Paragraph::create([
        'type' => 'quiz_question',
        'field_question' => $question['field_question'],
        'field_answers' => $answers,
    ]);
}

$new_submission = Node::create([
    'type' => 'quiz_submissions',
    'title' => 'Quiz Submission',
    'field_quiz' => $data['quizID'],
    'field_question_submission' => $questions,
]);
$new_submission->save();


Multivalue entity reference synchronization

Two way references are described in this drupal.org issue

Corresponding Entity References seems to be consensus solution there, but if it's no good for you, read whole thread, it provides interesting ideas and alternative approaches.


If the content you are importing is not supposed to be edited, I would suggest to follow the same method used on Drupal.org for some nodes: Implement hook_node_view().
In the Drupal.org case, the hook is used to output dynamic content for nodes that once were written using the PHP filter.

This method would allow showing the updated content without to periodically import the content into the node body, it avoids creating revisions for the node, and it avoids having a node body that is edited, and made different from the Github content.
To improve the performance, you can cache the values grabbed from the github, and avoiding accessing it (through drupal_http_request()) too frequently.


Image styles thumbnail, medium, large to default dimenssions

Go to Configuration -> Media -> Image Styles (or analogous path in non-7 versions). By default you have 3 styles there, the ones you mentioned. You can edit them to suit your needs, but deleting them is not supported - to many modules uses them.

On the other hand, styled image files are supposed to be created on first access. You shouldn't have them on your file system until something really needs them, so to get rid of those files simply turn off everything that uses them, and purge /sites/*/files/styles directory.


1.Use hook_node_create and hook_node_update, judge your node type to drup_goto, like:

function hook_node_create ($node) {
  if ($node->type == 'YOUR_NODE_TYPE') {
     drupal_goto('YOUR_DESTINATION');
  }
}

2.Use hook_form_alter change your node form, like:

function hook_form_alter (&$form, &$form_state, $form_id) {
  if ($form_id == 'YOUR_NODE_FORM_ID') {
    $form['actions']['submit']['#submit'][] = 'YOUR_NODE_FORM_ID_ls_submit';
  }
}

function YOUR_NODE_FORM_ID_ls_submit ($form, &$form_state) {
  $form_state['redirect'] = 'YOUR_DESTINATION'; // Not $form_state['#redirect']
}


The requested page "/http://.. could not be found. (puts slash in front of URL)

Check whether you have changed the $base_url variable in settings.php file in sites/default folder.


Programmatically accessing block content

Your code loads a configured block, not the content of a custom block.

This will load the field data of block content:

$custom_block = \Drupal::entityTypeManager()->getStorage('block_content')->load('1');
$fieldcontent = $custom_block->field_myfield->value;


You could write an automated test with SimpleTest.

Takes quite a bit of initial effort but once you have it, it is a matter of a few seconds to re-run your test.

Simpletest also automatically intercepts sent mails and you can then get them directly in the test with $this->drupalGetMails().

See for example How do I write automated tests for a Drupal site?


Is this record important?

Yes, it prevents some queries from failing if it's anonymous user who caused them.

  Does it have to be there?

There is a possibility site would stay browsable you remove it... but it would mess your login functionality and may prevent sessions from persisting.

  If yes, I'll do some trick to ignore it in my select.

Consider using EntityFieldQuery. Omit UIDs lower than 1, or select only users with name, etc.


Instead of drupal_add_js(array('MODULENAME' => array('testvar' => $testVariable)), array('type' => 'setting')); you use $build['#attached']['drupalSettings']['testvar'] = $testVariable;. Replace $build with the variable containing the form or the render array to which the settings are attached; in a form builder or hook_form_alter(), that would be $form.

The JavaScript code to attach to the page should then be defined as library, which is the only way to attach JavaScript and CSS to a page or a form.
It is explained in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module, so I will not repeat it here. I will just make notice that the library needs to declare at least two dependencies:

core/jquery, if the JavaScript code uses jQuery
core/drupalSettings, since the JavaScript code uses Drupal settings


How to have a required profile2 on user registrations, but allow admin-created users without a profile?

I'm going to guess the best option is to:

set the profile fields to not required
set the profile to show on the user registration form
then hook into the user registration form via a custom module to set the profile fields you want filled out as required (and admin-created users added via user/add will be able to skip these fields).


Drupal Commerce: Authorize.net payment from manual order

It's really just a simple matter that the payment terminal form doesn't fully imitate the checkout form on the front end, so redirected payment methods or direct post payment methods are not going to be supportable there.


How to create submenu based on content type and taxonomy?

You could use views to create your links for the content types and then use the views field view module http://drupal.org/project/views_field_view as a field on that to show the child taxonomy terms associated to the content type.


How to install and enable a default and admin theme in a Drupal 8 install profile with just YML (without using hook_install() or a .profile file)?

Ah ♂. Trying to install my rutherford theme via the web UI gave a The rutherford theme was not found. error message, so it seemed the theme was at fault, not the profile.

I inspected my theme's info file and realised it had a dependency which was not being met. Commenting out the dependency got everything working again!

It's a shame that the php www/core/scripts/drupal quick-start rocket did not give me any errors about this unmet theme dependency, otherwise I would have saved about six hours of trying various different configuration approaches! Ah well, ce la Drupal!


Pre-populate a field based on another node's field value

You should check out hook_form_alter. It would let you preload form values but still keep them editable.

Something like this would work to load something from the user's profile fields into the node form for new nodes.

<?php
  function custom_module_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
      case 'NODETYPE_node_form':
        global $user;
        $current_user = user_load($user->uid);
        // Set only on nodes that haven't already been saved
        if (!isset($form['#node']->nid)) {
          $form['field_YOUR_FIELD_NAME'][LANGUAGE_NONE][0]['value']['#default_value'] =
            $current_user->field_YOUR_USER_FIELD[LANGUAGE_NONE][0]['safe_value'];
        }
      break;
    }
  }
?>


$_POST returns empty value in custom service

You are passing every element as individual element, so you can't get these values in $_POST array. I have executed your code at my end and retrieve each element value by following call back function.

function _send_mail_service_create($nid, $recipient, $sender, $subject, $body) {
  echo "nid => ".$nid;
  echo "\nrecipient => ".$recipient;
  echo "\nsender => ".$sender;
  echo "\nsubject => ".$subject;
  echo "\nbody => ".$body;
}

Output:

nid => 1834
recipient => charubachi.rath@abc.com
sender => charubachi.rath@abc.com
subject => xyz
body => a

If you want to have these values in an array then you can use this in following way:

 /**
   * Implementation of hook_services_resources().
   */
  function send_mail_service_services_resources() {
    $api = array(
      'send_mail' => array(
        'operations' => array(
          'create' => array(
            'help' => 'Drupal 7 Services 3 test',
            'callback' => '_send_mail_service_create',
            'access callback' => 'user_access',
            'access arguments' => array('access content'),
            'access arguments append' => FALSE,
            'args' => array(
              array(
                'name' => 'title',
                'optional' => FALSE,
                'source' => 'data',
                'type' => 'string',
                'description' => 'The data collected through JSON',
              ),
            ),
          ),
        ),
      ),
    );
 return $api;
}

function _send_mail_service_create($arg) {
  print_r($arg);
}

Output:

Array
(
    [nid] => 1834
    [recipient] => charubachi.rath@abc.com
    [sender] => charubachi.rath@abc.com
    [subject] => xyz
    [body] => a
)


Why aren't the options in my dynamically inserted webform showing up?

I checked admin/reports/dblog and it turns out the select_or_other plugin wasn't properly installed, stopping the options from showing up at all.


Rule to autopopulate node reference field and redirect after content creation

Basically you need to create another event right after "create entity" which immediately saves the new entity before you move on to the redirect rule.

See also http://groups.drupal.org/node/204558#comment-688188.


If I understand your question correctly, you'll want to use the ImageCache module. This is in core as of Drupal 7. Try the documentation for Drupal 6 and/or this screencast if you need help understanding how to use this module.


Answer to second question is that the tax cannot be calculated until Billing address is present (as depends on 'territory' of store & user) - so tax line is not seen initially until user reaches review stage.  Once the tax (as an 'adjustment') is added to order, it then stays visible - eg if user goes back to cart to add/remove items. The tax value then gets updated to reflect new cart contents on clicking 'Update cart', or clicking Checkout.


A couple of things you can check...

In your subtheme, have you declared omega as your base theme in the .info file?

name = omega sub theme
description = my sub theme
base theme = omega

Have you enabled your subtheme as the default theme in admin/appearance?
Have you flushed the cache after making changes? ( configuration > development > performance > clear cache )
In dev tools, or whatever you use to inspect an element, when you have the source open, what is the path? Is it definitely coming from your sub theme folder?


No, and yes - sort of, in order.

The teaser system assumes that there will always be more to read so if you choose to show the teaser, by default it will always have a 'read more' link.

You can, however turn off the link entirely quite easily.  Copy node.tpl.php from your main theme into your custom theme directory and comment out this part:

<?php print render($content['links']); ?>

If you only want to show a read-more link when there is more to read, you almost certainly need to build a custom module for that.  There's lots of good documentation on how to do that, but we can probably help with the specifics here once you have a framework going if that's what you decide to do.

Note that if you only want to change the behaviour for a particular content type, put some logic around the line instead of commenting it out, like this:

<?php if ($node->type != 'article'): ?>
  <?php print render($content['links']); ?>
<?php endif; ?>


How do I do per-item shipping based on the number of products?

Pontus Nilsson has the right idea, just shared it as a comment instead of an answer?

I decided this was a good teachable moment (this also turned out to be a head scratcher at more than one turn), so below is the screencast of how to do this and a step-by-step:

https://www.youtube.com/watch?v=trLydGpimD4

STEP BY STEP

Install https://www.drupal.org/project/commerce_shipping and https://www.drupal.org/project/commerce_flat_rate
Create three different flat rates (I recommend you keep the "Title" different, but change the "Display Title" to be the same, so the rate change is transparent to the user)
Configure each flat rate component to have a condition on "Total product quantity comparison" so that only the appropriate rates show up based on number of products. Note this will only work if you use the standard line item type "Product" ... if you have custom line item types, you will have to create a component that does the comparison/counting that you need.
In order to count the number of eligible products, we will need to create a component rule that has a "line item" parameter and has an "number decimal" provided called "is_a_product".

This component simply needs to have a condition on entity bundle for "Product" and needs an action that "sets a data value" ... the is_a_product ... to the line-item:quantity.

Next, we will need to create a pricing rule for your first "Medium" level shipping price calculation.

A. Once you discover where to create the shipping price calculation rule you will need to create two conditions:

Entity has field (it should have the shipping service field)
Data Comparison (the shipping service field should equal the medium shipping service)

B. Now you will need to count the number of products. Let's add an action "create a variable" for an number decimal called "num_products"

C. Next you will need to loop over all the line items in the order.

D. Next you will add an action for the component you created in step 4.

E. Then you will need to "Calculate a value" by adding the "num_products" and the "is_a_product" (through some testing I confirmed the integer is zero by default) and then save the result by "setting a data value" and setting "num_products" to the result value

F. Finally, you will need to "Multiply the unit price by some amount" and select the num_products as the multiplier
Repeat step 5 for each breakdown of product quantity rate change


As documentation says:

  This hook is invoked before the field values are handed to formatters for display

It will not be called when content is served from cache - as values are not handed anywhere, it's just output taken from cache table (or other cache bin) and sent to display.


Assume that the path to the view you want to show is "SomePath". Then just create a rule with a Rules Action to "perform a redirect", to the path SomePath.

For a rule with such Rules Action, you just use whatever Rules Event that fits your needs (something related to user points I assume), and optionally add whatever Rules Conditions that fit. For a rule that you can probably use as a good starting point, have a look at my answer to "How to change user info with a rule when Points are granted to user (using userpoints module)?" (if you'd just add a Rules Action to redirect, you may be close already).


Drush API for downloading module from a script

If there's an API for this, I think it would be drush_invoke_process. I believe Drush uses that function internally when one command wants to execute another.

The primary function that executes the download work is drush_pm_download(), so you could probably just call it directly as well.

And of course, as a last resort, you could use exec(drush @alias dl $module).


Strategy for unit testing classes that interact with the Entity API

So I'm wondering, is it better to just write Kernel tests / Browser tests for classes that interact with the Entity API or am I simply writing my code wrong, which is making it hard to unit test?

In my opinion yes. The Entity API is not designed to work well for mocking/unit tests. Drupal 8 was a very different thing when we started designing and implementing it. Maybe we'd do things differently today, but the kind of extensibility it offers is hard to manage. And we also needed something that we could gradually convert the large Drupal core code base or it would never have been possible.

In regards to the testing pyramid, that is the ideal scenario, but it's not always feasible. I also think that it is makes more sense in a scenario where you built and control the whole system. By building on top of Drupal (which in turn builds on top of Symfony), a huge amount of the complexity and heavily lifting is already taken away from you and covered with the test coverage of those projects. Given that, it makes sense to me that there is a bigger focus on integration/E2E tests as you are mostly integrating existing components.

And if you do have your own components that actually do things worthy of unit tests (and not just shuffle data between forms, entities and templates) then one thing you could do is work with Adapter/Value objects that hide away the complexity of Entity Field API with an interface that you can mock.


CCK checkbox or dropdown widget as a field?

The checkbox field is provided by the "Options Widget" sub-module included with CCK. From the .info file:

  Defines selection, check box and radio button widgets for text and numeric fields.

If you're not seeing checkbox as an available type you probably don't have that module enabled.


How to modify attributes of fieldset-wrapper?

Looking at theme_fieldset the fieldset-wrapper class is hardcoded and that div doesn't take any additional classes from the $variables array.

So looks like the only option is to override theme_fieldset in your template.php of the active theme. If your conditional variables are present in $variables then you could do the logic straight in the theme_fieldset override function (replace mythemename with the name of your theme)

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

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend>' . $element['#title'] . '</legend>';
  }

  // Condition/logic here
  $class = '';
  if($variables['....'] == '....') {
    $class = ' well-small';
  }

  $output .= '
';
  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . '
';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }
  $output .= '
';
  $output .= "</fieldset>\n";
  return $output;
}

Otherwise, a more elegant solution (by @Mołot) would be to supply use drupal_attributes like so:

mythemename_fieldset(&$variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend>' . $element['#title'] . '</legend>';
  }

  $element['#wrapper-attributes']['class'][] = 'fieldset-wrapper';

  $output .= '
';
  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . '
';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }
  $output .= '
';
  $output .= "</fieldset>\n";
  return $output;
}


Trying to override the default taxonomy behavior, from a module

Don't implement hook_menu() to override menu items of other modules. Implement hook_menu_alter() for that.


Install routinely failing after database authentication

Guess there are a ton of answers here for the exact same problem: https://www.drupal.org/node/1171756.

Don't really want to duplicate them.

update: In my case I needed to chown -R www-data the directory my drupal files were in, apparently ownership was somehow changed from the apache server, had to change it back. there you have it.


How to copy data from one field to another in same content type using hook_update_N

The code doesn't work because it uses node_save(), which is a function Drupal 8 doesn't implement. (If you click on Same name and namespace in other branches on the documentation page, you will notice there isn't a link for any Drupal 8.x version.)
In Drupal 8, where a $node is an instance of a class implementing EntityInterface, a node is saved with $node->save().
The code is also using functions that are still implemented by Drupal 8, but they are deprecated and they will be removed on Drupal 9 or future Drupal versions.

The documentation for node_load() suggests to instead use \Drupal\node\Entity\Node::load(), but other methods could be used, including the ones the entity_type.manager offers.

Instead of db_query(), the object returned from \Drupal\Core\Database\Database::getConnection() should be used; preferably, the database connection should be injected.

For entities, instead of directly querying its database table, the entity_type.manager service should be used to obtain an instance of the class that handles queries to that entity's database table

taxonomy_term_load_multiple_by_name() has not been marked as deprecated, and it's still present in Drupal 9, but the function it uses (entity_load_multiple_by_properties()) has been marked as deprecated. Preferably, the entity_type.manager service should be used also in this case.

The hook to implement isn't hook_update_N(). As the documentation for that hook says, loading, saving, or performing any other CRUD operation on an entity is never safe to do inside hook_update_N().
The correct hook to implement in this case is hook_post_update_NAME(), which receives the same arguments hook_update_N() gets. The expected return values are the same values expected from hook_update_N().
Since updating all the nodes could possibly cause PHP to time out, depending on the number of nodes the site has, the operation needs to be executed in batches, using the argument hook_post_update_NAME() gets.
The code I would use is the following one.
// Add the following lines at the begin of the mymodule.post_update.php file,
// where this hook is expected to be.
// (Replace mymodule with the machine name of the module you are using to
// implement the hook, in the hook name and in the name of the file containing
// it.)
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\NodeInterface;
use Drupal\taxonomy\TermInterface;

function mymodule_post_update_update_taxonomy_references(&$sandbox) {
  $content_type = 'test_content_type';
  /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
  $entity_type_manager = \Drupal::entityTypeManager();
  /** @var \Drupal\Core\Entity\EntityStorageInterface $node_storage */
  $node_storage = $entity_type_manager->getStorage('node');
  /** @var \Drupal\Core\Entity\EntityStorageInterface $taxonomy_term_storage */
  $taxonomy_term_storage = $entity_type_manager->getStorage('taxonomy_term');
  if (!isset($sandbox['total'])) {
    $sandbox['current'] = 0;
    $sandbox['count'] = 0;
    $sandbox['total'] = $node_storage->getQuery()
      ->accessCheck(FALSE)
      ->condition('type', $content_type)
      ->count()->execute();
  }
  if (!empty($sandbox['total'])) {
    $nids = $node_storage->getQuery()
      ->accessCheck(FALSE)
      ->pager(50)
      ->condition('type', $content_type)
      ->condition('nid', $sandbox['current'], '>')
      ->sort('nid', 'ASC')
      ->execute();
    $nodes = $node_storage->loadMultiple($nids);
    /** @var \Drupal\node\NodeInterface $node */
    foreach ($nodes as $node) {
      $sandbox['current'] = $node->id();
      $sandbox['count']++;
      $taxonomy_terms = $taxonomy_term_storage->loadByProperties(['name' => $node->field_a]);
      if (!empty($taxonomy_terms) && is_array($taxonomy_terms)) {
        /** @var \Drupal\taxonomy\TermInterface $taxonomy_term */
        $taxonomy_term = reset($taxonomy_terms);
        $node->field_b->entity = $taxonomy_term;
        $node->setNewRevision();
        $node->save();
      }
    }
  }
  $sandbox['#finished'] = empty($sandbox['total']) ? 1 : $sandbox['count'] / $sandbox['total'];
}


Hope this will help you, In my case i did it by updating the node and node_revision table's status column set to "0".following code is for form submit action you can do it for your delete action..

function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'your form')   {
 $form['#submit'][] = 'mymodule_form_submit';
 }

}

function mymodule_form_submit($form, &$form_state){
if (//your condition)
            {
            $query = db_update('node')
            ->fields(array(
            'status' => 0,//unpublished the node
                ))
            ->condition('nid',$form['nid']['#value'], '=')
            ->execute();

            $query = db_update('node_revision')
            ->fields(array(
            'status' => 0,//unpublished the node
                ))
            ->condition('nid',$form['nid']['#value'], '=')
            ->execute();
            }
        //  drupal_flush_all_caches();

}


Hope this will help you,

In Drupal 7

The best way to do is to create a new field for user registration form. Lets call the field as domain.

Steps:

Go to admin/config + Account settings + Manage Fields
Add new field

After adding

If you want to show this field in registration then check this

NOTE: If prefer do not show on registration form. May be there a chance to edit. Even though if your making it as disable, it can be change.

When ever the user registration form load, alter the form using hook_form_alter and give the default value for it.

function mymodule_form_alter(&$form, $form_state, $form_id)  {
switch ($form_id)  {
    case 'user_register_form':
       //get field language
       $field_lang = field_language('user', 'field_user_domain');
       //assign default value
       $form['field_user_domain'][$field_lang['field_user_domain']][0]['#default_value'] = $_SERVER['HTTP_HOST'];
    break;
 }
}

When ever the users register the domain also saved.

You can use this field in views as per your requirement.


Proper way to display custom line item fields on checkout form

Solution to this problem is to create custom entity.tpl (Theme developer can suggest filename) and remove printing out entity title.


The previous published revision should be available for the visitors while the current revision is in needs review state

I solved it.

Before the revisioning I loaded the original node first. Then first save the new revision and then save the original node.

My code now looks like this.

$original_node = node_load($nid);
$node = node_load($nid);
$node->revision = 1;
$node->workbench_moderation_state_new = 'needs_review';
node_save($node);
node_save($original_node);


how to update order status in shopping cart to checkout

This is your problem:

$order = commerce_order_status_update($order, "Checkout: Checkout");

You should be passing the machine name for the status

$order = commerce_order_status_update($order, 'checkout_checkout');

See this API doc page on drupalcontrib.org: http://www.drupalcontrib.org/api/drupal/contributions!commerce!modules!order!commerce_order.module/function/commerce_order_status_update/7


Solution for the "to many lines" problem:

function YOURMODULE_views_default_views() {
    $files = file_scan_directory((drupal_get_path('module','YOURMODULE').'/views','.view'));
    foreach($files as $absolute => $file) {
        require $absolute;
        if(isset($view)) {
            $views[$view->name] = $view;
        }
    }
    return $views;
}

This way every view-code can be stored in it's own file inside a views subfolder inside YOURMODULE as some_name.view.


Facebook auto post module not posting to my FB page

Finally found the answer.

In admin/config/services/fbpermissions need to give Publish pages permission for users.


Any suggestions for a adobe indesign like body field?

The WYSIWYG module http://drupal.org/project/wysiwyg will allow you to offer a rich text editor for your users. You can combine that with the Media module http://drupal.org/project/media to embed media files. It won't be like indesign exactly but will allow users to have some freedom with the content.


How to customize drupal node using 'PANELS'

You can't customize the node detail page with panels. You will have to use display suite. DS allows you to do a lot of things, and one of them is "Display Suite allows you to take full control over how your content is displayed using a drag and drop interface."

Hope this helps


How do I collect field values of a submitted webform?

Have a look at Webform Mailchimp , different approach but may be of use

  Provides a webform component that lets users subscribe to a Mailchimp
  newsletter as they submit a webform.


Commerce Product is not visible for anonymous user in search result

Got solutions to Disable Apache Solr Access module and than search works fine for other users as well.
Thank you.


I think you can use Static Field module to add your text as a separate field. In this case it can be shown/hidden by conditional fields


Can I assign a taxonomy to a content type's term_reference field at runtime?

You can create a Content Type named Vehicle and make inherits his fields to your Cars, Van with the help of the Bundle Inherit module. Then you can create a Taxonomy for each kind of Vehicle then you will have.

Vehicle (color, number_of_seats, etc)
 - Car (field_car_tags)
 - Van (field_van_tags)

With this you don't need to write lines of code and you can reuse the fields of the Vehicle Content Type.


Trouble saving canvas as image to the public file directory

You need to create a module, and define a menu path in it using hook_menu(), and the page callback for that script will be your upload script.

function hook_menu()
{
  $menu['mymodule/upload'] = array
  (
    'title' => 'upload',
    'page callback' => 'mymodule_upload_callback',
    'access callback' => TRUE
  );

  return $menu;
}

Note that you'll need to name your hook in line with Drupal hook naming conventions: https://www.drupal.org/docs/7/creating-custom-modules/understanding-the-hook-system-for-drupal-modules

Then your upload callback:

function mymodule_upload_callback()
{
  // Handle your upload here. You will have
  // access to public:// and the rest of the Drupal API.

  // call drupal_exit at the end() to prevent your
  // script from going past this point.
  drupal_exit();
}


If you installed the Internationalization Module, you should have a sub-module called "Variable translation". If enabled, go to admin/config/regional/i18n/variable and choose the variables which you would like to translate.

In your case this would be the ones in the "User Emails" tab. Once checked and activated go to the user e-mail page (admin/config/people/accounts) and click on the different language links at the top of the page to translate.


Filter Images, Audio and video from Media in Views?

You may consider to use File: Mime type filter instead of File: Path.

For all video files the Mime type always has a pattern: video/[video source or format]

it might be for example:

video/youtube
video/vimeo
video/quicktime
video/mpeg
video/mp4

Applying the filter File: Mime type contains video will solve the problem for all video files, not only youtube.


How to add some custom text after a taxonomy field in panels?

You can achieve this by using display suite to add a prefix:

Download & enable the module Display Suite (if not already installed) https://www.drupal.org/project/ds
Go to <my_url>/admin/structure/ds/settings
Enable export field templates

Edit your cvtype taxonomy and click on the Manage Display tab

Choose the one column layout (and save) -> display the name field, click the gears icon & add the prefix


ERR_EMPTY_RESPONSE during installation with PHP 7.3

Drupal doesn’t officially (or unofficially as far as I’m aware) support PHP 7.3 at time of writing.

You should downgrade to PHP 7.2, and probably consider revising your operating procedures so you don’t end up using pre-release versions of PHP.

If you still see a problem, you probably haven’t configured Apache and mod_php correctly for the new version.


Is there a D7 module that allows you to create a content type to be displayed as a system message?

It would be a lot of overhead for this one function but Rules can trigger arbitrary system messages with Token support. Here is a screencast by Node One which can give you an overview and he does the system message example in a couple of the videos. I think that if you need extended interaction with users Rules can be very helpful.


webform "Load a pre-built option list" not shown

I had the formbuilder module activated. There is no possibility to "Load a pre-built option list"! I deactivated it then it works. The problem is, there is not a nice builder ui anymore ;-(


Node reference shows as empty to anonymous users

Found it!

I'm using Organic Groups on this site, and I didn't realize that you could grant access permission (view/edit) on a field level (contrary to the base Drupal permissions system, which works only with content types). Since it doesn't show up on the "normal" Permissions page, it's easy to miss. (It's in configuration > Organic groups > OG permissions overview).

So it was indeed a simple configuration issue.


CSS and JS are stored in files/ folder. This folder must writable in order for Drupal to store the aggregated files.


Exposed filter autocomplete has TID with taxonomy term

One solution can be custom javascript to remove the number from the result: like

(function($, Drupal, drupalSettings){
'use strict';

 Drupal.behaviors.my_module = {
   attach: function(context) {

  // Remove TID's onload.
  Drupal.my_module.remove_tid();

  // Remove TID's onchange.
  jQuery('body').find('#YOUR_FILTER_EXPOSED_ID').find('.form-autocomplete').on('autocompleteclose', function() {
    Drupal.my_module.remove_tid();
  });
}
};

Drupal.my_module = {
  remove_tid: function () {
    let field_autocomplete = jQuery('body').find('.form-autocomplete');
    let autocomplete_tid_stripped = field_autocomplete.val().split(' ')[0];
    field_autocomplete.val(autocomplete_tid_stripped);
  },
};

})(jQuery, Drupal, drupalSettings);

Another solution could be using views_autocomplete_filter module, add a relation to your taxonomy term and instead of entity filter and a filter on  terms name, so there will not id there. a little slower but works.


Why isn't hook_node_access() invoked when a node is created?

As documented in hook_ENTITY_TYPE_access(), hook_node_access() is only invoked when the users try to view, update, or delete a node. The documentation doesn't make it explicit, but when an entity is created, the invoked hooks are hook_ENTITY_TYPE_create_access() and hook_entity_create_access().
With both hook_ENTITY_TYPE_access() and hook_ENTITY_TYPE_create_access(), a single hook implementation returning AccessResult::forbidden() is sufficient to block users from acting on the entity. If you are noticing users aren't allowed to take an action on an entity when you expect them to be able to take that action, that is one of the probably causes.
I assume the code shown in the question is part of the code inside the mymodule.module file, or that a module with that machine name is installed on the site. Differently, Drupal would not consider that function a hook, and it would not invoke it (which could be a reason to say it doesn't work).
As side note, arg() is implemented in Drupal 4.6.x, 4.7.x, 5.x, 6.x, and 7.x, but not 8.x.y, nor 9.x.y. (Click on Same name and namespace in other branches in the documentation page to see the list of Drupal versions for which that function is implemented.)

The code shown in the question should thrown an error about a call to a not existing function.


How do I get the entity ID when inserting a new node?

The ID isn't available in hook_ENTITY_TYPE_presave() (pre meaning before, as in not saved so the database hasn't assigned it an ID yet), but is definitely available in hook_ENTITY_TYPE_insert().

This will work, for example:

function MODULE_node_insert(NodeInterface $node) {
  // No need to check `isNew()`; if it's in an insert hook, it's new.
  $nid = $node->id();
}


How to add only the postal code field to the user registration page?

Use this module Postal Code they can allow to only add postal code in user page

  A very minimal D7 Postal Code (ZIP Code) field with validation for one
  country or a combination of countries


Develop new content type for xml to html translation (Drupal 6)

Here is an idea that will keep coding to a minimum using already existing modules:

Using CCK if D6 or the fields if D7 create a regular content type and add an extra field for the XML as I will use the automatically added body to store the XSLT. On the content type display section hide the XSLT field, this way the data is collected, but it is not shown when the node is been view.
I will install the custom formatter module to create a text formatter where I can apply the XSLT to the XML and then present it as HTML.
If I can not apply the formatter directly to the body field in the content type display settings I will the hide both fields (body & XSLT) and using views attachment in D6 or EVA in D7 attach the body field with the formatter applied to the content type.
Last but not least if I plan to re-use this setup in others sites I will use the "Features" module to exported.


How to add number format function in decimal results in views 3

You could rewrite the field output and use PHP to adjust it to your needs.

EDIT: To be able to actually use PHP in your rewrite rules you need an additional module called Views Custom Field.


How to add a condition for an array on an entity query for a config entity?

A config entity doesn't use a normalized table structure, so the normal array conditions which use JOIN don't work. Instead do a condition on property.*:

$query = \Drupal::entityTypeManager()->getStorage('user_role')->getQuery();
$query->condition('permissions.*', 'administer nodes');
$query->execute();


You have to actually go into your entity reference field settings on your content type and enable the following:

Render Views filters as select list.
Provides a select list for Views filters on this field. This should not be used when there are over 100 entities, as it might cause an out of memory error.

This will then allow your exposed filter in views to be rendered as a select list.


How do I divide taxonomy term pages by content type?

A couple approaches come to mind, I will outline the one that does not use panels.

Start by overriding the default taxonomy page by enabling the one that comes with views.  At this point you will have the same behavior as the default taxonomy pages.

Clone the default taxonomy view and disable the clone (this is case you want to restore the view).

Now back to the taxonomy view

Remove the existing two contextual filters  (not this means the depth feature will no longer be available)

Add a contextual filter on "Content: Has taxonomy term ID"
Add another on "Content: Type".

Change the path to "taxonomy/term/%/page" (for page use the content type machine name you want for this tab)

Change "menu" setting to "default menu tab"

(A) Clone the "Page" display, I gave by clone the name of the content type for the tab

(B) Change the path so "page" is replaced with the next content type you want.

(C) Change "menu" setting to "menu tab"

Repeat (A) (B) and (C) for each content type/tab


Views3 - Is there are feature in Views3 that allows for authenticated users to change the fields in a view?

you can allow users acces to the views UI but you couldn't limit that just to "fields". It wouldn't be end user friendly either.

You might want to show all fields in your view and then hide the fields dynamically with css.

If you want it more robust you can use a hook like hook_views_post_execute to remove fields dynamically.


Make Openlayers center & bounds context aware

I figured it out. The key is adapting https://drupal.org/node/904898 by switching Geo Taxonomy to Geofield or Postgis for Drupal 7.


feeds_ex module tests returns me fatal error

Per the instructions for the Feeds extensible parsers module:

  To run tests locally, the TUnit module is required.

So you need to install the TUnit module, which contains the missing class.


You are dsm'ing a string, try dsm($view);


Can I use AddressBook values to populate a webform field?

I was able, lately, to use a list of existing profiles in a node field. As these profiles are entities, an 'entity reference' field can do the job. But I can't offer the possibility to choose from a list of entities in a webform though.
Now, I get a token related to this newly created field but not to the current user.


How to get add term form of taxonomy inside node type form?

Have you tried this module? It's pretty much what you could need:

Inline Entity Form


There are some different things which could be improved in your code, like using dependency injection, better naming etc, but none of these effect performance.

There are some different things which makes it quite trigger to give a good answer to this. Drupal 8 is still in beta and many performance optimizations are being made. The render cache and page cache should be usable in your case making subsequent requests cached and this a lot faster than the initial request. Being logged in / logged out make a big impact as Drupal has a hard time caching for logged in users, but this is nothing new.

That said, it still sounds a bit slow, but hardware, setup etc also have a lot to say.

So long story short, you can't really performance improve your code.


Finding entity/webform fields in the database

I used a query similar to this to help me find a list of tables and columns I needed to update:

SELECT DISTINCT
    table_name,
    column_name
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    column_name LIKE '%user%_target_id'
    AND (table_name LIKE 'field_data_field%'
    OR table_name LIKE 'field_revision_field%')

It's not ideal, and it still missed a couple tables.

I put the resulting list of tables and columns into a Python script and generated the SQL update statements I needed to run.

There is probably a better way to do it.


You need to create a block view with all content. Then filter content for your specific term by adding a filter-> content type.

Then add a Content: Has taxonomy term ID. On the config of the later. When the form value is not provided in the URL choose provide default value -> Taxonomy term ID from URL.

Enable load default filter from page and load default filter from node. On the latter enable your vocabulary.

Afterward, config the case that the ID is present on the URL. Specify validation criteria by choosing taxonomy term and again chose your vocabulary.

It should work!
Check the whole tutorial on http://www.drupalgardens.com/videos/410746


I can't create a book under Internet Explorer 7

Actually, it is an issue that continues into modern versions of IE as well.

If your site has the jQuery Update module running, http://drupal.org/node/860966 speaks of the issue; the real issue is found in comment #6.

The only reason I am following up on this post here is that it is has a high in Google search,  and I figured others are looking for how to solve the issue.


Ajax is not working for Drupal comments form

I had a similar issue with ajax pagination provided by views. I was equalising the heights of the columns using javascript but it was only working on the first page. Any columns loaded via ajax weren't having equal heights calculated. The solution to my problem was to stop using jQuery's once plugin in my behaviour. This was making it execute only once but I needed it to execute infinitely.

Usually a behaviour looks like this:

Drupal.behaviors.ajax = {
    attach: function(context, settings) {
      $('.your-target-element', context).once('ajax', function(){
       var $this = $(this);
       // do stuff with $this
      });
    }
  }

But you want to drop the once plugin like this:

Drupal.behaviors.ajax = {
    attach: function(context, settings) {
       // do stuff
    }
  }


Try to implement the hook_theme_registry_alter()

/**
 * Implements hook_theme_registry_alter().
 */
function sporthron_theme_registry_alter(&$theme_registry) {

  $module_path = drupal_get_path('module', 'sporthron');

  // Find all .tpl.php files in this module's folder recursively.
  $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
  // Iterate through all found template file objects.
  foreach ($template_file_objects as $key => $template_file_object) {
    // If the template has not already been overridden by a theme.
    if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
      // Alter the theme path and template elements.
      $theme_registry[$key]['theme path'] = $module_path;
      $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
      $theme_registry[$key]['type'] = 'module';
    }
  }
}


How do we know the required parameters of hook's callback method?

I've never had to use this specific hook before, but I have found a breakdown of the callback in the Drupal docs:

https://api.drupal.org/api/drupal/modules!filter!filter.api.php/function/callback_filter_process/7

Pretty sure everything you're after will be described in the documentation. You can view all the other Filter API functions within the documentation here:

https://api.drupal.org/api/drupal/modules!filter!filter.api.php/7


Modify the display of one field by the value of another field

Add a boolean field as a condition to hide the end-date is a fine solution. For hiding the field you can either check for the boolean in the template:

{% if $node->field_hide_end_date->value %}
    {{ $node->field_range->value|format_date('my_custom_date_format') }}
{% else %}
    {# Original version of the field #}
    {{ $content['field_range'] }}
{% endif %}

Or change the value in a preprocess method

function custom_module_preprocess_node(&$variables) {
  if (array_key_exists('field_period', $variables['elements'])) {
    $node = $variables['elements']['#node'];

    if ($node->field_hide_end_date->value) {
      $variables['elements']['field_period'] = [
        '#markup' => (new DrupalDateTime($node->field_period->value))->format('d-m-Y'),
      ];
    }
    // else: business as usual.
  }
}


Theme and Override Privatemsg messages/view/%thread

Take a look at privatemsg-view.tpl.php.

There is a preprocess hook where you may add theming variables to the privatemsg-view.tpl.php and execute any PHP code there. In my case it was:

<?
function MYTHEME_preprocess_privatemsg_view(&$vars) {
  $vars['author_uid'] = $vars['message']->author->uid;
  $vars['realname']= MYMODULE_get_realname($vars['message']->author);
}
?>

So here are some alternatives to populate the sidebar:

Use this PHP code to trigger a drupal context which will show a block on the sidebar
Programtically create other vars like the ones above. Those vars may contain sidebar data  you can use when theming the TPL file which contains the sidebar.

Also, here is a full privatemsg theming guide.


Drush says it needs Composer, but Composer is already installed?

There is a Drupal core isssue about this: Catch error(s) from composer install not being run and return friendly error.

tl;dr

Basically, you need to run composer install from inside your docroot.


You don't need PHPMailer. You will need an SMTP server of some description.

If your server is Linux, you will need to install some method of sending email such as postfix. You could either let the server distribute email itself, or configure postfix (or whatever) to relay it to another email server.

If it's Windows, I believe you can configure PHP to use an external SMTP server without needing one on the Drupal server itself.

If you were set on sending messages through Google's SMTP servers, you will probably want to use PHPMailer, as it's set up to make that sort of thing easy. Getting hold of your own SMTP server is not tremendously difficult, however.

Can you tell us more about your hosting environment? Maybe we could be more specific with the answer.


How to select a particular node reference in a view programmatically

Within the views API, you could use this field as an argument and then use PHP to supply the default argument.  This would then restrict the views to all catalog_items that have that specific category node referenced.

If you are doing this in code/a module/template/etc, you could do it also like this:

$nid=WHATEVERPHPCODEYOUWANT;
return views_embed_view(VIEWNAME,'default',$nid); // 'default' is the views display


How can I import a local database remotely without having a local database copy?

Well, there are two things that can be done with this.

1) Database sanitisation

You can write custom Drush sql-sanitize scripts that will sanitize the database, for example changing all usernames and passwords, as well as any other custom alterations required.

Drush SQL Sanitize scripts can be set up as webhooks, to ensure the sanitization happens automatically.

2) With D8, you mostly shouldn't need to give anyone the database at all. Functionality is migrated through configuration and the configuration API. Developers can work on code, then export their configuration, and push both the code changes as well as the exported configuration to the remote server. The configuration is then imported into the remote environment's active configuration in the database, providing the new functionality on the remote server.

I wrote a blog series on the Configuration API to help understand it better: https://www.morpht.com/blog/drupal-8-configuration-part-1-configuration-api


Unable to load URL when drupal is installed on a server

I know that deleting a module does not result in the URL not loading it simply removes the module from the Module List.

That's incorrect. If you delete a module without first disabling and uninstalling it, you could easily break the whole site. You're removing code that you've told the system exists when you installed the module, and it has no way to recover from that.

You should restore the deleted files temporarily, disable then uninstall the module properly with Drush, or through the UI, and only then should you delete the files.


In general, yes, the form should update with the values you set.  However, there are few different ways you can override form settings.

The two in question are cache and block_cache.  You need to search the files for lines that look like:

$conf['cache'] = FALSE;
$conf['block_cache'] = FALSE;

The integer 0 or the string '0' or "0" may be used instead.  Checking the settings.php for the site, and any custom modules.


How to hide a block enitirely which has empty content (unless for a specific role)?

From the question details (and comments to it), it appears to me that the "(empty)" is somehow the result of your Views output (formatted as a block).

But for anybody who has not the role of Photographer, the result of the View (the output of it) is just "empty". So you may want to try / experiment with the "No Results Behaviour", which is located in the most right column when editing the view details (within 'Advanced').

Also note that you should make a difference between "access" to the content of the nodes (or whatever) that are shown in the block (if not empty), and what Drupal shows as the wrapper/container of such list (such as the block your question is about). Maybe, just for debugging purposes, you should try to build a similar view formatted as a page (instead of a block), and see what kind of output (result) you get in both scenario's (somebody with the photographer role, and somebody who des not have that role). While doing this page-related experiment, you may get different results, depending on what you specified within the "No results behaviour". And that might help to understand that your (empty) block issue is also a matter of "No result behaviour".

If you cannot get it to work this way, you may want to consider using the BEAN module, which gives you way more granularity / flexibility for creating blocks.


Configuration Manager or hook_update() to enable modules

For site-specific changes, I would definitely go with using configuration deployments.

They have a very interesting advantage and difference to enabling modules in update hooks/through the API yourself. Config deployments can handle changed default configuration while installing the module.

A module might provide default configuration like views, settings and so on. They might also programatically do things during hook_install() that you want to customize (like configuring default formatters/widgets for fields they add) Configuration deployment allows you install a module locally, customize it and deploy the result as an atomic operation (as much as is possible) to production.

I'd only use the API and hook_update_N() if it's a functional change in a module, e.g. when a module is split up into a new one and/or has a new dependency that is mandatory for it to work.

Also note that I would advice against doing both in the same deployment. Update hooks might run code and create config that will result in differences on every run (like creating a new configurable field). Running config deployments first isn't possible anyway and will soon be prevented explicitly in core and running after might result in the deployment removing and re-adding configuration due to different UUID's.


Links in map markers are for default language pages, not localized

Here is how I solved it:

When creating View I added Language into Fields and Language into Filter Criteria.

That simple!


How to designate a region for regional shipping charges by weight with drupal commerce?

You can try out Commerce Shipping Postal Code Weight, which sounds like it might solve your problem.


How to add 'title' attributes to breadcrumbs links?

You can use hook_menu_breadcrumb_alter().
I think it is

$item['localized_options']['attributes']['title'] = 'The title';

Play around and report here if this works!

It is called from crumbs_CurrentPageInfo::breadcrumbItems(), with some useful data with each trail item.

However, this added data is only available if Crumbs is active. Your module with the hook_menu_breadcrumb_alter() implementation may no longer work correctly if you disable Crumbs.


I think Media Library Theme Reset may be what you're looking for. From the module description:

  this module takes on the responsibility of replicating Seven's CSS and
  attaching it, as a library, in the context of the Media Library, when
  accessed via Layout Builder.


Drupal has theme() which can be used to create a table in a form. Your theme function must be registered with hook_theme().

function MODULE_NAME_theme() {
  return array(
   'MODULE_NAME_header_menu' => array(
     'arguments' => array(
       'form' => NULL,
      ),
   ),
}

function theme_MODULE_NAME_header_menu($form) {
  $rows = array();
  foreach (element_children($form) as $key) {
    if (is_numeric($key)) {
      $wt = $form[$key]['weight' . $key]['#value'];
      $menu_title = drupal_render($form[$key]['title' . $key]);
      $row[] = array('data' => $menu_title);
      $href = drupal_render($form[$key]['href' . $key]);
      $row[] = array('data' => $href);
      $weight = drupal_render($form[$key]['weight' . $key]);
      $row[] = array('data' => $weight);
      $remove = drupal_render($form[$key]['remove' . $key]);
      $row[] = array('data' => $remove);
      $rows[$wt] = array('data' => $row);
      unset($row);
    }
  }
  // Individual table headers.
  $header = array();
  $header[] = array('data' => t('Title'), 'class' => 'menu-title');
  $header[] = array('data' => t('URL'), 'class' => 'menu-href');
  $header[] = array('data' => t('Weight'), 'class' => 'menu-weight');
  $header[] = array('data' => t('Remove'), 'class' => 'menu-remove');

  $output = theme('table', $header, $rows, array('id' => 'header-menu-table'));
  $output .=  drupal_render($form);

  return $output;
}

This creates a table with three columns (if the form has three numeric array keys: "title", "href", and "weight") plus a fourth column with a "remove" link.


It is not possible for the default price field, because Drupal locks down the field / widget settings for "locked" fields. This is a general Drupal issue, but you could work around it by using an alternate price field that you add custom to your product type paired with a product pricing rule that swaps that price in at the start of the pricing process. You'd have to do a form alter or something to hide the default price field from your product forms.


How might I create a "step-by-step process" content type?

I agree with Craig Hyatt but I thought I'd expand a bit more.

Train the authors to use ordered lists - Like you said it's more effort for you to train users. Your times better spent developing the final product in my opinion.

Organize each process into a book - Why re-invent the wheel? It provides you with the basics of your requirements out of the box. Using this will give you the extra time spent developing something to work on the cons of using this, or better put you get to spend more time adding helpful stuff than building it from the ground up.

Create a content type with a "step" field - You mention that this could be more work for you but it's not a huge amount, using CCK and nodereference this could give you a bit more flexibility compared to the book route.

Custom module - There's no need to do this, the above two points will give you enough freedom to code around drupals inbuilt options.

The clear winner for me would be to create a content type and build around that. You can actually set up a content type to use book functionality as well which is what I'm currently doing for a large project. So in this case you get the best of both worlds.


how to get all the fields that have been modified on entity save (form submit)?

When you are in the presave hook, the updated $node object will have $node->original, which is the node before things were changed.

Nodes also have a $node->toArray(), method that will flatten the object into a multidimensional associative array.

So, this

array_keys(DiffArray::diffAssocRecursive($node->toArray(), $node->original->toArray())

should

Take the $node and $node->original and convert them into arrays.
Run the two arrays through one of the Drupal helper classes that will generate differences in multidimensional associative arrays.
Return the top level keys.  Because of the ways nodes are built, this will be all of the changed property and field names.


Custom template file for custom view mode on site front page

First of all, tell me where do you put that code? what is its function? node_preprocess?
besides that It doesn't make any sense to define a specific view mode for your view then trying to theme it using views! I recommend you to define fields as view mode, select your fields and theme it in the theme hook suggestion.


You are viewing a Product Display Page. Therefore your context is the nid of the Product Display you are looking at. You now need to load the title and body field and pass that as a string to your view's contextual filter.

You can do this in various ways:

Use
hook_views_pre_view
in a custom module

  Allows altering a view at the very beginning of views processing,
  before anything is done.

  Adding output to the view can be accomplished by placing text on
  $view->attachment_before and $view->attachment_after.

  Parameters

  $view: The view object about to be processed.

  $display_id: The machine name of the active display.

  $args: An array of arguments passed into the view.

You implement this hook in a custom module
check the $view argument for your view's name and display id
load the Product Display using menu_get_object which will return the $node.
Inspect $node to get the title and body, which you then concatenate and you then
set this as the argument on $args which is one of the parameters passed by reference to hook_views_pre_view

.

Use Views Field
View

  There are a lot of cases in views where you want to embed a list
  inside each row. One example could be, you have a list of groups, and
  for each groups you want to list the first and last name of all of
  their members.

  This can be achieved with this module, as views_field_view allows you
  to embed one view into another view and pass arguments along.

For this method you create a parent view block of Product Display (nodes) and for the contextual filter take the node id from the url. This is the view that will display your related products. After you have constructed it test it so that it shows the exact same product as the product page you are embedding it on.

So now you have a block that shows the same Product Display as the main page shows. Now you need to link it to the search api view.

First change the fields. Make sure that you have title field and body field added to your parent view, then set them to be hidden. Add a global text field and using the tokens from the above two fields add them with a space between them as in : [title] [body] so that the title and body is now one field. Again set this field to be hidden.

Because you installed Views Field View you can now add another field Global:View field. This field allows you to select a view to embed. You now select your search api view. It also allows you to pass parameters to the view, so you select the token for the global text field that is hidden.

Lastly set caching to some time value for this view so that it performs quickly.

ADDED

For option 1 (custom module) the code will go roughly like this (I currently don't have Drupal installed so I can only provide pointers. You will have to inspect the $node object via dpm() to get to the body field, which may be on the Product Display node or on the referenced Product type)

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "VIEWMACHINENAME" && $display_id == "VIEWDISPLAYID") {
    $node = menu_get_object(); // defaults are fine
    dpm($node); // comment out when code works
    if (isset($node->content...)) {  // inspect output from dpm to get field
      $argument = strip_tags($node->content...); // same field from if statement
      $args = array($argument);
    }
  }
}


Any chance for alter system settings form via hook_form_alter?

Do not forget at the end of your hook_form_alter() or hook_form_FORM_ID_alter():

$form = system_settings_form($form);

If you don't want to add the "Save configuration" button, you have to add your custom callback submit with $form['#submit'][] = '_my_callback_form_submit'; and :

function _my_callback_form_submit($form, &$form_state) {
  variable_set('my_variable_name', $form_state['values']['my_variable_name']);
}


How to Display Custom Token in Rules UI Data Selector?

Here are 2 options you may want to try:

Rework your Rule so that part of the logic of it you move to another (new) Rules Component (which uses "node" as a parameter) and then in your rules component check in its conditions if those tokens become available.
Use the Conditional Rules module so that within your Rules Action you can add a "condition" where these tokens may show up.

As per your "It appears the token will appear in the field where I can select an email to be sent", either of both options should work, if you use those options AFTER the Rules Action where you can already use the token for sending an eMail.


Set a block region from the block edit page

In Drupal 7 you have the option to set the region of the block within the block's edit page.

I haven't seen a module for this for Drupal 6 let alone earlier versions. I would strongly recommend upgrading to Drupal 7 for this feature and the plethora of other desirable features of Drupal 7 compared to it's predecessors.

I hope that helps...


I think you can only style the view for print adding in your theme a print css hiding some field with css.

stylesheets[print][] = css/print.css