Your site local or not? Can you give a link?

You use standart theme or custom?

Try to edit node type configuration → http://somesite.ltd/admin/structure/types/manage/content_type_machine_name. Before open link you must change somesite.ltd & content_type_machine_neme


Create a views "exposed filter" to compare two fields

Solution 1

Make use of views php to do the compare with the help of https://www.drupal.org/project/views_php

In that case you have to write some code which is executed on each row, in the end it will work but it is very bad in maintaining. You do not have any integrated editor for error code checking etc etc. It is a solution but I do not recommend it.

Solution 2

Make use of the hook views_post_execute with parameter of the view name.

function YOURMODULENAME_views_post_execute(&$view){

For easy maintenance start with a switch

switch ($view->name){

    case "YOURVIEWNAMEA";
    case "YOURVIEWNAMEB";
    case "YOURCASEVIEW";

    foreach ($view->result as $row => $rowinfo) {

      // put here your code to do something with each result.

       // E.G Delete a value in the result of the view making use of unset statement
        unset ($view->result[$row]);

      }


Remove width and height from img tag in Drupal output (for certain content type)

function mytheme_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    unset($variables[$key]);
  }
}

copy this on template.php (replace "mytheme" to ur theme name) but you need to control over this because it will remove dimensions of all images in your theme.


How to promote nodes to front page using MySQL command line

UPDATE node SET promote=1 WHERE type="story" AND promote=0 LIMIT 200;


How to show "Alternative text" of image fields in a custom content type?

you can get "alt" property with node.FIELD_MACHINE_NAME.alt (and for image title as the same ), So your answer is

<img src="{{ file_url(node.field_news_image.entity.fileuri) }}" alt="{{ node.field_news_image.alt }}" >


If you prefer another approach, a little more clean and following the Drupal structure, you can use Inline Entity Form to do that.

I don't like Paragraphs and Field Collection for just one reason. They don't follow the way that Drupal storages data in DB. If you open your database and search for the tables that this modules create, you will be able to see some strange patterns.

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


Capturing keyup event (JavaScript) from Drupal editors (CKeditor)

Well, once again I've come up with my own answer, though it's not really the one I wanted.

First off, it does not appear that there is any Drupal JavaScript API for interacting with editors. So I had to go directly to the CKEditor API to capture the key up event.

This is the code I was eventually able to use:

CKEDITOR.on('instanceReady', function () {
  // Get the HTML ID of the textarea input that would be used if the editor were not enabled:
  var fieldID = $(".some_textarea").attr("id");
  if (CKEDITOR.instances[fieldID]) {
    // Add keyup listener.
    CKEDITOR.instances[fieldID].on("key", function () {
      // The last key pressed isn't available in editor.getData() when
      // the key is pressed. A workaround is to use setTimeout(), with no
      // time set to it, as this moves it to the end of the process queue,
      // when the last pressed key will be available.
      var editor = this;
      window.setTimeout(function () {
        var text = editor.getData();
        // Do something with the text.
        // Also note that the original textarea can be
        // retrieved from editor.element.$. So you could
        // do this:
        var originalTextarea = editor.element.$;
      });
    });
  }
});


How do I target different types of anonymous user after a gateway page?

Typical, no sooner than writing up my question do I find an answer.  Though I'd love to hear if there are better ideas.

I discovered that you can use php to check the contexts in visibility settings.  I didn't want to do this because I don't want to give the site admin access to php.  However, I can make a couple of ctools access rulesets and make those available to the site admin to control visibility.

I haven't tried it yet but I think this will work, as long as the ctools context plugins work as I think they should.

[edit: it worked]


Update from 8.1.3 to 8.1.7 gives me a fatal error on most pages

Fixed - tracked the problem down to the dev version of field permissions I was using. Updated to the latest dev version and all related issues were resolved.


The arg() function is taking argument parts from the url.
/taxonomy/term/2 means:
arg(0) = taxonomy
arg(1) = term
arg(2) = 2


CDN, SEO and image styles: 301 on GET request

I dont really understand your question, but we handled a similar problem.
We also did rewrtie for all images to static server (different server running lighttpd).
On the lighttpd the files folder was mounted as well, so all files are in sync.

We also had a domain that forced back to one of the webservers (varnish>drupal), and not to use the CDN server .
If the file did not exist in the static server it got rewrtitten (temporary) back to the webserver, which created the imagecache file.
From that moment, the file was there and it would always be there.

attr = lighty.stat(lighty.env['physical.path'])
 if (not attr) then
 lighty.header["Location"] = "http://directto.webserver.com"  .. lighty.env["request.uri"]
 return 302
end

Hope this can help.


Module content type not removed after uninstall

You shall have to uninstall the module to get the type deleted automatically.  Just disabling it will not remove anything.  Deleting the module after disabling it - without uninstalling it first - is not a good idea.

After disabling the module, click on the “uninstall” tab at the top of the modules page and check the module you want to uninstall, then click the "Uninstall" button.


Is there a 'official' place to put PHP snippets?

I would quickly answer no to your question (and explain myself below).

The only thing that comes to my mind as a kind of answer is "place it in a hook".
But as you probably know, there are tons of these.
So, there is not one single "official" place, if I get your point right.
Plus, using a hook means placing your PHP Snippets in files.
Is that in agreement with your question? Or, is your question better phrased as "Is there a 'official' place in the configuration to put PHP snippets?"

Well, hope this explained the "no" answer some, if I am off, please do elaborate some more.

Cheers!

P.S.1: Sounds interesting, sounds like you have something specific in mind. :-)
P.S.2: It's worth mentioning that there are even some modules like the Computed Field that guide you (through naming conventions) to place your snippets inside specific functions.
This is similar to the hook idea, but fantastically presented and suggested in the field's configuration.
It's one of the reasons I am so very fond of the Computed Field


Fatal error: Call to a member function raw() on a non-object in

You could try something like this instead, checking if the field value is set first and catching the exception.

function _gocoop_services_get_app_instance($wrapper) {
  $instance_id = FALSE;
  try {
    // Check if wrapper field set first
    if (isset($wrapper->field_seller) && isset($wrapper->field_seller->field_application_instance)) {
      $instance_id = $wrapper->field_seller->field_application_instance->raw();
    }
    if (!$instance_id) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'application_instance')
          ->entityCondition('bundle', 'application_instance')
          ->fieldCondition('field_internal', 'value', 1);
      $result = $query->execute();
      if ($result['application_instance']) {
        $instance_id = reset(array_keys($result['application_instance']));
      }
    }
  } catch (EntityMetadataWrapperException $e) {
    watchdog_exception('gocoop', $e);
  }
  return $instance_id;
}

You might also want to use a static cache for $instance_id, but that would need to vary based on your $wrapper id value.


How to migrate multilingual content from CSV to Drupal 8?

you need both migration-tasks, the yml files in the migration folder:

migrate.migration.external_translated_test_node.yml
migrate.migration.external_translated_test_node_translation.yml

Then in the Plugin (MigrateExternalTranslatedTestSource.php), you need to read your .csv (in initializeIterator()) into the structure of the import array:

  /**
   * The data to import.
   *
   * @var array
   */
   protected $import = [
    ['name' => 'cat', 'title' => 'Cat', 'lang' => 'English'],
    ['name' => 'cat', 'title' => 'Chat', 'lang' => 'French'],
    ['name' => 'cat', 'title' => 'Gato', 'lang' => 'Spanish'],
    ['name' => 'dog', 'title' => 'Dog', 'lang' => 'English'],
    ['name' => 'dog', 'title' => 'Chien', 'lang' => 'French'],
    ['name' => 'monkey', 'title' => 'Monkey', 'lang' => 'English'],
   ];


In order to use the @self alias, Drush must be able to detect and bootstrap your Drupal site based on the current working directory.  If your settings.php file is in the 'default' directory, then you may cd to your Drupal root directory, or any directory below it, and @self will work.  If your settings.php is in some other directory, then you must either cd to the directory that the settings.php file is in, or provide a --uri option to Drush.

You can also use @self without changing your working directory if you supply --root and --uri options to Drush.


How to add a placeholder to an exposed date filter form field?

jQuery may be a solution.

jQuery(document).ready(function(){
 jQuery('#edit-date-filter-value-datepicker-popup-0').attr("placeholder", "placeholder to show");
});


Drupal 8: Form fields are not updating when checking triggering element

You don't need to check the triggering element if you use it's own submit handler because the submit handler is only triggered by this element.

function your_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['previous_import'] = [
    '#type' => 'submit',  // changed to submit
    '#name' => 'import_previous',
    '#value' => t("Import the previous month's values"),
    '#weight' => -9999,
    '#submit' => ['import_previous_submit'],
  ];
}

function import_previous_submit(&$form, FormStateInterface $form_state) {
  // Example of altering / setting the field values. You have to adapt your foreach stuff.
  $user_input = $form_state->getUserInput();
  $user_input['title'] = [['value' => 'test']];
  $form_state->setUserInput($user_input);

  $form_state->setRebuild();
}


using EntityFieldQuery with flagging condition

Don't need to use EntityFieldQuery or views to perform this flag module has already give function to get is_flagged(). All you need to call functions like.

$flag = flag_get_flag('myflag');
$flag->is_flagged($node->nid);
if($flag && $flag->is_flagged($node->nid)) {
  print "This node is myflag!";
}


Warning: Invalid argument supplied for foreach() in taxonomy_field_formatter_view()

As per this post, this warning can be eliminated by editing the field on each file type which is having a field and unchecking Override in WYSIWYG (at /admin/structure/file-types). This happens because term reference doesn't support overridable in the WYSIWYG.

