Use my existing jquery function in drupal 7

Your are missign two important things. First, in Drupal 7 jQuery is namespaced to avoid conflict with other JavaScript libraries. So you should either wrap your code in an anonymous function to assign the jQuery object to the $ variable (ie. (function($){...})(jQuery);) or use jQuery instead of $.

Second, you shouldn't use $(document).ready() but add you code as a the attach function under the Drupal.behaviors.yourModule namespace. Behaviors are attached on the documentobject on load, but also to any new element added to the page by any well behaving scripts (the ones that call Drupal.attachBehaviors()). Finally, because behaviors could be attached several times to the same DOM tree, you should avoid processing the same element multiple times. This can easily be done with jQuery Once.

(function($){
  Drupal.behaviors.myFunkyModule = {
    attach: function(context, settings) {
      // Get the map wrapper element (anywhere in the document).
      var map_wrapper = $('#map-wrapper');
      //Set the map-wrapper width and height to match the img size only once.
      map_wrapper.once('my-funky-module').css({
        width: $('#map-wrapper img').width(),
        height: $('#map-wrapper img').height()
      })
      // Get the (un-processed) .pin elements, in the context (ie. DOM tree) our behavior is attached to.
      var pins = $(".pin", context).once('my-funky-module');
      // Process the pin elements (note: this could also be done using jQuery.each()).
      for (i=0; i<pins.length; i++) {
           var pin = pins.eq(i);
          // store initial tooltips contents within an array
          var tooltipContent = new Array();
          tooltipContent[i] = pin.html();

          // set tooltip direction type - up or down
          var tooltipDirection = 'tooltip-up';
          if (pin.hasClass('pin-down')) {
              tooltipDirection = 'tooltip-down';
          }

          // Append the tooltip elements to the #map_wrapper one.
          map_wrapper.append("

" + tooltipContent[i] + "

");
      }

      // Add event listeners to show/hide the tooltip, again this only need to be done once.
      $('.tooltip-up, .tooltip-down').once('my-funky-module').mouseenter(function(){
        $(this).children('.tooltip').fadeIn(100);
      }).mouseleave(function(){
        $(this).children('.tooltip').fadeOut(100);
      });
    }
  }
})(jQuery);


VBO showing error when using Drupal Commerce

I flushed out the database, and started with a new fresh version of VBO.


How to display multiple default items for field collection with unlimited cardinality?

1 solution to this is https://www.drupal.org/node/1337804#comment-6326678. I will post another solution if found without form rebuild.


"Place block" ajax error when using nginx

Sometimes writing it down helps to figure things out! The missing bit of configuration needed is fastcgi_param QUERY_STRING $query_string;

With the Drupal nginx recipe but with that line added in the location ~ '\.php$|^/update.php' { block its now working as expected, both the is-active class is added to the active menu link and the "Place block" ajax works properly.


Is the field item delta in the database reliable?

The answer is definitely "no", but it's a hard "no", not engine-dependent like it might appear. Under normal operation, the 0..n delta reset happens before the data is ever sent for storage.

If field values are saved using the API (field_attach_submit() etc), then they're unconditionally run through _field_filter_items():

function _field_filter_items($field, $items) {
  $function = $field['module'] . '_field_is_empty';
  foreach ((array) $items as $delta => $item) {
    // Explicitly break if the function is undefined.
    if ($function($item, $field)) {
      unset($items[$delta]);
    }
  }
  return array_values($items);
}

As you can see, any indices you might have manually set in the $items array will be discarded, and the resulting array will always be indexed 0..n. I don't think Drupal gives you another opportunity to affect that array before the data is persisted.


Configuring a basic multisite development environment in Linux

If you followed the exact instructions and you did not change any paths, then you have a typo: /var/www/html/drupal/sites/testsite.localhost/ See the extra 'html' directory? Make sure the paths in the apache config (step#3) match the actual paths in your file system.


Rewrite a Views Field to get rid of accents. I need roman alphabet characters for a csv export

Setting "Character encoding conversion" in the data export view's CSV file settings to:

ISO-8859-1//TRANSLIT

should accomplish what you're attempting. That will convert the names to the ISO-8859-1 character set, with transliteration of characters not included in the set to something that appears similar.


Different colors and fonts dependent on roles in views results

In your theme template.php file add this function

function THEMENAME_preprocess_html(&$vars) {
  foreach($vars['user']->roles as $role {
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}

This will add the current role(s) to the body classes.

Now you can style it like this

body.role-admin .view-VIEW-CLASS {
  background: #eeeeee;
  font-size: 16px;
}


views in D7 :: remove doubles in exposed filter list

The Views exposed filters block is a Drupal form, one that can be modified via a hook_form_alter or hook_form_FORM_ID_alter implementation. Here is a simple sample implementation of the more generic hook_form_alter.

/**
 * Implements hook_form_alter.
 */
function foo_helper_form_alter(&$form, &$form_state, $form_id = NULL) {
  if($form['#id'] == 'views-exposed-form-content-page') {
    // Do something with mah filters...
  }
}

If you are in doubt of what #id to use, you can always just implement this hook, go to your Views page, and watch the output of the $form variable to figure out what is the correct id to use. If you are in D7, the ID you are looking for will most likely be prepended with views-exposed....


Submitting webform without refreshing the page

Check out Webform AJAX module.

This module adds AJAX support to Webform (3.0 and above).
As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.

I think that may do what you are asking. Should then show up as options in form settings.

Also, be sure you are set to "no redirect"


Which hook to use in a custom module for tracking access to one particular page?

That's how I achieved that:

function grap_contact_export_csv_page() {
  grap_log_export(); // Calling another function to record tracking in DB
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"grape-export.csv\";" );
  header("Content-Transfer-Encoding: binary");
  $fp = fopen('export.csv', 'r') or die('Impossible d\'accéder au fichier');
  echo fread($fp, filesize('export.csv'));
  fclose($fp);
  drupal_exit();
}


How can I override a link in the language menu?

I'm certain there is a better way to do it than this...it's a little brute-force, but it gets the job done for me:

function THEME_preprocess_page(&$variables) {
  $markup = $variables['page']['my_region']['locale_language']['#markup'];

  // Do some string replaces on $markup to adjust the URLs

  $variables['page']['my_region']['locale_language']['#markup'] = $markup;
}

I know this isn't the Drupal way to do this. Part of the problem is that I only need to adjust the language links on a few Views pages, so figuring out how to do this in hook_menu_alter or in a module was too complicated...I needed a quick solution.

I'm hoping someone can pos the Drupal way of achieving this.


Restrict User Type to buy a Product Type in Drupal Commerce

You can create a different product display type (i.e. content type) for the renewal product (at admin/structure/types). Then you can restrict that content type to those with the members role (in admin/people/permissions).

Or, if you want to show the product display type, but restrict the actual purchase, I think you have to resort to custom code like this:

<?php
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the Commerce 'Add to Cart' form.
 */
function custom_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  global $user;
  $roles_allowed_to_buy = array(
    'Some Custom Member Role',
    'administrator',
  );
  if (!array_intersect($user->roles, $roles_allowed_to_buy)) {
    // Display a help message.
    $form['help'] = array(
      '#markup' => t('You do not have permission to buy this product.'),
    );
    // Disable the whole form.
    $form['#disabled'] = TRUE;
    // Remove any submit button(s).
    unset($form['submit']);
  }
}

(that's an example you would put inside a module called custom_module)


Drush, Omega 4 - Does not seem to recognize Drupal site

Not sure what has caused this but the solution is:

1) Enable the Omega theme (drush en omega) and set as default (drush vset theme_default omega)

2) Run drush omega-wizard


To filter by fields you should use fieldCondition() method instead of propertyCondition()

function get_list_of_users($site_id) {
  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'users_online')
    ->fieldCondition('field_website_id', $site_id)
    ->execute();
  if (!empty($entities['node'])) {
    $node = node_load(array_shift(array_keys($entities['node'])));
  }
}


How to display picture from field near every blog entry

You should be able to do this with standard field visibility.

Add an image field to your blog type.

Then click on display fields, you can have it displaying for teaser view, and hidden in the full view.


Field Collections not displaying in Content Template

Not necessarily an answer, but a viable workaround:

The Field Collection content is available to views, so I made a view block that prints out the Field Collection content where the contextual relationship is the node's NID. That block gets displayed on this content type only. With some Javascript trickery, I'll be able to position it where it needs to go.

I'm open to a real answer, but for now, this is all I've got.


Displaying page execution time using devel

Enabling the 'Display page timer' in the Devel settings should be enough to add it to every page. You could check:

That you are logged in as an administrator when viewing the pages and that you have got all the Devel permissions assigned (People > Permission).
Have a look at the source of your site, Devel appends the time to the very end of the page, after the closing HTML tag. It might be hidden by your browser or theme.

Otherwise have a look at your recent log messages (under reports) or your server error logs to see if something is going wrong.


From looking at these three modules closer, I see that only the opensearch module has a 7.x branch: https://drupal.org/node/74142/release.  You could try using that branch, but it probably not ready for a production system.

It looks like Kiam is the module author you may be able to contact him to find out if he is planning to complete the Drupal 7 version.


Could you try these steps

drush cex -y actual configs.
Find in your config folder yml file rest.resource.{YOUR_RESOURCE_NAME} and delete it.
drush cim -y this change, it will be correctly removed from DB.
drush cr for sure, and error will miss.

Some related discussion going here
https://www.drupal.org/project/restui/issues/2889860


You should do something like this

$form['raf_prize_type'] = array(
        '#type' => "select",
        "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
        "#title" => "Prize type",
        "#ajax" => array(
            'callback' => 'raffle_create_form_type_steam',
            'wrapper' => 'steam_options',
            'event' => 'change',
           'method' => 'replace',
        ),
    );

$form['raf_prize_name'] = array(
        '#type' => "textfield",
        "#title" => "Prize name",
        '#prefix' => '
',
        '#suffix' => '
'
    );

And your callback function should be

function raffle_create_form_type_steam($form, $form_state){

    return $form['raf_prize_name'];
}


Prevent site from being indexed by search engines?

Question 1: Shield will deny access to anyone that doesn't know the credentials, including robots.  Using this module should be suffiscient for the use case you describe.

As long as you use Shield, metatags doesn't matter.  If you do not use Shield, the metatag you list will prevent your site to be indexed by polite search engines (such as Google - read about Google's policy here).  It will have no effect on some other (impolite) search engines (such as Baidu).

