Looking at the linkedin module source code,  there's some ways that can run code on the way back (but only when are logging-in, it seems).

When they are logging-in:

hook_linkedin_external_login: if they don't already have an account and will be asked to register.
hook_linkedin_tie_external_login: if they already have an account and will be logged-in using that account.

When they are associating a linkedin account:

I do not see any hooks or any stable way of running code in this case.

Here's an example on how to hook into hook_linkedin_external_login:

In your mymodule.module file:

function mymodule_linkedin_external_login($uid) {
  // do something
}

But you'll have to be careful since linkedin_auth_linkedin_external_login does a drupal_goto() so you'll have to have your module hook called first, so that your function doesn't get skipped. See how drupal decide execution order of same hook in different modules?


ajax_command_invoke Question related to Commerce + Colorbox + AJAX

I'm editing my answer to directly address your question first:

ajax_command_invoke takes a css selector as its first argument.

 node-colorbox

isn't a css selector (or at the very least, not a valid one).

In addition, ajax_command_invoke does not allow for the execution of arbitrary javascript, but only allows for triggering registered jQuery events.  If you want to create a custom jQuery event for colorbox, you will have to manually create it and attach it to the colorbox object, using Drupal.behaviors.

http://www.sitepoint.com/jquery-custom-events/ should get your started.

Colorbox seems like it might be a good solution for your use-case, but it really isn't.  If you want a good floating window with ajax forms and automatic closure, using the chaos tools modal system is a better bet.  It supports what you're looking for right out of the box and makes working with forms easy.  In addition, almost everyone uses ctools, as it is a dependency for many different modules.

http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 should get you started.


Can I set Commerce to accept floats for quantity rather than just integers?

Drupal Commerce supports decimal quantities, there just isn't a UI based configuration mechanism for using that vs. integer quantities. You have to alter the Add to Cart form and Shopping Cart form to change the #datatype property on quantity text fields to 'decimal' (or whatever you prefer) and then add appropriate validate handlers to ensure valid decimal values are being submitted. Search the code for datatype and you'll see the integer example code.


How to alter output of markup on a specific views field

Views is mainly a UI tool, also for theming. Check this box in the field:

REWRITE RESULTS
[x] Override the output of this field with custom text

This opens a text box which accepts Twig code and field tokens of other fields which are placed above. Exclude those fields from display if you want to us them only in Twig. You can check the available tokens in REPLACEMENTS PATTERN below the text box. Look in REPLACEMENT PATTERNS for raw field values, don't use formatted output in Twig logic.


You can use the Views Reference Filter. You can create an entity reference view which will contain the all existing conference names, and then use this view as a filter for the main view.

  This module provides the views filter for entity ID or entity
  reference fields such as node ID, user ID, taxonomy term ID, term
  reference field (Drupal core) and entity reference field (Entity
  reference module).


How can I get the real password via hook_user_update()?

Implement hook_form_alter() (or one of it relatives) such that it array_unshift() a new submission handler to the user update form. The submission handler should add the password to the $form_state['values'] array. You also have to add the same key to $form_state['user'], because of the way user_profile_form_submit() calculates which keys from $form_state['values'] to pass as $edit to your hook_user_update() implementation.

If you did not insist on using hook_user_update(), I'd suggest handling your custom additions to the password update directly in your submission handler.

By the way, Drupal 7 does not use a simple MD5 hash to store passwords.


There is now the Workbench module, for Drupal 7.

  Workbench provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:

  a unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time
  the ability to control who has access to edit any content based on an organization's structure not the web site structure
  a customizable editorial workflow that integrates with the access control feature described above or works independently on its own


It will never be good. Human languages are not something perfectly unambiguous and logical*, so no computer software will ever be able to translate them perfectly. You need a human to properly translate human languages.

Google Translate is bad, but I haven't seen anything better. Sadly, Translate API got deprecated in 2011. This means that modules using it may work for now, but may stop working without notice. See GTranslate and i18n auto translate.

You can always use some code from above modules, and try another machine translator. See Comparison of machine translation applications article - deciding which one to implement is outside the scope of Drupal Answers, just remember that you want GPL software if you want to mix it with contrib modules' code without fees or legal risk.

* OK, there is Lojban, but that's an exception.


So I wasn't able to do this on a separate port, but for anyone who needs to secure the login page from public eye, this is what I did.

<VirtualHost _default_:443>
  ServerName example.com:443
  ServerAlias drupal
  DocumentRoot "/opt/rh/httpd24/root/var/www/html/example.com/current"
  <LocationMatch /(user|admin)>
        Require all denied
        Require ip 10
  </LocationMatch>
</VirtualHost>

This will require the user to be on a local IP. (I am in-housing the site, so when I access the site I'm on a local IP.)


Setting Values for TableSelect checkboxes

You just need to add your id as the key for each item in your $rows array, e.g.:

foreach ($dbresult as $dbrow) {
  $rows[$dbrow->id] = array(
    $dbrow->firstname,
    $dbrow->lastname,
  );
}

Then in your submit handler run:

// Limit the checkbox ids to only those selected by the user
$selected = array_filter($form_state['values']['checkboxes']);

db_delete('autoleads')
  ->condition('id', $selected, 'IN')
  ->execute();

And you should be good to go :)

There's no need to use #default_value unless you want to pre-select some of the checkboxes for the user. If you do, just set #default_value to an array of the ids that you want selected initially.


How to enable plain text format for body in specific content type

See the issue Allow text field to enforce a specific text format. You can use the patch from this issue or install the module Allowed Formats which provides these options in the text field configuration:


Is there a way to implement drag and drop for image upload in drupal 7

You can do this by using any of these modules :

Drag & Drop Upload.

  This module provides a Drag & Drop Upload element and widgets for a
  File and an Image fields.

Plup

  This module allows you to modify your content types with a plup field
  for drag and drop uploads.

Drag'n'Drop Uploads

  The Drag'n'Drop Uploads module adds the ability to drag an image from
  your local filesystem, drop it onto a node body textarea and have the
  file automatically uploaded and referenced in your node.


The problem is you're redirecting without also updating the order's status. The checkout router determines access to a checkout page by matching the order status to the URL, and it will prevent access to any page the order doesn't appear to have reached yet.

In your case, you should just use the same API function the Payment module uses when it needs to redirect past the off-site payment redirect page because an on-site payment method was used. The function is commerce_payment_redirect_pane_next_page() and you can view the function signature and docs in commerce_payment.module.


What I found out is:
Every available printing engine has it's own requirements for the HTML-structure of the generatred invoice.
TCPDF needs a header and footer-tag inside the document. If you dont provide this elements, TCPDF will render them empty, but will in fact attach an hr-tag after the empty header and before the empty footer.
I switched to DOMpdf as printing engine, which also offers the possibility to define a page header and footer, but ignores them when empty and doesn't render any additional HTLM by default.
pro: DOMpdf supports more CSS rules and makes it easier to style the invoice with CSS
con: DOMpdf takes some seconds to render/print the document from the HTML, while TCPDF is very fast.


I'm sure there is a better way to do it but the context module will allow this.

You can set up a condition for each term which sets the menu item as the reaction.


Cache_render table grows extremely fast, is there a way to remove the url.query_args cache context from ALL pages?

No, in a clean Drupal installation this should not happen. These are the default cache contexts set in core.services.yml:

parameters:
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

What you might have found are cache entries from the Internal Page Cache for anonymous requests, which doesn't use cache contexts. Instead it stores the cache entries with the complete URL including the query string as cid. There are a lot of complaints that the Internal Page Cache fills up the database even for sites with moderate traffic. Not only because of the variations by the query string, also because the entries have no expire date and there is no way to configure one in UI. But you can easily replace the Internal Page Cache with Varnish or a CDN. You only have to configure the third party solution to invalidate the Drupal cache tags. Another option is to replace the cache backend with a solution that provides an automatic expiration like Memcache or Redis.


field collection v seperate content types

Good question, but hard to answer. I can't tell you what to choose but I hope my thoughts will help.

If I understand your needs correctly, Field Collection definitely has some advantages. Firstly, field collections are purpose built to be related to other entities. Each field collection entity is always related to one (and only one) node. That seems so match your use case, although I wouldn't know how if it's easy to add multiple field collections to multiple nodes at once. In my experience, field collection provides a pretty smooth way for site maintainers to add new data, so that's good.

The downside of field collections is that many contrib modules are still node-centered. For every site you build, it's hard to predict which problems you will be solving or which features you will be adding 6 months after the launch. If you decide to use field collections, you may find yourself in a situation where you want to add something that would have been really easy with nodes.

Since you're exploring different solutions, maybe you should also look at Drupal Commerce, if only for inspiration. It's a really flexible system which adds line item entities to orders more or less like you want to add charges to properties.


How can I change the name of migration database in database array?

migrate is the default key used by the SqlBase class which is the base for the D7 source plugins. Its documentation explains in detail how it determines what key to use and how it can be changed. Of relevance:

As described above, the default source database is $databases['migrate']. If the source plugin needs another source connection, the database connection parameters should be added to the $databases array as, for instance, $databases['foo']. The source plugin can then use this connection by setting 'key' to 'foo' in its configuration.

So update the source.key value in your migration configuration to foo then re-import that configuration to change the default key used for that migration source.


Select from list or create other structured data in form field

You should check the examples module. Especially the ajax module. there is an example called Generate checkboxes This would lead you to the right direction.

The process would go as follows. You create the basic form then use create a button with Ajax call back. and return the required check box using the callback function.

This is the relavent function that generated the form.