This issue at Drupal.org: #2062721: Add a white list of file fields that can be overwritten when the file is added in the wysiwyg, aiming to solve that issue. At time of writing, there is still some patch which is in Needs review status.


How to 'store' email templates in the site?

It all depends on usage patterns of that feature.

For example if you only need one master template and edits are global (e.g apply to all events) then the "correct" storage could be inside the variable table.

You can expand on the above design by suffixing those variable keys with the node type (or whatever differentiates one template from another). So you could have entries such as:

mail_template_event
mail_template_publication
mail_template_press_release

or in the case of "typed" events:

mail_template_event_internal
mail_template_event_external
mail_template_event_generic

Keeping the mail template on a node field will be easier in terms of programming though. Because if you fetch the template from an "external" source (such as the variable table) you'll need to handle presentation within the node edit screen and update of the template in case it was altered.


I want to link file in views to files/fid

Adding a field above the field in the list doesnt works because, he has build content on content type that has attachment, and not mere files..Means the view is not build on files so it will not have the field file:filename or file:fid...
         The best solution is to use custom formatter module {https://www.drupal.org/project/custom_formatters} and in that use html plus tokens with following code

This will give the required link to the thumbnail, if you dont want thumbnail you can put text there....

and then in views select the custom formatter for the required image field...


How to create a different page.tpl.php for different page, if pathauto is active?

It is all outlined on the Drupal 7 Template (Theme Hook) Suggestions page.
eg. page--node--1.tpl.php


I have had good luck using the Smart Trim module. (This module is now available for Drupal 7 and 8.)

Choose the Smart Trimmed field formatter and check the Strip Out HTML checkbox to remove the image tags (and other formatting that you probably don't want in a teaser text).

It also gives you some other handy formatting options (limit to number of words or characters, add "read more" links, etc) and makes the formatting options available for fields in Views, as well.


How to add a complete menu as an item in other menus?

There is a sandbox project for combining menus: https://www.drupal.org/sandbox/klickreflex/1989788

Someone with a similar issue found code that was of value.

The poster also suggests Advanced Menu which has some merging capabilities.


This video is from Nodeone.se addresses sorting, but the entire series on Views is an excellent tutorial.


Skip user edit page on first login using fboauth

You can redirect the page using rules modules and drupal_goto function


There is no difference between Form Submit button's validate hook and Form Preview button's validate hook.

If you set the form's validate hook in HOOK_form_validate, you have set a secondary validation hook (it means if the default validation hook is passed, then it's the turn of the one you have set) which can be used for both Submit button and Preview button:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   $form['#validate'][] = 'XYZ_validate';
}


Redirect to entity ID after entity create form submit with AJAX

You should not use drupal_goto() for form redirects. You should set the redirect in the form state.

function mymodule_myform_submit($form, &$form_state) {
  // other code
  $form_state['redirect'] = 'path';
}

Ctools provides a way to do a redirect in an AJAX callback, a function called ctools_ajax_command_redirect.

I found an example of someone using this function in a form callback that is AJAX:

function mymodule_custom_ajax_form_submit($form, &$form_state) {
  //Close lightbox and redirect to the current page
  $path = $_SESSION['current_path'];
  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  $commands[] = ctools_ajax_command_redirect($path);
  print ajax_render($commands);
  exit;
}

So, in your case, you would need to know the entity id in the submit handler, and you can get the uri with entity_uri, which you can pass as the $path and that should work. Just load the entity object, and pass it to entity_uri. It should return 'myentity/(id)' ex 'node/123', which you can redirect to.


Referring created users to 'admins' that created them

Add a field (e.g. created_by) to the user profile by going to /admin/config/people/accounts/fields.

Then implement hook_user_insert to populate the field whenever a new user is added.

hook_user_insert is called after "A user account was created."
So both $edit->uid and $account->uid have the user id present.

If you changed any values in either of these objects you would need to call user_save in order to save your changes.

An alternative to avoid calling user_save again, just after the initial user object has been saved would be to use hook_user_presave that is called when "A user account is about to be created or updated"

The description of hook_user_presave goes on to say:

This hook is primarily intended for modules that want to store properties in the serialized {users}.data column, which is automatically loaded whenever a user account object is loaded, modules may add to $edit['data'] in order to have their data serialized on save.

So another option here would be instead of creating a new field (with a new table), this information could just be stored as a serialized array in the data column of the user table.

This would mean it would be slower to search for users created by a certain admin, but would would have less storage overheads.


Create a Role and assign set of users to that Role. Now go to your Webform configuration settings (Form Settings) >> Submission Access and assign newly created role to it.

For example in the following example I've created a 'moderator' rule and assigned users (those I want to assign users to take survey).

That's it. Now users under "Moderator" role only can access the form.


How do I get a field value in another field's template on a paragraph?

For non-paragraph fields, there is a node object available in the variables of the field template, so you can put this in a field.html.twig file:

{{ element['#object'].machine_name_of_other_field.value }}


How to create different Views pages for different taxonomy vocabularies?

The Taxonomy Views Switcher does the trick. It does something clever. If the default view page path is 'taxonomy/term/%' it will walk through the paths of the. If the vid of the term is 3 it will associate the term with the view that has vid/3 in the path and will when taxonomy/term/% is called pass it -- the second view -- the argument of the term ID. Since this is a separate view it can have any field, sort, filter or display plugin.

Now I need to trigger contexts based on views that are triggered.


You need to pass a contextual filter in the view of User ID, and pass the User ID from url as the value. It doesn't matter if this path is aliased, as it will look at the system path (user/uid) to get the value.

Then, the view will filter content based on relationship to that user id.

Without much more information, that is all I can give you to go on. But if it is a basic setup, that should work.

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

Then to show it on the form, it depends on what or where you want it.

One way would be to create a Block display of your View, and place it in a region on the block admin page. Be sure to set the visibility to authenticated roles, and the path to 'user/*/edit' so it only shows for users on the user edit form.

Another way, if you want to code it, would be embedding the output into the form with views_embed_view inside of a hook_form_alter for the user edit form. There are some examples on that doc page on how to use it.

Example:

$form['classes'] = [
  '#markup' => views_embed_view('your_view', 'block_display_id', $user_id);
]

Where $user_id is the user viewing the form.


Where is the class "placeholder" defined?

The only uses of the placeholder class in core are (filename, followed by line number, follby the line):

