404 Not found : Could not find the controller. Services module

This may not have been part of your issue, as I also think a node id should be where you wrote retrieve. But regarding spyc.php, I noticed that this file should be placed at sites/all/libraries/spyc/spyc.php or you will get an error message on your status page.


How to manually create a menu item for a taxonomy term?

I don't know if there is a module for this, but what you can do is to create it via views. There are two ways I can see:

Install Entityqueue.

  The Entityqueue module allows users to create queues of any entity
  type. Each queue is implemented as an Entityreference field, that can
  hold a single entity type.

  For instance you can create a queue of:

  Nodes
  Users
  Taxonomy Terms

Install Flag and Views Bulk Operations, then add a bulk operation on the flag in the specific view's UI.

Make sure to cache your views for better performance.


Yes there most definitely is. Checkout Pathauto. There are many contrib modules for this type of common functionality at Drupal.org.


Those variables have been changed in beta16/RC1.

See HTML template head, scripts, styles and scripts_bottom replaced with placeholder_token:

Before

{{ head }}
{{ styles }}
{{ scripts }}
{{ scripts_bottom }}

After

<head-placeholder token="{{ placeholder_token|raw }}">
<css-placeholder token="{{ placeholder_token|raw }}">
<js-placeholder token="{{ placeholder_token|raw }}">
<js-bottom-placeholder token="{{ placeholder_token|raw }}">

The markup should be stable now with RC1, but when you're having trouble with a custom template, always compare it with the core default markup in the module providing it and/or the classy theme.


In Views 2, display only one value and leave blank all other values

Have a look at the Views PHP module. This allows you to check any field of the view with an if-statement (or wgatever you like). Not really a very nice solution, but simple.


storage_api The file could not be uploaded

Found the issue.  Turns out the Directory Path in the local container, which is the initial container, for the storage class the content type is using NEEDS to have a trailing slash. As in:

sites/default/files/storage/

instead of:

sites/default/files/storage

it's that picky.  and the log does not say its the issue.  it just says it had trouble accessing the field.  I found it by trial and error.

I hope this helps someone.


How do you handle multiple feed URLs in a migration?

You should be able to list any URLs that should be fetched:

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  urls:
    - http://myfeed.com/newsfeed/get.php?id=123456
    - http://myfeed.com/newsfeed/get.php?id=123457
    - http://myfeed.com/newsfeed/get.php?id=123458

The Url plugin in migrate_plus converts single url values into an array by default: https://git.drupalcode.org/project/migrate_plus/blob/HEAD/src/Plugin/migrate/source/Url.php#L34


How to assign a section to a specific node with Workbench?

You could try an insert query to inject the access ID, node ID and access scheme into the workbench_access_node table.


Need help with superfish module on Bartik theme

You need to add this block in Featured region.Check out this https://d25zd.ply.st/

You don't need any code just place block by admin interface.


File Upload visible in $_FILES but drupal file functions create empty file

Drupal forms which include a file upload field must also set the encoding type to multipart/form-data.

  $form['#attributes']['enctype'] = 'multipart/form-data';

Reference: Drupal.org: Uploading Files

There is a good checklist for debugging your situation here:

https://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php

Not mentioned in the checklist there is that Suhosin, a commonly installed extension, can empty some submitted values. As well as following the checklist in the linked question, check to see if you have Suhosin installed - if so then you may be

One thing I'd try straight away is whether uploading a very small file triggers this bug. If so that might suggest that you're hitting a limit in PHP's max post data or Suhosin.


Concatenating translatable strings is not allowed, use placeholders instead and only one string literal

It means you have to use a placeholder, in the same way you used the %percentage placeholder.

$report .= '
' . t('%percentage of @content-type completed. %count', array('%percentage' => $percentage, '@content-type' => $node_type_get_types[$type]->name, '%count' => $count)) . '
';

I used a @-placeholder for the content type, in the same way done from node_add().

For a list of the placeholder types used from Drupal, see format_string(). The documentation for t() explain in details why concatenating is not possible in translatable strings.


Data export import module node id different after imported

You can use UUID module, some quote from module page :

  This module provides an API for adding universally unique identifiers
  (UUID) to Drupal objects, most notably entities. Features in Drupal 7
  version Automatic UUID generation

  UUIDs will be generated for all core entities. An API is provided for
  other modules to enable support for custom entities. UUID API for
  entities, properties and fields

  With this unified API you can load entities with entity_uuid_load() so
  that all supported properties and fields are made with UUID
  references. You can also save entities formatted this way with
  entity_uuid_save() (depends on Entity API). Export entities to use as
  default/demo content

  The integration with Features module provides the ability to export
  UUID enabled entities with intact dependencies and references to other
  entities. This functionality depends on Deploy module 7.x-2.0-alpha1
  (soon to be released) and is probably the most robust way for
  installation profiles and distributions to provide demo content!

The problem is that Drupal uses serial ids for the content (nodes), so if we have the same site installed different places, the id for the same content most likely will be different. (fx in one environment the node id might be 137, while it on another might be 153)
This makes it very hard to track changes on the same content in different environments. The idea with UUIDs is to create a id that is the same on all environments.


How do I programmatically create a new content type?

If I were you, I would consider using the Features module. The module enables exporting a subset of websites structure into a single feature to facilitate re-using this feature elsewhere.

Also, Features module enabled exporting content types/fields easily, you would just tick a certain content type and Voila! The Features module will generate Drupal hooks for you, and also export the code into a module.


There is a Notifications module for Drupal that creates a framework for sending out notifications. There are already many modules using the framework. There's a development version of an extension module called Notifications Rules for integrating this with the Rules module if needed.


Database corrupted getting the site crash

As webdrips has said, your error seems to be with the xmlsitemap module, and considering it is not critical for functionality, you should try disabling it.

Depending on the state of the website, if you are experiencing WSOD, you may need to disable the module through the database using phpmyadmin.

In the system table, find the xmlsitemap module, and edit the row where the column is "status", and set that to 0.


why is hook_access_node running three times?