function ajax_example_autocheckboxes($form, &$form_state) {
  // Since the form builder is called after every AJAX request, we rebuild
  // the form based on $form_state.
  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;

  $form['howmany_select'] = array(
    '#title' => t('How many checkboxes do you want?'),
    '#type' => 'select',
    '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
    '#default_value' => $num_checkboxes,
    '#ajax' => array(
      'callback' => 'ajax_example_autocheckboxes_callback',
      'wrapper' => 'checkboxes-div',
      //'method' defaults to replaceWith, but valid values also include
      // append, prepend, before and after.
      // 'method' => 'replaceWith',
      // 'effect' defaults to none. Other valid values are 'fade' and 'slide'.
      // See ajax_example_autotextfields for an example of 'fade'.
      'effect' => 'slide',
      // 'speed' defaults to 'slow'. You can also use 'fast'
      // or a number of milliseconds for the animation to last.
      // 'speed' => 'slow',
      // Don't show any throbber...
      'progress' => array('type' => 'none'),
    ),
  );

  $form['checkboxes_fieldset'] = array(
    '#title' => t("Generated Checkboxes"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('This is where we get automatically generated checkboxes'),
  );

  for ($i = 1; $i <= $num_checkboxes; $i++) {
    $form['checkboxes_fieldset']["checkbox$i"] = array(
      '#type' => 'checkbox',
      '#title' => "Checkbox $i",
    );
  }

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

  return $form;
}

There are couple of other examples related to the form api in the examples module that you can check out as well.


How to create an Ecommerce Loyalty scheme for customers?

This may be too much overhead for your system of point usage, but check out the Commerce Userpoints module.  It integrates Commerce with the Userpoints module, which should handle most of what you're after.


How can I change the delete message "This action cannot be undone." in a specific content type?

Try this code (it works for me - Drupal 6):

function module_change_default_messages_form_alter(&$form, $form_state, $form_id) {
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'delete') {
      $node = node_load(arg(1));
          if ($form_id == 'node_delete_confirm') {
              if($node->type == 'story'){
                $form['description'] = array('#value' => "here replace to \"this action cannot be undone\"");
              } else if($node->type == 'page'){
                $form['description'] = array('#value' => "this action cannot be undone");
              }
          }
      }
}

or you can use the PHP switch statement for more content types.


How to change the default navigation "active-trail" class to something different (or add an extra class)?

You can use the theme_menu_link function to add or remove classes from menu items. This will target all menu's on the page though.

Probably easiest is to target the menu directly with this function theme_menu_link__main_menu. You have to put display your menu as a block though. For bartik there is already a block available.

Steps

Uncheck Main menu at admin/appearance/settings/bartik
Put main menu block in a region (e.g. header region)
Now you can do:

function bartik_menu_link__main_menu (&$variables) {
  $link = $variables['element'];
   if (isset($link)) {
    if (isset($link['#attributes'])) {
     $link_classes = $link['#attributes']['class'];
     if (in_array('active-trail', $link_classes)) {
      $variables['element']['#attributes']['class'][] = 'myclass';
     }
    }
   }
 return theme_menu_link($variables);
}

If you want to style the main menu when it's not in a block you could use:

function bartik_links__system_main_menu($variables) {
  $links = $variables['links'];
  if ($links) {
    foreach ($links as $link) {
      $link_classes = $link['attributes']['class'];
      if (in_array('active-trail', $link_classes)) {
        // add or remove classes here
      }
    }
  }
  // return themed links
}


slide through nodes from the same content-type?

Views Slideshow
About this module
You could use the Views Slideshow module for this. Here is a quote from its project page:

... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
Potential uses:

News item slideshow (such as the title, image and teaser of the last 5 news articles submitted).
The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).
Rotate any image, based on any filters you can apply in views.
Hottest new products for any ecommerce drupal site.
Rotate contact links, share links, etc.
You could rotate entire nodes, categories, image galleries, etc. I wouldn't suggest it, but you have that power.
It's also a great space saver. Places where you had multiple images or multiple items such as RSS feeds or category listings can now be presented in a slideshow.

The possibilities are really endless, as the more ways you can think of to categorize and add to views, the more you can rotate.

How to install and use this module
Option a: Use the available (Community) Documentation
To actually enable and use this module, make sure you follow the instructions detailed in the module's Community Documentation within "3.x - Views Slideshow Tutorial". Especially this part of it:

...

Enable the Views slideshow and Views Slideshow: Cycle modules.

You should now see the new views style option called "Slideshow".

So make sure that you also enabled the Views Slideshow: Cycle sub-module.
Additional refinements:
Since in this case you want to do something special (tricky?), you need to do some extra things, within "settings of field thumbnail-design in my first view" (as in your last screenprint):

Where there is your "red arrow" (higlighter), it should say "link to" = "nothing" (you now have, in Dutch, "inhoud", which is "content"). FYI: That is what explains what is happening "now": you're asking a click on that image to be translated to something link "type an URL path = the path of the node where that image field is related to ...