Question 2: Disabling "View published content" for the anonymous user role will prevent any content on the site from being indexed.  Your site itself, and the placeholder string that is shown to the anonymous user when viewing published content is disabled ("No content has been created yet.") is still visible and may be indexed by search engines.


Restricting node access for nodes that are associated with other nodes which have user reference

I don't have enough rep to comment, however, if you are referring to an authenticated user (logged in). You can set the Access Control rules for the logged in user per node. If the user is not logged in, then it is not possible as anybody with a valid URL can view the node.

If you want to hide fields in a content type node. Go to Structure->Pages->View Node (you will have to enable this first in case it isn't). Then create a new variant for that content type and then manually add fields you want the authenticated/anonymous user to see. Make sure you have Context and Selection rules enabled and that admin roles are excepted from viewing that variant. In other words, admin will see everything.


Webform Issue with Drop Down and Key not Equaling Value

When I grab the submission data I get "1"

This is standard in Drupal for select & radio fields, you always get the key.

So all we have to do is use the key to retrieve the value.

$key = $webform_submission->getData()['field_select'];

// retrieve webform fields.
$webform_fields = $webform_submission->getWebform()->getElementsDecoded();

// use key to retrieve value of field_select.
$value = $webform_fields['field_select']['#options'][$key];


A colleague and I got this figured out after I posted the question.

To clarify the original question: the situation is, you've got a view with a path with one argument (e.g. user/%/prospects, where the argument is expected to be a uid), but you need to use that argument in two different contextual filters - in my case, two different taxonomy comparisons between the selected user and the content I've viewing.  The problem is, a contextual filter only lets you reference one relation.

The solution is to enter both contextual filters, but in the second one, in the "WHEN THE FILTER VALUE IS NOT IN THE URL" section, choose 'Provide default value', and in the type, choose (in this particular case) "User ID from URL".  Other 'from URL' types are available.  This allows you to 'share' one argument with two different contextual filters.


How to disable image caption in views block?

If you're not picky, a possible alternative quick fix is to just hide it with CSS. This way you don't have to worry about or spend time patching the module.

You can do it like this:

.image-field-caption { display: none; }

Note that the above will hide all captions, if you only want to hide the captions of a specific view:

.view-id-[name] .image-field-caption { display: none; }


I checked the permissions of the temporary files for our theme and sure enough, they were wrong. I am not sure what caused them to change, but they were set to root, whereas the dev site was set for www-data for both user and group. On our Debian server, Drupal uses the temporary files located at /tmp/example_theme.

To fix:

sudo chown -R www-data /var/example_theme

sudo chgrp -R www-data /var/example_theme

That fixed this and many other problems we were having today.


Drush hangs out on dl commerce_kickstart

I'm using drupal 7.60 with Commerce kickstart 2.55 now. I've figured it out. The problem was with the missing command line prompt asking to continue the installation in the current directory.
After debugging drush I noticed that i needed to type "y" than the process started to continue. Anyways it was very strange but finally it worked.


Twig Tokens in Views not Rendering Inside an HTML Element

Problem solved. There were two issue at play; first off when I was messing with the Twig templates to trying and format the view the hard way, I inserted an extra <a href=""> in one of the templates and failed to remove it. My template was wrapping the empty tag around the properly generated content making it useless.

The second problem was that for some odd reason, the block was calling/using the same custom theme hook twice. I haven't figured out what was causing this error, but deleting the bock and forcing the new one to revert to a more general template hook solved the rendering issue.

However Twig debug still shows that there are two custom theme hooks of the same name available for use. No clue what is causing this behavior.


How to set the time as 09.00 - 10.00 , 10.00 - 11.00 in day calendar view display?

Ranjani, if you want to collapse all times which don't contain events for the day, then I don't think you really need to be using a day-calendar format? I think your best bet would be to just do a regular table display for your view.

Change your view to be a table format
Have the time range in one column and the event title in the other
To get the range in the first column, just display your date in two separate fields, the first time, display the 'from' time, in the second one display the 'to' time
Go into your field settings (screenshot) and select those date fields to be shown inline.  You can then specify which character should separate the inline fields.  Use a '-' in your case.

Does that get things close to what you were hoping?


You can use hook_block_list_alter() to hide the blocks in your module code. See docs for more information on how to achieve this. This is the the alter for the function Drupal used to hide/show blocks.


How to auto resize the height of an iframe with Jquery?

I have implemented automatic iframe resizing using the cross-domain messaging ability of HTML5's window.postMessage() API.  Required reading: http://davidwalsh.name/window-postmessage, http://drupal.org/node/756722.

Example:

// "Sending" side (iframe)
Drupal.behaviors.yourIframeUpdateBehavior = {}
Drupal.behaviors.yourIframeUpdateBehavior.attach(context, settings) = {
  var data = {
    'bodyWidth':jQuery('body').width(),
    'bodyHeight':jQuery('body').height()
  }
  var domain = '*'; // Send to any domain.

  // Send current document dimensions to any parent of iframe
  parent.postMessage(data, domain);

  return false;
}

// "Receiving" side (iframe parent)
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
  $(window).bind('message', function(event) {
    var frameWidthPx = event.originalEvent.data.bodyWidth+'px';
    var frameHeightPx = event.originalEvent.data.bodyHeight+'px';
    $("#frame_id").width(frameWidthPx);
    $("#frame_id").height(frameHeightPx);
  });
});
// ]]></script>


How do I get posts of a content type on node writing

You can use the References Module, that can be used as a node reference of any other content type. After installing the module, go to deals content type manage fields, select the node reference to field to recommends content type and while configuring field make it as unlimited, and now go to deals content type writing panel, here you can see the multiple field and can access the node id or name of the references content type nodes.
You can list the selected nodes of references under deals node in views using relationship.


How do I force Twig output from my custom module, instead of from the theme?

Try adding the template array key to your theme hook:

function footer_block_theme($existing, $type, $theme, $path){
  return [
    'footer_menu' => [
      'variables' => [
        'address_title' => '',
        'address_content' => '',
      ],
      'template' => 'footer-menu',
    ],
  ];
}

Or try adding the block twig template suggestion as:

function footer_block_theme($existing, $type, $theme, $path){
  return [
    'footer_menu' => [
      'template' => 'footer-menu',
      'base hook' => 'block',
    ],
  ];
}


What is the syntax for setting 404 fast paths on all Drupal pages in D7 > 7.9

You used "/*$/i" as regular expression, but there is nothing before the asterisk; in other words, you are not saying what can be repeated zero or more times.
Valid regular expressions expressions such as "/.*/i", "/[a-zA-Z]*/i", "/(foo|bar)*/i".

drupal_fast_404() is called by drupal_deliver_html_page() when the result of menu_execute_active_handler() is MENU_NOT_FOUND, which means Drupal is asked to look for a path without any menu callback associated.
drupal_fast_404() first checks that $_GET['q'] doesn't match the regular expression contained in the "404_fast_paths_exclude" Drupal variable; if it doesn't match that regular expression, then it checks $_GET['q'] matches the regular expression contained in the "404_fast_paths" Drupal variable. The default value for that variable is '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i' which means the fast 404 page is returned when the request is for a file with the following extensions:

.txt
.png, .gif, .jpg, .jpeg
.css, .js
.ico, .swf, .flv
.cgi, .bat, .pl, .dll, .exe, .asp

If you want the fast 404 pages be used in any case, I would not touch the value of the "404_fast_paths_exclude" Drupal variable, and change the content of the "404_fast_paths" Drupal variable to '/.*/i', which would match any path that causes a 404 error, excluding the ones containing "styles."


As far as I know, there is not a direct solution for this. I have searched google for this,couldn't find a solution. But I will share what I think is correct.

The store in commerce market place is actually similar to an organic group, where you can add members and products.
The store is implemented as an entity. If you go to admin/structure/entity-type/commerce_store/store and add a store, you have created a store.
Now, if you try to add a product, you can type the name of the store that you had created, which will auto-fill for you.

Regarding the vendors, you may have to  create a role and give permission to create stores for that role.

Let me know how that goes.


What is an allternatve approach to many fields in an entity?

Like Clive said, testing would be the definitive answer. But if you look at the mysql queries that will have to be executed behind the scenes, I'm pretty sure you'd find that your bundle A with 30 fields will be simpler and faster than the bundle B option. You can use the Views Show Query module to output your view queries in both scenarios and compare them. In bundle B option, I'm pretty sure the mysql query will have to not only look up all of A's and B's fields but also look up the relationship between A and B bundles, an expensive additional JOIN.


Taxonomy term reference field only from top level terms of a vocabulary

If you replace your taxonomy term reference field with an Entity reference field you will be able to use the Reference field option limit module to restrict the available options for dependant fields. If you need to apply further restrictions you can also generate your options lists via special entity reference views.

Note however that by switching the field type to entity reference you will no longer be able to use taxonomy term specific fields and filters for those fields in views.


Steps to update vendor files after pulling changed composer.lock file