Yes it’s perfectly usual for a node access hook to be hit multiple times in one request, check the $op parameter to see what you’re dealing with each time.
Checks may be done for different $op values like view,update and delete.
(Answer from @Clive in comments, posted here as answer after his advice. Please see question's comments.)


From admin, when create users and assign roles i.e. admin/people/create, there is a textbox open where admin can insert the expiry date.


How can I debug a Views 2 block argument set via "Provide default argument" and "PHP Code"?

After more testing it appears that the watchdog function does work for debugging the embedded PHP code in the Argument Validator and Argument Default Value. I believe my validation was too strict previously and was preventing any output. For example embedding the line below in the "PHP validate code: " area gives all the argument components.

watchdog('block-args-php', var_export(arg(), TRUE));


Multiple submits form and Ajax: Select which submit button is triggered

My solution was to remove the Drupal click event:

'event' => 'click',

And to manually add it via jQuery by finding the next input button:

$('input.form-text', context).once('field_validation_keydown').keydown(function(event) {
  if (event.which == 13) {
    $(this).parent().nextAll('input.ajax-processed').trigger('mousedown');
  }
});

But if anyone has a better solution, I'm curious to know about it.


how to automatically retrieve selected value

You need to use Form API Ajax. There you can see how to use it, Examples for developers include good ajax forms too.

Just remember, to set value to display, use $form_state['input'], not $form_state['values'].


How To organize Taxonomy Vocabulary with overlapping terms - Content Display pages and future proofing

I'd not use a taxonomy at all for implementing what you're asking for. Instead I'd use the Entity Reference module and add an entity reference field like so (in the order specified):

create an extra content type (say) "Artist".
create a node for each Artist you ever want to be able to reference in any of those 4 fields.
make each of your 4 fields an entity reference field.

That's all you'd need.

If I may say, this would still be a solution that could work if some day you have hundreds (thousands?) of Artists. If however you'd use your option 1, or option 2 (using vocabularies), do you think that would still be "usable" (practical)?

However, you may then also want to enable the Inline Entity Form module which, as mentioned on its project page, "provides a widget for inline management (creation, modification, removal) of referenced entities".

More info

Have a look at the answers to these questions for some related topics:

What is the feasibility of using Entity Reference instead of Taxonomy?
Entity reference vs. taxonomy.
Convert taxonomy to entity reference.
Article about Inline Entity Form.

PS: this could work for either D7 or D8.


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

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

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


Related Content with References in Drupal 7

I am sure you could do all of this in one view using a contextual filter and using that as a relationship to point to the movies in question, but, if you don't mind some php coding, you can do all of this pretty easily yourself and one simpler view.

1.  create a view that has a contextual filter using the actor reference field, eg,
it returns just the movies that contain that actor, and in fields, just nid of the
movie node should be sufficient.  Make sure that this will reference any actor in the
movie, eg, all of the values of this field, not just the first one.

Then in your block hook, put in something along the lines of:

$node=menu_get_object();

$movies=array();
foreach ($node->NAME_OF_ACTOR_REFERENCE_FIELD as $actor) {
   $view=views_get_view('NAME_OF_VIEW_ABOVE');
   $view->set_arguments(array($actor['nid']));
   $view->execute();
   foreach ($view->result as $result) {
      $movies[$result->nid]=$result->nid;
   }
}

Assuming this is displayed on a page that is displaying a movie of course, what this does is grab the actors referenced in that node and then loops through them, grabbing each movie that has referenced them as well, and then stores that in an array.  Since we key this array to the movie's nid, we also create a unique list of movies.

So, now we have a list of movie nids so we can do something like:

foreach ($movies as $nid) {
  $node=node_load($nid);
  $content.='<div class="movie-title-link">' . l($node->title, $node->path) . ' </div>';
}

and return $content as the content of the block and style it however you want with css.

Caveat:  I am just learning D7 and a lot of times D6isms creep into play, and most of the above is just typed in from memory, so there may be subtle things you'll need to adjust (drupal_set_message() and print_r() are your friends) but this hopefully will help out.


I'm assuming you're familiar with Services.  In your endpoint,
Copy the pattern here:

                    array(
                        'name' => 'username',
                        'type' => 'string',
                        'description' => 'A valid username',
                        'source' => array('data' => 'username'),
                        'optional' => FALSE,
                    ),
                    array(
                        'name' => 'password',
                        'type' => 'string',
                        'description' => 'A valid password',
                        'source' => array('data' => 'password'),
                        'optional' => FALSE,
                    ),

For your arguments, and add your field machine names.

Inside your callback, you can set $form_state['values'][...] with the passed values, and then use

 drupal_form_submit('user_register_form', $form_state);

To register the user.


How to create a View showing subscribed content?

Subscriptions does not currently have views support.

There is an issue for it here - http://drupal.org/node/269472 - with a patch, however it is missing some parts and the author has not yet responded with the missing code.

I need it so I will be finishing the patch sometime in the next week unless someone beats me to it.

Until then, unless you want to code the views support yourself there is no views/subscriptions solution.


How to make [uc_order] token globally available?

I think you are going about this the wrong way.

You can make the uc_order token globally avaialbe, but it would be a bit messy since some users wont have an order and other people have more than one order.

Instead you should use hook_mail_alter to actually insert the password from the order. You could search for [uc_order:new-password] and if found load the correct order and replace the value with the value from the order.


Yuu can use https://www.drupal.org/project/webform_mysql_views to display submission.

For More info you can visit : https://knackforge.com/blog/sivaji/displaying-webform-submission-data-drupal-views


How do I show username & email address of currently logged in user on a page he is viewing?

You can create a block with the PHP code format (don't forget to activate the PHP filter module) and put inside:

<?php
  //Retrieve the global variable for the connected user
  global $user;
  echo 'Hello ' . $user->name;
  echo 'Your email is :' . $user->mail;
?>

Then you set up this block to show only for authenticated users and you place it in a region.

See Drupal global variables documentation.


Filtering on a field from field collection in a view

You can create a Relationship to the field collection, and then you'll have access to all the field collection's fields within the collection from both "Fields" and "Filters".


Can I store media files in the private directory?

You can use the private file system with media entities. Users who have permission to view the entity they are attached to will be able to access the files. So if your file is attached to a media entity that is attached to a publicly visible node, the node is public, so the file will be open to anyone. If you add some sort of viewing permissions to the node through a contributed module or something, then the files will only be visible to those users.
It is however possible to do custom permissions, using hook_file_download().


As MPD pointed out, page caching is your problem. Even with block caching disabled, the whole rendered page will be cached with page caching on, which includes any blocks no matter whether block caching is disabled or not.

As far as I know that leaves you with at least the following options:

Take the easy route, and just disable page caching.
Use JavasSript to set or update the time client side, you would
still need an initial time source though, perhaps as outlined
here.
As a much larger project you could see how authcache works for
serving it's blocks of user specific non-cached content while the
majority of the page is cached, and implement it for anonymous users
for just the time block.
Use an iframe and get the contents from somewhere it isn't cached.
There are probably more ways...


Field collection translation structure: entity translation vs. node-type translation

It turned out that while I had field collections enabled in /admin/config/regional/entity_translation, the language must be set to "Language neutral" for field collections. This creates a single "und" row, and the child text fields can have their own entries for language.

Also, make sure the "Field Translation" setting is disabled for field collections under /admin/structure/types/manage/{your_content_type}/fields/{your field collection field}. This way, the field collections won't be translated, but the underlying text fields will be.


Where do I fetch myself complete definition for a bundle?

To get the language specific configuration of a bundle use ContentLanguageSettings::loadByEntityTypeBundle.

For the translatability of the bundle, you'd use:

$settings = ContentLanguageSettings::loadByEntityTypeBundle($entity_type_id, $bundle_name);
$isBundleTranslatable = $settings->getThirdPartySetting("content_translation", "enabled");

You could also use ContentTranslationManager:

/** @var ContentTranslationManager $contentTranslationManager */
$contentTranslationManager = \Drupal::service('content_translation.manager');
$isBundleTranslatable = $contentTranslationManager->isEnabled($entity_type_id, $bundle_name);


global static variable to be accessed in comment.tpl.php, node.tpl.php and in page.tpl.php

You can use preprocess functions to add template variables in Drupal.

For example, you could use a generic preprocess function like

hook_preprocess

And add your variable there.

It will then be available in all the other template files.


Your css is the problem.   There is no images/bg.gif.  There is an image/bg.png file.

Change

body {
    background: url("images/bg.gif") repeat scroll 0 0 transparent;
    color: #666666;
    font-family: Tahoma;
    font-size: 12px;
    padding: 0;
    text-align: center;
}

to:

body {
    background: url("images/bg.png") repeat scroll 0 0 transparent;
    color: #666666;
    font-family: Tahoma;
    font-size: 12px;
    padding: 0;
    text-align: center;
}


You can retrieve the Drupal menu link & cache services to programmatically change the menu link status. Something like this example function:

function menu_state_toggle($menu_id, $enabled = TRUE) {
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $front_page_link = $menu_link_manager->getDefinition($menu_id);
  $front_page_link['enabled'] = $enabled ? 1 : 0;
  $menu_link_manager->updateDefinition($menu_id, $front_page_link);
  $cache = \Drupal::cache('menu');
  $cache->deleteAll();
}

menu_state_toggle('standard.front_page', FALSE);


Display all dates for a multi-day "event"

You have removed the repeat date option for date field. Please check your content type, for repeat date you must have to enable repeat option of date field.


Can I add to an existing Entity schema from my own custom module

your my_module_schema_alter is missing a schema parameter.

fixed:

function my_module_schema_alter(&$schema) {
  $schema = array();
  // Create the quiz node results table
  $schema['quiz_node_results']['fields']['time_taken'] = array(
    'type' => 'int',
    'size' => '10',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Stores the user inputted estimated time.',
  );
}


How to alter commerce cart view to show custom line item data - either through UI or custom module

If you're wanting to display information from inside the $order->data array, then you'll need to create a Views handler for each value and write some code to load the object, access the data, and then display it. An example of how to do this can be found in the GetID3 views integration. It loads file metadata and exposes it to views, but the idea is the same.


How to force child page added to book outline to top or bottom; update outline without clearing cache

As an answer to the first question above about updating a book outline display without clearing the cache:

Add the following to a custom .theme file (see drupal.org/docs/8/theming) to add a tag to the cached book navigation block:

function YOURTHEME_preprocess_block(&$vars)
{
  if ($vars['plugin_id'] == 'book_navigation') {
    $vars['#cache']['tags'] = ['node_type:{content-type}'];
  }
}

Then add the following to a custom .module file (see drupal.org/docs/8/creating-custom-modules) to flush the cached book navigation block whenever a node of the specified content type is changed or deleted:

use Drupal\node\NodeInterface;
use Drupal\Core\Cache\Cache;

function YOURMODULE_node_presave(NodeInterface $node)
{
  if ($node->getType() == '{content-type}') {
    Cache::invalidateTags(['node_type:{content-type}']);
  }
}

function YOURMODULE_node_delete(NodeInterface $node)
{
  if ($node->getType() == '{content-type}') {
    Cache::invalidateTags(['node_type:{content-type}']);
  }
}

Credit to @oknate for the second half of this answer. See How do you clear cache on a block when node of certain bundle added or updated? for more detail.


hide JSON:API endpoint parameters for a client application

Rather than the JSON:API I would go with the REST resource plugins. Here you are basically only writing controller methods and return what you want. That is already part of the Drupal core:
https://www.drupal.org/docs/drupal-apis/restful-web-services-api/restful-web-services-api-overview
Here is a code example (ServicekontoResource.php):
<?php

namespace Drupal\fms_api\Plugin\rest\resource;

use Drupal\fms_api\Exception\ServicekontoApi\NoServiceKontoResponseException;
use Drupal\fms_api\ServicekontoApi;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\servicekonto_integrator\Exception\ServicekontoResponseStorageException;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * @RestResource(
 *   id = "servicekonto_resource",
 *   label = @Translation("Servicekonto resource"),
 *   uri_paths = {
 *     "canonical" = "/fms-api/servicekonto-data/{session_hash}"
 *   }
 * )
 */
class ServicekontoResource extends ResourceBase {

  /**
   * @var \Drupal\fms_api\ServicekontoApi
   */
  private $servicekontoApi;

  public function __construct(array $configuration, string $plugin_id, array $plugin_definition, array $serializer_formats, LoggerInterface $logger, ServicekontoApi $servicekontoApi) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->serializerFormats = $serializer_formats;
    $this->logger = $logger;
    $this->servicekontoApi = $servicekontoApi;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('fms_api.servicekonto_api')
    );
  }

  public function get(string $sessionHash) {
    try {
      return new ResourceResponse($this->servicekontoApi->provideData($sessionHash));
    } catch (NoServiceKontoResponseException $exception) {
      $response = new Response('Could not retrieve dataset of service konto response.', 500);
      return $response;
    } catch (ServicekontoResponseStorageException $exception) {
      $response = new Response($exception->getMessage(), 400);
      return $response;
    }
  }

}