modules/dashboard/dashboard.js:35:        if ($('.placeholder', this).length == 0) {
modules/dashboard/dashboard.js:38:        $('.placeholder', this).html(empty_text);
modules/dashboard/dashboard.js:41:        $('.placeholder', this).remove();
modules/system/system.admin.css:264:.exposed-filters .current-filters .placeholder {

and also a few in jquery.ui that you can ignore:

misc/ui/jquery.ui.draggable.min.js:40
misc/ui/jquery.ui.sortable.min.js:26
misc/ui/jquery.ui.sortable.min.js:27
misc/ui/jquery.ui.sortable.min.js:29
misc/ui/jquery.ui.sortable.min.js:39
misc/ui/jquery.ui.sortable.min.js:40
misc/ui/jquery.ui.sortable.min.js:43
misc/ui/jquery.ui.sortable.min.js:55
misc/ui/jquery.ui.sortable.min.js:56
misc/ui/jquery.ui.sortable.min.js:59
misc/ui/jquery.ui.sortable.min.js:60

You can safely ignore all this and just implement your own css for the .placeholder class in your theme.


How to programatically change a view's style_options when user clicking the exposed filter apply button?

The hook_views_pre_render() works.

function my_misc_views_pre_render(&$view) {
  if($view->name == 'classrooms_map') {
    $view->style_plugin->options['map'] = ($view->exposed_data['type'] == 'All') ? 'all' : $view->exposed_data['type'];
  }
}


PHPUnit test complex method that use drupal service within it

Resurrecting this.  The first method would be to include the EntityFieldManager as an argument to your function or constructor, so you can send a mock object in.

The second would be to look at some of the tests in core.  Specifically core/tests/Drupal/Tests/Core/Config/Entity/ConfigEntityStorageTest.php where the container is mocked and dependencies set up.

$container = new ContainerBuilder();
$container->set('entity_type.manager', $entity_type_manager->reveal());
...
\Drupal::setContainer($container);


Using wildcards in custom module outputting sql query

Your code has the following errors:

The string delimiter for the query is the single quote character, which is the same delimiter you use for the string inside the query.
The table names are always surrounded with { and }, which allows Drupal to prepend the prefix set in settings.php to the table name.
If you need to use the % character as wildcard character, you need to escape it with another %, in a query passed to the database API.
If you need to limit the number of returned rows, in Drupal you use db_query_range() that allows to use a query that is compatible with every database engine for which there is a driver for Drupal.
If you look at the code used from that function for different database engines, you will notice it will use a different syntax for different database engines, such as:

MySQL/MySQLi

$query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
$query .= ' LIMIT ' . (int) $from . ', ' . (int) $count;

PostGreSQL

$query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
$query .= ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from;

Your code should be written as the following one:

$sql = "SELECT name, mail FROM {users} WHERE status = 1 AND mail LIKE '%%@hotmail%%'";
$result = db_query_range($sql, array(), 0, 25);

while ($row = db_fetch_object($result)) {
  // $row->name contains the username, and $row->main contains the email address.
}

This is code taken from a Drupal module that uses the LIKE operator:

  $query = "SELECT url, COUNT(url) AS hits, MAX(timestamp) AS last FROM {accesslog} WHERE url NOT LIKE '%%%s%%' AND url <> '' GROUP BY url";
  $query_cnt = "SELECT COUNT(DISTINCT(url)) FROM {accesslog} WHERE url <> '' AND url NOT LIKE '%%%s%%'";

The query uses 5 % because the first 2 are for using % as wildcard, the third is for the "%s" placeholder, and the last two are again for using % as wildcard.

This is an example of code used by a module that limits the number of rows the query returns:

        $sql = db_rewrite_sql("SELECT n.nid, n.title, l.comment_count, l.last_comment_timestamp FROM {node} n INNER JOIN {term_node} tn ON tn.vid = n.vid INNER JOIN {term_data} td ON td.tid = tn.tid INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.status = 1 AND td.vid = %d ORDER BY l.last_comment_timestamp DESC");
        $result = db_query_range($sql, variable_get('forum_nav_vocabulary', ''), 0, variable_get('forum_block_num_0', '5'));
        $content = node_title_list($result);

The query string is passed to db_rewrite_sql(), but that is irrelevant, here; the code would not change if it didn't need to use db_rewrite_sql().


How to copy data from Profile2 form to a new node using Rules.

Why do you want this through Rules?..according to me a simple submit handler, grabbing the data on submit and creating a node programatically will be a much better approach. I can provide you direction on this if you let me know you want to go with this approach.

Update:

Here is my suggested workflow:

Use hook_user_save() to grab the submitted profile field values. All the profiles2 field you add, will be available in the user object.
Next in the content type you want to save the values, create proper fields so that you can map and store data.
you can look up in google to see how you can progmatically create a node. So you can grab the required values, and map them to appropriate fields you added to the node and then save the node.

Just a thought, I am really curious why are you trying to do this?


try to set the location

'#upload_location' => 'public://',


Drupal 6: integer field, how to output the value + a 3% up for a field, programmatically

The actual values can be updated. To increase the values by 3% you could use a snippet like the following and run it once, say in a hook_cron, then remove it after the update is complete.

// Create a list of nodes of the required type
$result = db_query("SELECT nid FROM {node} n WHERE n.type = 'YourContentTpe'");
// Iterate through the list
foreach($result as $row) {
   // Load each node
   $node = node_load($row->nid);
   // Calculate your fields
   $node->field_1[0]['value'] = 1.03 * $node->field_1[0]['value'];
   // .. repeat for each field ..
   // Then save the node
   node_save($node);
}

This assumes that all the field values are set. To be rigorous, you should probably check this on each field before attempting to access them. This method uses Drupal functions to keep track of the updates, but hundreds of node_load and node_save functions could significantly impact your server performance while the code is being run.

To just display the altered information without changing the values in the database, You could create three computed fields, and use each to display the value in its base field incremented by 3% as suggested by Human love. This will probably lead to confusion in the future if new nodes are added and the author forgets to reduce the entered information by 3% to have it display correctly.

As much as I hate to advocate it, if this is a one-time update of the information, the most efficient method both in terms of your effort and of server resources would be direct manipulation of the database. Just make sure you back up the database before proceeding,:

UPDATE node n JOIN content_type_{YourContentType} f on n.nid = f.nid set f.field_field_1_value=(1.03 * f.field_field_1_value), f.field_field_2_value=(1.03 * f.field_field_2_value) WHERE n.type='YourContent_type';

for each of your fields. This assumes that the fields are exclusive to the content type. If the field is shared between content types, the field will appear in its own table and the above query should be modified accordingly.


How can I filter out specific words in a node body?

Apart from the Rules module,

the Wordfilter module allows site
administrators to filter certain words on all pages.
the Phonetic module goes a step further by including the phonetic characteristics in the comparison as well as a list of profane words.


Views - No results behavior with Exposed filter criteria

I think you selected the Autosubmit option in the exposed form settings.

    Autosubmit
    Automatically submit the form once an element is changed


how do I access raw URL from a File Field to render it in twig inside href?

In my case as I was using a views twig, and required the field's file path to be usable inside a href, I had to write it like this:

Download CV


Is there a way I could display a token (for exmaple user ID) as a default field content to a content type?

Do you want it to be editable or not?

Either way, its going to take a small custom module with hook_form_alter or hook_form_FORM_ID_alter if you want to target a specific form.

If you want it editable:

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#default_value

If you want it set at a value:

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#value

Start with downloading and enabling devel and a small module with just this to get a list of all the form elements on a page:

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  dsm($form_id);  // print form ID to messages
  dsm($form);  // pretty print array using Krumo to messages
}


Is it possible to add template suggestions for image styles?

hook_theme_suggestions_HOOK_alter doesn't use a third argument.
You are supposed to add the suggestions as string.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_style_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables['theme_hook_original'] . '__' . $variables['style_name'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables['theme_hook_original'] . '__' . $variables['style_name'];
}


How do I update jQuery to the latest version I can download?

One way is to install the dev version of jQuery Update, which gives you the option to use jQuery 1.7 (by visiting the settings page at http://mysite.com/admin/config/development/jquery_update).

Beware though, currently it's known to break JavaScript elsewhere in the site (for example the widget dropdown on a Manage Fields page will no longer work). If you're prepared to fix up that, and any other small annoyances, this is probably your best bet. You should also note that using the dev version of a module isn't without risks, as the chances of it having bugs is a lot higher than using a specific release.

If you want to do it manually then you'll have a lot of core javascript code to rewrite to make your site work as expected; jQuery changed an awful lot between version 1.4/1.5 and 1.7 so a lot of the core Drupal javascript code simply won't work with it.

If you want to just drop in a version of jQuery 1.7 then you could probably implement hook_js_alter(), unset the core jQuery file, and add your own in it's place:

function MYMODULE_js_alter(&$js) {
  $path = drupal_get_path('module', 'MYMODULE') . '/path/to/jquery.1.7.js';

  // Copy the current jQuery file settings and change
  $js[$path] = $js['misc/jquery.js'];

  // Update necessary settings
  $js[$path]['version'] = 1.7;
  $js[$path]['data'] = $path;

  // Finally remove the original jQuery
  unset($js['misc/jquery.js']);
}

Once you've done that, open up Developer Tools/Firebug and you'll see all the changes you're going to need to make to get the rest of the site JS to work :)

UPDATE

The latest version of jQuery update (7.x-2.3 at time of writing) will now allow you to update jQuery to v1.8. Very cool.

The jQuery Multi module is another option, thanks to goron for pointing that out in the comments. As he also notes, this module has a stable release and won't break any existing javascript.


Is it possible to get rid of content duplicates?

You can manage your Robots.txt file through Drupal using RobotsTxt module. This way you can exclude whatever content you want from Google, etc.


How to validate webform with JavaScript?

You can create a custom module for that:

webfv.info
webfv.module
webfv.js

Put all these files into a folder called webfv.

This is the webfv.module file:

<?php
function webfv_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'webform-client-form-80') {
    $form['#attached']['js'][] = array(
    'data' => drupal_get_path('module', 'webfv') . 'webfv.js',
    'type' => 'file',
  );
}
}

And this is the webfv.js file:

    (function($) {
      $(document).ready(function() {
      // Put your code here. //
      });
    }) (jQuery);

And of course, you should have a webfv.info file:

name = webfv
description = JavaScript Webform Validation
core = 7.x
files[] = webfv.module

Note: this is just one way of doing it, there are some other ways.


How to create a custom display mode for user in D8?

You need to create the view mode at Admin > Structure > Display Modes, then configure the new display mode at /admin/config/people/accounts/display.


get form_state values from ajax callback through hook_form_alter?

Some basics:

function mymodule_form_alter($form, &$form_state) {

hook_form_alter is a generic alter function that receives a third argument $form_id to distinguish the possible forms. Right now you would alter every form in your site.
The correct function signature is:

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

You can see, that the $form itself is passed as a reference and can be changed. There is no way of changing $form_state directly during the form building process, which is when hook_form_alter is invoked.

Concerning $form_state['values'] in validation and submit handlers: All elements defined in the $form array are by default inserted into a flat structure in $form_state['values']. This means that with your setup, you would access the value entered in $form['base']['st-volume-pricing']['till-amount'] as $form_state['values']['till-amount']. You can change that behavior by defining #treefor the form element's parent, see for example: https://drupal.org/node/48643

Edit: The general approach for ajax forms is that in the submit you store values inside $form_state, e.g. in $form_state['storage'], set $form_state['rebuild'] which assures that the form builder and hence your alter function is called again, and then test for the presence of stored values inside your form alter function. Depending on the submitted values you would then implement the logic to achieve what you want.


Filtering nodes shown on taxonomy menu block

Since you said you "would not mind temporarily touching the code" (I would highly advise not to touch and try to find alternative ways) here is my quick solution and also alternative ways of accomplishing it.

Assuming the field_expired is a boolean field (single on/off check-box values 1/0) and you are not using revisioning.(see the three lines I added), also make sure you resave at least one node to recalculate.

function _taxonomy_menu_term_count($tid) {
  $result = db_select('taxonomy_index', 'tn');
  $result->condition('tid', $tid);
  $result->join('node', 'n', 'n.nid = tn.nid AND n.status = 1');

  $result->join('field_data_field_expired', 'fdfe', 'fdfe.entity_id = tn.nid');
  $result->condition('fdfe.field_expired_value', '1', '=');
  $result->condition('fdfe.entity_type', 'node', '=');

  $result->addExpression('COUNT(n.nid)', 'term_count');
  $temp = $result->execute();
  $temp = $temp->fetchObject();
  return $temp->term_count;
}

Another ways of patching it would be to add a module_invoke_all higher up the code to allow other modules to interact (hook into), or use "addTag" along your query and allow other modules to alter the query itself (the latest one would be recommended). Both this require you to write your own custom module.


Correct way to render an custom entity and its custom field?

View Builder

Set the view_builder in ContentEntityType annotation to EntityViewBuilder to inherit some default behavior (or write your own).

Set your canonical router to something like what content_entity_example does in the examples module.

Berdir suggests using DefaultHtmlRouteProvider though that class is marked as @internal so it may not be stable to use long term.

content_entity_example.routing.yml

entity.content_entity_example_contact.canonical:
  path: '/content_entity_example_contact/{content_entity_example_contact}'
  defaults:
    _entity_view: 'content_entity_example_contact'
    _title: 'Contact Content'
  requirements:
    _entity_access: 'content_entity_example_contact.view'

Change your entity theme to something like what node module does, and have it display as a render element.

Use your entity or bundle's field display page to change what field formatters a given field will use.

Then you can print out {{ elements }} in the template for it to go through the entire render array for a given view mode. Again, you can follow something similar to node module.


The above code is correct, date time was saved into DB.
the problem is frontend.

frontend expected this format:

"2016-08-01T12:30:00", need a "T" as separator.

here is how to put that T as separator,

\DateTime::format("Y-m-d\Th:i:s"), need a escape character in-front of T.

2016-01-22 update:

By the way, I have found out in Drupal 8 , correct way to store datetime is follow:

1> first , find out current user timezone, \Drupal::currentUser()->getTimezone()

2> $given = new \Drupal\Core\Datetime\DrupalDateTime("2016-08-01T12:30:00",$user->getTimezone());

3> $given->setTimezone(new \DateTimeZone("UTC"));

4> then get back formated datetime string $given->format("Y-m-d\Th:i:s");


Setting field values on a per-import basis when using Feeds

There's also hook_feeds_after_parse() which lets you modify what's being saved to to your targets.  Something like this should work:

function my_module_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {

  if($result->title == 'title-of-feed-importer') {
    foreach($result->items as $item_key => &$item) {
      if ($item_key == "name-of-the-field") {
        $item = 'Value to set';
      }
    }
  }

}


How to set the text format of a field in a node object?

The following worked for me,

$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$node->body->value = 'body';
$node->body->format = 'full_html';//omitting this will retain existing format
$node->save();


Creating conditional fields: How should I implement hook_form_alter()?

The Conditional Fields module's features can be done with using #states attribute from form api in D7.

If you want to implement it, of course you need to use hook_form_alter() to bring additionaly attributes on existing fields. There many tutorials about the usage of hook_form_alter().

Example of using of #states attribute:

  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );
  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