In symfony I would delete vendor dir and run composer install. But in
  drupal not all files are in vendor dir.

  What is the best workflow in this case? Should I manually delete old
  vendor files (what dirs exactly?)

See .gitignore in your project dir:

# Ignore directories generated by Composer
/drush/contrib/
/vendor/
/web/core/
/web/modules/contrib/
/web/themes/contrib/
/web/profiles/contrib/
/web/libraries/

In case you want to do a fresh start with composer install you can delete all files with:

git clean -fdx .

See https://www.git-scm.com/docs/git-clean/1.7.0


View that filters content based on current page

Recreating Drupal 6 Views in Drupal 8 should be quite straightforward. What got you confused?

You need to create a list of all "Child" nodes (Publications) and add the Contextual filter for the Entity reference field that references the "parent". Configure that filter to use the "Provide default value", "Content ID from URL". Adjust all the other options in the filter to your specific needs.

When you add the Block to a region in your theme you also have to set the option again (in the Block settings) for the Contextual filter to use the Content ID from URL.


Drupal 7 Search Redirect (similar to the old AOL keyword search)

If there is only a few you and you don't need any advanced matching you can add a path alias for the search path pointing to the preferred page.

E.g. searching for brand a gives you the path search/node/brand a. This path you can add as a path alias at admin/config/search/path/add pointing to a node of your choice.

For more advanced matching (and a more solid solution) you should probably hook into hook_search_preprocess() and do something along the lines of your example code.


Drupal 7: How may I customize the user profile? And how do I add to it profile2 fields?

I don´t know if I should respond to my own question, because after two days not only I didn´t received any answer (which isn´t bad in itself, because nobody "has" to answer), but I´ve received a minus one point, without ANY explanation at all, wich I think is rude.

Anyway, as I´ve found by myself the problem, and other people maybe has the same issue, and as a good citizen, I shall say that the it was the "Display Suite" module.

That module, wich is installed in more than 45.400 sites, was the only reason my Drupal installation didn´t recognized the user-profile.tpl.php file.

I´m going to read more carefully DS readme, tutorials ans screencasts out there because it´s a more complex module than I thought it was. But people should know that it does that (at least right out of the box, in a D7 installation with some core profile fields, Profile2 installed, and without any tweaks in the default configuration).

Cheers.

Rosamunda


How to hook to content profile edit form validation

It will not work as it is not a hook.

Try hook_form_alter() to edit form so that $form['#validate'] can be defined.

$form['#validate'] = !empty($form['#validate']) ? $form['#validate'] + array('mycustom_validate_handler') : array('mycustom_validate_handler');

Then define your function

function mycustom_validate_handler($form, $form_state){
     // Do your validation.
}


You can create an exposed view filter using 'global: combine fields filter', and select all the fields where you want to search the 'hello' (or wathever word you want) word. As long as you don't specify a content type, you will get all the elements that contain one of those fields with the written word.

To add the fields to the combine filter you need to have them on the fields you are showing in the view, but you can hide them if you want.

  edit:  this is a solution in D7 and but I think D8 may provide a very similar system.


Have you tried looking into the comment.tpl.php file?

You should be able to hide the 'real' db driven comments there and only display your printed comments.


How to include any view into the same panel

If you can use a PHP snippet in your panel you could use views_embed_view($name, $display_id = 'default') to render the view from url.

Let's suppose your panel's url is /mypanel. You can use /mypanel/myviewsname/displayname to access that panel with a particular view and display using the following code in a PHP snippet:

<?php
$display = arg(2)?arg(2):"default";
print views_embed_view(arg(1), $display);
?>

arg() gets a list of arguments passed through url. views_embed_view() embed a view in a PHP snippet and it will return nothing if no adequate view name is passed. This should work whenever myveiwsname is an actual view name and displayname is an actual display of that view or is not provided.

You may be able to include PHP in a panel only if you have PHP filter module installed.

You should use PHP filter module with caution.


Multiple independent Views attachment pagers (load more)

Make sure you have unique pager id's for all your view displays.
You will find the option in Views under the paging section of your display.

EDIT

As noted below, attachments don't have the option to add a unique ID, this is a known limitation. See for example this discussion on Drupal.org.

It is currently not possible to solve this issue in Views only. If you want different paging options, you can not use attachments. A workaround is to use block displays and place them on the same page as the main view. (Do change the pager ID of the block views only if there are still problems).


How can I send myself an email whenever a user views a Panels page?

Add the code below to any of your module. I assumed the name of the module to be my_module.

define('MY_SPECIFIC_NODE_NID', 3); // define the nid for which you want to send email

function my_module_panels_post_render($panels_display, $renderer) {
  $content = $panels_display->content;
  foreach ( $content as $key => $value) {
    if($content[$key]->type == 'node' && $content[$key]->configuration['nid'] == MY_SPECIFIC_NODE_NID){
      dpm('This is my node. I will send email here!');
      // Uncomment the line below to actually send email - remember to substitute variables appropriately
      // drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE);
    }
  }
}

It should work for your scenario.


Insert my files inside a custom table after upload?

Don't. It's a fundamentally bad idea to store data in custom table in Drupal 8. There are enough APIs and no support for that. Of course, hooks are still there so you can implement hook_entity_presave and then take the field data and write it out... but just say no :)


Attaching two or more jQuery files to a theme

By default, multiple local files will be aggregated where possible. To disable this for a file, set its 'preprocess' flag to false.

mymodule:
  version: 1.x
  js:
    js/custom.js: {preprocess: false}
  dependencies:
    - core/jquery
    - core/jquery.ui


Bypassing internal cache via query parameter

The Internal Page Cache is designed to serve database content requested by a URL (the entire URL including query string). It works as long as you don't have any dynamic component, for example time based, or client request data not included in URL or session cookie, like request headers or custom cookies.

The Dynamic Page cache works on a different level. It doesn't depend on the URL directly but on the matched route. Any code using contextual data from the request or the matched route has to declare these dependencies as cache metadata.

Your problem is custom code in a Views hook. The old style Views hooks have a very narrow scope while at the same time you can access the entire View. So not all code snippets you find are good practice. Better use the Views plugin system for custom code.

For the caching part the easiest way would be to use the code of the Views caching plugins already in core which you control through the advanced settings of the View. If you only have anonymous traffic already cached by the Internal Page Cache you could disable caching of the View without impacting performance. Either through the none caching plugin or the time-based plugin which gives you finer control.


To add a field to custom content type you need

field.field.node.content-type.field-name.yml
field.storage.node.field-name.yml

The easiest way for you is create the content type and fields via UI and then just simply export it in admin/config/development/configuration/single/export (you have to install the config core module). Then remove  uuid and you are done.

While exporting, export following configuration types..

Content Type
Entity form display
Entity view display
Field
Field Storage

Hope this will help you.


How to show Total with taxes at admin/commerce/orders when order status is Review (using Commerce)?

You can use the Commerce price by components module.

  Extension to Drupal commerce that provides a price formatter to
  enable/disable price components such as discounts or taxes when
  displaying prices. This gives the admin absolute control over which
  components should be displayed and which shouldn't. It also provides
  two Views handlers to display/hide price components in cart totals and
  order totals. Additionally it has basic rules support that gives to
  the commerce administrators the ability to do conditions using price
  components such as discounts or taxes and react accordingly.

Install the module and change the commerce total field of the view with this one.


I suggest you use hook_user_update. Then you compare $account->mail and $account->original->mail. If the two email addresses are different, the user's email address changed. Next you generate the token and send an email to the user with a link to your page.

For the page, create a new menu entry via hook_menu and do the logic for the REST call there. You can get URL query parameters (especially the token) by using drupal_get_query_parameters. Maybe you should ensure that the token is unique and store it with the email address and the creation time (to check if it has expired) in the database.

The documentation for hook_menu (or 99% of all other modules available) should give you an example on how to use it.


How do I create and render a custom region?

I got the solution and so sharing with all, if it could help someone:

Creating a custom region in our theme if we are using display suite module is slightly different.

1.First define region in your theme's .info file (same as we do without display suite)

regions[name_of_region] = 'Name of Region'

2.Then print the following line in your template file wherever you want to display

print render(block_get_blocks_by_region('name_of_region'));


Preview template for node with custom template?

The naming convention is
node--[type]--[viewmode].html.twig

So in your case it would be

node--article-with-header--preview.html.twig

See https://www.drupal.org/docs/8/theming/twig/twig-template-naming-conventions
for more info.


Adding Class to views row if View style is Unformatted list / Content

You can try do this later in process or template, when the $vars['rows'] is flattened. You can pull all instances of field_breite out of the flattened row and put them into the classes of the row. For this the field_breite has to be in the custom view mode of course. This would be not so nice for coding, but much faster.

I would code it like this in mytheme_process_views_view(&$vars), but I'm sure you need some debugging:

Go row by row in $vars['rows']. Search the complete field with preg_match() by using the html tags of the field and set parenthesis in the regular expression to get the field value in $matches[1]. Add the field value in $matches[1] to $vars['classes_array'][$id] to set the row class. Cut the complete field out of the row with str_replace() by using $matches[0] from the first search and an empty string.


Altering the Title of node using Preprocess

You could use hook_node_view, which also gives you more flexibility, (e.g. control what view mode / language you affect):

function MY_MODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'your-node-type' && $view_mode == 'full') {
    drupal_set_title('your-title');
}

Instead of using a preprocess function, which is better for template changes, (for example, adding variables to it):

  The main role of the preprocessors is to set up variables to be placed
  within the template (.tpl.php) files.

Preprocess and process functions


Using module Unsubscribe
About the "not appearing in fields of user register form" in the question: it seems to me that the unsubscribe module might just be working as designed, and implemented. From its project page (I added some markup here):