Putting new configuration files in module hook_update_N upgrade?

You can parse and load the yaml file yourself, something like redirect_update_8003:

use Symfony\Component\Yaml\Yaml;

/**
 * Creates the new default redirect view.
 */
function redirect_update_8103() {
  $message = NULL;

  // Only create if the redirect view doesn't exist and views is enabled.
  if (\Drupal::moduleHandler()->moduleExists('views') && !View::load('redirect')) {
    $config_path = drupal_get_path('module', 'redirect') . '/config/install/views.view.redirect.yml';
    $data = Yaml::parseFile($config_path);
    \Drupal::configFactory()->getEditable('views.view.redirect')->setData($data)->save(TRUE);
    $message = 'The new redirect view has been created.';
  }
  else {
    $message = 'Not creating a redirect view since it already exists.';
  }
  return $message;
}


Drush archive-restore not restoring database nor giving error

run the same command with --debug and a MYSQL error will likely be outputted to the screen.

So try:

drush archive-restore /Users/abailey/Downloads/dev-sbirt-reg.20140321_200259.tar.gz dev-sbirt-reg --destination=./dev-sbirt-reg --debug


Where to save larger module content/settings?

Have you looked at Nodeblock?

There is not a general storage table like variable for larger values.

I would consider creating a content type; using the nodes from that content type to programmatically create the blocks, using taxonomy to get finer control if necessary; then admins can just edit the block content like they would a node.


Secondary submit function for form input button

The problem with your code is the default value for the form field attributes. In the case of the "button" form field, these are the default values:

#name => 'op'
#button_type => 'submit'
#executes_submit_callback => FALSE
#ahah['event'] => 'mousedown'

Those are also the default values for Drupal 7.

If you want to use a submission callback for a button, then you need to change the form field definition to the following one:

$form['questions']['buttons'][$counter] = array(
  '#type' => 'button',
  '#name' =>'button_' . $counter,
  '#value' => t('Remove'),
  '#executes_submit_callback' => TRUE,
  '#submit' => array('my_mod_remove_submit'),
);

As alternative, instead of using a "button" form field, you should use a "submit" form field.


You could make a wrapper script panopoly_starter_kit.sh, and determine the path to the script via $0.  Your script would then just run your drush command, supplying the --include variable.  See the drush script for an example of how a bash script can find the directory that the script itself is located.

UPDATE:

Another option would be to use a Drush script instead of a Drush command to do your installation.  You would lose your help output, but you could still process arguments and options.  See drush topic docs-examplescript for details.


Field Collection doesn't support Entity Translation, so my advice is to find another way to achieve your aim.

There is a patch available which has been under development for a long time, use at your own risk.

The Drupal.org issue with it's accompanying patch can be found here:
https://www.drupal.org/node/1344672


How to redirect to referenced entity form with Rules

You want to use Rules for this. It should already be installed since Drupal Commerce requires it.

Create a new rule by going to Admin > Config > Workflow > Rules, and click Add rule.

A rule consists of 3 parts.

The event, the action that triggers the rule.

The event that initiates the rule would be After adding a product to the cart.

The conditions, the checks to make sure the rule applies.

Use this to find your reference field;

Add a rule entity had field and check if the commerce_line_item (I suppose you get that by default) has a field commerce_product. Then add a second check to see if commerce_line_item:commerce_product has a field entity_reference.

Depending on where you created the field you might require several layers.

The actions, what to do if the rule is valid.

You want to use the Page redirect action in the system group. Make sure to click the data selector button, then you can search the redirect path. It suppose should look something like commerce_line_item:commerce_product:field_reference:url.


Rule to loop over products with one specific SKU in Drupal Commerce cart

Your real challenge appears to be this part of your question:

  ... put an if statement in the loop and look at whether the current line item has a specific SKU ...

Here is how to get that to work:

your Rules Loop is inside a Rules Action (of course).
but in a Rules Action you cannot use a Rules Condition ... except if you also use the Conditional Rules module, so that's what I'd recommend you to do to do what you're asking for.
For an example using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?". As an alternative to using the Conditional Rules module, you can also try to rework the relevant part of your Rules Actions into performing a Rules Component. Because in a Rules Component, it is possible to also add Rules Conditions. For more details on using Rules Components instead of Conditional Rules, refer to the answer to "What's the alternative to using the Conditional Rules module?".

Easy, no?

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


Remove shortlink link and meta tag generator

Above code is good but it didn't work because it was overwritten by Meta tag module. I adjust some settings in Configuration » Search and metadata and now generator tag and shortlink is gone.


Using Static Variables in a Custom Module

drupal_static() stores variables based on the name of the function they're related to (hence the use of __FUNCTION__ when you initialise it in the relevant function).

You can pick it up again in any other function by querying drupal_static() again, with the name of the originating function. So in your case:

function viewusercontact_foo() {
  $static_var = drupal_static('viewusercontact_locateuser');
  ...
}


Can't get Varnish working properly, not caching anything. (varnishd is running , status is tick)

By default, Varnish is not working on port 80 (and in this case it could not be either since your Apache is occupying that port). You should configure your Apache to listen to another port, then use that port for your backend setup in Varnish. You should also configure Varnish to listen to port 80.

To debug, you should try to figure out what port your Varnish is listening to now and browse using that port, then you should see traffic in varnishtop.

The reason I'm being vague on the varnish configuration is that I have only used Varnish on CentOS which reads in the startup defaults from /etc/sysconfig/varnish - since you are using Ubuntu you should try to find out where that default configuration is being kept on your system. A fair starting point might be the /etc/init.d/varnishd script which might give some clues.


Tabledrag in Drupal 7 admin pages only working in Firefox

There was a regression introduced in 7.52 related to dragging in the admin interface. It's fixed in the 7.53 release. It may be as simple as upgrading to the latest version of core.

The 7.53 release page, https://www.drupal.org/project/drupal/releases/7.53.


With Drupal there are so many way to do things - here is one way to achieve what you need:

Go to admin/blocks and add your block to the region you want it to show up in, then set it to display on only the page for that view
In your theme css hide that block (display:none)
Add some javascript to display the block and bind it to the onchange event for the value you want, either add the js in your module or your theme.

I have not gone into specifics as each step can have variations on how you would like to implement them, but the above is one potential solution to the problem

Using context could work if you submit the view filter to a different path and then set a context to show the block on that path, but if you wnat to do it via an onChange its easier using Js & Css.

Modules that may also help:

http://drupal.org/project/views_hacks
http://drupal.org/project/views_dependent_filters


How do I re-name my zone--content.tpl.php file for a separate front page layout?

This was too much for a comment so I put it in an answer. newdwardss's answer contains the right methodology, but it doesn't address the Omega theme.

You can use the same logic as in that answer, but customise it for the zone template:

function MYTHEME_preprocess_zone(&$vars) {
  if ($vars['zone'] == 'content' && drupal_is_front_page()) {
    $vars['theme_hook_suggestions'][] = 'zone__content__front';
  }
}

That will allow you to use a template file called zone--content--front.tpl.php which will only be used for that zone, and only when on the front page.


Append image style to an inline image in CKEditor

Use insert module

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

  This module was previously known as FileField Insert.

  Features

Support for all major WYSIWYG editors, including tinyMCE, CKeditor, the WYSIWYG project (the recommended approach), and plain

  text areas.
      Insert images using ImageCache presets
      Maximum width setting for inserted images (for combined use with the Image Resize Filter module)
      Per-field insert configuration

I used that on drupal 7 in several projects and it's what you want.I don't used Drupal 8 version yet,but hope works well.

Hopefully, in Drupal >= 8.8 it's on the core.

https://www.drupal.org/docs/8/core/modules/media-library-module/embedding-media-with-ckeditor


Result accessibility based on field value for specific group

The field permissions module lets you assign permissions to individual fields.


There is already a function that does exactly what you want:

  $result = views_get_view_result('my_view_name', 'default', $arg1, $arg2, ...);

Read more at its page at api.drupal.org:

https://api.drupal.org/api/views/views.module/function/views_get_view_result/7


How do I get all the options of a field?

Drupal 8.9.x still has the options_allowed_values() (a function implemented in the Options module). If the field uses a selection, check box, or a radio button widget, you could use the following code. The same function is still implemented in Drupal 9.3.x, the latest Drupal version under development, at the time I am adding this note.
$field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('entity', 'bundle');
if (isset($field_definitions['field'])) {
    $allowed_options = options_allowed_values($field_definitions['field']->getFieldStorageDefinition());
}

Replace 'entity' with the entity ID (for example, 'node' for nodes), 'bundle' with the bundle machine name (for example, 'article' for Article nodes), and 'field' with the field machine name.
Keep in mind that this code requires the Options module. The module using the code I shown should declare its dependency from it.
Using options_allowed_values() has the benefit that, if the field has a function returning the allowed values, that function is called. The following is the code used by options_allowed_values() to achieve that.
if (!isset($allowed_values[$cache_id])) {
  $function = $definition->getSetting('allowed_values_function');
  $cacheable = TRUE;
  if (!empty($function)) {
    $values = $function($definition, $entity, $cacheable);
  }
  else {
    $values = $definition->getSetting('allowed_values');
  }
  if ($cacheable) {
    $allowed_values[$cache_id] = $values;
  }
  else {
    return $values;
  }
}

Using options_allowed_values() also allow to cache the allowed values. In this way, calling options_allowed_values() for the same field (and same entity type) multiple times has a minimal impact on performance.


created block for image is not displaying

when you create block then you have options for visibility where you want to show this block like below:


I can't get the og_group_ref set in a node form rendered via a custom block

For the benefit of others, I realized the user was not a member of the child group they were trying to add content to. They were members of the parent, but that didn't allow them to add content to the child group in question, so permissions didn't propagate as expected. There is an OG subgroups module (https://drupal.org/project/og_subgroups) which is supposed to help with this, but I wasn't able to configure it correctly for some reason before realizing that this particular application required the user to be a member of the subgroup in order for them to actually post.


Looking for "Edit own Blocks" permission?

Block are not content. They don't have an owner, revision and all that. But there is another way round. You can make some of content to be a blocks with Nodeblock or one of it's competitors:

  This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

That way you can create content type Block, and apply node permissions to it. All of them, including "edit own block".


What does a basic module look like that includes a content type, a couple of fields and a view?

I don't know of an example module that has all of those pieces together, but I think you'll find that field_example and node_example from the Examples for Developers project useful.
As well, this page of the Features documentation mentions something interesting:

Technically, an exported Feature is a Drupal module – it has a .info file and a .module file (along with some .inc files matching the components of the feature).
If you're a developer and find a feature bundle a good starting point for a module, you could just extend the feature by editing its .module file (and if need be also the .info file) to include hooks and what have you.

So you may wish to export your Feature, then develop on it from there based on the samples in field_example and node_example.


How to populate nodes with imagefield programmatically?

I don't have the exact answer to your question, but you could check how other modules do it. Devel Generate for instance (part of Devel) can populate image fields. Check out devel_generate_fields() in devel_generate.fields.inc and image_devel_generate() in image.devel_generate.inc.

Hope that helps.


if you're using the Link module, you can choose how the link is displayed, including plain text

  The link module can be count to the top 50 modules in Drupal
  installations and provides a standard custom content field for links.
  With this module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.


Importing large amount of data slow process with cron and queue

I think it will be good to use multiple queues and separate php non blocking (shell_exec) process to read each queue, the idea is to call a php script to run in background which will pick a queue data and create nodes or whatever.


views display restricted number of results based on nid

You can do this by using the Node: Nid filter.

Add the Node: Nid filter
Select Operator > equal to > Is between and then select the nid before your node as the Min and the nid after your node as the Max.


How can I modify the login form using hook_form_alter()?

When I go to mysite/user/login it doesn't call the block where I have to alter the form. It simply doesn't call hook_form_alter().

example.com/user/login doesn't show the user login block; it shows the login form. Your code should work, even if I would rather make the code simpler (if you are not using "user-login-form" in any way).

function git_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    // …
  }
}

As for the reason why the code doesn't work, I can think of the following reasons:

The hook name doesn't match the short name used for the module; for example, the short name of the module is "git_form" and you are using git_form_alter() for the implementation of hook_form_alter() when it should be git_form_form_alter().
You are editing a module that is enabled. In this case, when you add a new hook to the code, you also need to flush the cache used by Drupal as Drupal caches the list of hooks implemented by third-party modules.
The module is not enabled.


How to change order of taxonomy terms related to specific node field?

I found one way to do this. We need to change the taxonomy field widget to autocomplete. Then you can swap the words there, thus changing the delta.


Your setup is correct.
On visibility settings > Show block on specific pages.
Selected: Only the listed pages:

<front>

Your problem might be that the second page is caching. And it is still showing on that page. Or you have another module conflicting and displaying the blocks.
Is your site publicly visible. Can you provide a URL?


How to exclude the user table using the drush sql-sync command

You can use --skip-tables-list flag on your drush sql-sync command

drush sql-sync @prod @dev --skip-tables-list=user

the table lists should be comma seperated.

For more options on sql-sync check this documentation.


You need to add the :urlencode suffix and change [webform_submission:values:e_mail] to [webform_submission:values:e_mail:urlencode]


Connect Content Type with Related Taxonomy Fields using Template

I solved this by creating two new regions in my theme underneath Content, then I created a View with two blocks: one for taxonomy B and one for taxonomy C.

The view pulls in taxonomy fields using the relationship: Content: Taxonomy terms on node.

I have setup the URL pattern for my content type to be contentTypeA/taxonomyB/taxonomyC. By doing this, I was able to reference the correct term by using a Contextual Filter: Content: Has taxonomy term ID.

The Contextual Filter was a little tricky for me. As it was coming from the URL at a specific level of the path, I found that I could access taxonomyB through the path component 2, and taxonomyC through path component 3.

Under WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED I used Specify validation criteria as the respective taxonomy term.

Finally, using Term name converted to Term ID allowed it to see the plain english term name in the URL path.


Conditionally assign a custom role on user registration

You need to use hook_user_presave. like below,

function mymodule_user_presave(&$edit, $account, $category) {
  if ($account->is_new) {
    $roles = user_roles(TRUE);
    $rid = array_search('Test', $roles);
    if ($rid != FALSE) {
      $edit['roles'][$rid] = 1;
    }
  }
}

Replace the Test with your role name. $account->is_new will be set to 1 during the registration process alone, so your code will not execute when a user updates the profile.


Importing products via Feeds csv import is generating error: "General error: 1366 Incorrect string value:"

Maybe the csv is encoded in UTF8, but everything else needs to be UTF8: UTF8 all the way through

I don't know exactly in what step is failing, did you check the databases and tables collation?
Drupal has by default the "SET NAMES="utf8", http://drupal.org/node/310447

Hopefully the Feeds maintainers have a look to your case here. http://drupal.org/node/1140194 , it seems you are not alone.


Performance: is preferable to use Rules or node_presave/node_save/other hook ?

In practice, it is far easier to debug a hook than a rule that includes a PHP function.  So, not only are hooks faster, they are easier to maintain and less likely to present security risks.

You do not need to remember "in which module foo happens" if you put all your hooks in a single custom module for the site.  Unless you have an extremely large number of tweaks, using a single module (and version controlling it!) is probably the easiest way to do this.

Regardless of the size of the site, if you want to write custom PHP, you should use a custom module, not rules.


Path Auto Use Parent Tag, If it doesnt exist use current tag

Ok I figured it out.
Use the Custom Token Module. Turn on PHP Filter in Core Drupal Modules
Create a new Custom Token in structure
Choose Nodeds in the Token Type
then use this code:

<?php
if (isset($data['node'])) {
    $parent = token_replace('[node:field-tags:0:parent]', $data);
    return ($parent != '[node:field-tags:0:parent]') ? token_replace('[node:field-tags:0:parent]', $data) : token_replace('[node:field-tags:0:name]', $data);
}
?>

It will return the parent tag of the first tag in the list and if none exist it will return the first tag in the list


How to embed username and password in a URL?

There is currently a sandbox module called URL Login waiting to get approved to become a full project. See the project page and the full project application issue.

That module provides a secure way to log in through an URL. If that module is useful to you, I suggest you mention that in the linked issue so that it can become a full project soon.


The api documentation for FormBuilder::submitForm is not exactly correct. The $form_arg argument no longer can be a function, but it refers to the class name or form object of the form. In this case ThemeSettingsForm is the class corresponding to system_theme_settings per its getFormId() method return value.

However I am not sure that calling FormBuilder::submitForm will work from your question because form state may not be valid for the system theme settings form. It may be better to track down what specifically color module is requiring in order to set/save the necessary configuration instead of trying to mock form submission.


How to get nid from URL alias in drupal 7?

The $_SERVER['HTTP_REFERER'] will return the full URL, but the function drupal_lookup_path() takes only the alias as argument, so parse you URL and pass only the alias, john/video/nature-beauty then it will work.

$url = $_SERVER['HTTP_REFERER'];
$path = preg_replace('/\//','',parse_url($url,PHP_URL_PATH),1);
$org_path = drupal_lookup_path("source", $path);
$node = menu_get_object("node", 1, $org_path);
$nid=$node->nid;
print $nid;


How to change the value of the Submit button text when extending ConfigFormBase

The submit button is defined in the base class and you can change it:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['actions']['submit']['#value'] = $this->t('Save my configuration');
    ...


Using the Flag module seems like a no brainer to me to get this to work. Combine it with the Rules module to have a custom (not global) flag automatically flag such article, based on whatever rules Event that would fit. And since Flags are fieldable, you could even add an extra field to it to let your user indicate some type of rating, if that's what you want.


Make a carousel of every node associated with a term in a particular vocabulary

Here are the steps

Make a views of taxonomy terms.
Add a relationship referencing node from that taxonomy terms
Now you will have the required node fields available in views field
Add the required field and change the display to carousel.

I hope this will help.


Views Slideshow Cycle doesn't re-initialize properly after an AJAX content update

I would expect the behaviors mechanism to somehow kill the old scripts
  and settings and replace them with new ones upon processing an AJAX
  response but it doesn't seem to happen and I can't find any
  documentation on this particular aspect.

The D7 Managing Javascript docs explains this well:

  Drupal.behaviors will often be called multiple times on a page. For
  example, every time a form performs some Ajax operation, all Drupal
  behaviors will be executed again after page load, in order to attach
  any relevant JavaScript to the newly loaded elements. This can have
  the undesired affect of applying JavaScript to elements each time
  Drupal behaviors are executed, resulting in the same code being
  applied multiple times. To ensure that the JavaScript is applied only
  once, we can use the jQuery $.once() function. This function will
  ensure that the code inside the function is not executed if it has
  already been executed for the given element.

The D8 Javascript Overview docs tells you how to use $.once() in D8.

If your code is not recognizing the ajaxed in divs, then you need to attach the behaviors to the ajax wrapper, with drupal.attachBehaviors($('.ajax-wrapper'));