Where there is your "red cross" (rewrite result), within the 'text' box ('Tekst' in Dutch), you need to further refine what you already have (with that div and token). More specifically, you need to REWORK that to something that corresponds to an hyperlink ('href', etc) (in which you can still use that div, with its class, and image token you already have). The PATH in that href needs to match the exact path that will bring you to what further on in your question you described as "I want every link to direct to the corresponding slide, because every thumbnails has it's own content.". What exactly that path is I cannot tell (I hope YOU know that path, if not we're done). However read on in the next bullet for 1 more hint to CREATE that path for the hyperlink to be added in this tekst box here ...

To create the correct path in the previous bullet, I "expect" that you might need something like the "nid", or something similar, of the actual node. It is possible that it is not available (yet) in the list of tokens within "replacement patterns". In my environment, at first I did not have the [nid] token available at first, only things like [title], %1, !1,  %2 and !2 . However, also making the [nid] token available is possible like so: add an extra field (node Id) BEFORE (important) the field you already have, and mark it with "exclude from display". That's tricky, but that's how this works in Drupal ...

Option b: Restart from scratch
From the details provided in the question, it appears that it might be an option to consider starting from scratch (which is what I sometimes also do ...). Use HOW TO INSTALL & SETUP VIEWS SLIDESHOW MODULE ON DRUPAL7? as a possible step-by-step tutorial to do so.
As a variation, carefully review that tutorial to get ideas about what in your current approach seems to be wrong, and go back to option 'a'.
Option c: Try another module
If you rather want to change to using "Views Bootstrap" (cfr. one of the prior "versions" of this question, which contained "Views slideshow didn´t pop-up while creating a view, so I used Views Bootstrap."), then please create a NEW question about using Views Bootstrap (which I'd be happy to answer "also" if I can. Because that is a completely different question (and compliant to recent guidance / instructions from @Clive also).
Further enhancements
Possibly you may want to further extended this with related modules  (there are dozens of modules to further enhance views) such as Views Slideshow: Galleria. Here is a quote from that module's project page:

Integrating Galleria with Views Slideshow.
Galleria is a JavaScript image gallery framework built on top of the jQuery library. The aim is to simplify the process of creating professional image galleries for the web and mobile devices.

jCarousel
Another option is to consider the jCarousel module. Here is a quote from its project page:

... This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.
Features:

Built-in Views support.
AJAX-loading of additional items as needed.
Carousel pager/navigation to jump between multiple pages.
Circular wrapping of items.
API for direct usage of jCarousel without Views.


Remove tags from dependent term ref field when dependee is deactivated

Fixed...
In the conditional fields settings I had used the following:

The dependent field is: visible

When the dependee: is checked

For some reason this does not revert the dependent to its default value if the dependee is deactivated on saving. Instead, I used these settings and it works:

The dependent field is: visible

When the dependee: is has value

(select the name of the checkbox)

This might be because I have used the label as the value for the checkboxes (instead of the default 0 & 1).


How to avoid appending incremental number to filename

The Upload File Replace module should do the trick:

  Module Page Description

  This is a small utility module that automatically stops Drupal from
  renaming new files upload via filefield CCK. When 2 files with the
  same name exist, the older files will be renamed.

Edit: Sorry, I missed the part where you are expecting a prompt. According to the comment below, it is not possible.


Is there a way to pop form errors off the display stack and/or prevent their display?

If you know the message was the last one set, a  simple hack is to just:

array_pop($_SESSION['messages']['error']);

Just be aware this only removes the message, your form will still be in error state.


Why are some CKEditor configurations working and not others?

There was an error in my code. The config statments needed to be surrounded by:

CKEDITOR.editorConfig = function(config) {

and

}

which I discovered by looking at ckeditor.config.js in the CKEditor module.


Drupal files on NFS, performance degredation

Assuming APC is installed; inside php.ini

; http://www.php.net/manual/en/ini.core.php#ini.sect.performance
realpath_cache_size=1M ; 1MB
realpath_cache_ttl=3600 ; 1 hour

; APC
; http://www.php.net/manual/en/apc.configuration.php
apc.ttl=2419200 ; 4 weeks
apc.localcache = 1
apc.localcache.size = 1024
apc.num_files_hint = 2048
apc.user_entries_hint = 128

apc.file_update_protection = 10
apc.stat = 0
apc.stat_ctime = 0
apc.file_md5 = 1

; OPcache
; http://www.php.net/manual/en/opcache.configuration.php
opcache.enable_file_override = 1
opcache.validate_timestamps = 0

Then when your code changes you need to restart Apache or run

apc_clear_cache('opcode');
opcache_reset();

And for Drupal install the following modules as these are designed to help with the drupal files dir when used on a NFS filesystem
https://drupal.org/project/imageinfo_cache
https://drupal.org/project/advagg
https://drupal.org/project/httprl (will speed up the above 2 modules)


How to create language object from language string (e.g. 'en')?

Use language_list() function:

<?php

function get_langugage_object($language) {
  $installed_languages = language_list();
  return $installed_languages[$language];
}

?>


How to build a block on form submission?

I will encourage you to look at bean contributed module. Using this you can create block types whose instances can be created using bean_create function.

Example snippet:

$values = array(
  'delta' => 'test_bean',
  'label' => t('Test Bean'),
  'title' => t('Test Bean'),
  'type' => some_block_type_that_you_will_create_through_UI,
  'view_mode' => 'default',
  'data' => array(
    'test_boolean' => FALSE,
    'test_string' => t('New String'),
    'test_array' => array(
      'test_array_1' => 'new_value',
    ),
  ),
);

$bean = bean_create($values);

The bean content (block) can then be placed around the site just like any other block.


In a multi-value text field, and assuming D7, the values are something like this:

// if set, this is the first value...
$node->FIELD_NAME[$node->language][0]['value']
// if at least one set, this is the last value...
$node->FIELD_NAME[$node->language][count($node->FIELD_NAME[$node->language])-1]['value']

so depending on what you mean by 'on top,' one of these values is most probably what you are looking for.  (If D6, just take out the [$node->language] part)


You seem to have your field's cardinality set to greater than 1. Change it to 1 and the problem should be fixed.

In case you already have data in the field but you are sure to only have one value stored per entity change the column "cardinality" in the "field_config" table manually to 1.


Cache rebuild causes an error with missing plugin

This morning I had similar problem and drush cr was actually not clearing the discovery cache but after

drush sql-query 'TRUNCATE TABLE cache_discovery;'

I was able to get rid of this error


Does db_query and db_insert escape input values? prevent sql injection?

these functions are abstractions on top of php's PDO library. They are essentially prepared sql statements ... passed values to the query are safe from SQL-injection.

Feel free to jump into the PHP PDO Manual.

EDIT:

eg,

  Many of the more mature databases support the concept of prepared
  statements. What are they? They can be thought of as a kind of
  compiled template for the SQL that an application wants to run, that
  can be customized using variable parameters. Prepared statements offer
  two major benefits:

  The query only needs to be parsed (or prepared) once, but can be
  executed multiple times with the same or different parameters. When
  the query is prepared, the database will analyze, compile and optimize
  its plan for executing the query. For complex queries this process can
  take up enough time that it will noticeably slow down an application
  if there is a need to repeat the same query many times with different
  parameters. By using a prepared statement the application avoids
  repeating the analyze/compile/optimize cycle. This means that prepared
  statements use fewer resources and thus run faster.

  The parameters to
  prepared statements don't need to be quoted; the driver automatically
  handles this. If an application exclusively uses prepared statements,
  the developer can be sure that no SQL injection will occur (however,
  if other portions of the query are being built up with unescaped
  input, SQL injection is still possible).


List 2 fields of a content type and group them based on one of them with views

The answer is "views distinct" module which checks the values of each row and then removes/aggregates the similar ones.


Reorganize Language Switcher based on Country/Region

You can take a clue from below modules..

Hierarchical Select Module ...

  Hierarchical Select module defines the "hierarchical_select" form
  element, which is a greatly enhanced way for letting the user select
  items in a hierarchy.

Language Switcher Dropdown Module..

  Language Switcher Dropdown is a very simple module that exposes a new
  block, similar to the default Language Switcher block provided by
  Locale module. The new block allows site visitors to switch languages
  using a drop-down select list instead of using hyperlinks.

You need to build a custom module which displays region > countries using hierarchical select module
On Form Submit you need to do below actions which lang drop down does to redirect.

Please find submit handler code below from lang dropdown module..

function lang_dropdown_form_submit($form, &$form_state) {

  $language_code = check_plain($form_state['values']['lang_dropdown_select']);
  $type = $form_state['values']['lang_dropdown_type'];
  $tohome = $form_state['values']['lang_dropdown_tohome'];

  $language_codes = locale_language_list('language');
  if (!in_array($language_code, $language_codes)) return;

  $types = language_types_configurable(FALSE);
  if (!in_array($type, $types)) $type = 'language';

  $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
  $languages = language_negotiation_get_switch_links($type, $path);

  $language = $languages->links[$language_code];

  $newpath = (isset($language['href']) && $tohome == 0) ? $language['href'] : '<front>';

  if (!isset($language['query'])) {
    $language['query'] = drupal_get_query_parameters();
  }

  $form_state['redirect'] = array($newpath, $language);

}


I think this really depends on what you need.

For page specific help, returning translated text does appear to be the norm from the modules I have surveyed, and does follow the Help text standard (for core and contrib).

For the text on the admin/help page, I think that using the README.txt is best, since that should really be a "one-stop-shop" for help with the module, and you don't want to have to track your changes in two places.  It is also a pain to format that much text with code.  However, this does make translation hard.

I have not seen a "standard" way to handle the README.txt.  If you look at the Module documentation guidelines, they give this example for Drupal 6:

function mymodule_help($path, $arg) {
  switch ($path) {
    case 'admin/help#mymodule':
      // Return a line-break version of the module README.txt
      return filter_filter('process', 1, NULL, file_get_contents( dirname(__FILE__) . "/README.txt") );
  }
}

and there is a comment for a Drupal 7 version:

function mymodule_help($path, $arg) {
  switch ($path) {
    case 'admin/help#mymodule':
      // Return a line-break version of the module README.txt
      return check_markup(file_get_contents( dirname(__FILE__) . "/README.txt") );
  }
}

Personally, the version I like what Features does:

function features_help($path, $arg) {
  switch ($path) {
    case 'admin/help#features':
      $output = file_get_contents(drupal_get_path('module', 'features') .'/README.txt');
      return module_exists('markdown') ? filter_xss_admin(module_invoke('markdown', 'filter', 'process', 0, -1, $output)) : '<pre>'. check_plain($output) .'</pre>';
    // ...
  }
}


CSS resets usually take the emphasis off of <strong> and <em> tags by default.

All you need to do is add a rule like this to your main style sheet (main.css):

strong {font-weight: bold;}
em {font-style: italic;}

That will re-reset the <strong> and <em> tags to display as you'd normally expect.


How to create a payment form / pane directly from order_id

I got it doing the following :

with a link in user/%/orders/% page like go_to_checkout/$order_id

/**
 * Implements hook_menu();
 * Callback to pass order_id to checkout fn
 */
function commerce_partial_payment_menu() {

  $items['go_to_checkout'] = array(
    'title' => 'balance',
    'description' => 'Pay order balance',
    'page callback' => 'commerce_partial_payment_redirect_to_checkout',
    'page arguments' => array(1),
    'access arguments' =>  TRUE,//still have to change that, maybe see own orders permission
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/*
 * Prepare checkout process and redirects to checkout/%/review
 */
function commerce_partial_payment_redirect_to_checkout($order_id) {

  $order = commerce_order_load($order_id);
  commerce_order_status_update($order, 'checkout_review', $skip_save = FALSE, $revision = TRUE, $log = '');

  drupal_goto('checkout/' . $order->order_id. '/review');
}


Devel themer not working (cant see the checkbox)

Check to see if the module is still enabled.
Clear the cache.
Check to see if the currently logged-in user has appropriate permissions to see devel_themer info.

It's likely #3.


How to control editing access when node ownership keeps changing?

See my recent answer here: https://drupal.stackexchange.com/a/55144/7153

But basically, you can use

nodeaccess_userreference

or

nodeaccess_nodereference

to acheive that access control functionality there.

Basically you could deny author access and control edit access with one multi-value reference field instead.

More info, including screenshots at first link.


Where does Drupal save the trim length for the body field?

In Drupal 7, field settings are saved into {field_config_instance} and {field_config} database table.

Trim length for a body field is saved in the data column in the {field_config_instance} table.  The data column is stored in BLOB format, so you are not able to see the value of this.

You can use the field_info_instance() function to extract information about a particular field in a particular entity bundle/type:

$body = field_info_instance('node', 'body', 'page');
print_r($body);


hook_update_N - expose new field to views after module update

Yep, you can use hook_views_data_alter():

Alter table structure.
You can add/edit/remove existing tables defined by hook_views_data().


Displaying content based on the field value

Under Sort criteria add your check-box field and set it to Sort ascending (it may be descending in your case depending on your field values).

Then if you have more than one Sort criteria Rearrange them so that the checkbox field comes first, on top. This way the results are first sorted by the check-box field value.

This works independently of the image field. Is your image field tied to the check-box somehow?


How to send an eMail notification when a specific field of a node or user has been changed?

You can use the Rules module for this. Here are some details about how to do so:

Rules Event: Before saving content.
Rules Condition: Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different.
Rules Condition: Send an eMail (which is typically implemented as a separate "Rules Component" (that is invoked as the Rules Action), whereas you pass the values like node id, current user, maybe author, etc. Within the Rules Component, you then compose the actual eMail (template) that you want to be eMailed. For an example of such a Rules component, have a look at my answer to "How can I set a reminder for a specific user to be triggered on a specific date?" (which includes such component in Rules export format also).

Should be straight forward to "develop" such rule, no (PHP) coding at all involved (only site building using admin UI).


Drush command to download AND enable a module

The following will download and enable the module:

drush en module_name -y

Edit:  The download (dl) command is not needed.  When trying to enable a module that is not downloaded yet, Drush will ask if you want to download it and then ask if you want to enable it. The -y automates the "yes" answers to these questions.

This was added in Drush 6.0.0 (#1364814 by eiriksm, jonhattan: Added Extend pm-enable to offer downloading the project for missing extensions.)


How to convert hook_filter and hook_filter_tips in Drupal 7?

The code you should use in Drupal 7 is similar to the following one.

function custom_inline_filter_info() {
  $filters['custom_inline_filter'] = array(
    'title' => t('Custom Inline Filter'),
    'description' => t('Substitutes @inline tags with the uploaded inline images of the node.', array('@inline' => '<!-- INLINE -->')),
    'cache' => TRUE,
    'process callback' => 'custom_inline_substitute',
    'tips callback' => 'custom_inline_filter_tips',
  );

  return $filters;
}

function custom_inline_substitute($text, $filter, $format, $langcode, $cache, $cache_id) {
  // …
}

function custom_inline_filter_tips($filter, $format, $long) {
  if ($long) {
    return t('You may link to uploaded images within the current node using the wysiwyg editor toolbar icons.
      The Custom Inline Filter is to replace added image placeholders with uploaded inline images.'
    );
  }
  else {
    return t('Use the wysiwyg editor toolbar icons to display uploaded images inline.');
  }
}

The documentation for the input filter implementations is provided in more than one page:

hook_filter_info()
hook_filter_FILTER_settings()
hook_filter_FILTER_prepare()
hook_filter_FILTER_process()
hook_filter_FILTER_tips()

For the parameters passed to the callbacks defined from an input filter module, see hook_filter_FILTER_settings(), hook_filter_FILTER_prepare(), hook_filter_FILTER_process(), and hook_filter_FILTER_tips().
In particular, it is relevant to know that:

$filter is a filter object, not a string that identifies the input filter; it contains information about the input filter, but what an input filter implementation normally uses is $filter->settings, which is an array of settings defined from the input filter.
$format is a format object, described in filter_format_save(); it doesn't contain information that an input filter normally uses.

To notice that only the first one is actually a hook; the others are callbacks. The documentation shows them as hooks because a limit of the module used to add documentation pages on Drupal.org API: A documentation page is added only if the function is contained in a module (a Drupal core module, or a third-party module), or it is a hook described in a .api.php file.


In the above code example the event is KernelEvents::Request and checkAuthStatus is the method called when the Request event is dispatched.

You can use Drupal Console debug:event command to list all subscribers for a given event:

vendor/bin/drupal debug:event kernel.request

And that will give you something like:

  Drupal\Core\EventSubscriber\OptionsRequestSubscriber                   onRequest: 1000
  Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber           redirect: 1000
  Drupal\Core\EventSubscriber\AuthenticationSubscriber                   onKernelRequestAuthenticate: 300
  Drupal\language\EventSubscriber\LanguageRequestSubscriber              onKernelRequestLanguage: 255
  Drupal\Core\EventSubscriber\RedirectResponseSubscriber                 sanitizeDestination: 100
  Drupal\Core\EventSubscriber\AjaxResponseSubscriber                     onRequest: 50
  Symfony\Component\HttpKernel\EventListener\RouterListener              onKernelRequest: 32
  Drupal\Core\EventSubscriber\AuthenticationSubscriber                   onKernelRequestFilterProvider: 31
  Drupal\user\EventSubscriber\MaintenanceModeSubscriber                  onKernelRequestMaintenance: 31
  Drupal\Core\EventSubscriber\MaintenanceModeSubscriber                  onKernelRequestMaintenance: 30
  Drupal\Core\Routing\RoutePreloader                                     onRequest: 0
  Drupal\Core\EventSubscriber\ReplicaDatabaseIgnoreSubscriber            checkReplicaServer: 0

If you use Drush and have the devel module installed, you can do:

vendor/bin/drush devel-event kernel.request


On Centos, to install wget:

sudo yum install wget

To install curl the following should suffice:

sudo yum install php-curl
sudo service httpd restart

++++++++++++++++++++ EDIT +++++++++++++++++++++++++

According to this post, "unable to fork" errors are likely to result from too many processes running.  They recommend increasing the limit like so:

sysctl -w kern.maxprocs=1000000


Forms display label elements as placeholder

SOLUTION 1:

There is a function through which you can add placeholder to every text field based on its title.

function MYMODULE_auto_placeholders(&$element) {
  if ($element['#type'] == 'textfield') {
    $element['#attributes']['placeholder'] = $element['#title'];
  }
  foreach (element_children($element) as $key) {
    MYMODULE_auto_placeholders($element[$key]);
  }
}

Now in your form_alter() function just call this function;

MYMODULE_auto_placeholders($form);

SOLUTION 2:

To add placeholder to inputs of individual from you can use hook_form_alter .

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'id_of_form') {
    $form['your_element']['#attributes']['placeholder'] = t('Placeholder text');
  }
}

SOLUTION 3:

There is also a module to add placeholder to form input.

Placaeholder:

  This project adds an extra FAPI attribute called '#placeholder' to textfield field elements. Often textfields should have some text in them like "Enter your text here" until the user clicks on (or tabs to) the element in question. At that point, the text should disappear and the user can enter his or her desired input.


How can I translate those translatable texts defined in t() in contribute/custom modules?

You can use the Translation template extractor module to extract all the t() calls you've done.

Another option is to get the t()processed, by viewing the pages where they are defined and then translate them in the interface you mention. (New strings will only be added once they have appeared once).


How to redirect to a node/add page after clicking on a flag link

Ok, I myself test this for you, please first install and enable Rule and Rules UI  ,after it (I suppose you have a flag with 'myflag') .
Go to dmin/config/workflow/rules  and Add new rule ,set your name and in  React on event  in flag group select A node has been flagged, under "myflag"  save it ,after it in Actions section  choose Add action , in Select the action to add in system group choose Page redirect ,after it set your path want to redirect it in Value. (is better check Force redirect).
I hope works for you correctly.


Multiple choices select with data module created view

*markus_petrux* answered, and josepvalis gave a helpful example of this in Drupal Groups in 2010.

You can use hook_views_pre_view to alter the filter to use 'OR'. Trimming josepvalis's example, try redefining the filter & applying that:

function my_module_views_pre_view(&$view) {
    $new_view_filters['field_multiselect_value'] = array(
        'id' => 'field_multiselect_value',
        'table' => 'my_table',
        'field' => 'my_column',
        'operator' => 'or',
        'value' => $array_of_values,
        'group' => '0',
        'exposed' => FALSE,
        'relationship' => 'none',
    );
    $view_overrides = array();
    $view_overrides['filters'] = $new_view_filters;
    foreach ($view_overrides as $option => $definition) {
        $view->display_handler->override_option($option, $definition);
    }
}


Site broken after upgrading with Pathauto < 8.x-1.6

Based on the comments above from leymannx, I've manually uploaded Pathauto 1.6 to my site via FTP. Returning to /update.php, I got the option to update the database and that worked and my site is back up again.

Note: The first time I tried this, I renamed the old Pathauto module folder to "pathauto_old", and uploaded the new version to a newly created folder just called "pathauto", and that did not work. update.php continued to report and out of date Pathauto. After that, I deleted both folders, re-uploaded pathauto 1.6, and then it worked.


is it possible to add a class to header found in page.tpl based on a node id?

You probably already have a specific class for the page on the <body> tag.

For example :

<body class="html not-front not-logged-in page-node page-node- page-node-5 node-type-page">

Then a css should work for you :

body.page-node-5 #main-content-header { ... }

or

body.node-type-page #main-content-header { ... }


How do I download an image/file to a specified location on the disk?

This behavior is largely up to browser itself, and this can't be controlled over how the browser has been configured.

Above settings are from Google Chrome browser. If user has checked "Ask where to save each file before downloading" checkbox, then browser will prompt to choose location else download to default location set in "Download Location".

Instead try educating the user before they download. That's the best way.

Ref : Prompt user to save file to a specific location


Term object is not loaded with loadTree by default a basic php object is loaded instead.

You have to load the term object for each term using $term_obj = Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term->tid);

Your code should look like this

$vid = 'hospital';
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
  $term_obj = Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term->tid);
  $url = "";
  if(isset($term_obj->get('field_hospital_image')->entity)){
    $url = file_create_url($term_obj->get('field_hospital_image')->entity->getFileUri());
  }

  $term_data[] = [
    'tid' => $term->tid,
    'tname' => $term->name,
    'contact' => $term_obj->get('field_hospital_contact_no_')->value,
    'image_url' => $url,
  ];
}

NOTE: Alternatively you can also use loadTree($vid, 0, NULL, TRUE) to load the entities directly on the $terms array but perhaps it should be avoided on very large vocabularies.  More info on the loadTree method


How do I get the raw field value in a twig template?

{{ entity.field_name.value }} to get the true raw value, includes tags and encoding.

Example: {{ node.body.value }}
result:
Batman &amp; Robin

{{ content.field_name.0 }} to get the raw value minus tags and encoding.

Example: {{ content.body.0 }}
result: Batman & Robin

  raw

  This filter should be avoided whenever possible, particularly if
  you're outputting data that could be user-entered. See this page for
  more information on auto-escape in Drupal 8.

  source: Filters - Modifying Variables In Twig Templates

  The raw filter marks the value as being "safe", which means that in an
  environment with automatic escaping enabled this variable will not be
  escaped if raw is the last filter applied to it

  source: Twig's official docs

For example, you can use:

{{ node.body.value|striptags }}

{{ paragraph.field_text.value|striptags }}

  The problem with using twig's |striptags is double encoding of html entities,
  not markup, so & becomes &amp; and then &amp;amp; – Berdir


Is it possible to create a view to show a field from a user acc and content?

To do that you need to link the user account some how to content which i assume could be possible using  $node_author, you also need to connect both the contents with each other using reference field.

In drupal view you can use Relationships tab which available above the Arguments in the center colum of the view add/edit form. To learn about Using View's relationship pleases refer to How To: Using View's Relationships


Here is the snippet code works for @Saba original author of the post in case someone needs it.

function YourModuleName_eu_cookie_compliance_show_popup_alter(&$show_popup) {
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
  if (in_array('administrator', $roles)) {
    $show_popup = FALSE;
  }
}


Alternative to Webform + Bala's answer is Multistep Nodeform. Using it you can redesign node creation into multistep form and simply allow anonymous to add noeds of given content type.

  For each step you can define which fields should be included in this step. "Fields" includes core-fields like "Title", "Body" or "Authoring information" as well as fields defined by other modules (e.g. Date).


How to customize pagination for the taxonomy term view page for different vocabulary?

I've used the Taxonomy Views Integrator module which helped me set custom pagination and view modes by creating taxonomy view page for different taxonomy terms and vocabularies. Some details about this module (from its project page):

The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabulary.
TVI will try not to interfere with views or taxonomy/term page displays if no TVI views exist for the current page request.


This is probably not a full answer, but you will need to use field template suggestions.

field--[type|name[--content-type]|content-type].tpl.php
base template: field.tpl.php
Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php
Note that underscores in a Field's machine name are replaced by hyphens. Also remember to include "field-" in custom field names, e.g: field--field-phone.tpl.php.

The above is taken from https://drupal.org/node/1089656, so it for more information. As a side note, if there are a lot of fields being displayed or you are using a broad template, you would probably want to use a templating function instead, such an example can be seen in Bartik's bartik_field__taxonomy_term_reference (Link here). The functions have a similar naming scheme to the .tpl.php files but with underscors instead of dashes.

Update:
You can cover all fields of a certain type with field--field-type.tpl.php (or function theme_field__field_type()), or all fields on a content type with field--content-type.tpl.php (or function theme_field__content_type()). You can then override these functions by using a more specific template (They have an order of preference). This can really cut down on the number of theming templates or functions required, essentially if a content type has 100 fields, you could theme them all with one template or function, if you so wished.

So you could use 1 function to theme all the fields on a content type if you wished, no matter their type or name. Alternatively you could field all fields of a certain type (eg. taxonomy_term_reference in the case of Bartik) no matter what their field names are or which content types they are on.

You could override one of these more general templates or functions with one which is more specific, from the field.tpl.php documentation above field--field-type.tpl.php will be overridden by any of the ones listed above it, if a relevant function exists. While field--field-name--content-type.tpl.php has the highest preference and will not be overridden by any of the others. This is just core behaviour, custom modules may alter the list, including adding new ones, which can lead to quite a powerful set of themeing functionality.

Templates are easier for themers to work with, I am told. I prefer functions because it avoids what may be a large number of includes in some cases.


Drupal 7: pull out just the Twitter job as its own Cron job so that we could run it every minute

There are a couple of different cron managers available, personally I use Elysia Cron

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

But there's also Ultimate Cron which I understand is very good too

  Runs cron jobs individually in parallel using configurable rules, pool management and load balancing.

Either of those will let you isolate the Twitter cron job to be run more frequently than the normal one.


What is the difference between wysiwyg module + ckeditor and ckeditor module?

I've played with both recently and can offer some insight, at least for Drupal 7.

The Wysiwyg module lets you use any number of editors, such as CKEditor. It also integrates with the Media module if you use that. If you don't want to use CKEditor, but, say, TinyMCE, then you'll want to use Wysiwyg.

The CKEditor module is (obviously) just for CKEditor, and has more options specific to CKEditor. For example, you can change the skin CKEditor uses (Office 2003, Karma, etc). You can also set advanced CKEditor config options which you can't do with Wysiwig+CKEditor. It also integrates with some file browser modules like CKFinder. And I believe you can use the Media module with new versions of CKEditor.

One of the big reasons I went with the CKEditor module is that it doesn't strip out JavaScript. I couldn't find a way to get Wysiwyg+CKEditor to preserve JavaScript.


How can I featurise / store changes to a view provided by a module?

As far as I know, you cannot featurize a view that is provided by a module. What you can do is clone the view and featurize that.

I don't know about the Workbench modules specifically, but some modules allow you to choose which view is displayed via the UI. If they don't allow that, you will likely need to go in and modify the view call manually in a custom module.


Using Custom Formatters module to output an image's URI

You should take a look at the file module, which does a lot of this already

For Drupal 7:

/**
 * Implements hook_field_formatter_info().
 */
function file_field_formatter_info() {
  return array(
    'file_default' => array(
      'label' => t('Generic file'),
      'field types' => array('file'),
    ),
    ...
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function file_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'file_default':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#theme' => 'file_link',
          '#file' => (object) $item,
        );
      }
      break;
    ...
  }
  return $element;
}