The module design is very basic. When a user unsubscribes, they are added to an "unsubscribe list," which is stored in the database. Whenever Drupal sends mail, the unsubscribe module will check to see if the recipient is on the unsubscribe list. If so, the email is blocked. You can exempt specific modules from this blocking via the configuration page. You can also use hooks to alter exemptions, or override the blocking.
Emails sent by the system and user modules are currently exempt by default.

From the question it is not clear to me what you have done regarding the "exempts" (on the module's configuration page). If nothing yet, then that might be the explanation for why it is not appearing on the user register form, no?
Using some other module
As per your "any other module that provides a similar function/feature": it appears to me that the Rules module should be worth considering, possibly combined with the Message module.
If you're not familiar enough with these 2 modules, then I suggest to review this great introduction to the Rules module: Rules for admin notifications, Part 1: New user registrations. Maybe also the related Rules for admin notifications, Part 2: New comments and content.


how to subtract 2 months from current month?

If you try to change format to dmY for example:
echo date("dmY", strtotime("-2 months"));
You will see that result is 01122016.

You can check comments from this question also:
https://stackoverflow.com/questions/10586615/current-date-2-months

And you can check solution here: https://stackoverflow.com/questions/9058523/php-date-and-strtotime-return-wrong-months-on-31st

Pass second parameter.


Working with Drupal 7 and Date module, if you enable Date Views sub-module, you may create a Views block with a filter criteria based on your Date field. There, you will just have to enter a relative date (now) and filter your nodes with your birthday's dates. (i.e. Date field value is equal to : now).

Hope this helps.


Create 3 different contexts, in each context add path condition and set the paths as follow:

First Context:

checkout/*
~checkout/*/review
~checkout/*/complete

Second Context:

~checkout/*
checkout/*/review
~checkout/*/complete

Third Context:

~checkout/*
~checkout/*/review
checkout/*/complete

According to Context documentation ~ character (tilde) can be used to exclude one or more paths.


Hosting a directory of legacy static HTML files on Drupal

As long as you're using the default rewrite rules you don't need to do anything.

Drupal's .htaccess file contains this:

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

So requests for existing files won't be re-written, the file will just be served.


theme profile2 fields on registration form

This link should help you in achieving it.


Content type with a field of multiple values of other content type (1-n relation)

The Entity reference would be the best choice for your requirement. It is also a successor of the References module.

  References will most probably be deprecated in the near future in
  favor of Entity Reference, which should probably be considered first
  on fresh D7 projects.

The Relation module is more suitable for complex relationship. You can see this clearly in its module page:

  Relation is an API module and storage model for both simple and the
  most complex relations between entities. The module can handle both
  directional and symmetrical relations very well.

  Relations are entities and can therefore have fields. This makes
  Relation the most flexible and powerful relation model out there.


This doesn't work for contrib code, but if it's your code and you know it well, I recommend writing a drush command to do the work.  Within drush, limit drupal_bootstrap() to the appropriate bootstrap level.  I can't recall the actual numbers, but a very large percentage of time for every drupal request is spent in bootstrap, and you can save a lot of time there.

Furthermore, check out the guts of the Migrate module.  I don't know how it does it's mojo (never taken the time to grok it), but it can blaze through huge batches of nodes very quickly.


I think ive sorted it with

margin-left: 845px;
    position: fixed;
    top: 0;
    width: 110px;

Thanks


how to return a db_query as an option list and display it

You can make use of DatabaseStatementInterface::fetchAllKeyed(), but as you only need 2 columns it would be wise to change your query slightly. Essentially you want to select just one for the identifier, and one for the label. Something like this:

$sql = '
    SELECT realname.uid, realname.realname
    FROM {users} users
    INNER JOIN {users_roles} users_roles ON users.uid = users_roles.uid
    LEFT JOIN {realname} realname ON users.uid = realname.uid
    WHERE users.status <> :status AND users_roles.rid = :rid
    ORDER BY realname.realname';

$args = array(':status' => 0, ':rid' => 5);

return db_query($sql, $args)->fetchAllKeyed();

That will return an array with the 1st column (uid) as keys and the 2nd column (realname) as values, which you can use verbatim as options for a form element.

You don't have to return just 2 columns from the query, as fetchAllKeyed() allows you to specify the index for both key and value; but as you're not using the data for anything else, it makes sense to avoid the overhead of the extra columns.

Slightly unrelated: you shouldn't call exceute() on the return from db_query(), as the query has already been executed by that point. You can either use one of the helper methods like fetchAllKeyed(), or iterate directly over the values, e.g.

foreach (db_query($sql) as $row) {
  // ...


How to set up registration for event with parallel sessions?

Make a node type for sessions, then add the registration field to it. You should make a small module which compares a time/date range/duration field on your session node types to ensure the user cannot register for sessions that are conflicting.

If you have multiple events on your site, consider making a node-reference field to another node type: "events". Then update your session conflict module to take events into account.

This is for Entity Registration (D7)


Disable plugin ckeditor per content type

You need create different "body field" in one of your content type.
I.e. For first content type use the same "body field" and use first ckeditor profile.
For next content type create a new "body field" - like a "content_type_name_body" and use last ckeditor profile.


Found the problem ... I was defining the output type in the settings array vs directly in the display array.

field_view_field('node', $node, 'field_geo',
    array(
      'label' => 'hidden',
      'type' => 'geofield_map_map'
    )
);

Hope this helps someone else.


Make sure "registered users" have permission to use that input format and "role test" does not have permission to use that input format. "role test" could have permissions for the editor format without having permissions for the input format for the profile field.


No sub theme folder inside bootstrap theme folder

Have a look in the starterkits folder then choose between less or cdn.

For more information, have a look on files within docs folder


Edit display of commerce kickstart shopping cart

Solved with the Menu Minipanels module. Here is a quote from its project page:

  A system for building "megamenu" -style dropdown menus using Mini Panels, which provides tremendous flexibility in what can be displayed.

The project page also points to an interesting Click-by-click beginner's tutorial


How to bulk update existing path alias after changing the URL alias pattern?

it works only to URL which does not have path alias – Vamsi

Then first go to /admin/config/search/path/delete_bulk and delete the aliases
in question.

Then update /admin/config/search/path/update_bulk


The page layout is broken but I assume that you are talking about Services menu block. Based on the HTML source it is a menu block and a main menu to be specific. So to the change the link go to Structure > Menus > Main Menu and change the link path there.

UPDATE:

Since the page is broken in my end my above answer is wrong. As @iamroald comment it is created via Views. Go to Structure > Views > Services. It seems like there is a Token substitution in there.


When I clear cache, my menu ordering seems to go out of order

I believe this had something to do with mysql's setting max_allowed_packet. Mine was only set to 1MB, when drupal recommended 16mb.


How to make 1 or more of total 4 fields mandatory

You have to implement your own validation logic through a hook_form_alter().

    <?php
    function MY_MODULE_form_alter(&$form, &$form_state, $form_id){
      if ($form_id === 'YOUR_FORM_ID')
        $form$form['#validate'][] = 'YOUR_VALIDATION_FUNCTION';
      }
    }

    function YOUR_VALIDATION_FUCNTION($form, $form_state){
      $assingned_values = 0;
      if(!empty($form_state['values']['FIELD1']['und'][0]['value'])){
        $assigned_values++;
      }
      if(!empty($form_state['values']['FIELD2']['und'][0]['value'])){
        $assigned_values++;
      }
      if(!empty($form_state['values']['FIELD3']['und'][0]['value'])){
        $assigned_values++;
      }
      if(!empty($form_state['values']['FIELD4']['und'][0]['value'])){
        $assigned_values++;
      }
      if ($assigned_values === 0){
        form_set_error('', 'You must set at least one field');
      }
    }


How to pass a form field value from THEME_system_theme_settings_alter() to THEME_form_system_theme_settings_submit()

The answer to the question is quite simple, but not easy to find in the d.o. docs. Thanks to Clive and Jack-PL who gave me the right direction. To reuse the example from the start question we need to summarize:

A form field input value needs to get splitt off (intercepted) from its usual way getting stored for a short moment. Why? For us to do our own processing while submission before theme-settings.php Party is over. Our form field:

// theme-settings.php
function THEME_form_system_theme_settings_alter(&$form, &$form_state) {
// Test form
$form['whatever_fieldset_group']['user_input'] = array(
    '#type' => 'textfield',
    '#title' => t('Test to get value'),
    '#default_value' => theme_get_setting('user_input'),
    '#description' => t('
         Type some text in textfield
         to get shown in submit message'),
);
}

Now the value will get stored when the user hits submit button. But what if we need to get in between before?

Injecting ...

drupal_set_message('<pre>' . print_r($form_state['input'],1));

... in function THEME_form_system_theme_settings_submit for a moment has revealed, that we were looking for $form_state['input']['user_input'], were our fruits are hanging. Searching the value with drupal_set_message('<pre>' . print_r($form_state['input'],1)); gives us orientation to be able to intercept the right value for our own value processing, demonstrated here in a simple representational form with another little drupal_set_message() scenario:

// theme-settings.php
function THEME_form_system_theme_settings_submit($form, &$form_state) {

    // the following will not work inside theme-settings.php
    // because value is not known yet by theme_get_setting()
    // $data = theme_get_setting('user_input');

    // But this works!
    $data = $form_state['input']['user_input'];

    drupal_set_message(
          'For testing purposes we submit that you have
           filled the textfield with the following
           mindless value: '. $data
          );
}

In my case, I was able to save user input into a file now with file_unmanaged_save_data($form_state['input']['user_input'],$filepath); while the user hits submit.

Thanks to Clive and Jack-PL for the fast reply. It helped me a lot!


Drupal Media Library - File Upload Library shows “No files available.”

Answer from basti:

  The problem could be solved by removing the Query Tag under "Query settings" inside the view options. I have no idea why, but after removing it, anything works just fine.


If I have added extra fields to a user profile, how can I programmatically check if those fields are empty?

I would advise against keeping those fields around after an uninstall. It's a module's responsibility to clean up after itself, and a user of your module should be able to assume that if they disable the module, the functionality will be gone, but the data remains in the database.  If the user uninstalls the module, the assumption is that the module will clean up after itself - delete all its data, custom tables, created variables, etc.

If you don't want to lose any data, just disable your module without uninstalling it - then the uninstall hook doesn't run.  But my suggestion is to keep to the community's expectations and properly clean up the custom database tables, fields and variables that your module has created in the uninstall_hook.

I think with open source projects like Drupal, where there are tons and tons of contributing authors and contrib modules, it's even more important for each of us to conform to the expectations of a module's behavior.  Otherwise, if each module does what it wants upon uninstall, we wouldn't know what to expect in terms of our databases.  What if a user has another contrib module that conflicts with your module's fields, for example?  How could they ever get rid of them if your uninstall hook doesn't clean them up?


You have picked up correctly, the root cause for this issue is the object_id used by ctools multistep form, which is being generated per session. And for different tabs in a browser, we have the same session. So basically we need to figure out a way to get different object_id for each tab. This can be done in two ways:
1. Modify session mechanism to have a different session per tab. (Difficult)
2. Use query_parameters to handle two different requests. (For eg: time as id)

So, using 2nd way to solve our the problem:
Get object_id dynamically.

$object_id = _module_get_object_id();

Ensure if id exists in URL, else return newly generated id.

function _module_get_object_id() {
  $params = drupal_get_query_parameters();
  if (isset($params['id'])) {
    return $params['id'];
  }
  else {
    $params['id'] = time();
    return $params['id'];
  }
}

and most important step, for adding id in URL as query parameter we need to add following code in the ctools_multistep_wizard_next function:

drupal_goto($form_state['redirect'][0], array('query' => array('id' => $form_state['object_id'])));

Reference: http://savaslabs.com/2015/06/23/implementing-ctools-multi-step-form-block.html


Commerce - Product and Total Price(s) on summary page not being updated by rule

It's best to use separate questions for separate issues here. The one from the title is almost certainly due to a regression introduced in Rules 2.8 and documented in the Commerce 7.x-1.11 release notes: https://www.drupal.org/node/2408705

You can downgrade to Rules 2.7 until a fix is put into Rules.


Using Migrate API to select items from within an Events JSON array

Have you tried mapping directly rather than using extract?

field_importdate: event_instances/0/event_instance/start


Form behavior when form creation data changes

If you include a function myform_validate, you can test the value in the $formstate array against a query for the current value in the database.  IF they do not match, return false and the original form will be redisplayed. This is explained in greater detail in the documentation for the form api


How can I show anonymous users their own content?

An anonymous user is a user with uid=0. So all (repeat all) anonymous users have the same uid value, and therefor there is no way to do what you are asking for out of the box.

There are various techniques you could programmatically do, but of course they all have their limitations.

Starting an anonymous session. Here when the node is created you add the Node ID in a $_SESSION variable and you can use this to retrieve the Node ID and pass that to the views arguments. Obviously, the limitation is that as soon as you close the browser, the session ends and you can no longer tell if it's the same user. So you have to start the cycle again, create a new node, etc...

Using cookies same as above but with cookies. Once cookie expires or it's cleared it's over.

Using IP You would save the IP as a field in the Node and you can query the DB to retrieve the Node that belongs to that IP. Obviously, the limitation here is if the user's IP changes it ends here.

Combination of all 3 Lastly, you could do all 3, have the other 2 as possible backups.


There are many specific ways to do this, but here's the general idea:

Create a special content type for your home page that allows Anonymous access.

Then, set your other content types to require an authenticated user.

If you get stuck on a specific part of this process, or have more specific questions you may get better responses.


How do I iterate through views result with pagination in a template file?

Set up a second display on your view or a new view that has no pagination or limit on the number of items displayed and use views_get_view_result to retrieve the object.


Your form is called admin_scores() but your submit function is called admin_scores_form_submit()...this isn't Drupal's naming convention so your submit handler will never be executed.

Either change the name of your submit handler:

function admin_scores_submit($form, &$form_state) {

}

Or add your non-standard submit handler in the form itself:

$form['#submit'][] = 'admin_scores_form_submit';

Also the signature you're using for your form function is slightly wrong, in Drupal 7 it's like this:

function admin_scores($form, &$form_state) {


Use image field in an entity query condition

You could try:
$query->notExists('field_image');


As said by @Jayendra Kainthola
You need to store current path value in a session

$_SESSION['current_path'] = current_path();

Then use it inside your callback function as follows :

function mymodule_ajax_callback($form, &$form_state) {

$current_path = $_SESSION['current_path']  ;//gives the current path

}


Failed validation redirects to normal path

In your custom module add below code,It check If url not in alias path, redirect it to aliased path.

function mymodule_init() {
    if(module_exists('subpathauto'){
  $alias = subpathauto_lookup_subpath('alias', current_path(), current_path());
  if (!empty($alias) && $alias != request_path()) {
    drupal_goto($alias, array(), 301);
  }
 }
}


Showing comment form under each paragraph

I think you will need to do a couple of things. First is to create a comment form under each paragraph:

Drupal 7:

$comment = new stdClass;
$comment->nid = $nid;
$form = drupal_get_form('comment_form', $comment);

print render($form);

Then I would suggest using some jQuery to hide the forms, showing it only when the user clicks on the link. You can assign a unique class to the $form (see form API reference for more info) so that only the comment form for the specific paragraph shows, instead of all of them when any given link is clicked.


You can configure this in UI, see the checkbox at the end of the theme list in /admin/appearance:

  [x] Use the administration theme when editing or creating content

This config option is then used to alter the route in the following code example, which would also answer how to alter the route in a route subscriber:

NodeAdminRouteSubscriber::alterRoutes()

  protected function alterRoutes(RouteCollection $collection) {
    if ($this->configFactory->get('node.settings')->get('use_admin_theme')) {
      foreach ($collection->all() as $route) {
        if ($route->hasOption('_node_operation_route')) {
          $route->setOption('_admin_route', TRUE);
        }
      }
    }
  }

More info https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones


How to resave all user accounts on a schedule?

Ultimate Cron
Provides a UI where you can schedule all the cron jobs. Example:

Job Scheduler
Provides an API to schedule jobs.
Simple example:

// Declare scheduler.

  function example_cron_job_scheduler_info() {
    $schedulers = [];
    $schedulers['example_unpublish'] = [
      'worker callback' => 'example_unpublish_nodes',
    ];
    return $schedulers;
  }

// Add a job.

  $job = [
    'name' => 'example_unpublish',
    'type' => 'story',
    'id' => 12, // must be unique
    'crontab' => * 3 * * 0, // Every Sunday at 3 AM
    'periodic' => TRUE, // set to false if you want to just run once.
  ];
  $service = \Drupal::service('job_scheduler.manager');
  $service->set($job);

// Work off a job.

  function example_update_users_total(\Drupal\job_scheduler\Entity\JobSchedule $job) {
    // Do stuff.
  }

There is more examples & info in the READ.ME, so read it.

Important
It's important to note that the above in reality is scheduled to run the next time someone visits the site after 3am on Sunday. So if no one visits the site until say 9am on Sunday, it will not run until 9am. This is because Drupal's Cron can only run when Drupal is initialized.
The only way to be sure that it runs at 3am, you have to set a cron job in your server (just know that your server time may not be the same as your timezone, so you'll have to check that), using the crontab -e command (for linux) will open the file where you can add jobs to the server. Have this server job run a file that contains code that performs a GET request on your site. OR alternatively a custom Drush command like Kevin commented.


Can I use the feeds module to import csv data to 2 different content type?

Unless anything has changed in the last couple of weeks, I don't think it's possible to set up one feed to import to multiple content types out of the box.  There's some discussion here.

That said, someone did mention the Feeds Node Helper module which apparently does allow this feature, although I'm no sure how robust it is.

  Feeds Node Helper is a collection of useful Feeds Import targets and
  Tampers. This is how book content can be imported and exported between
  Drupal sites. It provides helpers for the following:

  UUIDs
  Book parent based UUIDs
  Book Weights
  Node Types (by default Feeds just maps to 1 type, this allows multiple)

EDIT

If the module doesn't work, I don't see any reason why you couldn't simply set up two feeds that both use the same source CSV file; one for each content type.


Find a URL inside Twig file from content made from another content type (referenced/ has a relationship)

You can use path function with the route for node (entity.node.canonical) and the entry.id (node id) for your blog entry. Pass the id in with the "node" parameter.

More info here: https://www.drupal.org/docs/theming-drupal/twig-in-drupal/functions-in-twig-templates


Creating a block to show content in the same group of the current node

Add contextual filter "Content: Has taxonomy term ID" and make configuration like below

Provide default value : Taxonomy term Id from URL
Load default filter from node page, that's good for related
taxonomy blocks


I had this problem too, due to a bug in my PHP code and the fact php.ini was not set to display errors.

Find the line display_errors = Off in php.ini and change it to display_errors = On. This way you'll see the specific php error message instead of the generic internal server error.


Drush misidentifies my D7 site as drupal 8

I'm using Drush Commandline Tool 9.2.1 in a Drupal 7

Drush 9 only works with Drupal 8.4+

As seen on: http://docs.drush.org/en/master/install/

Uninstall Drush 9

composer global remove drush/drush

and install Drush 8

composer global require drush/drush:8.x


Field Collection Data Deletion for particular Content type

My suggestion is to do this using code. IF your using D7, try following code in any custom module or in a basic page.

//Use a query to get all nodes of your particular content type.

$results = db_query("SELECT nid FROM node WHERE type = 'your-content-type'");
$nids = array();
foreach($results as $result){
  $nids[] = $result->nid;
}

foreach($nids as $nid){ // use for loop for testing
  $node = node_load($nid);
  foreach ($node->field_international_activity[LANGUAGE_NONE] as $key => $value) {
   // Build array of field collection values.
   $field_collection_item_values[] = $value['value'];

   // Unset them.
   unset($node->field_international_activity[LANGUAGE_NONE][$key]);
  }

// Delete field collection items.
entity_delete_multiple('field_collection_item', $field_collection_item_values);
node_save($node);
}

For more details please refer link1, link2

This code is not tested, first just try for a single node by using a for loop instead of foreach.


Best practice for custom module variable names?

It is possible to use a Drupal variable to contain an array; that is what Drupal core modules do too (see book_type_is_allowed()).

It is possible to use a single Drupal variable to contain different settings used by a module into an array. With the form #tree attribute is still possible to use system_settings_form() to save the array into a Drupal variable without writing any additional code. Serializing the de-serializing the code is automatically done by the Drupal core functions that handle Drupal variables (see  the code of variable_set()).

The question is then: when should a single Drupal variable be used to contain different settings? I would use a single variable for settings that are used by a function, or a group of functions; if the array contains values used by (for example) 10 different functions, but those functions access a single value (or a couple of values) from that array, then I would not use a single persistent variable for the settings.


How to sort content in Views by menu weight

1: Referencing a user contributed module: Views menu sort which at #48 has a D7 version. I have not tested this but others report success.

2: Another method you could use is to use a PHP field in your view like in this article on tappetyclick.com. (I have used this method before)

3: Or you can use the module menu node views which requires menu node.


howto use tokens as "views filter criteria"

Try adding a contextual filter - Content: Author uid and make it like below. I think this is what you need.


Try this, http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_links/7:

function THEMENAME_links__system_MENUNAME_menu($variables) {
  $output = '';
  foreach ($variables['links'] as $link) {
    $output .= l('
 $class)) . '>' .''. check_plain($link['title']) .'' . '
', $link['href'], $link);
  }
  return $output;
}

Is the
 inside the ?


You can use hook_mail_alter() to get (and alter) the contents of an e-mail message before it gets sent out:

function mymodule_mail_alter(&$message) {
  dpm($message);
}

One thing to keep in mind is that not all modules use drupal_mail(), the function that'll call hook_mail_alter(), for various reasons. In that case, you'll have to identify where in the module's code the mail is sent out and see if they provide their own alter hooks: look for the functions drupal_alter('foo') (implemented via hook_foo_alter()), module_implements('foo'), module_invoke('foo'), or module_invoke_all('foo') (all implemented by hook_foo()).

Failing that, you may have to temporarily add the dpm() call directly to the module in the right place.


You can create a custom field formatter (theme function for fields) where you can define how the image field should be rendered. Here you can add the a tag or any other special markup.

There are a lot of guides on how to do this, both here on the site and on the web, so I won't go into details about how to create a field formatter here, but it's nothing more than a few hooks and a theme function.


$entity_wrapper->save(true) vs. entity_save('node', $entity)?

You need just one save call. All of them invoke the same code, the controller's save method (or node_save in node's case).

The wrapper modifies the original entity by reference, so it doesn't need an explicit save of its own (and the other way around).


How can I add folders to my template directory and have Twig find them?

In your "task" module you must have a task_theme function where you've defined your templates. In there you'll need to update with your new paths too. e.g.

This

'template' => "field--expire-date.html.twig"

becomes:

'template' => "fields/field--expire-date.html.twig"


feed import on node reference doesn't add language in database

The issue you have run into looks like it may be identified here: https://www.drupal.org/node/1183440.  I walked through this issue queue and was able to get my feed processor to specify the language it was importing.  The comment #193 was particularly useful.  I'll elaborate on his directions a little bit.

For the record, this patch applies only to the feeds module, but you will need to have Feeds Entity Translation installed as well (which you probably already do).

drush dis feeds -y
rm -rf feeds - remove feeds directory entirely
git-pull the feeds repo and checkout older commit:

git clone --branch 7.x-2.x http://git.drupal.org/project/feeds.git

cd feeds

git checkout 006234fc3cc859e4fec0cb261675577efcf389b8
enable all feeds modules that were disabled from step 1:

drush en feeds, feeds_ui, feeds_tamper, feeds_tamper_ui, feeds_et, feeds_ex -y
patch feeds:

wget https://www.drupal.org/files/issues/feeds-field_translations-1183440-191.patch

git apply < feeds-field_translations-1183440-191.patch
confirm patch by building new feed. you should see a language option under the processor settings.

There is a little bit of work to do on this patch before it can be incorporated in the Feeds trunk, but I'm hopeful it will be in place within a few months.


Why this message "You are not authorized to access this page." coming on user edit page?

Ohhhhh,
At last i figured it out. when i signup via Facebook or Twitter , user's language does not save and when i access the user edit page it gives error that you are authorized to access this page,
and now i write my own function which set the default language for user and everything working like charm !!! thanks


Multiple results in a view due to taxonomy?

Use aggregation. It's just above query settings.


Block above content should be simple however

There is a number of Block related access modules that can help you:

Block Access allows you to set individual Block permissions. So after you create those Blocks, allow the specific user Role to edit only those particular blocks above Login and other pages.

You might also create a special Region within your theme just for this purpose, and set permissions for that Region blocks with Block Region Permissions.

You can set finer control over the Admin Block pages with Block Content Permissions.


Operations between the same field of a content type

Install views_php module. This module adds a field to the view and it also provides a few tokens. You can use the current row values. Note that you have to insert the main fields before the PHP field and exclude the Price field from display, Then the $results,$data,$row objects will give you the value of the row, Do the mathematical calculations and output the result.


Multisite- different localizations and domains but same codebase and user base

You're going to have lots of fun with this one if you're a "knoob".

The module you want to look at is Domain Access. This will do pretty much exactly what you want to do. It's a slightly heavy configuration so if you are new, then you might struggle but you can probably get some assistance on #drupal-support on freenode.


you can change the weight of the links like this:

$form['links']['#weight'] = 10000;

now it should be after the submit button :)


How to connect panel and translated panel after 'Add translation' node?

Maybe too late, but just in case you still need it: http://drupal.org/node/1994046


I wrote a detailed description about this problem and a possible debugging solution here: https://drupal.org/node/1275042#comment-7814971

In my case, Views Slideshow was problematic, I just created a tiny patch for that:
https://drupal.org/node/2078689#comment-7815015

For convenience, I'm copying my post linked above:

  As merlinofchaos said, this really has nothing to do with Views. The
  "fix" in #6 is NOT actually a fix...

  In my case, I had two whitespaces in front of the <?xml tag, so the
  RSS feed started like this: "  <?xml". I never thought I will find the
  source of the problem with such an ugly solution, but this is quick
  and works - it's really dirty, so use it only on a local development
  copy, do NOT test it on a production site:
  https://drupal.org/node/175137#comment-1526410
  in includes/module.inc file, in the module_load_all() function, after the
  drupal_load('module', $module);, soyarma suggests you to put in the
  following line temporarily: print $module.'|'; This way you'll get a
  list of your modules in the beginning of the output separated by the
  pipe (|) character. When there are unnecessary whitespaces before the
  module's name and the pipe character, then you just found the buggy
  module.

  For example, in my case, Views Slideshow was the source of the problem:
  views_bulk_operations|views_content|  views_slideshow|views_slideshow_cycle (this is just the end of the huge list)

  As you can see, there are two spaces before views_slideshow. This is
  where I should start searching for the source of the problem. I found
  it in views_slideshow/theme/views_slideshow.theme.inc: the code starts
  with two whitespaces, and the PHP block is just after that: "  <?php"
  You can also see it here:
  http://drupalcode.org/project/views_slideshow.git/blob/d9fd60c20add43a7b...

  And YESSS, after deleting the two spaces, http://validator.w3.org/
  congratulated me that my RSS feed is valid. Thank you, soyarma!

  Don't forget to revert the changes in module.inc (don't ever hurt the
  core's code! :) ), and delete the print $module.'|'; line.

  I'll report an issue to the Views Slideshow's queue, and I hope that
  this helped someone.

  ====
  EDIT:
  I reported the bug to the issue queue, and also created a patch, see #2078689: Unnecessary two whitespaces before the PHP code
  block in views_slideshow.theme.inc, which can cause RSS feeds to get
  invalid.


How do I remove default comment validation in drupal 7?

You can see error message because comment_body is required for comment entity.
You can delete #required parameter for comment_body:

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if(strpos($form_id, 'comment_node_erpal_task_form') !== FALSE) {
    $form['comment_body'][LANGUAGE_NONE][0]['#required'] = FALSE;
  }
}

But just know that you'll have php notice then. Because posting comment without the body is not right:

  Notice: Undefined offset: 0 in comment_submit() (line 2197 of
  W:\home\erpal.local\www\modules\comment\comment.module).

Make sure yhat you added custom validation for body field.

You you can handle validation callbacks for the whole form in $form['#validate'] array. Also you can handle validation callbacks for each form element in #element_validate array. E.g. for comment_body:

$form['comment_body'][LANGUAGE_NONE]['#element_validate'][] = '_my_module_comment_body_validate';

Update

You musn't change any code in Drupal core modules, it's very bad hardcode. You can do all your logic that you added to comment.module in hook_form_alter.

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if(strpos($form_id, 'comment_node_erpal_task_form') !== FALSE) {
    $form['comment_body'][LANGUAGE_NONE][0]['#required'] = FALSE;

    if(isset($form['#node']->type) && $form['#node']->type=='iks_videos_youtube_video') {
      $vtype='yt';
    }
    else {
      $vtype='v';
    }

    $url = url('video/' . $form['#node']->video_id[LANGUAGE_NONE][0]['value'] . '/'.$vtype.'/' . strtolower(str_replace(' ', '_', $form['#node']->title)));
    $form['#action'] =  $url;
  }
}


Failed SELECT value from Date field (single value)

It would be a lot easier to use a different set of API calls to do this, you can avoid having to manipulate the database directly:

// Extract the first field item
$date_items = field_get_items('node', $node, 'field_date_start_rent');
$date_item = array_shift($date_items);

// Get the field value
$start_rent = $date_item['value'];

// Update the other field
$node->field_cubagan[$node->language][0]['value'] = $start_rent;

// Save the node
node_save($node);

Just as an aside: you're not making the best use of the DB API at the moment, you should be using placeholders and provide arguments to db_query() rather than interpolating them directly into the query string. The equivalent of your SELECT statement written the recommended way would be:

$args = array(':nid' => $node->nid);
$sql = 'SELECT field_date_start_rent_value FROM {field_data_field_date_start_rent} WHERE entity_id = :nid';
$startrent = db_query($sql, $args)->fetchField();


To summarize one of the comments, when you encounter weirdness with the API, you need to do two things.

First, look at the API call you are using, and see what hooks it invokes.  Then, check your code for any hook implementations that could cause the weirdness.  In this case node_save() invokes a few: hook_node_presave(), hook_entity_presave, hook_node_update, and hook_node_update for nodes that exist.

Second, you need to check any Rules that are attached to the the API call you are doing.  In this case, you would check for rules that run when nodes are saved.

Doing these two things will usually lead you to the problem.


It seems it was a silly mistake on my behalf.

My module defined a custom path to send the email and the theme files for the pdf were in the admin theme folder, so I had to set my path to use the admin theme for the email theme files to be found.
I did so by implementing HOOK_custom_theme.

function custom_send_email_custom_theme() {
  return variable_get('admin_theme');
}

I will leave this question up as the code may help someone in the future (and maybe me if I need to send an email with attachments again :) )


In lieu of using Views to handle the query, for performance reasons you are probably better off doing something more direct with the db, just make sure that you follow standards for security when accessing the db via any method. Here is a link to the Writing Secure Code documentation - a must read for anyone delving into this area.


How does Drupal handle non Drupal sub directories?

The default .htaccess file has these lines in it:

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

So Drupal will only attempt to take control of a path if the file or directory doesn't already exist. All requests to your flat HTML site should be served without Drupal getting involved.

Maybe you've got some 404s in your flat HTML site? If they point to a folder underneath the web root that might explain why Drupal is getting hit.


There are two ways to do this that come to mind:

Use Computed Fields: https://drupal.org/project/computed_field. I haven't personally used this module but I've seen it recommended a number of times. You could create a hidden field on each piece of content which computes the value you desire. Then this can be used in the view as easily as any other field for both display and filtering.
Use views_php field: https://drupal.org/project/views_php. This will show up in the view options as 'Global: PHP' and will allow you to do pretty much anything with your data that you want to. The authors caution it's use because it's pretty easy to mess things up. I've found it to be a quick solution to problems. (As a side note, the most recent release of this functions differently in what variables it allows you to access, so be careful if doing updates. I would suggest using the most recent version.) Your code could be as simple as this in the output box:

<?php
$new_value = $row->value_1 * $row->value_2;
print $new_value;
?>

Then you could create a "Global: PHP" sort by with something like this:

$first = $row1->value_1 * $row1->value_2;
$second = $row2->value_1 * $row2->value_2;

if ($first > $second) {
  return 1;
}elseif ($first < $second){
  return -1;
}else{
  return 0;
}


D8 - Cannot make Custom EntityType translatable

I think you also need to add it to the entity keys:

entity_keys = {
  "id" = "id",
  "label" = "title",
  "uuid" = "uuid",
  "langcode" = "langcode"
}

Also make sure you're running drush entity-updates and clearing cache when making changes to base fields/annotations.


echo $link = $content['field_link_url']['und'][0]['value'];

This way must be correct!
Check *field_link_url* key in content variable with dsm or kpr fucntion.

And try to get *field_link_url* value from this key.


Possible solution 1: The Pollfield module seems to be a good starting point. This should do what you need for Drupal 6. However, it might not be a stable solution for Drupal 7.

Possible solution 2: It seems the Poll Improved module might be fit your requirements seeing that provides a field for polls. Though it also doesn't have a stable D7 release.

  They don't want to create an extra poll with no connection to the original article.

You can use references (or entityreference) to have your article nodes reference a poll node. Though that would require another step for your content creators.


Image field in field collection not working

1) Check if your web-server has read/write access to sites/default/files(typically uploaded files go here).

2) Other reason might be the file you're trying to upload is bigger than allowed. Increase max-allowed upload file-size in .htaccess file

php_value upload_max_filesize  "20M"


Menu elements not being links, just to create submenu?

I'm not sure how you'd get exactly that to work with the way Drupal's menus are structured.

Core provides a barebones page callback for handling the same sort of situation itself, the system_admin_menu_block_page() function. All it does for the page display is list the menu items that are underneath it in the hierarchy (like the node/add page). Think of it as a landing page for a menu item that doesn't need any other form/page data.

I believe if there are no sub-items under the parent, the menu link won't actually be displayed so that method should get you pretty close.

$items['admin/something'] = array(
  'title' => 'Something',
  'access arguments' => array('some permission'),
  'page callback' => 'system_admin_menu_block_page',
  'file' => 'system.admin.inc',
  'file path' => drupal_get_path('module', 'system'),
);

Then your other module can define paths like 'admin/something/something-else' and they'll appear underneath the parent


In Drupal 7, how do I allow users to see their own unpublished content?

view own unpublished content permission allows just that - to see /node/%nid even if it is unpublished. Test it, I'm sure it will work.

If you want your users to be able to list their content, well, that's other topic. Easiest way is to use Views to create listings filtered by authors, with filters like is_published or author == current_user).


Sort the entity obtained from the Query class with values from the Statistics module

The code you are showing doesn't work because totalcount is not a property set for the node entity. That is a value saved in a different database table, not used from the node entity. See statistics_get(), which retrieves the value you are looking for.

  if ($nid > 0) {
    // Retrieve an array with both totalcount and daycount.
    return db_query('SELECT totalcount, daycount, timestamp FROM {node_counter} WHERE nid = :nid', array(':nid' => $nid), array('target' => 'replica'))->fetchAssoc();
  }

Since the entity query doesn't allow to join tables, you need to:

Add a tag to the entity query you are using
Implement hook_query_TAG_alter() to alter the queries with the tag you added (Replace TAG with the tag you added to the entity query)

node_query_node_access_alter() is the implementation of that hook done from the Node module to allow an entity query to return just the nodes the currently logged-in user has access. You can use its code as guide to write your own implementation.

For example, I would start trying with the following code.

$query = \Drupal::entityQuery('node')
  ->addTag('statistics_totalcount')
  ->condition('status', 1)
  ->range(0, 5)
  ->sort('totalcount', 'DESC');

$result = $query->execute();

function mymodule_query_stastics_totalcount_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->join('node_counter', 'nc', '%alias.nid = n.nid');
}


How to upcast webform submission in custom routes resp. controller?

You probably just need to declare the parameter type:

confirm:
  path: '/node/{node}/submission/{webform_submission}/confirm'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MymoduleController::confirm'
    _title: 'Confirm your submission'
  requirements:
    _permission: 'confirm webform submission'
  options:
    parameters:
      webform_submission:
        type: entity:webform_submission

The parameter names also need to match, so update your controller accordingly:

public function confirm(EntityInterface $node = null, EntityInterface $webform_submission = null) {


Show highest and lowest price in a view from a node reference

There may be a more fancy-pants way to do this, but I would take the view template, extract the car type, and do a manual MIN() MAX() query to fetch these values.


Using Drush to update Drupal 6 core on multisite installation

There's no one single command to do it but we use a bash script that follows this pattern:

ls sites folder for all directories
pass resulting output to drush -l $variable sql-dump > /home/user/backup/$variable.sql
pass resulting output to drush -l $variable updb --yes

Hope this helps.


Looking into the Views Alias module, it does exactly what you need. Rather than making the change during the Views argument validation, this module will create a path alias to this View for every taxonomy term that can be an argument on the Views you select. Thus, example.com/box/45 can be accessed via example.com/box/portfolio, etc.


It sounds like you're starting with node type B, whereas you should be starting with node type C.

Create your view with appropriate filters so that you only see nodes of type C
Add a "Entity Reference: Referencing entity" (not "Referenced entity) relationship for the B->C entity reference field, give it an identifier of something like "Entity B", tick "Require this relationship
Add another "Entity Reference: Referencing entity" relationship for the A->B entity reference field, use relationship "Entity B", give it an identifier of "Entity A", tick "Require this relationship
Add a filter (a regular filter, not a contextual one) requiring that your field has a value of "4", use relationship "Entity A"


What's the difference between using Drupal's jQuery library and adding it in html.tpl.php?

Its better to add javascript using your:
a) theme's .info file using scripts[] = "some/filename.js"
b) in the theme dynamically ... such as mytheme_node_view() { drupal_add_js('file', 'some/filename.js'); }
c) or in a custom module ... (similar to above)

depending entirely on your site's needs.

the reason its better to approach this this way is:
1) the theme's scripts[] array is cacheable and will attach the javascript to every page.
2) dynamically attaching it allows the script to be used only when needed.
3) you don't force the client to load anything they don't need.
4) if its attached in one of the above ways, it can be minified if needed --- allowing the client to download one big javascript file instead of a dozen separate ones.


Ubercart Authorize.Net checkout loops back to cart page

I reinstalled Drupal, and it was able to identify the missing image files. It was an issue with Drupal after all. Good thing I don't get dismissed so easily.


I haven't done this before, but if you have a module that loaded a user account, perhaps using user_load(), you can manually re-set the $account->created.  Clues given in the user_save() function.  Let me know how you get on...

code will look something like this:

$account = user_load($users_uid_here);
$account->created = $date_timestamp_here; // eg. REQUEST_TIME
user_save($account);


How on node forms do I show weight of all menu items?

Doing a hook_form_alter on the node edit form should do the trick:

  use Drupal\Core\Form\FormStateInterface;

  function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** to appear on the node/add/page form, change this or add more for other content types **/
  if ($form_id == 'node_page_form') {
    $menuItems = $form['menu']['link']['menu_parent']['#options'];
    $menuItemsWithWeight = array();
    foreach ($menuItems as $menuKey => $menuValue) {
      $storage =  Drupal::entityManager()->getStorage('menu_link_content');
      $uuid = ltrim(strstr($menuKey, ':'), ':');
      $uuid = ltrim(strstr($uuid, ':'), ':');
      $link = $storage->loadByProperties(['uuid' => $uuid]);
      if(count($link) > 0) {
        $link = reset($link);
        $weight = $link->getWeight();
        $menuValue = $menuValue . ' ('.$weight.')';
      }
      $menuItemsWithWeight[$menuKey] = $menuValue;
    }
    $form['menu']['link']['menu_parent']['#options'] = $menuItemsWithWeight;
   }
  }