Ex:

$.ajax({
    url: '/some/url',
    type: 'GET',
    success: function (data) {
        var result = $(data).find('.some-wrapper').html();
        $('.ajax-wrapper').html(result);
        Drupal.attachBehaviors($('.ajax-wrapper'));

    }
});


How come there are different UUIDs for multiple environments?

The right way to do it is to create a config_sync folder, you can set it like this in the settings.php file.

$config_directories['sync'] = 'path/to/config-folder';

Then you can run drush cex to export current configuration, and run drush cim to import. I am doing this on all my drupal sites and have never ran into any issues.

You shall commit the config files if you are using git so you can import them on production.

UPDATE: As it is described on drupal.org the full export, on the config page is only to use if you move from one copy of a site to another.

  Or the full site configuration can also be dumped as yml files to a tar.gz file. This only works if you're moving configuration between two copies of the same site (e.g. development and production) and for that reason the sites UUIDs must match.

Try to use the drush cex command instead.


Yes, you can add fields to the user entity with the Field API to

Admin > Config > Account settings > Manage fields

The variety of field types are available and each user has their own field value


You could try to override this in your theme. The video module provides the video-play-html5.tpl.php file. You can copy this file to your active theme (copy it to all if your site supports more themes) and add the loop="true" setting to the following line:

<video width="<?php echo $width; ?>" height="<?php echo $height; ?>" preload="<?php echo $preload; ?>" controls="controls" poster="<?php echo $poster; ?>"<?php echo $autoplayattr; ?>>

Clear the cache to have Drupal detect your template override. That should make the video loop. However this would make every video always loop. If you need control per video, you will have to patch bigger portions of the module, add variables etc. It should be handled in the feature request instead. (It would be out of scope here.)


Multi-site - can I route second site to different urls?

Redirecting to a different domain

Redirect URLs From Old To New Domain Using 301 Redirects In .htaccess

When you need to switch a website from an old domain to a new domain, you need to  redirect all your page URLs, this is when htaccess is your friend.

The code below will create 301 url redirects for both the www and non-www version of ‘olddomain.com‘ to the new domain  ‘newdomain.com‘.

Add this .htaccess file to the OLD site webroot and upload the files from the old site to the new to see a seamless switch from an old domain to a new one.

So the example below is redirecting all URLs from olddomain.com to newdomain.com

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.olddomain\.com$
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} !^olddomain\.com$
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

You can also apply this to a subdomain – so the example below is redirecting all URLs from subdomain.olddomain.com to subdomain.newdomain.com

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^subdomain.olddomain.com$
RewriteRule ^(.*)$ http://subdomain.newdomain.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.subdomain.olddomain.com$
RewriteRule ^(.*)$ http://subdomain.newdomain.com/$1 [R=301,L]

For more details


Entering views result to field through rules

I created a sql query through the Views Rules module and it did the trick.


Passive / light-weight / serializable translatables?

See https://www.drupal.org/node/2893029.

Ther isn't really a workaround until that is fixed.


Create separate Group of filters and move a "title" filter there.

Maybe also check all OR and AND (but they seems fine for me...)


I believe that you have machine name of content type while altering node_type_edit_form. So I assume that $node_type is the variable in which machine name can be accessible.

So as stated in drupal list changes, variable_get and variable_set is replaced by config system in drupal 8.

To save a configuration you need to add this code in your submit function :

\Drupal::configFactory()->getEditable('modulename.settings')
    ->set('checkboxsetting_' . $node_type, $form_state->getValues()['checkboxsettings'])
    ->set('radiosettings' . $node_type, $form_state->getValues()['radiosettings'])
    ->save();

and to get the saved values you need to :

\Drupal::config('modulename.settings')->get('checkboxsetting_' . $node_type);

To set the default configuration from yml file. Create a yml file and content will be :

modulename/config/install/modulename.settings.yml

checkboxsetting_page: whatever
checkboxsetting_article: whatever
radio_page: whatever
radio_article: whatever


Update some field values after user update own account

Drupal core doesn't use any hook_ENTITY_TYPE_save() hook and hook_ENTITY_TYPE_update() is called after saving in the database an entity that has been updated.
As the documentation says, that hook implementations may not alter the stored entity data. They shouldn't call save() on the entity they receive as argument, or that will invoke those hook implementations once again; if then those hook implementations don't check if they have been already invoked (which is the case of most, if not all, the hook implementations) and save again the entity they received as argument, that would cause an infinite loop.

The only hook invoked before the entity is saved is hook_ENTITY_TYPE_presave(), which is invoked either when an entity is created or updated. It's easy to understand in which case the hook is invoked, since in the latter case $entity->original will contain the entity before the change.

As side note, the documentation reference to that hook as hook_ENTITY_TYPE_presave(); the implementation done from the mymodule module for the User entity is mymodule_user_presave(). (Replace ENTITY_TYPE with the entity type for which the hook should be invoked, such as user for the User entity and node for the Node entity.)

As for the used code, that is wrong since:

There isn't the need to load the account with \Drupal\user\Entity\User::load($account->id()) because the full User object is already passed to the hook as argument
Since the hook is invoked whenever a new user is created, or an existing user is updated, the code needs to first verify $account->original is defined
The code is setting the username for $current_user, but Drupal core is saving $account; since in PHP those are two different objects, the code isn't changing the username for the User object being saved
$original_email != $updated_email is not comparing the changed email with the original email, but it's comparing the email before the User object is edited with the original email (which is still the email before the User object is edited)

I would use the following code.

function custom_module_user_presave($account) {
  if (isset($account->original)) {
    $original_email = $account->original->get('mail')->value;
    $updated_email = $account->get('mail')->value;

    if ($original_email != $updated_email) {
      $account->setUsername($updated_email);
    }
  }
}

Even better, the code should check the value returned from $account->isNew().

function custom_module_user_presave($account) {
  if (!$account->isNew()) {
    $original_email = $account->original->get('mail')->value;
    $updated_email = $account->get('mail')->value;

    if ($original_email != $updated_email) {
      $account->setUsername($updated_email);
    }
  }
}


How to create a Rule to create a new entity of type Comment and a body with tokens?

Have a look at Comment # 10 of the Rules (support) issue titled "Access and Set Comment extra fields ". It includes a Rule example that looks like so:

{ "rules_test" : {
    "LABEL" : "Comment bot",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_status" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : "zzz",
            "param_node" : [ "node" ],
            "param_author" : [ "node:author" ],
            "param_comment_body" : { "value" : {
                "value" : "This text will be replaced in the next action.",
                "format" : "filtered_html"
              }
            }
          },
          "PROVIDE" : { "entity_created" : { "new_comment" : "New comment" } }
        }
      },
      { "data_set" : {
          "data" : [ "new-comment:comment-body:value" ],
          "value" : [ "node:field-status" ]
        }
      }
   ]
  }
}

The clue to solve your issue (= work around?) is to use that last Rules Action starting with "data_set".


Exposed date filter doesn't work with 'greater than' or 'less than' and 'is equal to'

A friend of mine helped me out, the problem was me not adding time to the search query. I found this already along the way in finding a solution but I didn't understand it at that moment. Now I do.

By not entering a time in the search field (so searching for 28-02-2018) the search will go to 28-02-2018 00:00:00 which is the same as 27-02-2018 23:59:59.

So what I had to do was search for 28-02-2018 23:59:59 instead, when entering this in the search field, the right items do show.


How to have a field that counts the nodes submitted by the current user?

You can use the Computed Field module but you need to consider this:

  When is the field actually computed?

  If you wish to store the values
  in the database then you have to update or re-submit the node to
  compute the value of the field.

  If it is not stored in the database then the value computes when the
  node loads and only when the node is loaded. The field will not work
  in views nor will it function properly if it depends on other
  non-stored computed fields.

This is the code of your field:

global $user;
$type = 'article';

$query = new EntityFieldQuery;
$result = $query
->entityCondition('entity_type', 'node')
->propertyCondition('status', 1)
->propertyCondition('type', $type)
->propertyCondition('uid', $user->uid)
->execute();

$cant = count($result['node']);
$entity_field[0]['value'] = $cant;

Another way that come to my mind is have a variable to store this value, and you will edit this var each time a new node is created (hook_node_insert) or deleted (hook_node_delete), so in this case you will have always the real value.

Rerefences:

Computed Field


I've managed to create new payment and modify authorisation amount. Here is what I have so far:

public static function getSubscribedEvents() {
  $events = ['commerce_order.place.post_transition' => ['captureFee', -50]];
  return $events;
}

public function captureFee(WorkflowTransitionEvent $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();

  if ($order->bundle() != 'training') {
    return;
  }

  /** @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface $payment_gateway */
  $payment_gateway = $order->payment_gateway->entity;
  $payment_gateway_plugin = $payment_gateway->getPlugin();

  $payment_storage = $this->entityTypeManager->getStorage('commerce_payment');

  // Load first order payment
  $payments = $payment_storage->loadMultipleByOrder($order);
  $first_payment = current($payments);

  // Only proceed if payment is not captured
  if ($first_payment->isCompleted()) {
    return;
  }

  // Default fee amount
  $fee_amount = new \Drupal\commerce_price\Price('50.00', 'USD');

  // Get fee amount from product variation
  if (isset($order->getItems()[0]->getPurchasedEntity()->field_app_fee) && !$order->getItems()[0]->getPurchasedEntity()->field_app_fee->isEmpty()) {
    $fee_amount = $order->getItems()[0]->getPurchasedEntity()->field_app_fee->first()->toPrice();
  }

  // Create fee payment
  /** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */
  $payment = $payment_storage->create([
    'state' => 'new',
    'amount' => $fee_amount,
    'payment_gateway' => $payment_gateway->id(),
    'order_id' => $order->id(),
  ]);

  // Capture fee payment
  if ($payment_gateway_plugin instanceof OnsitePaymentGatewayInterface) {
    $payment->payment_method = $order->payment_method->entity;
    $payment_gateway_plugin->createPayment($payment, 'capture');
  }
  elseif ($payment_gateway_plugin instanceof ManualPaymentGatewayInterface) {
    $payment_gateway_plugin->createPayment($payment, TRUE);
  }
  else {
    return;
  }

  // Subtract captured amount from authorized amount and save first payment
  $first_payment_amount = $first_payment->getAmount();
  $first_payment->setAmount($first_payment_amount->subtract($fee_amount));
  $first_payment->save();

}