You could copy this and create your own theme function, all it needs to do, would be to print the uri and you're done.


Potentially cancel all other submit handlers after my own

Ensure that your implementation of hook_form_alter() is the last one to be called. Your implementation of hook_form_alter() can then unshift one validation function and push a second validation function. The second validation function would then have complete information about whether other validation functions objected to saving the node (by calling form_get_errors()).

You can ensure that your your implementation of hook_form_alter() is the last one to be called by implementing hook_module_implements_alter()


how to set a webform field value in my custom module

Ok, try not to confuse Webform module stuff with core drupal FAPI stuff.

You cannot set $form['submitted']['test_id']['#value'] = 'COURSE_ID-123456'; in the form_alter because $form is not passed in by reference and the submitted key values is set after the form is POSTed to my knowledge.

So you're trying to put stuff into the form in the wrong time and place. If I was just using FAPI and not webform. I would not use a "hidden" form value (which isnt really hidden on the page), but use Form build_args or $form_state['MYMODULE_temporary'] to hold my custom course_id in the FAPI form lifecycle so that the client never sees these values, but they are passed along through form validation and submission.

You can probably do the same technique I describe above and then implement hook_webform_submission_insert(), or hook_webform_submission_update() (if your form supports Drafts) to perform submission logic and look at your custom course_id stuff ...