Put node url in href to all img tags with jquery

There is no reason to wrap document.ready inside another call to document.ready. If it's ready, then it's already ready!
The reason your code does not work is because it is assigning the same link to all images on the page. You want your code to link to the node that contains the image.
I would not use jQuery for this at all. Views+Imagecache were designed to do this sort of thing and they do it well. Use views to create the page, and use when displaying the image use the "Image linked to node" option.
If you really really don't want to do it that way, then change your code to be this to give it proper scope (right now it is affecting images outside the target node and causing your page to get images wrapped in 20 different  tags!):

Or better yet, don't add it via php and put this in a js file included by your theme instead:

  jQuery(document).ready(function($) {
    $('article img').each(function() {
      var url = $(this).closest('article').find('h1.node-title a').attr('href');
      $(this).wrap('');
    });
  });


I think Views data export module is what you need.


Add a conditional CSS class to the label of the view exposed form

I don't think you need to check for "required" here, just check if the field is not empty, right?

You are first checking if a field is not empty so in the elseif the title will always be empty. You should have two ifs I for your logic to work I believe.

If not empty, do this: if it has this particular value do this otherwise do that.


Theme Preprocess Conditional Field Display

Can you hide it with CSS? In which case you could do something simple like:

<?php

/**
 * Implements template_preprocess_hook().
 *
 * Adapt logic, field names etc to suit your needs.
 */