Example from Examples for Developers module - form_example module


I hate to say that there is an only way that I know to have multi-value field groups in Drupal 7 is Field Collection module. It is based on Entity API. It creates a new entity of which you can add any number of fields, and attaches that to the content type or any other entity you create.


Is it possible to replace html outside form with ajax?

This due to this part of ajax.js

// We don't know what response.data contains: it might be a string of text
// without HTML, so don't rely on jQuery correctly iterpreting
// $(response.data) as new HTML rather than a CSS selector. Also, if
// response.data contains top-level text nodes, they get lost with either
// $(response.data) or $('

').replaceWith(response.data).
var new_content_wrapped = $('

').html(response.data);
var new_content = new_content_wrapped.contents();

// For legacy reasons, the effects processing code assumes that new_content
// consists of a single top-level element. Also, it has not been
// sufficiently tested whether attachBehaviors() can be successfully called
// with a context object that includes top-level text nodes. However, to
// give developers full control of the HTML appearing in the page, and to
// enable Ajax content to be inserted in places where DIV elements are not
// allowed (e.g., within TABLE, TR, and SPAN parents), we check if the new
// content satisfies the requirement of a single top-level element, and
// only use the container DIV created above when it doesn't. For more
// information, please see http://drupal.org/node/736066.
if (new_content.length != 1 || new_content.get(0).nodeType != 1) {
  new_content = new_content_wrapped;
}

This ensures that text nodes are not lost when replacing contents. The second parts of the script checks if the data sent is a single top-level HTML node, and if not, wraps it in a

Back to your problem, the solution is to make sure that theme('custom_theme_function', array('test_param' => 11,)) returns your content in a single HTML node (div, span, ul, li... as long as it is single)


How to link one given Image field to a specific view?

Here is an idea:

On the content type hide the image from the display as you will show it with as an EVA field.
Using Views EVA attach the image to the content type so that the image is visible again, don't forget to check the views arguments to that the right images is shown in the node.
Re-write the image to be display as a link and there you can put the path to the view. Here you can also play with the image formatter as well.


First of all, I'm a big Panels fan, so I definitely think you should be using it, but I'm not sure it's the best for the task you are trying to achieve.

Some options, in what I feel is descending order of usefulness to you.

Since it sounds like it's necessary for you to mix several fields into a single render element, you could implement a Ctools "content type". How does one create a new ctools plugin should be helpful here. This easily allows you any custom logic in rendering the fields on a per entity basis. You should still separete the logic from the rendering, by declaring your own template. See Correct way to render a modules output through a template?
If the output you describe above completely dominates the page, then perhaps it would make sense to move the rendering up a level. A panels "layout"-plugin could be useful instead. The plugin link from above is still the source for more information.
If it makes sense to work with individual fields, which I doubt in your case, a custom field formatter could be what you are looking for. See How do I make the output of field X look like Y?
This one is mostly speculcation, I haven't attempted it, but if you are working with a Field collection, it being an entity, perhaps you can use Display suite to control it's output, and then have Panels render it inline. Or you could skip DS and directly template the FC entity.


Users don't have access to view as soon as relation is added, drupal commerce

This is an issue listed in the Drupal Commerce issues queue. http://drupal.org/node/1276450 Its happens when your view has a relationship to a commerce product.  I came across this earlier today when I was doing the same thing as you.

Two different solutions are suggested at comments 5 and 6 on the issues page. The first is to disable SQL rewriting under the Advanced > SQL Settings section of the view.  This can have security implications if your using contextual or exposed filters.  The other suggestion is give all user roles the 'View any product of any type' permission under permissions.  This is what worked for me.


How do I render a node queue as custom JSON?

There are some Views JSON modules if you look around, but I typically do this outside of views itself.  And you are correct, you are halfway there.

You want to wire up a hook_menu() to create a custom path in a module.  See our canonical question on this topic for more information.

Then in the menu callback, you do use views_embed_view().  Something like this:

function MYMODULE_the_callback() {
  $output = views_embed_view('nodequeue_1', 'the_display');

  print drupal_json($output);
  exit;
}

You can also use the $view object directly:

function MYMODULE_the_callback() {
  $view = views_get_view('nodequeue_1');
  $view->set_display('the_display');
  $view->pre_execute();
  $view->execute();

  $output = $view->render();

  print drupal_json($output);
  exit;
}

Using the later form, you can poke through the $view object and tailor your JSON accordingly.

This should give you a head start.

Keep in mind as you research this, that the plumbing is a little different for rendering JSON in Drupal 6 vs 7.  In 7, you would use drupal_json_output() and drupal_exit();


You can change who has permission to use which input format under Settings (Site Configuration) -> Input formats for Drupal 6 or Configuration -> Text formats for Drupal 7.

If you uncheck all the other options (I'm assuming the one with the editor is set as default) then the option won't appear for those users who only have the default checked.

That's at least one way.


How to modify the comment body while in comment.tpl.php

If you insist, you can always go like that:

 print str_replace(
   array('♦','♥'),
   array('♦', '♥'),
   render($content)
 );

But instead of deprecated , use  and CSS. Consider classes for all 4 colours, for black and red, and for card marks altogether, for future styling ease.


How to automatically delete all product displays when a product is deleted?

1) You need the commerce product id (which is the one of the commerce product that has been deleted) and not the nid because of the reference you are using. If this parameter is not available you must bring it into scope using a proper validation.

Notice that after deleting the commerce product there is no product id so no products are referencing it. The correct trigger should be "before deleting commerce product" but does not exist by default.

Also, how do you handle a Product display (node) with multiple product variations? Should this node be deleted? There should be an additional condition to check if there are other variations for the same product display. Except if you have a 1 to 1 reference.

2) Another option should be to do the opposite which is to fetch all the nodes (Product displays) that have an empty commerce product reference. This is easier to create.


How to set DB log only to log CRON TYPE and SEVERITY NOTICE message?

The Drupal error handler _drupal_error_handler_real() utilized PHP's error_reporting() to determine what gets logged to the DB. By setting the PHP error_reporting to E_ERROR it will only PHP errors.

This PHP setting can be set in many places: the system php.ini, a php.ini/.user.ini instance in webroot, .htaccess in Apache. The Drupal centric way to do this, is to use ini_set() function in settings.php:

ini_set('error_reporting', E_ERROR);

See PHPs error constant page for other values to set error_reporting.


Previewable email templates token replacement

Put the token [webform:sid] in template

Use
function mymodule_pet_substitutions_alter(&$substitutions, $params) {
$substitutions['webform'] = array('sid'=> {value});
}


Attach drupal ajax events to links that were loaded via ajax

Try using the "use-ajax" class on the link

  In addition to using Form API for doing in-form modification, Ajax may
  be enabled by adding classes to buttons and links.

  By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call.

  When using this method, the href of the link can contain '/nojs/' as
  part of the path. When the Ajax framework makes the request, it will
  convert this to '/ajax/'.

  The server is then able to easily tell if
  this request was made through an actual Ajax request or in a degraded
  state, and respond appropriately.

  Source: http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7

e.g:

array(
    '#type' => 'link',
    '#title' => t($title),
    '#href' => $href,
    '#attributes' => array(
        'class' => array('use-ajax'),
        'rel' => url($href),
    ),
);


Access violation with Drupal 7 multisite using shared DB

The question is closed. It seams to be that to have some tables in a separate database:
1) that second db should be placed at the same host as default one.
2) the user who has access to the default db should also has access to the second db.