I have "training" bundle that is limited to 1 item per cart. This is the result with variation price set to $2,100.00 and $45.00 fee.


is installing a module on a live site ill advised?

I successfully installed modules on sites with thousands hits a day. Maybe even an hour. And I must tell it's not wise, from the point of my experience. Sometimes you have no choice (installing captcha on the spam wave when client forbids technical break), but way to many things can go wrong. If your site has any significant number of visitors and you care about your reputation, either:

Install module on a copy of your site
Put your site in maintenance mode
Add .htaccess "maintenance mode" screen
Sync files
Sync data

Or simplier, but with longer break:

Put your site in maintenance mode
Add .htaccess "maintenance mode" screen
Install module

That way if your site dies, visitors will see nice static html screen saying "Sorry, technical break" and you will be able to revert from backups.


How to reverse a drupal patch on netbeans

Use patch to reverse

patch -p1 -R < path/to/patchfile

Use git to reverse

git apply -R path/to/patchfile


hook_node_presave() is only invoked for modules, so you can't implement it in a theme.

It'll need to go in a custom module instead.

From a best practice point of view, that sort of logic definitely shouldn't be at the theme layer, it should be in a module.


Is it possible to hide fields on node edit form or split node edit form in two screens?

You could use different modes on the two routes. Go to /admin/structure/types/manage/fooxx/form-display and there you can configure which fields you want see on which mode.

You can add new modes here: /admin/structure/display-modes

  Note: While Drupal 8 core already comes with "form modes", in Drupal 7 you need to install the
  flexiform module.


Try Popup forms or Colorbox modules. These provide this functionality.


Unset widget tab from media browser programmatically

It should be possible with some code like this:

function MY_MODULE_form_entity_browser_MY_FORM_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#pre_render'][] = 'MY_MODULE_pre_render';
}

function MY_MODULE_pre_render($element) {
  kint($element); //Find the tab you want to remove.
  if (...) {
    unset($element['...']);
  }
  return $element;
}

Another commonly used solution is to create 2 or 3 media browsers depending on your needs.
So you will have an image media browser, a video media browser and an image + video media browser.

Then you just select which one to use in the field settings.


I think you've indented too far. The line following header: true is directly beneath it in the example you linked to.

global-styling:
  version: 1.3.2
  css:
    theme:
      includes/mapquest/css/mapquest.css: {}
js-header:
  header: true
  js:
    includes/mapquest/js/mapquest.js: {}


block to display nodes using entityQuery with pager

The first step is to include a pager in the query $query->pager(10), which you have already done. Then you need a render element pager:

  $build['result'] => $out;
  $build['pager'] = [
    '#type' => 'pager',
  ];
  return $build;

If you have multiple pagers on the site, which is probably the case for a block placed on different pages, you have to connect query and pager with a pager id:

  $element = '123';

  $query->pager(10, $element);

  $build['pager'] = [
    '#type' => 'pager',
    '#element' => $element,
  ];


Add a JS app in Acquia root domain folder

is your frontend an Angular / React / Vue app?
Anyway I don't know Acquia cloud but I can confirm that your setup works on an Apache server. I have my Angular app in the root folder along with the vendor and and web folders, and then I have in the web folder the core, libraries, modules eccc.. folders.


How do I filter only the root terms in a vocabulary in a view?

For displaying only the root terms, I have a solution which surely will make someone facepalm (at least I did that):

Add a contextual filter to your taxonomy view
Select Taxonomy term: parent term.

Set it up like this: When a filter value is not available: Provide default value - Fixed value. Set the value to 0.

Yeah, that's all. Terms without parent have 0 here. See the description of the parent field of the taxonomy_term_hierarchy table:

  Primary Key: The {taxonomy_term_data}.tid of the term's parent. 0
  indicates no parent.


Create user accounts from a content type

One solution is using VBO module, create a view with what content type you want ("membership") then perform a run a PHP code operation on them, and put something like this in Php code

$name = $entity->title; //fill it with what field you want
$email = $entity->YOUR_EMAIL_FIELD_MACHINE_NAME['und'][0]['value'];
$pass = $entity->YOUR_PASS_FIELD_MACHINE_NAME['und'][0]['value'];
$new_user = array(
  'name' => $name,
  'pass' => $pass, // note: do not use md5
  'mail' => $email,
  'status' => 1,
  'init' => $email,
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);

and another solution is create your custom Batch operation   and try some thing like up snippet.


views related content block // show content with specific initial letter

Set argument for second view using hook_views_pre_view().

$view->set_arguments(array('A'));


Remove a code from core module without modifying it(using hooks?)

1) The suggested hook_link_alter() (in your linked question) does not exist in Drupal 7 so it doesn't work like you already found out. On the API page there's hook_node_view_alter() being mentioned which can be used instead. You can implement this specific hook both in a module and your theme's template.php file. To unset the comment link the following should work (updated based on the comment by Ajit):

function myThemeOrModule_node_view_alter(&$build) {
  if ($build['#node']->type == 'book') {
    unset($build['links']['comment']['#links']['comment-add']);
  }
}

If it's not quite right you can try (in your development environment) finding out what to unset by adding the following line inside the function: drupal_set_message('<pre>'.var_export($build['links'], TRUE).'</pre>'); (until you have a better tool available).

2) Overriding template files is handled like paul-m already mentioned by creating a copy of the necessary tpl.php file inside your theme folder and doing all the changes there.

3) If you end up needing to override theme functions then you should create a copy of it inside your theme's template.php file where you can modify it.

Don't forget to clear the caches after adding a new function or template.


Drupal is not powerful enough for this.  Had to write my own module and my own SQL query to get it ordered the way I want.  Maybe in Drupal 8 this feature will be available.


<?php
$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);
?>

Works for me. Make sure that your Content: Nid field is ABOVE the Global: PHP field, otherwise (when it's below it) $row->nid is not available as a variable.

Update
After reading your Q more carefully, since you want it in the footer then you need to specify the node id of the form. (Under what node this comment will be stored) For Example: /node/1
<?php
$comment = new stdClass;
$comment->nid = 1;
$form = drupal_get_form('comment_form', $comment);
print render($form);
?>

If you want /node/5 you change this line to $comment->nid = 5;
OR
If you want this to be dynamic, the nid to be based on the page you're viewing. Then use
<?php
if ($node = menu_get_object()) {
$comment = new stdClass;
$comment->nid = $node->nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);
}
?>

Note: The form will not render/show on views preview, but it will show up when you visit the node.


Implementing the most basic route in Drupal 8 require:

The file containing the routing definitions (helloworld.routing.yml)

helloworld.hi:
  pattern: '/helloworld'
  defaults:
    _controller: '\Drupal\helloworld\Controller\HelloWorldController::hi'
  requirements:
    _permission: 'access content'

A controller class that returns a render array or a string (src/Controller/HelloWordCOntroller.php)

namespace Drupal\helloworld\Controller;

class HelloWorldController {
  function hi() {
    return 'Hello world!';
  }
}

This is the equivalent of what in Drupal 7 was a MENU_CALLBACK. Implementing a local task, or a local action requires other files to be added, differently from Drupal 7, where a local tab would be implemented using the same hook used for a MENU_CALLBACK.


Purchases with points occupying ubercart

Yes you can use userpoints and userpoints ubercart. I did this in the past using drupal7. If you want to use drupal8, you need to check if the modules have been converted.

users can be allocated points by the admin person. the alternative is you have a product for purchasing points.
on checkout, points is presented as a payment option.
users can see their points balance and orders via their account page.

Another alternative is to use commerce_userpoints with its dependent modules (commerce, userpoints). But I believe this approach has a few outstanding bugs on the issues queue.


How to render HTML page with attachments only from the render array?

So this is a working solution. The response has getContent() method so it can be used in code and not only as route response.

function renderHtml($some_content) {
    $html = [
      '#type' => 'html',
      'page' => [
        '#type' => 'page',
        '#title' => 'Some page',
        'content' => $some_content,
        '#attached' => [
          // At least one of these have to have value,
          // otherwise the head placeholder won't get replaced.
          'html_head_link' => [],
          'html_head' => []
        ]
      ]
    ];

    $html['page']['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'Sometag',
        'content' => 'somevalue',
      ),
    ], 'someid'];

    $active_theme = \Drupal::theme()->getActiveTheme();
    $render_theme_extension = \Drupal::service('theme_handler')->getTheme('rendering_theme');
    $new_active_theme = \Drupal::service('theme.initialization')->getActiveTheme($render_theme_extension);
    \Drupal::theme()->setActiveTheme($new_active_theme);

    \Drupal::service('renderer')->renderRoot($html);
    $response = new HtmlResponse();
    $response->setContent($html);
    $response->setMaxAge(0);
    $response = \Drupal::service('html_response.attachments_processor')->processAttachments($response);

    \Drupal::theme()->setActiveTheme($active_theme);

    return $response;
}