function MYTHEME_preprocess_page(&$variables) {

  if (empty($variables['node']->get('my_field_2')->value)) {
    $variables['page_classes']['#plain_text'] .= ' field_two--display-none';
  }

}

/* CSS */
.field_two--display-none { display: none; }

Not super elegant but would do the trick.

Your other option is to use the conditional fields module.


Making an Entityform field required using jQuery

Javascript can only handle soft (client-side) validation, unless you start looking into AJAX validation.

You need to alter the form on the server side to ensure that the data is validated properly - never rely on JS validation, it should only be used for UI/display purposes, and form data can easily be overridden by the user.


Core request handler documentation maybe has conflicting information?

I'm pretty sure the advice stems from this issue: Replace almost all remaining superglobals ($_GET, $_POST, etc.) with Symfony Request object. The opening gambit from that post is:

  In order to depend on using the Request object to determine caching, we need to ensure that everything uses it, rather than raw PHP variables for $_SERVER, $_REQUEST, $_GET, $_POST.

I don't the quoted comment is suggesting they're deprecated in PHP as such, just that using them in Drupal isn't going to be reliable.


Try out tinybox simple splash

  TinyBox module uses TinyBox, a lightweight and standalone modal window
  script. The main purpose of this module is to provide Splash
  Screen/Window as simple as possible.