Adding one more db to settings.php is not needed. It my case the correct settings.php db config has to look like:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'oxone',
      'username' => 'oxone',
      'password' => '*********',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
         'default'   => 'oxone.',
         'users'     => 'oxshared.',
         'users_roles'     => 'oxshared.',
         'sessions'  => 'oxshared.',
         'role'      => 'oxshared.',
         'role_permission'      => 'oxshared.',
         'authmap'   => 'oxshared.',
     ),
    ),
  ),
);


Removing "node" path from "node/add/*" URLs

If you go to admin/config/search/path/add then you can easily alias node/add/type to whatever you want.  For example, if you're using a node type called contact-form for a contact page, then just add contact-form as an alias for node/add/contact-form.


Media queries only applied for authenticated users

As Molot commented it is just a cache problem. You need to clear your browser cache to get the updated css. Another trick that works for me is to add a query string in the URL (e.g http://example.com/node/test?awy). You may need to turn off the css aggregation under Performance page to make sure that you will get the updated css and not the cached copy.

You can use Drush to clear your cache by using drush cc all.


For the profile part, you can just use the profile2 module. It allows you to add any kind of field to user profiles. Install it, enable it, clear caches, and go to structure > profile types.  For the actual fields, you might want to use the url field module, to enable validation of urls, etc. You can then create all the url fields you want, and give them appropriate names, like "facebook page", "twitter page" etc.

To display a block on nodes authored by the user, you could do the following:

Create a view of profiles.
Create a block display for the view
Choose fields (your social media link fields)
Click on advanced and then "contextual filter"
Add "profile: user uid" as a contextual filter and click 'apply'
Under "When the filter value is NOT in the url", select "Provide default value"
Select "PHP code"
Paste in the following PHP:

$node = menu_get_object();
return $node->uid;
Click "apply" and then save your view.

You can now add your block to the content types your users are allowed to create.


$form_state['redirect'] vs drupal_goto() in Drupal 6

$form_state['redirect'] is not well documented in 6, but my understanding is that when it's populated it will not always work (see the part about exceptions), so although that's documentation for 7, check that other elements of your $form_state are not interfering. If you are working with a multi-step form, it might be that you need to unset $form_state['storage'] first.

drupal_goto() is simply a function will take the user away from the current page to whatever path you specify, and has a bunch of extra features for doing extra things (see the documentation). It is actually called anyway when your form redirects.

When a Drupal form is submitted,$form_state['redirect'] overrides the default form redirect (which will take you to the form you've just submitted) and thus is calling drupal_goto() on your behalf. By putting it in a variable, you can ensure that Drupal handles, in the background, when to do the redirect, rather than you having to specify drupal_goto() directly and getting it wrong.


View or module that shows which nodes are linking to the current node?

Drupal is far too complex to do this in regards of all the modules there are.

You could use a module like this:
https://www.drupal.org/project/intlinks

Still not all texts that are available on you page can be applied to this.

Only thing you could use is a rather weird and costly JS thing. I mean Google Analytics tracks any link on your site. So this already happens. But is this a wise idea for your internal linking? imho not.

For reliable links between Drupal Entities please rely on a node or entity reference field. By this you have links you can query and evaluate.


Switching theme for comments as well as nodes (ThemeKey?)

You may use hook_custom_theme if you want to set theme for the comments pages.


Access denied when I try to delete the user menu

You cannot delete any of the following menus; they come with the core. You can delete any menu you created yourself.

To disable them from displaying go to admin/structure/block.


Redirecting user after login when using the ip_login module

As mentioned by charan in a comment, this works in version 6.x-2.0-rc1 of the IP Login module.


Drupal Views: Add Views signature to all SQL queries adding view name to Inner Join

The issue was the relationship added to the view. I removed the relationship and this fixed my issue.


If you want to prevent users from downloading the file directly by URL, you should not use the public download method. You should use the private method and use the functions in file.inc to access the files with PHP.


Programmatically Place View With Defined Fixed Contextual Filter

Use views_embed_view:

function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  // Remove $name and $display_id from the arguments.
  unset($args[0], $args[1]);

  $view = Views::getView($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return [
    '#type' => 'view',
    '#name' => $name,
    '#display_id' => $display_id,
    '#arguments' => $args,
  ];
}

Btw. Twig Tweak maps this function one to one:

  {# This accepts views arguments as well. #}

View:

{{ drupal_view('view_name', 'page_1') }}

Example

So if you want to filter the node 123 in the contextual filter you've shown in the question, you use this as third argument:

PHP

views_embed_view('view_name', 'block_1', '123');

TWIG (using the module Twig Tweak)

{{ drupal_view('view_name', 'block_1', '123') }}


Apply custom css class while rendering an image

field_view_value returns a renderable array so you should be able to just do.

$image = field_get_items('node',node_load($nid, NULL, TRUE), 'field_menu_image');
$output=field_view_value('node', node_load($nid, NULL, TRUE), 'field_menu_image',$image[0]);
$output['#item']["attributes"]["class"] = array('test');
print render ($output);


How to drop all MySQL tables using drush?

It seems there is a single drush command to Drop all tables in a given database. Just run:

$ drush sql-drop


You can use the key to get the value by referencing the options array in the original form element:

$key = $form_state['values']['submitted_tree']['company_1'];
$value = $form['submitted_tree']['company_1']['#options'][$key];


You can use the States API to make a field visually required, visible/hidden and so on.

One simple example from https://randyfay.com/states

  $form['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name=student_type]' => array('value' => t('High School')),
      ),
    ),
  );

There are UI modules to configure this, like https://www.drupal.org/project/conditional_fields, but I think none is ported to D8 yet. So you have to form alter it in.

Also, keep in mind that this is UI only. You still need to implement corresponding server-side validation.


What hooks are being invoked on a node edit form

hooks are basically functions provided by drupal to developer , so as to create a communicating medium between developer and drupal.
hooks get called or render on a page when particular action associated with them take place it is more like drupal send a message to hook "describing what action drupal is doing " and hook ask developer "drupal is doing this do you want to add more stuffs or to perform any action on this action of drupal"

so depending on action taking place hooks are invoked


This doesn't sound like a Rules problem. (yet)
To re-state the issue: you are trying to output display the values, and use a delimiter when there are multiple values.  Correct?

If so, where is the display taking place, of for example, "Name1" / "Name2"
Is this in a Node, View, Module ... or elsewhere?  Please be as specific as possible.

A Rules problem would sound like "for Trigger X I expect Action Y to take place".


How to list all nodes with alphabetical headings?

You can achieve this using the Views module (http://drupal.org/project/views) which actually comes with a pre-built view called "Glossary". Enable that and tweak it to suit your needs.

Hope this helps.


May be this can help - Views Dependent Filter.

  Allows the presence of exposed filters on a view to be controlled by
  values in another exposed filter. Dependent filters are hidden when
  not relevant, and their values are not considered when the exposed
  form is submitted.


Check whether a field value exists in a custom table when a webform is submitted

Just replace

$result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub));

with

$result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub))->fetchAll();

and try, hope it will work


Set "Use the administration theme when editing or creating content" to true in install profile

Setting it is as simple as:

variable_set('node_admin_theme', 1);

Most (not all, but most) config settings used in Drupal are managed using a system_settings_form(), which basically takes the array keys of the elements used in that form, and saves them as variables.

So an abridged version of the theme settings form would be

function some_form($form, &$form_state) {
  $form['node_admin_theme'] = array(
    '#title' => t('Use the administration theme when editing or creating content'),
    '#type' => 'checkbox',
    '#default_value' => variable_get('node_admin_theme', 0),
  );

  return system_settings_form($form);
}

When Drupal processes that form, a variable called node_admin_theme is created/updated with the appropriate value.

If you're certain a form is using system_settings_form(), finding the names of the associated variables is as easy as inspecting the elements themselves and looking at the 'name' parameter, e.g.

If you're not sure, lookup the function that defines the form and check. If it does use system_settings_form() then great, and if not you get an insight into how that form actually manages its data.


Would redirecting users in hook_menu's access callback have any undesirable effects?

I think you could do this by altering the delivery callback function. If the access callback returns FALSE that's what's passed to the delivery callback. If you wanted this redirect behaviour just on specific pages you could modify the delivery callback just for those pages via hook_menu() or hook_menu_alter(). If you want the behaviour to be global, you can use a hook_page_delivery_callback_alter() to change it.

Here's an example delivery callback.

function custom_deliver_html_page($page_callback_result) {
  if ($page_callback_result === MENU_ACCESS_DENIED) {
    drupal_goto('<front>');
  }
  drupal_deliver_html_page($page_callback_result);
 }

Btw this is untested, and I've never actually altered the delivery callback myself previously.


You can essentially download and upload a new theme to your site by following the instructions here:

https://drupal.org/getting-started/install-contrib/themes


Prevent logged in users from seeing other registered users information

You should change the permission for authenticated users.

Go to admin/people/permissions and under user permissions dissallow authenticated users to View user information


Determining current user's relationship to node author

It looks like you can use the user_relationships_load() function. The following code will load all relationship objects that exist in the system between 2 users. From there you can inspect the relationships for their type/properties and make your decision based on that:

// Set up the user ids
global $user;
$current_user_uid = $user->uid;
$node_author_uid = $node->uid;

// Set up the parameters
$params = array('between' => array($current_user_uid, $node_author_uid));

// Get the relationships
$relationships = user_relationships_load($params);


Why is Drupal 7 loading the wrong .js file?

Turns out the issue was with a rogue server that was hitting our site. The old web server was hitting our database and caching the old files.

It was hard to find because the two servers had the same hostname for some reason.


how to change teaser display output via views