Note: when you are using this via ajax callback, you have to unset the ajax_page_state from the post request, otherwise you'll be most likely be missing some libraries.


It looks like the block disappears because no content is returned by the view. You're filtering for both a taxonomy term id and a node id, while only a taxonomy term is present in the url of a taxonomy term page. Since there are no nodes that match the criterium 'no nid' there are no results. I believe this should work if you use only the taxonomy contextual filter. (This is if I'm understanding correctly what you're trying to do).


How do I do a 'required if other field = x' using the entity validation api?

That sounds like a job for Drupal's Form API states.

Just add a hook_form_alter similar to this, in a custom module:

function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'FORM_ID_TO_ALTER') {
    $form['OPTIONALLY_REQUIRED_FIELD']['#states'] = array(
      'visible' => array(
        ':input[name="CHECKBOX_NAME"]' => array('checked' => 'checked'),
      ),
      'required' => array(
        ':input[name="CHECKBOX_NAME"]' => array('checked' => 'checked'),
      ),
    );
  }
}


How to show one page over another in custom way

I think you are looking for Popup module or Lightbox


The only thing I can think of offhand is to play with hook_url_outbound_alter() and make a regex to alter only the file paths url in question (not just any and all urls on the site) and strip out the context.

There might be a better way to do this ... maybe like theme_link or theme_links overridden for the given region ?


Check this module:

Conditional Fields

This module lets you to set things such a visibility, depending on other form elements.

It works based on Drupal's States API ( which you could also use in your custom module to achieve what you want )


Drupal 7 site crashed after enabling module - No DB backup. What do?

The mention of "I do not have a backup of the DB" in the question/title makes it clear that you want to roll-back the change as opposed to debugging and making the modules work where it is - for that, you do not need a backup, but access to the code and logs.

Another way to bypass the blog module, an alternative to what @Jimajamma said is to remove the module from the filesystem.
Remember to clear the cache and ideally rebuilt the module registry after these steps.

drush cc all --yes;
drush rr;


Webservice endpoint with hook_services_resources()

Example from the module itself, the child is defined in the relationships:

'events' => array(
  'operations' => array(
    'retrieve' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_retrieve',
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node to get',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('view'),
      'access arguments append' => TRUE,
    ),
    'create' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_create',
      'args' => array(
        array(
          'name' => 'node',
          'optional' => FALSE,
          'source' => 'data',
          'description' => 'The node data to create',
          'type' => 'array',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('create'),
      'access arguments append' => TRUE,
    ),
    'update' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_update',
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node to get',
        ),
        array(
          'name' => 'node',
          'optional' => FALSE,
          'source' => 'data',
          'description' => 'The node data to update',
          'type' => 'array',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('update'),
      'access arguments append' => TRUE,
    ),
    'delete' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_delete',
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
        ),
      ),
      'access callback' => '_node_resource_access',
      'access arguments' => array('delete'),
      'access arguments append' => TRUE,
    ),
    'index' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_index',
      'args' => array(
        array(
          'name' => 'page',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'The zero-based index of the page to get, defaults to 0.',
          'default value' => 0,
          'source' => array('param' => 'page'),
        ),
        array(
          'name' => 'fields',
          'optional' => TRUE,
          'type' => 'string',
          'description' => 'The fields to get.',
          'default value' => '*',
          'source' => array('param' => 'fields'),
        ),
        array(
          'name' => 'parameters',
          'optional' => TRUE,
          'type' => 'array',
          'description' => 'Parameters array',
          'default value' => array(),
          'source' => array('param' => 'parameters'),
        ),
        array(
          'name' => 'pagesize',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'Number of records to get per page.',
          'default value' => variable_get('services_node_index_page_size', 20),
          'source' => array('param' => 'pagesize'),
        ),
      ),
      'access arguments' => array('access content'),
    ),
  ),
  'targeted_actions' => array(
    'attach_file' => array(
      'help' => 'Upload and attach file(s) to a node. POST multipart/form-data to node/123/attach_file',
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'callback' => '_node_resource_attach_file',
      'access callback' => '_node_resource_access',
      'access arguments' => array('update'),
      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node to attach a file to',
        ),
        array(
          'name' => 'field_name',
          'optional' => FALSE,
          'source' => array('data' => 'field_name'),
          'description' => 'The file parameters',
          'type' => 'string',
        ),
        array(
          'name' => 'attach',
          'optional' => TRUE,
          'source' => array('data' => 'attach'),
          'description' => 'Attach the file(s) to the node. If FALSE, this clears ALL files attached, and attaches the files',
          'type' => 'int',
          'default value' => TRUE,
        ),
        array(
          'name' => 'field_values',
          'optional' => TRUE,
          'source' => array('data' => 'field_values'),
          'description' => 'The extra field values',
          'type' => 'array',
          'default value' => array(),
        ),
      ),
    ),
  ),
  'relationships' => array(
    'resources' => array(
      'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
      'help'   => t('This method returns files associated with a node.'),
      'access callback' => '_node_resource_access',
      'access arguments' => array('view'),
      'access arguments append' => TRUE,
      'callback' => '_node_resource_load_node_files',
      'args'     => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('path' => 0),
          'type' => 'int',
          'description' => 'The nid of the node whose files we are getting',
        ),
        array(
          'name' => 'file_contents',
          'type' => 'int',
          'description'  => t('To return file contents or not.'),
          'source' => array('path' => 2),
          'optional' => TRUE,
          'default value' => TRUE,
        ),
        array(
          'name'         => 'image_styles',
          'type'         => 'int',
          'description'  => t('To return image styles or not.'),
          'source'       => array('path' => 3),
          'optional'     => TRUE,
          'default value' => FALSE,
        ),
      ),
    ),
  ),


How to limit the amount of User Points users get?

I found a solution for my question; maybe it can help others too. I actually created a 'correction' Rule that's activated after a user was awarded userpoints and a 'Content' node was flagged with 'Publish Content and grant points to user'. This is how I set up the Rule:

EVENT

User was awarded userpoints
A node has been flagged, under 'Publish Content and grant points to user'

Then, I checked whether the amount of points is higher than 5.

CONDITIONS

Data comparison: [userpoints-transaction:points] is greater than 5

Finally, I calculated the difference between the added userpoints and 5 and substracted this value from the user's userpoints.

ACTIONS

Calculate a value: [userpoints-transaction:points] "-" 5 (variable name: difference)
Calculate a value: [difference] "*" -1 (variable name: substract)
Grant points to a user: grant [userpoints-transaction:user] substract points

I had to insert the second calculation, because otherwise, I couldn't substract the 'difference' from the user's userpoints.


Saving the value for a taxonomy term field

Yes, as @Trupal said, forget about the internal properties of the term objects, that's internal details that are not relevant to you.

If you want to see what's inside, try $term->toArray() and look at the result of that in your debugger. Or access the field value with $term->field_foo->value.


How to set permission for exposed filter in Views block

If you expose the filter as a block from within the view (Advanced - exposed form in block) then you could set the permissions on the exposed form block in the block system to Admin role users. Alternatively I can only think that you might need to use hook_form_alter to amend the permissions on that form if you want everyone others to see the view but not the exposed form.


htaccess multisite config crashed after sites move to other host

It was a matter of the firefox cached data. After cleaning the cache it works.


Administer block permission let the user to see admin theme name

I have had such a issue in the recent past, the only solution to this is the "Block Access" Module.


How to restyle GeoField's proximity filter controls?

I had a similar issue with editing the exposed form. Form alter is not the right way to go though. You'll need to use element info alter. Take a look at this custom module I threw together for editing the geofield proximity search. You can see what I did, and add/modify functionalities for your needs (although I think i did exactly what you wanted).


How to add password reset link to user page?

You can create a custom module for that:

modules/custom/resetpassmodule/resetpassmodule.info.yml

name: 'resetPassModule'
type: module
description: 'Reset Password link for administrators'
core: 8.x
package: 'Custom'

modules/custom/resetpassmodule/resetpassmodule.module

<?php

/**
 * @file
 * Contains resetpassmodule.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\Component\Utility\Html;

/**
 * Implements hook_help().
 */
function resetpassmodule_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the resetpassmodule module.
    case 'help.page.resetpassmodule':
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('Reset Password link for administrators') . '
';
      return $output;

    default:
  }
}