Have the same rendered output, whether the video is a local or remote ressource

Haven't tried it yet, but I believe that is what is good about the mediafront module.  It wraps the youtube or local videos in it's own themeable player.

You could also try http://drupal.org/project/mediaelement module, though I'm not sure how well that display's youtube videos.


If you check the change records you should find the following: drupal_set_title() and drupal_get_title() were removed.

You'll have to read the change notice for all of the info, but here is a starting point:

  drupal_get_title()

  As titles on routes now can be set on various ways (see above),
  drupal_get_title() has been removed. In its place you should call the
  title_resolver service.

  Drupal 7

<?php
  $title = drupal_get_title();
?>

  Drupal 8

<?php
  $request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  }
?>


How to add first and last classes to local task items?

You can use jQuery :first and :last selectors, example:

$('ul li:first').addClass(‘first’);
$('ul li:last’).addClass(‘last’);

Or you can use CSS :first-child and :last-child selectors, example:

li:first-child { add your css here }
li:last-child { add your css here }

The CSS way will give better performance.


How to access the published field in my PHP code?

It is

$slider->status == 1

instead of

$slider->$status == 1


Changing position of the header in a view

In your custom theme check if there is a templates/views-view.html.twig file

If not you you can get a copy from core/themes/stable/templates/views/views-view.html.twig and modify the position of header section to be below exposed

the content should look similar to the following after your change

...
{{ exposed }}
{% if header %}
  <header>
    {{ header }}
  </header>
{% endif %}
...

This will customize all views in your current installation

If you want to only modify a specific view you can name the file templates/views-view--VIEWNAME.html.twig

Here is more info on the template naming convention


Term Reference Autocomplete field that searches fields besides name

As far as I've been able to determine, there is no way to modify what autocomplete searches in a term reference field, though if seems possible, even likely that there might be a module or hook that does this, I didn't find it.

To answer my second question, yes, making this an entity reference enables the use of views to power the autocomplete, at which point you can handle the formatting and search fields of the autocomplete.

Better answers on this are very welcome!


Trying to get property of non-object throws exception that cannot be handled

I actually over-simplified by question. The crash doesn't happen in the simple case I posted, just an error and execution continues. It arises when I use field API syntax to refer to a null referenced entity, and only then when the target_id is not null.

$node->field_foo->target_id = 999; // term 999 does not exist
try {
  // The next line results in an unhandled exception
  $v = $node->field_foo->entity->field_bar->value;
} catch (\Exception $e) {
  // Never gets here
  watchdog_exception('example', $e);
}
// And never gets to continue here

The issue was why and Drupal does this. The solution (thanks @Clive) is to replace catch (\Exception $e) with catch (\Throwable $e)


This isn't exactly what you asked for, however:

I have tried a bunch of slideshows that claim various degrees of responsiveness and the best out of the box solution I have found that works as expected, is easy to set up, and is properly responsive, is the flexslider module, which can either be used by itself, or can be used with the views slideshow module.

If you haven't tried it it is definitely worth trying.


If all you are doing is adding to an existing menu, there is no need to use a menu alter. Instead stick with plain old hook_menu().

function ymlp_svm_mail_menu() {
  $items['admin/settings/ymlp-svm-mail/update'] = array(
    'title' => 'Update YMLP Accounts Manually',
    'page callback' => 'ymlp_update',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

Don't forget to flush the menu cache after the module is installed


Update a content type field's allowed values programmatically

Those are settings, you get them using $ip_sec_zone_storage_values->getSetting('allowed_values'),, in there you'll find those settings, you can add another one, set the settings back with setSetting('allowed_values', $allowed_values) and then ->save() to save the field storage config:

$allowed_values = $ip_sec_zone_storage_values->getSetting('allowed_values');
// The new value.
$allowed_values[$ipseczone] = $ipseczone;
$ip_sec_zone_storage_values->setSetting('allowed_values', $allowed_values);
$ip_sec_zone_storage_values->save();


You are looking for functionality that is available in some ready modules. Login Destination looks like a solid bet:

  The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them.

Seems to be exactly what you need.


Migrate into Multi-value Checkbox from CSV

Turns out typos can send you down a completely misguided rabbit hole!

Within the explode plugin, the property should be delimiter, not delimeter (incorrect spelling).

After that switch, things are working great.
Yay.


Role Hierarchy and Management of Assigned Users

You could try to use Organic Groups, it's a module used in many distributions, Open Atrium probably would be the most popular.

With OG you could create groups and assign permissions to create/update content only in those groups.


You can add your library in your file theme.libraries.yml (or module.libraries.yml) like this:

# Parsley use for contact_form.
parsley:
  js:
    dist/js/vendors/parsley.min.js: { minified: true }
  dependencies:
    - core/jquery

After, you can include your library like any other libraries with a hook or a template.


Attempt URL alias for spanish version of page - "The path */* is either invalid or you do not have access to it."

As @prkos mentioned enable the languages module. In the Configuration/Regional and language/Languages settings you select the code you wish to use for your languages. The choice is obviously yours but when I have a multilingual site I prefer to use the ISO language code to help define the languages on the site.


How to show hide other content fields when we select radio buttons?

This could also be done by using states that are available in Drupal core. For example you could set that an element in a form should only be visible if another element has the value "x".

    $form['my_element']['#states'] = array(
      'visible' => array(
        ':input[name="some_other_element"]' => array('value' => 'some_value_that_has_to_be_set'),
      ),
    );

More examples at form_example_states_form.

You can add states to elements in an implementation of hook_form_alter or add it directly to the form if you are programming it yourself.


A hook that would check if the module is enable?

module_exists($module) will do that for you.  From the API:

Parameters
string $module: The name of the module (without the .module extension).
Return value
bool TRUE if the module is both installed and enabled, FALSE otherwise.


Can't get template suggestions to be recognized

It took me a bit to figure this out and what I came up with is that the issue appears to be that Drupal's Theme System will only look for dynamic templates if they are in an actual theme, not in with a module.

So, you can do one of two things, the first one obviously being to copy all of your facet-item templates into your theme directory and call it a day after clearing caches for Drupal to pick them up.

Or... you could get creative like the Views Module does and create theme registry hooks for each of the template files like so:

function dsfacet_theme($existing, $type, $theme, $path) {

  $hooks=array();
  $modulepath = drupal_get_path('module', 'dsfacet');

  $hooks['facet_item']= array(
    'variables' => array('facet_name' => NULL, 'facet_values' => array()),
    'pattern' => 'facet_item__',
    'template' => 'facet-item',
    'path' => $modulepath . '/tpl/facet-items',
  );

  $hooks += drupal_find_theme_templates($hooks, '.tpl.php', $hooks['facet_item']['path']);
  // $hooks += _views_find_module_templates($hooks, $hooks['facet_item']['path']);

  return $hooks;

}

which if you have Views installed will actually use Views' _views_find_module_templates() function to do all the work for you. (it basically goes through the directory passed to it and looks for template files and creates $hooks['facet_name__foo'] for each one it finds.) If you don't have or want Views installed, you can just copy it out of views.module and include and rename it accordingly in your own module.

ADDITION/CORRECTION:  DUH; YOU CAN USE drupal_find_theme_templates() just as easily without worry about using/including Views' similiar private implementation.

And now if you have put all your facet-item templates under your module in their own directory structure (mostly so the find template function doesn't find any other templates and spin its wheels doing extra work) and cleared caches, you should now see all of your templates.


Content Type and Fields programmatically

I answered pretty much the same once already I think, but I can't find that answer anymore.

You add fields and their widget and formatter configuration in the same way. By adding all the relevant config entities.

You can find almost all of them by exporting configuration into the staging folder and then search for files that contain "announce_type" in the file name. That gives you the fields, the form and view displays configurations.

Then you also need the field storages. These are shared across bundles, so they don't have the node type in them (unless you prefixes your fields with your node type/module, which is a good idea if you want to make them part of your module).

Put all those fields in config/install and you're done.


It seems you added the field field_time_to_finish_countdown_timer to your content type challenge after you created some content for this type.

The previously created content do not have any value for this field, causing this error. You may define a default value for this field, such as 0 to get rid of this error.


How do I export fields of a content type in one website and import it into another website?

Create a rss feed of your view or using Views Bonus Pack create a csv of your data.
Create the Content Type that will be the container for your new content. Or alternatively export the content type using the "Content Copy" module shipped with cck and then import it on the new site.
Using Feeds Create a node importer to import your nodes. Details in the video linked.


I think you forgot to send the the view_name that is a non-optinal argument. Check the code of the resource:

'view_name' => array(
  'name' => 'view_name',
  'type' => 'string',
  'description' => 'The name of the view to get.',
  'source' => array('path' => '0'),
  'optional' => FALSE,
),


How can I retrieve the value of a field in a flagging?

According to the Flag API

flagging_load

  Loads a flagging entity. Parameters

  $flagging_id: The 'flagging_id' database serial column.

  $reset: Whether to reset the DrupalDefaultEntityController cache.
  Return value

  The entity object, or FALSE if it can't be found

Therefore something like this might work:

$flaggings = flag_get_user_flags('node', $node->nid);
if (isset($flaggings['spam'])) {
    $flagging = flagging_load($flaggings['spam']->flagging_id);
}

You will then find your field in:

$flagging->field_reason


If you go through its possible to make it as horizontal. Try this code wherever needed:

jQuery('#toolbar-bar button').each(function(){
  if(jQuery(this).html() === 'Vertical orientation'){
    jQuery(this).click();
  }
  if(jQuery(this).find('span.label').text() === 'Tools'){
    var open = jQuery(".toolbar-box").find('.open').length;
    if (open > 0) {
      jQuery(this).find('span.label').click();
    }
  }
});

For checking try this in the console first and add snippet to your JS file.


How to remove panel-separator CSS in mini-panels?

All you need is to override the panels_default_style_render_region function.

Open your template.php file that can be found here:
/sites/all/themes/YOURTHEME/
Create a  new function in end of the file

function YOURTHEME_panels_default_style_render_region($vars) {
    $output = '';
    $output .= implode('', $vars['panes']);
    return $output;
}


You could use the computed field module.

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

You can get all the information that you add in other fields with in the computed field. Since you have not yet saved the node you might want to add the following code at the beginning to make the nid available.

https://drupal.org/node/149225


What is the proper function for multi dimensional localized menu?

menu_tree($menu_name) Seems to do that. It runs the items through  _menu_item_localize.

It works if your menu is translatable. In my setup menu items were not assigned to language, but translated with 18n_menu from site default language.

This atleast gets translated menu. Localized menu might imply also to version where certain items are only shown with specific language active(in that case this answer migth not work).


How to move Composer created folder of drupal-8.x.x up one level to html?

Since you are using composer to manage dependencies, you should install Drupal with Composer instead of using drush pm-download:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#download-core

Also, you should use Composer to manage contributed modules instead of using drush pm-install:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#managing-contributed

You can even use Composer to manage third-party libraries:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#third-party-libraries

And to apply patches to Drupal core and contrib modules:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#patches

Don't worry, you'll still use drush for a lot of things -- but once you've switched to using Composer to manage dependencies, you should stick with it as much as possible and avoid using Drush makefiles or installing / upgrading with Drush.

Here's an article with some common "gotchas" you may encounter when managing Drupal with Composer:

https://www.jeffgeerling.com/blog/2017/composer-and-drupal-are-still-strange-bedfellows


CDN module enabling "Far Future expiration" breaks whole site theme drupal 7

These modules might help you out (quotes added here are from their project pages):

Advanced CSS/JS Aggregation:

  On demand generation of CSS/JS Aggregates. If the file doesn't exist it will be generated on demand.
  Stampede protection for CSS and JS aggregation. Uses locking so multiple requests for the same thing will result in only one thread doing the work.
  Fully cached CSS/JS assets allow for zero file I/O if the Aggregated file already exists. Results in better page generation performance.
  Can add JS to any region of the theme & have it work and be aggregated.
  Combine CSS files by using media queries.
  Prevent more than 4095 CSS selectors in an aggregated CSS file (IE 6-9 limitation).
  ...

Imageinfo Cache:

  ... will generate image styles right after an image is uploaded and also on entity save. This will help with front end performance as the needed image style will already have been generated; thus the end user doesn't have to wait for the image to be generated. This can also mitigate some issues with image style generation if your CDN is configured incorrectly as the images will be generated without the request going through the CDN.


How to access Vertical Tabs from Contrib Modules in Panels?

Sounds like this should work.

In your 1) scenario, where you restricted your installation to the minimum amount of modules -- you might have run into a change/bug with a module version which you intentionaly have upgraded. Try not to test with "most recent versions".

Because you phrased your experience as "in the past you could ...".


How to pass argument from one view to another view?

Here is how you can do it programmatically:

// load and display view A
$view_A = views_get_view('view_A_name');
// execute view
$view_A->execute();
// get all nids from the result
foreach ($view_A->result as $result) {
   // capture the result of your field in an array.
   $values[] = $result->field_machine_name;
}
// render view
print $view_A->render();

// now load view B
$view_B = views_get_view('view_B_name');
// set arguments for view
$view_B->set_arguments(array(implode(",", $values)));
// execute view
$view_B->execute();
// render view
print $view_B->render();


You can simply do this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
// all other conditions go here

if (isset($my_field_val)) {
  $query->fieldCondition('my_field', 'value', $my_field_val);
}
$result = $query->execute();

Untried code as I don't have access to my files at the moment.


Printing to a strict template (multipage invoices / multiple delivery labels per sheet etc)

You can look into Fill PDF as an option. For this, you'd have to pre-create the templates with fillable form fields and would probably need a bit of programmatic glue to deal with page breaks, number of pages, etc. Fill PDf basically lets you use tokens from nodes and webforms to populate fillable PDF fields.

It would probably make achieving your template easiser.


Excluding empty(Null) fields when using EntityFieldQuery query condition

If you look on the fieldCondition documentation page you will see the following warning:

  Note that entities with empty field values will be excluded from the EntityFieldQuery results when using this method.

Checking whether a field exists or not has been added to entityFieldQuery in Drupal 8, but unfortunately won't be backported to Drupal 7.

There are various methods to achieve this:

Using a tag and hook_query_TAG_alter as mentioned by @Clive, see comment 4 on  the Drupal issue for an example ;
First query all non NULL entries, then query all entries excluding the previous ones, as described in @seddonym's answer and in comment 5 on the Drupal issue ;
You can write your query using SelectQuery rathen than EntityfieldQuery as such:

_

$q = db_select('node', 'n');
$q->fields('n', array('type'))
  ->condition('n.type', 'my_node_type', '=')
  ->addJoin('LEFT', 'field_data_field_my_field', 'f', 'f.entity_id = n.nid');
$q->isNull('f.value');
$r = $q->execute();


I created a custom module for this functionality. This module file used for creating a send a copy of message to me functionality

function sendmail_webform_form_alter(&$form, &$form_state, $form_id) {
     error_reporting(E_ALL);
     ini_set('display_errors', 1);
     // webform_client_form_52  webform id
     if($form_id == 'webform_client_form_52') {
         $form['submitted']['send_a_mail_yourself'] = array(
         '#type' => checkbox,
         '#form_key' => 'send_a_mail_yourself',
         '#title'=> 'Send a copy of yourself',
         '#weight' => 4, // As your needed
         '#field_prefix' => '
',
         '#field_suffix' => '
',
         '#default_value' => array('yes' => t('send a copy of yourself')),
       );
       $form['#submit'][] = '_sendmail_webform_submit';

       }
     }

   function _sendmail_webform_submit($form, &$form_state) {
     $param = array();
     foreach($form_state['input']['submitted'] as $key => $values) {
        if(valid_email_address($values)) {
             $to = $values; //to email address
        }
        else if($key == 'send_a_mail_yourself' && $values == 1) {
              $send_a_mail = $values;  // Check send a mail to yourself checkbox

        } else {
          if($values) {
               $param[]  = $values;  // All remaining values to store to param array for use of email body
          }
        }
       }

          if($send_a_mail == 1) {
         $from = 'noreply@example.com';
                 foreach($param as $param_values) {
            $body[] = $param_values;
           }

        $to = $to; // Set this email address - emails will be sent to this email address!
        $params = array(
            'body' => $body,
            'subject' => 'Website Information Request',
     );
        if (drupal_mail('sendmail_webform', 'some_mail_key', $to, language_default(), $params, $from, TRUE)) {
            drupal_set_message('Thanks, we will be in contact with more information soon.');
     } else {
            drupal_set_message('There was an error subscribing you. Please try again later');
        }

    }
  }

 function sendmail_webform_mail($key, &$message, $params) {
     $headers = array(
         'MIME-Version' => '1.0',
         'Content-Type' => 'text/html; charset=UTF-8;',
         'Content-Transfer-Encoding' => '8Bit',
         'X-Mailer' => 'Drupal'
    );
    foreach ($headers as $key => $value) {
         $message['headers'][$key] = $value;
    }
      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];
 }


How do I show a submenu when hovering over a menu item?

Mega Menu module will create a Block in Blocks section(admin/structure/block).

Enable that block in a particular region and see it in action.


Changing the content of one node reflecting in other node created using node clone

The problem with using node clone on node which uses field collection is, it preserves entity reference.

  The group of fields is simply an entity. When you use node clone to
  clone a node the reference to the entity is preserved.

  Quoting from this article.


Is it necessary to cache data generated by menu_tree_all_data and menu_tree_output called in preprocess_page

No need to cache menu_tree_all_data() as it is already cached; which leaves menu_tree_output(). This function looks fairly light; but it really depends on how many items are in $main_menu_tree. Note that it's not 100% safe to cache menu_tree_output() the way you're currently using it as it uses menu_get_item(). If you were to use the tab_root_href key as part of the cid then that would probably work. If this code only gets called once (my guess as it's in hook_preprocess_page()) then the static cache will not help. The important questions are how fast is your cache backend, how many items are in $main_menu_tree, and how often does this code get called. Knowing that will tell you what's better.

Questions like this can be answered with some help from microtime(). Example below:

// Get current menu item.
$router_item = menu_get_item();
$menu_name = 'main-menu';
// Get the cache ID.
$cid = 'ctm_mobile_menu:' . $vars['language']->language . ':' . $router_item['tab_root_href'] . ':' . $menu_name;

// Try core static cache.
$menu_output = &drupal_static('menu_tree', array());
if (!empty($menu_output) && !empty($menu_output[$menu_name])) {
  $mobile_menu = $menu_output[$menu_name];
}
else {
  // Try cache backend
  if ($cache = cache_get($cid) && !empty($cache->data)) {
    $mobile_menu = $cache->data;
  }
  else {
    // Get the rendered output for the $menu_name variable.
    $mobile_menu = menu_tree($menu_name);
    // Save to the cache bin.
    cache_set($cid, $mobile_menu, 'cache');
  }
}

$time_start = microtime(true);
    // Get the entire main menu tree.
    $main_menu_tree = menu_tree_all_data('main-menu');
    // Add the rendered output to the $mobile_menu variable
    $mobile_menu = menu_tree_output($main_menu_tree);
$time_end = microtime(true);
$time = round($time_end - $time_start, 4);
echo "Did non-cached in $time seconds\n";

$time_start = microtime(true);
    // Get current menu item.
    $router_item = menu_get_item();
    // Get the cache ID.
    $cid = 'ctm_mobile_menu:' . $vars['language']->language . ':' . $router_item['tab_root_href'];

    // Try cache backend
    if ($cache = cache_get($cid)) {
      $mobile_menu = $cache->data;
    }
$time_end = microtime(true);
$time = round($time_end - $time_start, 4);
echo "Did cached in $time seconds\n";


Register nodes seen in a view as not "new"

The New or Updated mark is generated by a simple theme function (theme_mark) which can be overriden. Normally you would do that in your template.php but since this theme function is used in the admin theme, that's not gonna work.

A workaround for this is to add your own theme function to a custom module, like this:

/**
 * Implements hook_mark().
 */
function yourmodule_mark($variables) {
  // Always return an empty string.
  return '';
}

Now, we need to add this function to the theme registry like this:

/**
 * Implements hook_theme_registry_alter().
 */
function yourmodule_theme_registry_alter(&$theme_registry) {
  // Check if the default theme function of mark exists
  // and override it with our own theme function.
  if (isset($theme_registry['mark']['function']) {
    $theme_registry['mark']['function'] = 'yourmodule_mark';
  }
}

Clear your cache and your done.

You'll find the original theme function here in the Drupal docs.

Note that this code will permanently override the output of this function where ever it is used.


Probably the easiest way to do it would be to pass the path in a GET variable and use a token.

So on your node page edit the webform link to include the path like so

Webform link

Then on your webform for that textfield use [current-page:query:yoururl] as your default value.

Obviously replace yoururl with whatever you want to name the variable.


How to hide exposed sort if view return empty result?

In views-view.tpl.php, just replace this code

<?php if ($exposed): ?>

      <?php print $exposed; ?>

  <?php endif; ?>

with

<?php if ($exposed && $rows): ?>

      <?php print $exposed; ?>

  <?php endif; ?>

Cheers


Remove password field from user registration form

You can use Generate Password module to achieve this goal.
This module makes the password field optional (or hidden) on the add new user page (admin & registration). If the password field is not set during registration, the system will generate a password. You can optionally display this password at the time it's created.

For more info go through the documentation of this module.


How Change the Style of views based on user option

Sounds like this will need to be done programmatically.

Use hook_views_pre_render() to be able to change the settings of a view based on certain conditions.

https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7

Then using the global $user definition to lookup the logged in user, use that to create a condition and alter the settings of the actual view.


Can views pages be indexed and be searchable by apachesolr?

Thought I would post about how we ended up solving this:

Installed the module https://drupal.org/project/viewfield (which has a 7.x-dev release)
Created a new content type called 'Section Overview'
Added a viewsfield to the content type 'Section Overview' that allows the author to choose the view they wish to embed from a dropdown list
Told apachesolr to index nodes of type 'Section Overview'

In the end it was not that hard, just took some lateral thinking.


Is there any way to connect Acquia Cloud intance with issue tracker?

I use the combo of BitBucket/JIRA. There are many people that like GitHub's issue tracker too. Acquia has tutorial on setting up either service as a 2nd remote repo. Either service will give you a way to track issues against your commits.


Add 'Or Condition' to specific field in Entity Query

So, the simplest way to rewrite this, would be:

$searchname = 'test';
$searchtype = 'type_1';

$field_types_array = [$searchtype, 'both'];
$query->condition('status', NODE_PUBLISHED);
$query->condition('field_type', $field_types_array, 'IN');
$query->sort('created','DESC');

The use of an array for the condition method forces the SQL query to be written as an IN query.

Reference documentation: QueryInterface::condition


PDOException error - Google AdWords Conversion module

OK I would take this approach. First off you need to look at the system table within your Drupal DB. Since you can't for whatever reason disable the module from the UI you'll need to disable it from here. You can do this by navigating to the row representing the module, and setting the status column to 0. Once you've done this clear your cache.

The error message you're getting is due to a database schema inconsistancy, so what I would try do is navigate to the Modules -> Uninstall (/admin/modules/uninstall) and see if I can now uninstall the module. Depending on how the module is written, this should invoke hook_uninstall and undo any database scheme alterations made when the module was initially installed.

Hopefully this will get rid of the nasty PDOException you're running into when editing your webform.


How can I find out a list of available $string values for user_access($string) function?

As @Berdir said, the easiest way to see which permissions are available is to go to the permissions admin/people/permissions in Drupal 7.

The problem I kept running into is that I could never figure out what string I needed to supply as an 'access argument' to actually make use of the permission.  Well, here is how you find the string name for the permissions you want to use (This example uses Google Chrome.)

Step one. Go to admin/people/permissions find the permission you would like to use and right click on a check box to the right of the permission you would like to use.  Select 'Inspect Element' or just go look at the source.

Next look for the value of the check box and note the value. (In this case the string is 'create coupon content')

This is the string you need to supply as an access argument in hook_menu()

Example Code: (non-relevant items removed, don't forget title, callback, etc. in hook_menu())

function fsrsys_menu() {
    $items = array();
    $items['my-custom-url'] = array(
        'access callback' => 'user_access',
        'access arguments' => array('create coupon content'),
    );
    return $items;
}


Where should I put this JavaScript code ... the Drupal way?

Why don't you simply use the Maxlength module that does exactly what you want already pre-packaged?

Otherwise, I would either write a custom module and use drupal_add_js() and hook_form_alter(), or use them in your template.php file without having to write a module.

If you're stumped, and want to know how to do it, why don't you download the Maxlength module and analyse how it is written to clarify the processes involved?


Standard practice for adding new fields to a table created by a contrib module

Well, you could always use hook_update to generate a new field in the table. This gets executed when you do a database update.

It's even possible to use it in your own module.

http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_update/7


Is it possible to get rid of the Javascript code?

At drupal.org user Jaypan propsed to implement a new module (named e.g. killjs) which would have to implement hook_js_alter()

<?php
function killjs_js_alter(&$javascript) {
  // Insert code to check whether JS should be killed or not.
  $javascript = array();
}
?>

This, however, would be very laborious for non-experts since it would be necessary to do a more or less complete analysis of the Drupal code base first. User leymannx proposed a solution which may be realized without developing a new module:

Javascript is deactivated only for a specific theme, here called custom_garland.
Copy file modules/system/html.tpl.php into the customized theme folder as /sites/all/themes/custom_garland/html.tpl.php.
In the copied file html.tpl.php delete the line <?php print $scripts; ?>.
Clear the drupal cache.
Select custom_garland as default theme.

Now for guests the page is clean of Javascript! In the backplane, Javascript is still active due to file maintenance-page.tpl.php. This means one can still adust the Garland/Bartik colors or drag blocks.

For me, the maintenance mode works with the above modified theme. Stefan Korn presented a refinement of this apporoach where JavaScript is fully activated for users which are logged in.


populating a webform select list from a view?

Take a look at the sandbox project Webform Views Select.

  This module will let you populate a webform select component with data from a view.


Programmatically add custom meta description via metatag module

Instead of directly altering the metatag, you might want to look into creating a custom token: As described in this article

This will give you more freedom and flexibility. Then you can just use that custom token in the backend of metatags and configure it for content types that you like.

/admin/config/search/metatags

If you however, still prefer to use the hook in the op, don't forget that those are cached, you will need to clear all caches before it might appear.


There are set of other modules which helps you create meta tags

Page Title
Meta Tag
Meta Tags Quick

Note: Meta Tag Module supports panels too!!!


It is safe to use the 7.x-1.x-dev version now. The updates happen incrementally, based on a number that is updated for every new update function.

It was only before the 7.x-1.x-beta releases, where upgrading was not supported (And apart from some bugs during the beta IIRC) for the -dev version.


How to create a contact form using FAPI in a custom module?

When dealing with Form API in Drupal 7 there are two major steps:

Step 1: Create and implement the form in a module

In this step 1, you will setup the form, and then validate and submit the form, as further detailed below.

a) Setup the form

    function form_example() {
       $form['first_name']=array(
       '#type' => 'textfield',
       '#title' => t('First name'),
       '#description' => t('Enter first name'),
        );
        $form['last_name']=array(
        '#type' => 'textfield',
        '#title' => t('Last name'),
        '#description' => t('Enter last name'),
        );
    $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Click Here!'),
        );

    return $form;
    }

    function form_example_validate($form, &$form_state) {

    }
    function form_example_submit($form, &$form_state) {

    }

b) Validate and submit the form

Now the form is ready to be displayed.

One way to display the form, is to theme the form in the module and then print the form.

function mytheme_theme($existing, $type, $theme, $path) {
   'theme_contact_form' => array (
        'variables' => array(
            'contact_form' => FALSE,
            ),
        'template' =>'theme-contact-form',
    ),
 }
function mytheme_block_info() {
   $blocks['block_contact_form'] = array(
      'info' => t('My Theme Contact form'),
      );
   return $blocks;
}
function mytheme_block_view($delta = '') {
  $block = array();
  switch ($delta) {
  case 'block_contact_form':
        $block['content'] = array(
            '#theme' => 'theme_contact_form',
            '#contact_form' => drupal_get_form('form_example'),
            );
        break;
  }
  return $block;
}

Then create theme-contact-form.tpl.php in the module file and print the form:

<?php print render($contact_form); ?>

With all previous steps complpeted, the form is created and implemented in the module.

Step 2: style the form

To style the form from theme layer, refer to How to a use a template file to theme a form?


How to send variable value in POST Method in Drupal

It would just be a standard form with post as the method.

<form method="post" action="/other-page">
  <input type="text" name="yourfield" value="Value">
  <input type="submit" value="Submit">
</form>


Why my button element don't trigger the submitForm method?

Your first "submit" button doesn't get recognized by Drupal as a button because you use an inline template.

If you want to add a class on your button use:

$form['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes'=> ['class'=>['glyphicon', 'glyphicon-search']],
];


Single value "db_query": How to SELECT value that related to the node

You should not use direct queries to the database tables used for fields, for the simple fact the fields could not use database tables to store their value; this is what happens by default, but if a different storage implementation is exposed by a module, the information will be saved in another place. That is actually what happens with the Mongodb module.

If you know the node ID, and you want to get the value of a field associated to it, you can use the following code.

$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');

$values is an array whose structure depends from the field. It contains at least an item, but the exact number depends from how many values the field can have. (It is normally set in the setting page for the field.)
To see the structure of that array, you should install the Devel module, and use test code similar to the following one.

$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');
dsm($values);

For example, the first screenshot shows the structure used for a node body, while the second one shows the structure used for an image field.

If you need to find all the nodes of a specific content type, and filter out the list basing on the value set for a field, you should use the EntityFieldQuery class, as in the following code.

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'yearly_rent')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_subscription_period', 'value', $minimum_value, '>')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

addMetaData('account', user_load(1)) is necessary because the EntityFieldQuery class respects the access permission associated with fields; if the current user doesn't have access to the field, fieldCondition() would fail.
Once you have the node object, you can use field_get_items(). If you want to obtain a value to render, you should call field_view_field().


Use a form to filter table data in a module

It sounds like your problem is about passing the selected value to your page rendering function, upon form submission.  There are a few different ways to pass that value from within the form_submit function, including via a URL argument, or setting a cookie, or using some javascript to post the value - or even using variable_set() in the right circumstances. There might be easier better ways than those, and I'd like to know what they are if they exist.

Here's a way to do it via a URL argument:

In the form_submit() function, pass the select data to the page rendering function via drupal_goto().  Eg: drupal_goto( 'this/page/' . $form_state['values']['city']
Be sure that your page rendering function can accept the right argument.
in your hook_menu:
'page arguments' => array( 2 ),
(or you can just grab the argument using arg( 2 ) from within the page rendering function)

I'm not saying this is necessarily the best way to get the job done, but this should work.


How to make taxonomy term checkbox display multicolumn?

You can accomplish this using CSS, specifically flexbox. The exact element you need to target with your CSS rules will depend on your theme. You will need to add the following CSS to the element that contains your checkbox items.

.container {
  display:flex;
  flex-direction: column;
  flex-wrap: wrap;
  height:20vh; /* You will need to set a height on the container
                  to get the look you want, this is an example height */
}

In my example, I'm using Drupal 8 and the Seven administration theme. On an add/edit node page, I have a taxonomy field (the default tags) using  checkboxes. You can see in the below image that each checkbox element is wrapped in a div and all of those divs are wrapped in a container div with the id edit-field-tags. So, if I apply the above CSS to that container, I get the results that match your goal:

You may want to play around with the alignment or spacing of the flex elements, for more information on that that I recommend checking out "A Complete Guide to Flexbox" on CSS Tricks.


php include inside .tpl.php template file

Its better to modify the shared template inside hook_theme and use Drupal theme engine:

<?php print theme('your_shared_template_file', $args); ?>