Download and enable Display Suite module.

Then go to /admin/structure/types/manage/{content-type}/display/teaser and select layout of your choice.

Then add the links feature to the region of your choice


If you are adding the attributes in Twig you can set multiple attributes by chaining the setAttribute calls like this:

{{ attributes.setAttribute('id', 'value').setAttribute('data-info', 'value'); }}


How to make a template for content type with panels

Google searching I found this solution.

https://www.drupal.org/node/1422454

Best regards!


Keep only the last revision of content with multi-version module

Actually, now (March 30 2018) it has a 8.x version. So this is your module:

Node Revision Delete

  The Node Revision Delete module lets you to track and prune old
  revisions of content types.

  Features:

  Define the max amount of revisions to keep per content type.
  Run on Drush, cron run or on a different period (daily, weekly, etc).


Relationships in Views always 4 results also if no reference for the field

I think the best way to do via https://www.drupal.org/project/views_field_view . So, below is the steps:-

Create a view for the meal which shows all meals and add one more field "nid" as a hidden parameter(just tick exclude from display) so that we will have an available token for nid.
Now, create another block of wine and pass meal's nid as a contextual fitler. so, it will give you all wine as per single meals.
The next step do the trick. Go back to block #1(meal's view) and and add global:view field and pass "[nid]" of the meal as a contextual filter in that field(you will find an option don't worry) and select the view and display of the #2(wine's block).
That's it, here you have all the meals with wines. :)

Hope it will solve your problem.


Rules - Page redirect not working on "after saving new content"

There are a couple of serious bugs in the Rules 7.x beta (frequent 503 errors). Release candidate just came out that fixes these bugs. Try an update to the latest module version and see if the error goes away.


How to prevent showing background code in Drupal 7 admin?

Sounds like it may be related to (caused by) JQuery Update, similar to what is described in "Cannot edit my views.. I get a JSON string?".

Maybe you want to (temporary) try any of these potential work arounds:

Disable or change the settings within JQuery Update (to see if it solves the issue).
Change the admin theme to any theme included in the Drupal version you downloaded.


How to display add node form with node reference?

Don't worry, there's a module for that! http://drupal.org/project/formblock I believe this can work with node-references with a bit of configuration. If not, you can use this tutorial to populate the node reference: http://grayside.org/comment/830 which should get carried over by the FormBlock module.


How to prevent executing .php files in sites/default/files directory for nginx+php7.0-fpm?

This is what works for nginx and only targets files directory:

location ~ /files/.*\.php$ {
    return 403;
}

This is more generic and wont let any php file in a directory execute directly:

location ~ /.*/.*\.php$ {
    return 403;
}

WARNING, this is posted all over the web but only works for hidden directories:

location ~ \..*/.*\.php$ {
    return 403;
}


How to: Multilanguage site, but single language backend?

I know this post is getting old and the OP probably has this sorted by now but I came here looking for the same answer and thought I'd post a follow up for anyone looking for details. I've made this as easy and basic as possible in case you're new to Drupal.

My version is 7.21.

Ok, here's what I just did to get the back end in English and the site content in Spanish. I'm assuming you have all the translating modules installed and set up, etc.

Go to your admin profile and set your languages, for me its this:

Administration Language = Default administration language, currently English

Language Settings
Language = English

Then go get the Administration Language module that Patrick linked to. (its currently the Dev version but works fine for me, look in the red area for the DL). Install and enable.

Then go to Administration > Configuration > Regional and language > Languages:

Scroll to the bottom and you'll have an option of "Use administration language in the administration menu".
Set that to Enabled

Save it and now everything should show in what ever language while the back end stays in the language you set for your admin profile.

I hope this helps!


how to call a JQuery function inside an ajax callback function

As Jose Daniel said: use ajax_command_invoke() in your ajax callback:

$commands[] = ajax_command_invoke(NULL, "your_function");
$output = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($output);

Your JS-File:

(function ($) {
  $(document).ready(function(){
    $.fn.your_function = function() {
      // do cool stuff
    }
  });
})(jQuery);


How can I create another user login block?

You can't have the option assign a block to different region.But you can use the Multiblock

it will allowing you to create multiple Block Instances of already existing blocks.

If you want customize the login block with your own design, then this link will help you.


Pauthauto breaking for one specific page

The redirect issue described here is pretty common for sites where the Redirect module (drupal.org/project/redirect) is enabled. The module has a default config setting that creates a redirect anytime the url on the node is edited (this includes through bulk operations such as a pathauto alias generation process).

This setting can lead to the infinite redirect issue when a user changes an alias and then changes it back, resulting in a circular reference/infinite redirect.

I highly recommend disabling this setting for sites under construction (where urls are in flux) and enabling once deployed to production.  You can toggle it at /admin/config/search/redirect/settings (it's the very first setting on the page, shown in the partial screenshot below)

For production sites, be wary of changing a url multiple times- check/manage the list of redirects associated with the node on the node edit form as shown below

You can also check/manage redirects from the full list of redirects assigned in Drupal at /admin/config/search/redirect


Filter taxonomy term attached to user field

One way to do it is a bit of a multi-step process.

First, in the view itself under ADVANCED -> CONTEXTUAL FILTERS set up a contextual filter for the taxonomy field you want to filter the view based on (make sure that field is also added to the view's fields.

second, you'll need to add a bit of code to a custom module. You'll want to implement hook_views_pre_view

/**
 * Implements hook_views_pre_view().
 *
 * @param ViewExecutable $view
 * @param string $display_id
 * @param array $args
 * @return void
 */
function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  $account = \Drupal::currentUser();

  // DO A LOOKUP FOR THE USER'S FIELD
  $VALUE_FROM_USER_FIELD_LOOKUP = 'SOMETHING';

  // IF WE ARE IN THE RIGHT VIEW AND DISPLAY
  if($view->id() == 'MY VIEW ID' && $view->getDisplay()->display['id'] == 'MY DISPLAY ID') {
    // ADD SOME CUSTOM ARGS TO THE CONTEXT FILTER
    $args = [implode("+", $VALUE_FROM_USER_FIELD_LOOKUP)]; //implode on + or some other character? for multi-value contextual filters...
  }

}


How to create dependent exposed filters in a view

I think you should use Simple Hierarchical Select, this also works with views and exposed filters out of the box.


Add a field to your view of type Content:Path and drag it to the top of your field list. Then your href should be:


Found the issue: I had the language detection under /admin/config/regional/language/detection messed up - content language detection was identical to UI language detection (which was User account first, URL second). Used URL only for content language detection and now it works.


how to show a message after a node form is submitted

You can create an additional submission callback.  Not sure if it will run late enough for you.  May be worth a shot.

Create a form alter hook using hook_form_alter();
Within there add an additional submit function to the #submit array

Example:

hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  drupal_set_message('your message');
}

You could try going 1 step further and adding the submit hook to #submit in the #after_build.  This will ensure it is the very last submit callback (unless other higher weighted modules also use the afterbuild)

Example:

hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#after_build'][] = 'custom_afterbuild_function';
}

function custom_afterbuild_function($form, &$form_state) {
  $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  drupal_set_message('your message');
}

I hope this helps

[update] added drupal_set_messages to code examples.


How do I translate/change the text of the order receipt email in Commerce 2?

You can find the Subject on the UI translate page (/admin/config/regional/translate).  Search for Order #.

The rest can be found in a twig template:

/modules/contrib/commerce/modules/order/templates/commerce-order-receipt.html.twig

Copy this template to your theme and then edit as desired.  You can also use the template as a guide for what to search for on the translation UI screen to translate everything.


Migrating to XAMPP local install - Configure the temporary directory

This issue has nothing to do with Drupal config. Its related the your tmp folder permission. You got to update the tmp folder permission, so that apache user have proper write permission.

chmod -R 0700 chmod -R 0700 /tmp


Cancel if condition not met, show status

You can use hook_mail_alter() for that, e.g.

function MYMODULE_mail_alter(&$message) {
  if ($message['id'] == 'MYMODULE_foo' && any_other_condition()) {
    $message['send'] = FALSE;
  }
}


Managed to delete Event_Calendar_Status and cannot reinstate

I have not checked the module, but here are few things I can suggest take a database backup before you take any step.Uninstalling calendar module should be not helpful, as it seems settings to be changed in event_calendar module.

How you deleted the status term,did you make any direct changes to database?can you revert back those changes? You can setup event_calendar module on fresh drupal installation to track what changes can be done to make it work.

Not sure, but keep uninstalling and reinstalling event_calendar module as last option.

I guess event_calendar provides UI for mailing notifications settings, as the project page says

  This module also gives an Admin UI to change status (approval/denied)
  of events and a mailing system.


Drupal 6 did not have {file_managed} at all. Also, user profiles wasn't really fieldable. And both styles and fields changed between 6 and 7. 3 big changes affecting one value - that's bound to create problems.

To get around it, you can use Views Data Export to expose users from old site, and then import your users back using for example Feeds

  Import or aggregate data as nodes, users, taxonomy terms or simple database records.

with Feeds Image Grabber

  an addon for Feeds module, which grabs image for each feed-item from their respective webpages and maps it to an image field


Here is an example of how to use drupal_http_request().