/**
 * Alter the user edit form
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function resetpassmodule_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

  //Load the current user roles
  $user = \Drupal::currentUser()->getRoles();
  // Only show the reset link button if the user is administrator.
  if(in_array("administrator", $user)) {

    //Add the reset button to the form.
    $form['actions']['sendresetlink'] = [
      '#type' => 'submit',
      '#weight' => 999,
      '#limit_validation_errors' => [],
      '#button_type' => 'danger',
      '#submit' => [
        'resetpassmodule_send_reset_link_to_account_form'
      ],
      '#value' => t('Sent reset link to account email'),
    ];
  }

}

/**
 * Custom submit handler for the password reset button
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function resetpassmodule_send_reset_link_to_account_form(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

  // Load the user entity of the form.
  $account = $form_state->getFormObject()->getEntity();

  // Create a timestamp.
  $timestamp = \Drupal::time()->getRequestTime();
  // Set the redirect location after the user of the one time login.
  $path = '' ;

  // Create login link from route (Copy pasted this from the drush package)
  $link = Url::fromRoute(
    'user.reset.login',
    [
      'uid' => $account->id(),
      'timestamp' => $timestamp,
      'hash' => user_pass_rehash($account, $timestamp),
    ],
    [
      'absolute' => true,
      'query' => $path ? ['destination' => $path] : [],
      'language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()),
    ]
  )->toString();

  // Genereate mail.
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'resetpassmodule';
  $key = 'user_reset_links'; // Replace with Your key
  $to = $account->getEmail();
  $langcode = \Drupal::currentUser()->getPreferredLangcode();
  $send = true;

  // Set the message and the subject.
  $params['message'] = $link;
  $params['title'] = "One time login link";

  // Send mail and collect the result.
  $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
  if ($result['result'] != true) {
    $message = t('There was a problem sending your email notification to @email.', array('@email' => $to));
    drupal_set_message($message, 'error');
    \Drupal::logger('mail-log')->error($message);
    return;
  }

  $message = t('An email notification has been sent to @email ', array('@email' => $to));
  drupal_set_message($message);
  \Drupal::logger('mail-log')->notice($message);

}

/**
 * Implements hook_mail().
 */
function resetpassmodule_mail($key, &$message, $params) {
$options = array(
  'langcode' => $message['langcode'],
);
  switch ($key) {
    case 'user_reset_links':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('Your mail subject Here: @title', array('@title' => $params['title']), $options);
      $message['body'][] = Html::escape($params['message']);
      break;
  }
}


Drupal Views adding a view to node-customcontenttype.tpl.php

In Drupal 7 you should use two dashes : node--content-type.tpl.php.

Embeding view:

<?php print views_embed_view('articles','block', $node->nid); ?>

articles - name of view, block - type of view, $node->nid - argument.


Which events are invoked when an order is removed or cancelled?

$events = [
  // State change events fired on workflow transitions from state_machine.
  'commerce_order.place.post_transition' => ['onOrderPlace', -100],
  'commerce_order.cancel.post_transition' => ['onOrderCancel', -100],
  // Order storage events dispatched during entity operations in CommerceContentEntityStorage.
  // ORDER_UPDATE handles new order items since ORDER_ITEM_INSERT doesn't.
  'commerce_order.commerce_order.update' => ['onOrderUpdate', -100],
  'commerce_order.commerce_order.predelete' => ['onOrderDelete', -100],
  /* OrderEvents::ORDER_ITEM_UPDATE => ['onOrderItemUpdate', -100],
  OrderEvents::ORDER_ITEM_DELETE => ['onOrderItemDelete', -100], */

  'commerce_payment.filter_payment_gateways' => ['onPayment', -100],
  ];
return $events;
}


I'd convert that argument into a filter, then use http://drupal.org/project/views_or for it.

To convert an argument into a filter, you can use hook_views_query_substitutions or hook_views_pre_view to replace a specific value (for example ***NID***) with what you need (e.g. arg(1)).


I just found the answer. The problem occurs when the option "Use source translation" is checked in the Rate configuration section. Here is a patch to solve the problem source translation option on untranslated nodes causes 0 votes display


Are you talking about the front page or a custom view?

If you are in the front page view, you have probably set the content type for slideshow images to be promoted to front page. Disable that in

admin/structure/types

by clicking manage and in the footer untick 'promoted to front page'

and they will stop showing up unformatted.
In that case you aren't actually talking about a 'block', but the system content that is displayed in the main content block defined in the themes page.tpl.php page with

<!-- Page Content -->
<?php print render($page['content']); ?>


How do I change the Views (Entity Reference) filter via AJAX?

I am going to answer my own question in hopes this ccan help someone.  However I am welcome to hear other options :)

What I ended up doing was attach a javascript that updates the autocomplete's path.  Meaning when a user clicks on the checkbox it updates the input box for the autocomplete's attribute. The attribute called data-autocomplete-path.  I appended a query string without messing with the functionality of it.  This extra value gets sent to hook_views_pre_view.

This worked for me


Drush make Distribution throwing errors: exec() unable to fork bootstrap.inc:636

This is probably related to some resources limit or temporary glitch. So first try to restart your Apache.

If this won't help, make sure that you've necessary requirements to run drush (which is either curl or wget).

Otherwise it could be some resource limitation on your environment. E.g. check for ulimit -a or kern.maxprocs.

If there is still problem, please add -v for verbose mode or -d for debug messages for drush, you could more easily track the issue.


Remove Locale settings from Logintoboggan

I seem to have fixed the issue by myself (again). For some reason the site-wide locale settings didn't stick so I just disabled and re-enable Logintoboggan and it works fine now


JQuery accordion works in admin but not for anonymous

jQuery UI is bundled with core in D7 ( see /misc/ui ).
To add jQuery Accordion JS you can just go:

e.g, in template.php

function THEMENAME_preprocess_html(&$variables) {
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.accordion');
}

After that, clear all caches and check the javascript files have been added in the HTML source of the page as anon.


How do I alter the title display with hook_user_view?

You don't. To alter display, you have to create or edit user-profile.tpl.php file in your theme, or template_preprocess_user_profile() function in template.php


Architecture Guidance: Many off-the-shelf templated sites

I've made an infrastructure close to what you're describing, where we launch sites in 24h after a customer orders it.

Basically the architecture is:

Aegir on a VPS. This allows us to spin up websites, service them, migrate them and sometimes clone them without messing on the server.
An aegir platform with an install profile for our use case
A generic zen subtheme for our use case with a bundle of front-end code
Sweaver CSS for the layout customization of the specific site
A basic features module that is installed by the install profile and multiple optional feature modules with extra views and content types, layouts managed by contexts, that administrators toggle using Feature Sets.
Some additional optional contrib-space modules for things like node access customization

I try to avoid Panels as much as possible because of how much complication it adds. If you absolutely want your users to create fancy layouts, that may be a good choice, but at low price points the users have little tolerance for complicated usage. You might just be creating a lot of failure demand on yourself.

If you're going to just zip up sites, at least give Aegir and site cloning a chance first. You're going to save yourself a lot of work.


If you call drupal_add_js() without parameters it will return an array of all the JavaScript already installed. You can iterate over the elements to look for the jQuery UI version you need. For example

  $installed_js = drupal_add_js();
  foreach ($installed_js as $file => $details) {
    if (preg_match('/jquery\.ui/', $file)) {
      $version = $details['version'];
      break;
    }
  }
  list($major, $minor, $update) = explode('.', $version);
  if ($major != '1' && $minor != '12' && $update != '1') {
    // Add drupal_add_js call here
  }

You might need a more robust regex to check for a wider variety of possible filenames but the above code should work in principle. I should also point out, it's not totally robust - if for some bizarre reason the file was named blah.js, this approach would not find it, so your module's jQuery code should also check to make sure the right version is loaded.


How to add attributes to menu and menu items on the block level in THEME_preprocess_block()?

There are actually functions available for specific menus too:

  Targeted overrides (suggestions) available for theme_menu_link() and
  theme_menu_tree()

  In addition to other changes to menu rendering, a Drupal 7
  theme can implement a THEMENAME_menu_tree__MENU_NAME() and/or
  THEMENAME_menu_link__MENU_NAME() function to override
  theme_menu_tree()/theme_menu_link() for a specific menu. For example,
  THEMENAME_menu_link__management() would override theme_menu_link() for
  links within the "Management" menu. This is similar to how
  "node--article.tpl.php" overrides "node.tpl.php".

Source: https://drupal.org/node/254940#theme-suggestions-for-menus


Set value on a new term based on a vocabulary custom field

You can add an extra validation step to those forms that checks and changes the value accordingly like so.

function polaris_drupal_taxonomy_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_term_category_form':
    case 'taxonomy_term_article_type_form':
    case 'taxonomy_term_main_purpose_form':
    case 'taxonomy_term_tags_form':
    case 'taxonomy_term_content_partnership_form':
    case 'taxonomy_term_traffic_source_form':
    case 'taxonomy_term_client_form':
      $form['#validate'][] = '_polaris_drupal_add_field_index_page';
  }
}

function _polaris_drupal_add_field_index_page(&$form, FormStateInterface $form_state) {
  $promote_to_index = $form_state->getValue('promote_to_index');
  if ($promote_to_index['value']) {
    $form_state->setValue('field_index_page', [ 'value' => TRUE ]);
  }
  else {
    $form_state->setValue('field_index_page', [ 'value' => FALSE ]);
  }
}

This will check the field promote_to_index of the form and set the field field_index_page before executing the submit handlers of the form.


How do I populate a webform component with a %_GET variable token?

I use tokens to get keys from the URL. The token for the %get variable would be [current-page:query:?], where the ? = the query name in the url. For example, if your url is mysite.com/page?foo=bar, you would use [current-page:query:foo] to return "bar".


Given that you have loaded the node in $node you can do:

$queues = nodequeue_load_queues_by_type($node->type, 'links');
$subqueues = nodequeue_get_subqueues_by_node($queues, $node);


How to implement Page not found (404) for unpublished content?

You should be able to do it with Rules:

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

Using Rules...

Event: Content is being Viewed (by content type if you desire)

Condition: Content is Published, Negate

Event: Redirect to custom 404 page

This requires that you set up a custom 404 page, but most people do that anyways, and core takes care of everything else.

Specify 403 and 404 error pages for more info on setting up a custom 403 and 404 page


Install conditional fields module and it creates relationship between fields.


One answer in this situation is never to permit deletions in the first place.  Use the publish flag or some other mechanism to remove the content from view, but retain it in the database.  An admin would be able to restore any content simply by 'publishing' it again.