Multiple login attempts from different IP Addresses

You can use Rename Admin Paths module to override the admin path.

  This module allows you to:

rename path like '/admin/...' to '/something/...'
rename path like '/user/..' to '/something else/..'

  It can be effective against registration spam bots or malicious
  people.

And using the Login Security module you can

  limit the number of invalid login attempts before blocking accounts,
  or deny access by IP address, temporarily or permanently.

  A set of notifications by email or Nagios may help the site
  administrator to know when something is happening with the login form
  of their site:

  password and account guessing,
  bruteforce login attempts or just unexpected behaviour with the login
  operation.

  For alternative controls, Login Security can disable Drupal core's
  login error messages, obfuscating the reason for the login failure.
  This could make it harder for an attacker to discover whether the
  account even exists.

The use of the Flood control module is another option to control variables like the login attempt limiters and any future hidden variables.


How can I load a JavaScript file only when a page has an element whose class is "test"?

Well one way would be to just add the script always and check for the existence of test class there.
(function ($, Drupal) {
    Drupal.behaviors.tester = {

        attach: function (context) {
           if (context.querySelector('.test')) {
               // Do something
               // Or maybe load another JS file dynamically
           }
        }

})(jQuery, Drupal);


Exposed filter checkbox for "has comments"

You can add your own filter trough a custom module. I was in need of the same thing. The following code should work.

<?php
/**
 * Implements hook_views_api()
 */
function my_module_views_api() {
  return array(
    'api' => 3,
  );
}

/**
* Implements hook_views_data().
*/
function mymodule_views_data() {

  // comment_count
  $data['node_comment_statistics']['has_comment'] = array(
    'title' => t('Has comment'),
    'real field' => 'comment_count',
    'help' => t('Filter to see if entity has comments.'),
    'filter' => array(
      'handler' => 'cjsm_ikz_handler_filter_has_comments',
    ),
  );

  return $data;
}

The next thing should be a filter in an include file.

<?php
/**
* @file
* Definition of mymodule_handler_filter_has_comments.
*/

/**
 * Simple filter to see if entity has comments or not.
 *
 * @ingroup views_filter_handlers
 */
class mymodule_handler_filter_has_comments extends views_handler_filter_boolean_operator {
  function query() {
    $this->ensure_my_table();
    $field = "$this->table_alias.$this->real_field";

    if (empty($this->value)) {
      if ($this->accept_null) {
        $or = db_or()
        ->condition($field, 0, '=')
        ->condition($field, NULL, 'IS NULL');
        $this->query->add_where($this->options['group'], $or);
      }
      else {
        $this->query->add_where($this->options['group'], $field, 0, '=');
      }
    }
    else {
      $this->query->add_where($this->options['group'], $field, 0, '<>');
    }
  }
}

For me this is providing a selectbox. Because I also want to be able to see nodes with and without comments at the same time. But it does exactly what you are looking for. If you are having trouble implementing this I suggest you search for the ins and outs of creating custom views filters.


Display field inputs side-by-side in node edit form

If you are using Field Collections you can have them displayed in a few different ways, one of which is a table, which is more relevant for some situations than others. Have a look at Field Collection Table and see if it suits your needs.
It will, in your example, put the three fields side by side - but in table cells.


How to subscribe to any or all taxonomy terms on one page?

Subscriptions
The Subscriptions module (with over 5K reported installs) is a typical solution used to setup such Subscriptions. Some details about it (from its project page):

This module enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made. Admins can turn this on by default.

Total Subscription
The Total Subscription module (only a bit over 100 reported installs)  seems like a possible alternative for such subscriptions. Some details about it (from its project page):

Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.
... provides users the ability to:

Subscribe to a specific content type through the node page.
Subscribe to the related taxonomy terms associated with the node on the node page.
Subscribe to a specific taxonomy term from the term page.
Unsubscribe from any previous subscription.
Add a separate ctools content type - "subscription", which could be integrated with any panel page.
Add a "subscription" block to the any region.

Refer to its Community documentation for more details about it, or this video tutorial (without sound ...) that takes you through various admin screens.
Apart from that, to understand what this module is about, the readme.txt might be helpful also.
Module comparison
Some more details about how both modules compare (from the Total Subscription project page):

Subscriptions provides the following features which are not there in Total Subscription, namely it allows subscription to new comments in specific forums, or additions to some category of blog. More control on subscription management for user. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made which can be turned off by admin. But the biggest disadvantage of Subscriptions is it does not allow anonymous users to subscribe, which Total Subscription provide. Total Subscription also has Views and Token integration.


Turn off cron and hook_cron for every module in Drupal

It is a good practice to run cron on your site. You might decide upon the frequency, keep it a high value but it is necessary to run cron to keep your site in healthy state.

If you are worried about loosing the caches when cron is run, you can install Cache Lifetime Options module and set Minimum Cache Lifetime to a very high value. This will make sure that your caches are not cleared on cron runs. Then you can Expire module for your cache invalidation strategy.

If you do not want to run all the hook_cron implementations but only a selected ones then you should consider using Elysia Cron module. It lets you run cron for selected modules at selective frequences.


Upload and get images in custom module with custom block form

In Drupal there is not much help available to store images in configuration. You would need to do most things yourself, like build the form fields, submit and store the images and take care how they should be rendered.

But Drupal has a great infrastructure to store images in content. So the better approach is probably not to use a block plugin, but to create a custom block type, which is content like a node. Here you can add the image fields  and configure how they should be rendered in ui.