$options = array(
  'method' => 'POST',
  'data' => 'name=Test&email=example...',
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$result = drupal_http_request('http://example.com', $options);

In $result, you will get an object with the data of the request.
Check the $result object and make sure the payment is gone through (or whatever the condition that should pass before redirecting the user).

Then, use drupal_goto() to redirect the user to the new location.

Note that this is just a normal redirect (GET) and data is already submitted to the Payment server by your site.

If you want to use Paypal IPN-like requests that the user POSTs data to the server, you need to create a form instead.

function _test_payment_form() {
  $form = array();

  $form['user'] = array(
    '#type' => 'hidden',
    '#name-info' => 'user', // this is the field name that will become name attribute of the input tag. No need to use this if your $form['KEY'] is same as this one.
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Proceed to @server for the payment', array('@server' => 'Paypal')),
  );

  $form['#action'] = 'http://example-payment-server.com/example/2/3/4'; // Information will now be submitted to this URL other than Drupal.
  $form['#method'] = 'POST', // Just for clarification. This is the default value.

   return $form;
}

You can print the form using the following code.

print drupal_render(drupal_get_form('_test_payment_form'));

You can also use the following code, where render arrays are accepted.

drupal_get_form('_test_payment_form');


What are the various steps to contribute my own module to Drupal.org?

The main pages you need to read are Best practices for creating and maintaining projects and Project application checklist.  If you have never done this before, you need to read Creating a sandbox (experimental) project

In short, you need to

Obtain git access on drupal.org
Create your sandbox project
Commit your code
Submit it for review
If approved, it will be promoted to be a full project

Keep in mind that your project will likely never be officially reviewed unless you get a review bonus.  Participating in other reviews is also a good way to learn about best practices so you can get through the initial review smoothly.


In addition to what @Gisle Hannemyr said, I would recommend the spamicide module (sets hidden field that if it is filled by a bot on registration, it will not create the account) and the re-captcha module on your registration forms.


How do I add a node field widget to a custom form?

Answering my own question, I ended up using the following:
<?php
//Create an empty representative entity
$node = \Drupal::service('entity_type.manager')->getStorage('node')->create(array(
                'type' => 'article'
            )
        );

//Get the EntityFormDisplay (i.e. the default Form Display) of this content type
$entity_form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')
                                        ->load('node.article.default');

$form['#parents'] = []; // Mandatory, otherwise the widget class throws an error

//Get the body field widget and add it to the form
if ($widget = $entity_form_display->getRenderer('body')) { //Returns the widget class
  $items = $node->get('body'); //Returns the FieldItemsList interface
  $items->filterEmptyItems();
  $form['body'] = $widget->form($items, $form, $form_state); //Builds the widget form and attach it to your form
  $form['body']['#access'] = $items->access('edit');
}

see EntityFormDisplay::buildForm


Display different fields depending on field value in node template

You may find it easier to use the Conditional Fields Module:

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API. You can, for example, define
  a custom “Article teaser" field that is shown only if a "Has teaser"
  checkbox is checked.


Combining Drupal & WordPress on a Multi-Site Project

I would advise reconsidering your proposed solution and making sure any benefits are worth the potential extra effort/hassle, because I don't really see any pros for doing it and there is a very large con of complexity (for no real gain).

In terms of your current reasoning for wanting to do this:

Advantage 1: Using two different CMS's will help me differentiate the sites.

Why not just use different themes for different sites to differentiate them?
You could have different themes for admin, or front end, or both, depending on what you aim to achieve.
The themes could be totally different, or they could just be the same theme in different colours, or something in between.

Also, wouldn't it be easier if the editing/admin experience is the same for all sites instead of being different?
This also goes for any user interaction with the site from non-admins.
Consistency is an excellent thing.

Advantage 2: A special feature not available on one CMS might be available on the other CMS.

Both platforms are very mature and can handle most things. If you want to do something really different you're probably going to have to write code to do it regardless of the platform. If you have two different platforms and you want to do something custom on both that means you have to write both a drupal module and a wordpress plugin (or modify existing modules/plugins for both platforms), so you're making more work for yourself.

It also sounds like the special features you talk of are things you might think of in future.
If you are choosing platforms try to think of all the features you want first (and features that maybe you might want in future), then choose the platform that is best for implementing those features.
Obviously you might think of things in future that you didn't originally think of but there isn't much you can do about that so the platform you consider the most flexible, and the platform you prefer to do custom code for wins points in this regard if you think that complex new functionality might be required in future (remember here that a large amount of commonly used functionality is available on both platforms).

Now there are the disadvantages, which include but are probably not limited to (I don't know exactly what your plan is for these sites to work together or interact with each other but these things are still likely relevant):

Possibly doubling effort when you have to write custom code (as mentioned above).
Adding effort when doing maintenance, like module/plugin updates.
Added complexity, which could make it harder to develop the new features you come up with in future, could make it harder to track down problems when they occur, could make it harder to use the sites (or understand how they work together) in general.
System requirement mismatches. These two platforms require basically the same things but sometimes to do something on a given platform you need a specific version of PHP, or MySQL, jQuery versions etc. Getting two platforms sorted out with specific library versions will be harder than one (if they have to match, maybe they don't).

Basically I think it is best to achieve what you want in the simplest way possible.
Sometimes adding complexity is necessary for the requirements, or you may be able to create something that much better and it will be worth the effort/hassle but if not, and you are adding complexity and gaining nothing of value in return (or the potential value doesn't outweigh the potential troubles), then you are losing out.


How do I make a panel visibility rule work when the element to check for has to be not set or empty?

use flags module, and rules module, make a rule when save/update your content type, condition: your_field_value is empty, if true, flag your node, then in panels add your panels-rule visibility  based on your new flag.


Download a backup of the files directory

There is actually Backup and Migrate Files too.


Customizing form for product attributes and features?

I am not an expert as I am going through a learning curve with Drupal myself, however, I do have database experience and started using Ubercart myself.

As to your question on auto-created SKU, I think as a learner you are complicating things, unless you are looking into a huge and fast growing database for which you want to create auto SKU, which serves for Stock Keeping Unit.  There is a modul Commerce AutoSKU.

As a method to setting up your "research project" implementer 'Role', you can create a form (e.g. Project Form), allowing the enduser to Name (Title) the project, but ID to that project can be in incremental order assigned by the table (project_id, auto_increment).  You can allow access to that specific form to the persons implementing the research projects.

As to making use of Ubercart's default system and its capability to advanced features such as customizing methods, I find there is quite the flexibility as to adjusting your own custom forms and assigning fields with the 'Hook System'.  It is a steep learning curve, I found.

I have been following the following videos.  The presenter is quite fast, but I found his instructions helped me to understand my capability.  It is a youtube video series consisting of 10 videos (15-20 mins long each).

Creating an E-commerce Site Using Ubercart

Sorry that I cannot help you further, but I hope I am able to get you one step closer to your project.


What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?

Some reasons:

Code in your database can not be version controlled and is also harder to find in general later on.
Eval()'d code is much slower than something hardcoded in a file.
If there is an error somewhere in that code, you will get a very unhelpful error message (error in eval()'d code at line 3) and you might even have go through your database manually to find and fix the error. If it is inside a block that is displayed on all pages and results in a fatal error all the time for example.
The above is also true when upgrading from Drupal 6 to 7 and whatever API's you used were changed. So you will have to port your code while migrating. If the code is in a module, you can port it in advance, test it, and only deploy it on the new site. Inside a node or block, it will only work with either Drupal 6 or 7.
Writing and maintaing that code is also harder, because you are working in a textfield inside your browser. Having it in a module allows you to use an editor/IDE with syntax highlighting, autocomplete and so on.
There is always the possibility of a misconfiguration that gives people access to a text format/block/whatever with php execution enabled. If php.module (in D7, D6 is not so strict, for example for block access rules) isn't even enabled, that risk is much lower already.
If your CMS allows execution of PHP then an attacker who finds a security vulnerability of XSS or privilege escalation can now use your server for enormously malicious things (as part of a DDOS, sending spam, hosting malware, hacking into other sites/databases on the server, hacking into other servers on the network that might be behind firewalls). In addition to making small vulnerabilities more painful, this makes the site a more likely target of attack if its known that it can be used to execute php.

There might be more reasons, but that should be enough :)


You should create an exposed filter for the View page, probably based on the full text search field, and then set the filter form to show in a block.

All can be done from within the Views UI on the edit form for the search page.


I deleted /devel_themer folder now my website reports an error

I know its answered in comment, but for others who land here.

Increasing the execution time in php.ini can solve this. An ideal value would be 120.

If it doesn't solve the problem we might need to disable and uninstall the module and fix the problem. Ofcourse you can install it back after things are fixed.

If you can access the admin page:

Disable the module.
Uninstall the module from the uninstall tab in modules page and delete the module folder.
Clear the site cache if required.

If you can't access the admin page:

Delete the module folder.
Run update.php

If you were not logged in at the time of the error you will have problem accessing the update.php, then you will have to either use drush the command drush updatedb or temporarily enable access to update.php by changing settings.php file.

If you had drush, you an also consider disabling the module with it.

Line to change:

$update_free_access = FALSE;


How to add more than one tags for content?

You already seem to have 1 field for this content type that is a term reference, whereas the corresponding taxonomy has at least 2 terms (i.e. "test" en "new").

Solution 1:

Allow "multiple" or "unlimited" values for the term reference you're already using, which is an option with the field settings of your existing term reference. Which you'll find at /admin/structure/types/manage/mycontenttype/fields/field_term_ref, assuming field_term_ref is the machine name of your term reference, and mycontenttype is the machine name of your content type.

Solution 2:

Create an additional term reference field for this content type, and add one of those 2 terms to the new field, and delete it from the term reference field you already have.

Note: Which solution to choose depends a bit on your use case:

If the terms are somehow "related", then solution 1 is what you should use. E.g.: Target audience with terms like visitors, members, editors, administrators.
If the terms are not at all "related", then go for solution 2. E.g. Topic and Target audience.


How to render random image on every refresh page

Previously I write a small module for this purpose, named Many to one image

This is a small display formatter, Download and install then go to manage display and select it.


Suggestions for creating a more complex tiered content type

I would definitely suggest using paragraphs, it's a killer module for multi-valued, arbitrary ordered fields inside content types.


Is making a feature of literally everything available actually a smart thing to do?

Yes.

Combined with placing your Feature module(s) in version control and carefully reviewing the diffs, this is a good way to keep track of administrative changes to the sites you maintain.  I do this on most sites I maintain.

However:

If you're using Strongarm, you shouldn't export literally everything.  Some system variables are caches, and will change frequently; exporting these caches to a Feature module will just cause the Feature to appear overridden all the time, without providing any maintenance value.  Over on this answer I provided a list of variables to exclude.
I wouldn't expect Features to increase performance, though.  I elaborated on that over here.


How can I modify the $submitted variable for a custom node template?

You can do this.In your theme_preprocess_node function create a new variable which is used in your node--blog_post.tpl.php .

 function yourtheme_preprocess_node(&$variables) {
 $node = $variables['node'];
  if ($node->type == 'blog_post') {
    $created = $node->created;
    $date = date('F j,Y', $created);
    $name = $node->name;
    $variables['new_variable'] = "By ".$name." | ".$date;
  }
}

then print this new_variable in your tpl like this.

  <div class="content clearfix"<?php print $content_attributes; ?>>
<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['comments']);
  hide($content['links']);
  print render($content);
  print $new_variable;
?>

Output show like this


Offload cached pages to different Apache process

It is not a direct answer to your question, but play around with setting MaxMemFree and MaxRequestsPerChild in the prefork section of your httpd.conf.  MaxMemFree should force Apache to free memory that it doesn't need, and MaxRequestsPerChild will force Apache to fork a new process (and free memory in the process) after servicing a particular number of requests.  You may have some performance impacts, but gain memory improvements.


Try doing it like this, which works fine for me:

For date format select Custom and then enter Y-m-d\TH:i:sP


How to print and/or manipulate individual image attributes and suppress width and height via the image.html.twig template

Copy the image.html.twig file from core/modules/system/templates/ to your theme /templates folder.

If you want to simply hide width and height as image attributes:

{%
set classes = [
    style_name ? 'image-style-' ~ style_name|clean_class,
]
%}
<img{{ attributes|without('width','height').addClass(classes) }} />

If you want to do further things it would be probably better to use template preprocessing functions in the theme file (because of too much logic here) - so this is more a use case for the possibilities in twig files ...

If you want to hide width and height and also want to hide empty class and alt attributes for example:

{%
    set classes = [
        style_name ? 'image-style-' ~ style_name|clean_class,
    ]
%}
{% set printattributes = attributes.addClass(classes)|without('src','alt','class','width','height') %}
{% set printclass = attributes.class.value() ? 'class="' ~ attributes.class ~ '"' : '' %}
{% set printalt = alt ? 'alt="' ~ alt ~ '"' : '' %}

<img {{ printclass|passthrough }} src="{{uri}}" {{ printattributes }} {{ printalt|passthrough }} />

This is also very useful in this context: http://drupal.stackexchange.com/questions/137652/override-image-formatter-html-twig/141340#141340


In the dashboard, Go to Configuration > Node Export > Reset Values on Import.

...

I love answering my own questions. In fact, every question I've asked here ..well, have been answered by me, and me only. Thanks for all the wonderful help from the (non-existent) Drupal community.


How to filter on taxonomy term but only match one field on the node, where two fields (primary and secondary) both use the same vocabulary

Ok - This is also out of the box Taxonomy Term behavior.  My issue was I was selecting the wrong option for what I wanted.  I wanted the behavior that converts term string to tid, and so the full solution is:

Contextual filter on Content: Primary Category field
Specify Validation > Taxonomy Term, my vocabulary
Select the option Term name converted to Term ID

Bam!  Success!  Now I get my list of nodes matching that vocabulary's terms as strings but only for the one of the multiple taxonomy fields of that vocabulary on the node.  To further exemplify, my next step will be to create another View that is all the Secondary matching terms as "related" but not primary like this one is.


How to send an email when the content is unpublished?

hook_scheduler_api() accepts two parameters -

1. $node is the node object being processed
2. $action is either 'publish' or 'unpublish'

hook_scheduler_api()

<?php
    function yourmodule_scheduler_api($node, $action) {
  if (some condition) {
    // parameters: drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE) {
    drupal_mail('yourmodule', 'mail key', $user->mail, etc depending on your needs);
  }
}
?>

hook_mail()

<?php

function yourmodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'this-mail-key':
      $message['subject'] .= 'your subject';
      $message['body'][] = 'text';
      // etc ...
      break;
    // etc ...
}
?>


'default_value' plugin does not run if 'get' returns null or empty value

The catch here is that you should not use the get process plugin explicitly. The behaviour you want is already implicitly used the default_value plugin. This is because get is the default process plugin and can be shorthanded. In your case this should work:

 field_privacy:
   plugin: default_value
   source: field_office_privacy
   default_value: 'open’

Also see documentation for get and default_value


Form multiselect item and url encoding with GET method

I am not sure if this is gonna work, but I think it might help you a little bit.

$query = explode('&', $_SERVER['QUERY_STRING']);
$combined = '';

foreach($query as $key => $value) {
  if ($key == 'option') {
    $combined .= $value;
  }
}

drupal_goto($_SERVER['REQUEST_URI'] . '&option=' . $combined);


What is the specificity limit of EntityFieldQuery / fieldCondition?

Yes, it is possible.

The second question is different, what you are describing is exactly what EFQ can do.

Something like this should work:

->fieldCondition('field_answer_quiz', 'nid', $nid)

The column names in the field tables are a combination of the field name and the column name, you need to split that up like the above example.


I think Picture module help you to solve your query.

Please check Responsive Images in Drupal with the Picture Module.

OR you can try these also :

Flickr
Responsive images and styles


How do form #states interact with dialog action buttons, if at all?

This doesn't answer the question itself, but since I struggled for a while to get this all syncd up I figured I should drop the work into something that people might hit from google. To get the attributes all syncd up you can use the following js file:

(function ($, Drupal, drupalSettings) {
  var handler = Drupal.behaviors.commentsRatingFlexible = {
    attach: function (context, settings) {
      // If our form is loaded in a modal, then the context is
      // the form itself. Therefore we cannot look for the form
      // inside of context. As such, we need to check for forms
      // that exist in both situations an handle accordingly.
      var formInstances = [];

      // This would be the class for your particular form
      $('.comment-rating-flexible-form', context).each(function () {
        formInstances.push($(this));
      })

      if ($(context).hasClass('comment-rating-flexible-form')) {
        formInstances.push($(context));
      }

      // Lookup any rating-flexible-forms and disable the submit
      // button by default, since it shouldn't allow an empty val
      // for the fivestar field (if it's present)
      for (var k in formInstances) {
        var $form = formInstances[k];
        var $submit = $('.form-submit', $form);
        var $fivestarSelect = $('[name="field_fivestar_rating[0][rating]"]', $form);

        if (!$fivestarSelect.length) {
          return
        }

        handler.dialogSubmitButtonHandler($form); //must be called first
        handler.observeAttributes($submit);

        if ($fivestarSelect.val() == '-' || $fivestarSelect.val() == '0') {
          // #states don't apply on form load, only on change,
          // so we need to disable the form button here and
          // sync that onto the dialog's button
          $submit.attr('disabled', "");
        }
      }
    },
    /**
     * Syncs attributes from real form-submit onto dialog submit btn.
     *
     * @param $form
     *   The form contained in the dialog
     */
    dialogSubmitButtonHandler: function ($form) {
      var $drupalModal = $form.parent();

      // If the form is loaded outside the context of a modal, don't execute
      if ($drupalModal.attr('id') !== 'drupal-modal') {
        return;
      }

      // The actual modal and the rest of its contents won't exists
      // on the initial load. As such, we need to add a watcher to
      // the DOM to find out when our dialog action buttons exist
      // so that we can act on them then.
      var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
          if (!mutation.addedNodes.length) {
            return
          }

          mutation.addedNodes.forEach(function (node) {
            var $node = $(node);
            if (!$node.hasClass('ui-dialog-buttonpane')) {
              return;
            }

            var $formSubmitButton = $('.form-submit', $form);
            var $dialogSubmitButton = $('.form-submit', $node);

            // Watch for our custom $.event from observeAttributes
            $formSubmitButton.on('attributeUpdated', function (e, attrData) {
              $dialogSubmitButton.attr(
                attrData.attributeName,
                attrData.attributeNewValue
              );
            })

            observer.disconnect();
          })
        })
      })

      observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: false,
        characterData: false
      })
    },
    /**
     * Fires an event when an element's attributes change.
     *
     * @param $el
     *   The jQuery element being observed
     */
    observeAttributes: function ($el) {
      var observer = new MutationObserver(function (mutationList, observer) {
        var eventData = [];

        mutationList.forEach(function (mutation) {
          if (mutation.attributeName === 'style') {
            return;
          }

          var attributeName = (mutation.attributeName === 'class') ? 'classList' : mutation.attributeName;

          $el.trigger('attributeUpdated', {
            'attributeName': mutation.attributeName,
            'attributeNewValue': mutation.target[attributeName],
            'attributeOldValue': mutation.oldValue
          })
        })
      });

      observer.observe($el[0], {
        attributes: true,
        attributeOldValue: true,
      });
    },
  }
})(jQuery, Drupal, drupalSettings);


I ended up creating a Flag and sorting by flag and using hook_views_query_alter() to remove the sort condidtion if the filters were not set in the views.


How can I load the #totals property for the receipt theme in a custom module?

Use the service
'#totals' => \Drupal::service('commerce_order.order_total_summary')->buildTotals($order),