How to create complex conditional clauses / queries?

Actually your final method is a right way, however the condition function is expecting 2 or 3 arguments(else only one DatabaseCondition instance as Molot said) and if you're not passing DatabaseCondition instance then your first argument should be the table column name. But you're passing an Array as the first argument. That's why you got unknown column 'Array' error.

So you should revise it like below,

$db_and = db_and();
$db_and->condition('my_field', array(0, 100), 'BETWEEN');
$db_and->condition('my_field', array(23, 48, 97), 'NOT IN');
$db_or = db_or();
$db_or->condition('my_field', array(107, 123, 126, 128), 'IN');
$db_or->condition($db_and);
$query->condition($db_or);

Further note your second approach is also right, however you put a extra -> before calling the db_or() function. So you should write it in the following way,

$query->condition(db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN')));


I think your easiest approach would be to modify the field template and add a wrapping span with classes you need.

field--field-name.html.twig:

{% for item in items %}
  {{ item.content }}
{% endfor %}

or replace span and content with to add class directly to  tag:

{{ item.content['#title'] }}


Feeds with multiple Entity References per node?

To my knowledge the solution you are looking for is not available directly through published modules.

You can find the beginning of the answering you are looking for at

http://clikfocus.com/blog/drupal-developer-tip-multiple-entity-references-using-feeds-importer

Create a custom target callback for your field importer. The targets array is keyed by the name of the target so it is necessary to differentiate your custom handler from the standard field handler for that entity reference field.

function my_module_feeds_processor_targets_alter() {

  foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {
    $info = field_info_field($name);

    if ($info['type'] == 'entityreference') {
      $targets[$name .':custom_handler'] = array (link is external)(
        'name'        => check_plain($instance['label'] .t(' (Import multiple values into multi-instance field')),
        'callback'    => 'my_module_set_target_entity_reference',
        'description' => t(''),
      );
    }
  }
}


How can I create a menu item corresponding to a link to another (external) site?

You are not allowed to add external link to menu items as this link confirms it too.


My piece of working code:

$time_intervals = array(30, 3600, 10800, 21600, 43200, 86400, 172800, 259200, 604800, 1209600, 2592000, 5184000, 7776000);

$options = $this->build_options($time_intervals);

Also i have defined following function in the same class:

function build_options(array $time_intervals, $granularity = 2, $langcode = NULL) {
  $callback = function ($value) use ($granularity, $langcode) {
    return \Drupal::service('date.formatter')->formatInterval($value, $granularity, $langcode);
  };

  return array_combine($time_intervals, array_map($callback, $time_intervals));
}


Style views row layout debending on result count

You could implement hook_views_pre_render and count the number of results, then apply a class to the wrapper element.

function hook_views_pre_render(&$view) {
  switch($view->name) {
    case 'MY_VIEW_NAME':
      switch($view->current_display) {
        case 'MY_DISPLAY_ID':

          $numResults = count($view->result);

          /*
            Do your logic with $numResults here
          */
          if ($numResults <= 4) {
            $grid = 2;
          }
          else {
            $grid = 3;
          }

          $view->style_plugin->options['class'] = (isset($view->style_plugin->options['class'])) ? $view->style_plugin->options['class'] . ' grid-' . $grid : 'grid-' . $grid;

          break;
      }
      break;
  }
}

So then you can style the width of the views-row under grid-2 to be 50%, and 33% width for views-row under grid-3 in your CSS.

Your View display needs to use "HTML List" format for this code to work.


How to download files which are stored in the folder

Make the link point to the PDF file
Make sure that the PDF is public accessible.


Views - Change view based on number of results

The only way I can think to do this will require some views, and a little code:

Build view that gets the list of nodes as Node IDs (nids) for a given taxonomy term.
Then build a view that gets your nodes and has filters as needed. It should take multiple, comma separated nids as an argument.

a: Add a display (block, pane, whatever type you need) that shows nodes in full, but limit it to one row.
b: Add another display that handles the list version.

With these building blocks you can call the appropriate Views display using some code. You can write this and either put it in in your own module, custom theme or simply add PHP snippet into a node or custom Panel pane.

The pseudocode looks like this:

call the first view and get the result with $result = views_get_view_result()
count() how many rows are returned in $results, set $single_result = TRUE accordingly.
take the $results array and turn it in to a comma-separated string of nids with implode(',', $result)
If there's a $single_result then embed the view display for a single full node in the page and pass it $results as an argument, like so: views_embed_view('your_view_name, 'your_full_view_display_name', $results)
If there's not a $single_result then embed the view display for multiple entries, with $results passed to it.

The above has most of the core functions you'll need... I'll leave it to you to turn this into proper code!


can i register using same email id for a 3 different profile types

You may need Shared Email module for this. It allows multiple email accounts with same email address.


Make sure you are not using user 1, because you can't cancel user 1.
Clear caches after changing permissions.

Update:
Check for any modules you have which may affect Permissions.
In this case Administer Users by Role may be lacking some permissions that you need to set.


Is it safe to apply last update when a module has several updates available?

Installing the latest version straight off should be fine in most cases.**

If the module updates only contain minor code changes then there's almost certainly nothing to worry about.

If the module updates contain more major changes such as alterations to the database schema then the module maintainer should be using the hook_update_N() function in a "module_name.install" file which will allow Drupal to determine which updates fall between your currently installed version and the latest version, and apply the necessary modifications in sequence, meaning no breakage should occur. Drupal core is no different to any other module in this respect, so you should also be able to update to the latest core version without any problem.

**If the module has seen a major version increase, for example, you have 6.x-1.7 installed and the latest version is 6.x-3.2, then you should check the module's project page and documentation for any compatibility notes or special instructions for updating. In some cases the versions may not be compatible and would need to be manually migrated, or some dependency may have changed, which the module maintainer should inform you about somewhere.

The only other problem I can think of is the unlikely situation where an API change has occurred in Drupal core at some point and one of your modules was abandoned and never updated to take account of the API change. In that case, you may need to find a patch in the module's issue queue, disable the module, or find an alternative module.

Also, this may be stating the obvious, but if your site is running on Drupal 6, you won't be able to install any module updates with version numbers beginning 7.x- because those are for Drupal 7 and won't be backwards compatible. You'll have to stick to the latest 6.x- version.

Having said all that, you should always carry out a test run of the update process in a testing environment before you go anywhere near the production server. Make sure to clone the live database and all the Drupal files from your production server to your test environment so that you can safely determine exactly what effects the updates will have.


Error uploading file. An unrecoverable error occurred

This error is for this line in file.module
241 --if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {

You should revise your URL


Update webform field value using AJAX realtime

add wrapper to your text field which you want to update.

 function fence_quote_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'webform_client_form_1'){
    $form['buttons']['fence_quote']  = array(
      '#type' => 'button',
      '#value' => t('Get online estimates'),
      '#ajax' => array(
          'callback' => 'fence_quote_form_callback',
          'wrapper' => 'changeText',
      ),
    );
    /* Please add Wrapper to text_field */
    $form['wrapper']['your_textfield_name']['#prefix'] = '
';
    $form['wrapper']['your_textfield_name']['#sufix'] = '
';
  }

}

function fence_quote_form_callback($form, &$form_state) {
     $form_state['values']['meters']['und'][0]['value'] = '111';
     return $form['wrapper'];
 }


How to implement global messaging system in drupal for multiple sites?

The nice thing in the "Drupal Remote Dashboard" module that you can run cron on your sites, so I would suggest that you build a custom messaging module that pull messages from master site (using cron to fire that).
- you can use services module to push your messages out


Tracking multiple items in a Commerce order individually

Since line items are fieldable, why not consider adding a field to the line item type and either switching to the Inline Entity Form for line item management on the order edit page or else creating a custom interface (Views + editablefields?) for manipulating the value of those fields?

That's what I'm going to be doing on a friend's site to track related eBay listings.


User Relationships view showing the right number of users, but showing my profile link, not theirs

Fixed it. I was using the requestee fields when I should have been using the requester fields. What was:

Should have been:

Problem solved.


You can create template file with name block--section_contact.tpl.php, put there code from default block.tpl.php file, replace h2 tag by h4 and all blocks in section_contact region will have h4 heading.


Drupal's Alias is what your looking for

<?php
$path = drupal_get_path_alias($_GET['q']);
if ($path == 'the/path') {
  // do stuff
}
?>

Others Below:

Full URL

<?php
global $base_root;
$base_root . request_uri()
?>

Drupal's "Internal" URL

<?php
$arg = arg();
// Path of 'node/234' -> $arg[0] == 'node' && $arg[1] == 234
?>


You need to use a preprocess function.  Take a look at template_preprocess_block().  In your template.php you can use:

function YOURTHEME_preprocess_block(&$variables) {
  $variables['sub_count'] = db_query("SELECT count FROM {sub_count}")->fetchField();
}

and can print into the .tpl.php file as you did above.

A few good articles to learn more about preprocess functions are

About overriding themable output
Setting up variables for use in a template (preprocess and process functions)

As a basic overview of preprocess functions, from the second article:

  Preprocess functions only apply to theming hooks implemented as
  templates. The main role of the preprocessor is to set up variables to
  be placed within the template (.tpl.php) files. Plain theme functions
  do not interact with preprocessors.

  Notes:

  Preprocessors are also used for providing template suggestions.
  In versions 5 and below, the function _phptemplate_variables served the
  same purpose. It has been deprecated in 6.
  Prior to Drupal 6.7, for your theme to have its preprocessors recognized, the template
  associated with the hook had to exist inside the theme. When a default
  template exists, copy it to your theme and clear the registry (or you
  should really be upgrading to a later version of Drupal anyway for
  security reasons, at which point you don't have to worry about this).


How can I add Google Tag Manager's code to my website?

There is an officially released module (since early 2014): GoogleTagManager.

  Allow the non-technical stakeholders to manage the analytics for their website using the Google Tag Manager (GTM). This module allows you to trigger the insertion of tags and tracking systems onto the pages of the site.


How to set access permission to roles due to the content's vocabulary

Have you tried these Drupal modules (quotes included are from their project pages):

Taxonomy Access Control:

Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.

ACL:

The ACL module, short for Access Control Lists, is an API for other modules to create lists of users and give them access to nodes. It has no UI of its own and will not do anything by itself; install this module only if some other module tells you to.


I think what you are talking about is the concept of product variations introduced by Commerce Kickstart 2.0.  Product variations allow you to group together commerce products based on choices like size and color and price.  So for example say you create a Product Variation Type called T-Shirt.   You can group together the different sizes.

There are a few ways to get this done.  You can install Commerce Kickstart 2 and follow their tutorials.

You can install their stand alone module called commerce_backoffice and its dependencies.  I recommend the book Getting Started With Drupal Commerce by Richard Jones for an explanation of how to use back office.

As a note, I started out trying to get all of the functionality I wanted from the stand alone, but found that it was better to use Commerce Kickstart 2.0


Changing group visibility needs group content to be resaved when group content visibility field is set to "Use group defaults"

Reason. I assume you see this behavior because all the node permissions are cached in Drupal, and only updated when (re-)saving a node or rebuilding the permissions.

Workaround. So instead of re-saving all nodes of your group individually, a faster workaround would be to go to admin/reports/status/rebuild and rebuild all permissions at once. This would probably also be the place to hook into for a real bugfix: rebuilding of the group nodes permissions, triggered when saving the group node with a different value in the "Group visibility" field.

(This answer is an educated guess, I didn't test myself so far.)

Redesign discussion. A still better solution would however be a larger rework of the OG permissions system, as discussed in Drupal issue #1122388. See esp. comment #10 there, discussing that the "Group content visibility: use group defaults" value is not that meaningful as it prohibits a use case where one wants the group itself publicly visible, but have its content default to private, and setting that via a fallback to the group setting so that later changes are simple. This scenario (publicly visible group node with private group content nodes) is supported by newer versions of Drupal Commons 7.x-3.x (using OG 7.x-2.7 here), but changing the setting only affects group content nodes added afterwards. So it's not the "fallback to group provided default" we want here, even though the "Group content visibility" field has "use group defaults" as its default value (which is not used though). That could be reported as a bug / improvement request to Drupal Commons.


If you're looking for a relatively simple option, Entity Reference is probably best:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field Four widgets: Two implemented on top
  of the Options module (Select and Radios/Checkboxes), Two autocomplete
  widgets (one with one text field per entry, one tag-style with
  comma-separated entries in the same text field) Two formatters: A
  "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.) A "Rendered
  entity" formatter, that renders the references entity using a
  configurable view mode Integration with Views (for both forward and
  backward references) Integration with Entity Metadata (and as a
  consequence with Search API and the like) Integration with Devel
  generate Integration with Feeds and Migrate (>= 2.3) for painless data
  import

EDIT #1

To set up the view as described in comments:

Create the view for Employee Content Type, and make settings how you desire
Add a Relationship to Entity Reference: Referenced Entity for the entity reference field, Require this relationship

Now you have access to the fields in the referenced (position) content type and can display them in your view.  One thing of note, Title field may not work from Position, so you may have to include a separate field for the Position Title. Otherwise, everything should work as a normal view


Commerce currently does not work correctly with default_content. The commerce guys are looking into solutions for delivering default content.

AFAIK the next version of yaml_content is gonna be able to play nicely with commerce. However as of now, the module has no commands for exporting content, only for importing.

default_content - Question about architecture

yaml_content - Content Export Support


Since, there is no proper way, I opted for hack (or work around) to get this working. As already mentioned by @Clive, removing/disabling caching mechanism would require more work. This solution just skips the caching part.

Step1: Copy the entire misc/autocomplete.js to your module js scripts directory.

Step2: Comment or remove the following line from the copied file

// See if this key has been searched for before.
  //if (this.cache[searchString]) {
      // We dont want some things to be cached
    //return this.owner.found(this.cache[searchString]);
  //}

Step3: Implement hook_js_alter to override it to specific pages you like.

/**
 * Implements hook_js_alter
 * @param array $javascript
 */
function MYMODULE_js_alter(&$javascript) {
  if (arg(0) == 'MYPAGE') {
    $javascript['misc/autocomplete.js']['data'] = drupal_get_path('module', 'MYMODULE') . '/js/autocomplete.js';
  }
}


Give users a stripped down version of add node page and then require admin approval

You can assign permissions to fields, the content permissions module should give you what you want. Look in the permissions pages and you can see what rolls have access to which fields.

A simple way to set up the workflow you suggested is to set the default node status to unpublished (look under workflow settings on the edit content type page). Then make sure only your admin role has the administer nodes permission.


Check out the Views Filter Harmonizer module. It allows you to have a contextual filter argument apply only when there is no corresponding regular (exposed) filter value present.

Here is a quote about it (from its project page):

  Views Filter Harmonizer solves an operational foible with the Views
  module regarding filtering.
  Normally, when a Views field has been assigned both an exposed filter
  and a contextual filter, then both filters get applied to the View's
  results set -- always. This is not configurable behaviour. It's
  hard-coded.

  As a consequence, contradictory search clauses easily occur, causing a
  counter-intuitive user experience with some White Screens of
  Disillusionment. Since the contextual filter sets the "bounds" for the
  page, any filtering by the visitor through the exposed filter on that
  page can only narrow down the results set, not broaden it. In other
  words the exposed filter appears not to be working properly.

  This small module allows you to have a contextual filter argument
  apply only when there is no corresponding regular (exposed) filter
  value present.

  This is most common on initial page load. After that the contextual
  filters will silently retreat and let the exposed filter values as
  selected by the visitor do their thing without interfering.

  This means that you can take advantage of friendly URLs using
  contextual arguments instead of ugly and verbose query parameters. Put
  the URLs anywhere on your site, in emails and in newsletters to take
  visitors to tailored Views pages. Having arrived there, visitors may
  then further filter these pages to their heart's content using the
  View's regular filters you exposed. And they won't experience any odd
  behaviour.


javasript invoking custom module to update user response

So, lets start from the top.

You have a table with userid, nodeid, responseid declared in a hook_schema. This will create the table.

Then, you declare with hook_menu a callback to capture incorrect values and db_insert them into the table.

Then, on the form page with the multiple choice, you extend the behaviour that if the answer is incorrect upon click, it makes an ajax request with the item selected and the node id to the callback, and the callback will determine the user from the current user session, and store it in the table.

So for the content type, you will probably have a multifield for the potential answers, and a single field with the relative id for the correct answer. So if the content creator creates five answers, and the first item is the correct item, a hook form alter will need to extract and #attach the correct answer so that the behaviour on the page can pick it up, use it to determine which of the items is the correct one, extract the field id of the incorrect items and then ping it to the server.


How to access library version details in JavaScript

Library definitions can be accessed via the library.discovery service (LibraryDiscovery).

$libraryDiscovery = \Drupal::get('library.discovery');
// Where mytheme is the name of your theme.
$definition = $libraryDiscovery->getLibraryByName('mytheme/global');

Then you would need to pull out $definition['version'] into a JavaScript settings or do something with it in your theme.


Adding ajax to text field in node edit form

You don't need ajax, you can do this with jQuery or javascript. Something like this might work.

First, create an external js file and set up your change events.

jQuery(document).ready(
    function()
    {
        jQuery("#field2").change(subtract_fields);
        jQuery("#field1").change(subtract_fields);

        function subtract_fields()
        {
            if (jQuery("#field1").value != "" && jQuery("#field2").value != "")
            {
                return jQuery("#field1").value - jQuery("#field2").value;
            }

            return "";
        }
    }
);

Next, load the external js file using drupal_add_js.

Clear your cache and voila.


Why is an empty field on translated taxonomy term showing default language value?

You may get it to work by using the Internationalizations Views module, which extends the i18n module with multilingual support for Views.

To make Views results correspond to the language switcher, add a filter for Content Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the User's Current Language is available in the filter criteria form, then verify your configuration at Configuration -> Languages -> detection and selection: The order should be URL, Default, User and not something like Default, URL, User (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

Note: True, the Internationalizations Views module only has a DEV / Alfa version for D7, but right now there are over 37K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because +37K users can't be wrong, right?


How to automatically capture images from URLs?

Check out Opengraph filter module

  When you post a link on facebook, you get a little summary of that
  site under your comment or post (with or without thumbnail). This
  works with OpenGraph metatags. Basicly Facebook scrapes the content of
  the url and makes a nice little summary.


Page title not displayed at the top of the Content area

According to your node.tpl.php, if the node is viewed in teaser mode, that $title variable will be output. (if (!$page):)

For the node view in full page mode (if ($page == TRUE):) then you need to have print $title in your theme page.tpl.php

i.e:

  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h1 class="title" id="page-title">
      <?php print $title; ?>
    </h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>


Installing the 7.x-2.x-dev version of jquery allowed me to select version 1.5 of jquery for administrative pages and solves my problems.


Programmatically embed fields of one content type in the create/edit form of another content type and store all

I think it would be tricky as you would need a way of tracking a relationship between the two nodes as well. You would need to decide on which way the relationship would go if you were to use node reference as its only one way in drupal 6.

This is what I would do
1. Add a node reference field to Y
2. Use hook_form_alter to add the required fields (Embedding cck fields will be tricky better of just sticking to fapi fields)
3. add a custom validation handler for the x fields if required
3. Save x field values as a node programticaly when presave is triggered by hook_node_api http://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook_nodeapi/6
4. Update the noderefrence in Y with the new X nid
5. Use hook_node_api to update X when Y is updated

Another possibility might be to use Rules to create and update for you


How to migrate Drupal Commerce configuration between environments

Commerce Features has helped me in the past.

Apart from that, you're looking at update hooks (or possibly the Configuration Management module).


display a node in the sidebar region of another node

You could in your template file just render the comment section in your sidebar.


Why does nothing change when I attempt to restore a backup?

This sounds like a bug of Backup and Migrate module, since file_directory_path() no longer exists in Drupal 7.

So instead of file_directory_path() you should use:

file_stream_wrapper_get_instance_by_scheme(file_default_scheme())->getDirectoryPath()

or:

variable_get('file_public_path', conf_path() . '/files')

So please upgrade your module to development version (but it's not fixed yet at time of writing) or use this patch available at: #2618516 - Fatal error when restoring "Entire Site" which goes like:

--- a/includes/sources.archivesource.inc
+++ b/includes/sources.archivesource.inc
@@ -208,7 +208,7 @@ class backup_migrate_files_destination_archivesource extends backup_migrate_dest

       // Move the files from the temp directory.
       if ($filepath && file_exists($filepath)) {
-        _backup_migrate_move_files($filepath, file_directory_path());
+        _backup_migrate_move_files($filepath, variable_get('file_public_path', conf_path() . '/files') );
       }


How do priorities work in the *.services.yml YAML file?

Drupal uses the EventDispatcher from Symfony and there the priority is used to control in which order the event listeners are triggered:

  An optional priority integer (higher equals more important and
  therefore that the listener will be triggered earlier) that determines
  when a listener is triggered versus other listeners (defaults to 0).
  If two listeners have the same priority, they are executed in the
  order that they were added to the dispatcher.

So the priority in D8 is exactly the opposite of the weight in D7.

The example you used in the question is not an event subscriber, but it uses the same concept of priorities.


template preprocess override not respected

Try the following...

function THEME_preprocess_views_exposed_form(&$vars, $hook)
{
        if ($vars['form']['#id'] == 'FORM_ID')
        {
              // blah blah
        }
}

This way you shouldnt override the core stuff, thus not affecting your code either.


Take a look at Packaging a distribution on Drupal.org

Here are the steps:

Assemble the pre-requisites
Create a Drush Make file
Convert to a Drupal.org-specific Drush Make file
Build and verify it works
Commit your code to Git
Release your code on Drupal.org
Maintain your distribution

Another great tutorial How to Write a Drupal 7 Installation Profile

Also there is Profiler Builder module.

  Profiler Builder is a module for automating the creation of
  installation profiles and distributions. It has support for the
  Profiler installation profile simplifier library but is able to run
  independent of it (1.0-RC4+). This module creates a downloadable tar
  package that gives you a well made installation profile and associated
  drush make file based on the site its installed on.


Use PHP's date() function.

Example:

echo date('m/d/Y', 1299446702);

Check Unix Timestamp Conversion Tools online


Sounds like a job for the Taxonomy Views Integrator module. It allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice.


You can override the set media queries in your custom css or less files. For the menu, you need to change at least two classes like so:

To hide the menu in a wider breakpoint (> 768)

@media (max-width: 900px){
  .navbar-toggle {
    display: none;
  }
  .navbar-collapse.collapse {
    display: block;
  }
}

To hide the menu in a smaller breakpoint (< 768) you have to override everything from your breakpoint up to 768:

@media (min-width: 480px) and (max-width: 768px){
  .navbar-toggle {
    display: none;
  }
  .navbar-collapse.collapse {
    display: block;
  }
}


How to make rendered product variations show in a grid rather than a list?

You can quite easily create a View display to list your products in a grid.

Add a new View ( Admin > Structure > Views )
Add a page display
Add relevant filters for entity type etc..
Set the style to "Grid" layout
Tinker from there with fields etc..

That should do it.


If you using D7 and not D8, take a look at page_title module. I just googled it for you.

  The word "title" is a bit overloaded. Every piece of content in Drupal
  has a title, and so does every page. The page title is the one found
  in the HTML head inside the  tag. It is also used on SERPs
  (Search Engine Result Pages) and can greatly enhance your websites SEO
  (Search Engine Optimization).

  This module gives you granular control over the page title. You can
  specify patterns for how the title should be structured and, on
  content creation pages, specify the page title separately to the
  content's title.


Automating module activation during installation of Drupal

You can create a custom installation profile

  Installation profiles combine core Drupal, contributed modules, themes, and pre-defined configuration into one download. Installation profiles provide specific site features and functions for a specific purpose or type of site. They make it possible to quickly set up a complex, use-specific site in fewer steps than if installing and configuring elements individually.

See How to write a Drupal 7 installation profile and the Install profile API for more info.


Is there a way to access the full list of results in a Solr search page?

Yes and no. In any sane situation, it is the solr server that is handling the pagination. In essence, the server receives parameters, rows and start that tell it which "page" it will send.

You could write custom code that would get you all the rows but that would require at keast one more query to the solr server. The first query (the default one) would find out how many results there are in total; the second one would fetch the whole set, setting rows to the total amount and start to 0.


Can I use Node Reference Field as a Text Field if there are no references?

Use the Node Reference Create module.

  Node Reference Create is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.

  When no matching node is selected, the new nodes are automatically created allowing for a seamless and intuitive user experience that is similar to free tagging.


I understood the problem. It is because the first time it sets the cookie, and in the second time it becomes available to PHP; hence two refreshes.


Restore hacked website from database without source

You can set status to '0' in table 'system' for missing modules
P. S. 'drush cc all' is a must-run command after the manipulation like this or manually empty cache tables


Access from different Network, one allow admin roles the other not

Ok so the best solution I found wich might even work with a cache engine and without altering core was to remove the roles from the global $user in a hook_boot() :

function myModule_boot() {
  global $user;

  // if the user is connected and I am on network B
  if ($user->uid != 0 && variable_get('networkB', FALSE)) {
    // then we remove the role BO from the global $user
    // wich are stocked in a variable (roles_back_office) as a string (rid separated by pipes).
    foreach(explode('|', variable_get('roles_back_office')) as $rid) {
      if (isset($user->roles[$rid])) unset($user->roles[$rid]);
    }
  }
}


Updating a module via backend or manually didn't work. No drush available. What else can I try?

Have you flushed your caches? Sometimes you will see old data, even in regard to modules because of cache issues.


Total number of nodes based on content type

In your views, section "OTHER", use aggregation.

It will provide you with options like COUNT in your views fields. You then can simply use the nid field, with a content type filter, and then display the count of the nodes.


Unable to uninstall the Field Collection module

I guess you solved this already, but if somebody else stumbels over this, here my 5 cent on how to get rid of field collection. I encountered the same issue as @nitnac23 and was only able to get it out via direct data base manipulation:

definitely make a DB backup this time (might save your website)
Remove all field collection fields from your entities
run the cron potentially multiple times (this cleanes up the entities - fingers_crossed)
it is important, that you no longer have fields pending deletion as a reason for not beeing able to dissable fields collection (under /admin/modules/uninstall/) - if you still have it, try running the cron again (more infos here)
clear the contents of the database tables field_collection_item and field_collection_item_revision directly in the database
uninstall field collections now via /admin/modules/uninstall/
if you have still field_deleted_* tables in your DB, drop them (I had 12 before runing the cron and still 2 after unsintsalling the module)

That should do it hopefully :)


load balancing multiple horizontal drupal instances

Having multiple webservers behind a load balancer/reverse proxy is quite common for Drupal and well supported. Varnish is typically used in the Linux world because that thing is just insanely fast when being able to actually use it, meaning anonymous visitors. Which is obviously not the case for your site.

Sessions are stored in the database by default, so that's not a problem. The only other thing that needs to be shared across all servers is the public files directory and any other like the private files if you're using something like that). In most cases, a shared/distributed file system like NFS is used for this although there are some more advanced approaches. On one site where I'm involved is the file system provided by yet another server that is an NFS-mount on the Drupal servers (so access there is slow) and is being distributed under a different domain by Lighthttpd. But again, that is probably not so relevant for you as you're not going to server lots of images and css files, I guess.

As mentioned by rocketeerbkw, there are cache backends for Memcache, Redis and others. So far, Ive only used Memcache but I recently started to look into Redis and it looks very promising but I'm not sure if it is available for Windows. However, it would be possible to set up a separate Linux server to be used for the cache. Drupal 7 relies heavily on caches, being able to get them off the database is very important for two reasons:

Tools like Redis and Memcache are designed for fast key based lookups and they keep their data always in memory to make the lookup as fast as possible. They have also built in support for automatically cleaning up old cache data if the configured limit gets closer.
Maybe even more important, it helps to get database load down. Once you have the basic setup in place, adding additional webservers is easy. Once you start reaching the limits of a single database server, things get much more complicated and you need to look into things like master/master replication (Drupal 7 doesn't really gain much from master/slave environments).

So, it's basically just your own API that you need to take care of. If possibly, you need to make sure that everything is always available from all servers. You can use either the databse, the file system or something else (Drupal can also use MongoDB to store certain data, e.g. fields). If that is not an option, then you will need to use sticky sessions so that users always end up on the same instance. You should however really try to avoid that because if one of the server fails then all users which were on that server need to re-connect to another server, possibly losing data.


How do I use Hook_update_N to update an FieldConfigStorage?

FieldConfigStorage::load() isn't static, so you can't use it statically.

Get an instance of FieldConfigStorage instead, and use that

if ($storage->load('image_byline')) {
  // ...
}


You can test a user's status very early with event subscriber in a custom module that subscribes to KernelEvents::REQUEST.

First, you register the event subscriber in mymodule.services.yml in your module folder:

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\RedirectAnonymousSubscriber
    arguments: []
    tags:
      - {name: event_subscriber}

Then add RedirectAnonymousSubscriber.php  for your custom event subscriber in your module in the /src/EventSubscriber/ folder.

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {

    if ($this->account->isAnonymous() && \Drupal::routeMatch()->getRouteName() != 'user.login') {

      // add logic to check other routes you want available to anonymous users,
      // otherwise, redirect to login page.
      $route_name = \Drupal::routeMatch()->getRouteName();
      if (strpos($route_name, 'view') === 0 && strpos($route_name, 'rest_') !== FALSE) {
        return;
      }

      $response = new RedirectResponse('/user/login', 301);
      $event->setResponse($response);
      $event->stopPropagation();
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkAuthStatus');
    return $events;
  }

}


Why isn't my custom form element theme function being called?

OK, so you need several things combined in order for this to work:

#theme => unique_name_for_theme_function on the form element.
In your template.php mytemplate_theme() function you need to return an array something like: array( 'unique_name_for_theme_function' => array('function') => 'myfunc') );. This was the bit I was missing.
Then in your template.php you need to add a myfunc. I found it easiest to just google "Drupal theme_form_element", "Drupal theme_checkboxes" or whatever, and then copy paste the code I found in to a mytemplate_theme_checkboxes function which I then modified to suit my needs.
Then you need to flush cache for Drupal to find your theme function.


Where is links__system_main_menu defined?

Drupal 7 core doesn't actually define this function.

links__system_main_menu is a theme hook pattern of the form [base hook]__[context]. When links are themed with theme('links__system_main_menu', $vars), theme() will search for and use theme_links__system_main_menu() if it has been defined. If not, it will use theme_links().

See theme() for the official documentation of this behavior. Chapter 3 of Drupal 7 Module Development does an excellent job of explaining this and provides several examples.

BTW, the same principle applies to template files. If, for example, we call theme('node__article__1', $vars), theme() will search for a node--article--1.tpl.php file, and then for node--article.tpl.php, finally falling back to node.tpl.php if neither of them are defined.


You could use views to create a list of all the nodes on the site and make sure the role has access to see it. This is by far the simplest and quickest way of implementing such a feature.

A more complex way would be to alter the menu link and change it's access control but I wouldn't recommend doing this.


Display a node form in default theme for admin

There is a hook that you can use to set which pages use the admin theme and which don't.

The hook is hook_admin_paths().

The node module uses this hook to provide the functionaity where you can set node forms to use the admin theme (see node_admin_paths()).

If you wanted to set certain paths to use the admin them (or not use it) you could implement that hook, however if you want to change admin paths that another module has already defined you need to use hook_admin_paths_alter().

In this case the node module defines a wild card path for all node add pages like this 'node/add/*' => TRUE

Since you only care about a specific node type you can ignore that and do this:

/**
 * Implements hook_admin_paths().
 */
function MODULENAME_admin_paths() {
  // We have configured the site to use the admin theme for node forms
  // however we want the article content type to use the default theme
  // instead of the admin theme.
  $paths = array(
    'node/add/article' => FALSE,
  );
  return $paths;
}

As you can see in path_is_admin(), where the check is done to see if the current page is an admin page, for a page to be an admin page it must have a matching path that is TRUE and also not have one that is FALSE.
So by adding this FALSE in for this specific page you are overriding the wildcard node/add/* from the node module.

The problem that you then have is the node edit page (if you also want that to use the same theme as the node add form), because the URL for the node edit page has nothing in it that relates to the content type so you can't override node edit pages based on their type.

You could get the node IDs of all nodes of your specific type and add each individual node edit path however if you have a large number of nodes that is not going to be ideal.


Does a guide for installation of drupal Cartaro distribution exist?

Have a look at Cartaro's Getting Started guide. Especially see the quoted commands to set up permissions for PostGIS properly.

Additionally, there have been changes to the error reporting of Cartaro in July which should result in more precise error messages in case something is wrong with PostGIS.

Please report any bugs in Cartaro using its bug tracker on the Drupal site so that is does not get overlooked. We'd be happy to see a report there regarding the GeoServer terminology along with a more verbose description.


Composer generated installation can't be completely cloned

This is perfectly explain on https://getcomposer.org/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md

In short, that's because git kind of treats folders with a .git as submodules.

The composer.lock file exists to be able to re-install an exact copy with the same commits of dependencies and so on. Or another option is building .tar.gz, containers or similar packages that can be used for efficient deployments.


How to change the redirect URL of a form that's already been set in a module?

You should be able to achieve this by adding your own submit function to the end of the submit handler array and overriding $form_state['#redirect'] there. Example code:

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

function mymodule_node_gallery_custom_submission(&$form, &$form_state) {
  $form_state['redirect'] = 'my_url';
}


How to migrate users from one website to another website?

Users Export to export the user from your Kickstart and User Import to your new website.

For the future you should use consider using something similar to Deploy or Configuration Management so you can keep track from your changes.


How can I make or render a website with wiki features(for e.g wikipedia) with Drupal?

To allow contributors to easily link between multiple pages, check out the Freelinking module.

To enable simple plain-text formatting, check out the Markdown module.

To allow editing subsections of text individually, check out the Edit Section module.

To automatically generate a Table of Contents for each node, check out the Table of Contents module.

To move comments to a separate page (similar to the Wikipedia "Talk" pages), check out the Talk module.


Redirect to a Multi-site Install Failing

From the looks of your folder structure you're missing the most important file for a multisite install...sites.php.

Copy example.sites.php to sites.php, edit it to add all sites in the installation to their respective paths, and try again...it should work.

These are the code samples example.sites.php for convenience:

// URL: http://dev.drupal.org
$sites['dev.drupal.org'] = 'example.com';

// URL: http://localhost/example
$sites['localhost.example'] = 'example.com';

// URL: http://localhost:8080/example
$sites['8080.localhost.example'] = 'example.com';

// URL: http://www.drupal.org:8080/mysite/test/
$sites['8080.www.drupal.org.mysite.test'] = 'example.com';

The format is:

'<port>.<domain>.<path>' => 'directory'


How do I disable cache in my entityQuery?

You'll need to make this an un-cachable block and place it on your template file, otherwise, you would have to turn off page caching.

But unless this is the only thing on that page, and there isn't something else in here worth caching, then you could alternately turn off caching for this specific page(s).


Most appropriate simple IP direct for Drupal 7

All of the modules you have listed only provide APIs, choose one for which you need least maintanence. For geoIp you need to keep updating County List DAT file manually once in 3~4 months, I am not sure about others. Once you choose your module you have to write logic for your scenario, something like this

$cc = geoip_country_code();
if($cc == "AU"){
  drupal_goto(MY_AUSTRALIAN_SITE_URL);
}

You can use page--front.tpl.php or make use of drupal_is_front_page() in page.tpl.php to write your own logic.


Pass variables from controller to existing node template file

I believe that node--custom_content_type.html.twig is referring to template overriding.  In template overriding, you are still using the default theme with it's defined variables.  If you are generating the render block in your controller, you can set the variables defined in the default theme. These are generally listed in the default template.

An alternative to passing variables into templates is to use the specific theme preprocess hook.

Finally, if you set up your local site to deal with debugging twig, you will see information about the template and available hooks for various parts of the output.  See the docs for how to set this up.


Module, no. At least none I know about. You can, however, add text field for css rules and output it inside style tag in your template. Would require some clever javascript to show it in realtime during edit, but should be possible without to much hacking.


How can I override the HTML of options on the user edit page so that they do not appear as collapsible fieldsets?

The easier way is to set the #collapsible property to FALSE.
As far as I know, when #collapsible is set to FALSE, #collapsed is not used anymore, which means the fieldsets are shown as visible; if that is not the case, then set also #collapsed to FALSE.

Clearly, this works only for fieldsets; for other form fields, those properties are not used.

As side note, on Drupal 8 collapsible fieldsets are implemented using "details" as form field (at least from the Drupal core code); if you are going to loop through the elements of a form to check for which ones the property should be set, the code should be similar to the following one, for Drupal 8.

foreach (element_children($form) as $id) {
  if (!empty($form[$id]) && ($form[$id]['#type'] == 'details' || $form[$id]['#type'] == 'fieldset')) {
    $form[$id]['#collapsible'] = FALSE;
    $form[$id]['#collapsed'] = FALSE;
  }
}


Enable a node's menu item when on that node?

I will write a method that you can use by simply editing your theme's template.php file (without having to write your own module), and overriding

theme_link(),
theme_links(),
theme_site_map_menu_link(),
theme_superfish_build() AND
theme_menu_link()

functions. YES, that's correct, unfortunately for the correct markup, you have to override all of the above mentioned functions in your own theme, to avoid rendering empty
 elements in the default main menu, in the Superfish menu or the Site map module's own menu. I will assume you haven't already overridden them.
I tested it, so this code should be working, but please ask if you have any kind of questions.

First, please open your theme's template.php in a text editor of your choice.
Paste the whole code below into the opened template.php.

/**
 * Should this link be hidden?
 *
 * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
 *
 * @param string $link_path The path that should be inspected.
 * @return boolean
 */
function YOURTHEMENAME_link_should_be_hidden($link_path) {

    // in this example, I let "contact" and "node/9" links only be visible
    // on their own path (so for example, I let "contact" path be visible
    // in the menu if the user opened "example.com/contact").
    $your_paths_to_show_in_menu_only_on_their_own_path = array('contact', 'node/9'); // SUBSTITUTE IT with yours - empty cache every time you change that
    $is_link_to_hide = in_array($link_path, $your_paths_to_show_in_menu_only_on_their_own_path);
    if ($is_link_to_hide) {
        $is_current_page_self = ($link_path == $_GET['q']);
        // these links will be visible only on their own paths -
        // BUT here you can define other paths too where they can be visible at!
        // So for example, you want "example.com/node/9" to be visible when visiting its own path
        // AND when visiting "example.com/node/3" OR "example.com/any_other_path".
        // But if you do NOT want any other pages for these links to be visible at, then
        // just leave it empty (like this: array()).
        $link_also_visible_at_paths = array('node/3', 'any_other_path'); // SUBSTITUTE IT with your paths! - empty cache every time you change that
        $element_can_be_visible = $is_current_page_self || (!empty($link_also_visible_at_paths) && in_array($_GET['q'], $link_also_visible_at_paths));

        if (!$element_can_be_visible) {
            return TRUE;
        }
    }
    return FALSE;
}

/**
 * Overriding theme_menu_link()
 *
 * @see http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7
 */
function YOURTHEMENAME_menu_link(array $variables) {
    /**
     * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
     */
    if (YOURTHEMENAME_link_should_be_hidden($variables['element']['#href'])) {
        return '';
    }

    $element = $variables['element'];
    $sub_menu = '';

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    return '
' . $output . $sub_menu . "
\n";
}

/**
 * Helper function that builds the nested lists of a Superfish menu.
 * @see theme_superfish_build()
 */
function YOURTHEMENAME_superfish_build($variables) {

    $output = array('content' => '');
    $id = $variables['id'];
    $menu = $variables['menu'];
    $depth = $variables['depth'];
    $trail = $variables['trail'];
    // Keep $sfsettings untouched as we need to pass it to the child menus.
    $settings = $sfsettings = $variables['sfsettings'];
    $megamenu = $settings['megamenu'];
    $total_children = $parent_children = $single_children = 0;
    $i = 1;

    // Reckon the total number of available menu items.
    foreach ($menu as $menu_item) {
        if (!isset($menu_item['link']['hidden']) || $menu_item['link']['hidden'] == 0) {
            $total_children++;
        }
    }

    foreach ($menu as $menu_item) {

        $show_children = $megamenu_wrapper = $megamenu_column = $megamenu_content = FALSE;
        $item_class = $link_options = $link_class = array();
        $mlid = $menu_item['link']['mlid'];

        /**
         * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
         */
        if (YOURTHEMENAME_link_should_be_hidden($menu_item['link']['link_path'])) {
            continue;
        }

        if (!isset($menu_item['link']['hidden']) || $menu_item['link']['hidden'] == 0) {
            $item_class[] = ($trail && in_array($mlid, $trail)) ? 'active-trail' : '';

            // Add helper classes to the menu items and hyperlinks.
            $settings['firstlast'] = ($settings['dfirstlast'] == 1 && $total_children == 1) ? 0 : $settings['firstlast'];
            $item_class[] = ($settings['firstlast'] == 1) ? (($i == 1) ? 'first' : (($i == $total_children) ? 'last' : 'middle')) : '';
            $settings['zebra'] = ($settings['dzebra'] == 1 && $total_children == 1) ? 0 : $settings['zebra'];
            $item_class[] = ($settings['zebra'] == 1) ? (($i % 2) ? 'odd' : 'even') : '';
            $item_class[] = ($settings['itemcount'] == 1) ? 'sf-item-' . $i : '';
            $item_class[] = ($settings['itemdepth'] == 1) ? 'sf-depth-' . $menu_item['link']['depth'] : '';
            $link_class[] = ($settings['itemdepth'] == 1) ? 'sf-depth-' . $menu_item['link']['depth'] : '';
            $item_class[] = ($settings['liclass']) ? $settings['liclass'] : '';
            if (strpos($settings['hlclass'], ' ')) {
                $l = explode(' ', $settings['hlclass']);
                foreach ($l as $c) {
                    $link_class[] = $c;
                }
            }
            else {
                $link_class[] = $settings['hlclass'];
            }
            $i++;

            // Add hyperlinks description (title) to their text.
            $show_linkdescription = ($settings['linkdescription'] == 1 && !empty($menu_item['link']['localized_options']['attributes']['title'])) ? TRUE : FALSE;
            if ($show_linkdescription) {
                if (!empty($settings['hldmenus'])) {
                    $show_linkdescription = (is_array($settings['hldmenus'])) ? ((in_array($mlid, $settings['hldmenus'])) ? TRUE : FALSE) : (($mlid == $settings['hldmenus']) ? TRUE : FALSE);
                }
                if (!empty($settings['hldexclude'])) {
                    $show_linkdescription = (is_array($settings['hldexclude'])) ? ((in_array($mlid, $settings['hldexclude'])) ? FALSE : $show_linkdescription) : (($settings['hldexclude'] == $mlid) ? FALSE : $show_linkdescription);
                }
                if ($show_linkdescription) {
                    $menu_item['link']['title'] .= '';
                    $menu_item['link']['title'] .= (!empty($menu_item['link']['localized_options']['attributes']['title'])) ? $menu_item['link']['localized_options']['attributes']['title'] : array();
                    $menu_item['link']['title'] .= '';
                    $link_options['html'] = TRUE;
                }
            }

            // Add custom HTML codes around the menu items.
            if ($sfsettings['wrapul'] && strpos($sfsettings['wrapul'], ',') !== FALSE) {
                $wul = explode(',', $sfsettings['wrapul']);
                // In case you just wanted to add something after the element.
                if (drupal_substr($sfsettings['wrapul'], 0) == ',') {
                    array_unshift($wul, '');
                }
            }
            else {
                $wul = array();
            }

            // Add custom HTML codes around the hyperlinks.
            if ($settings['wraphl'] && strpos($settings['wraphl'], ',') !== FALSE) {
                $whl = explode(',', $settings['wraphl']);
                // The same as above
                if (drupal_substr($settings['wraphl'], 0) == ',') {
                    array_unshift($whl, '');
                }
            }
            else {
                $whl = array();
            }

            // Add custom HTML codes around the hyperlinks text.
            if ($settings['wraphlt'] && strpos($settings['wraphlt'], ',') !== FALSE) {
                $whlt = explode(',', $settings['wraphlt']);
                // The same as above
                if (drupal_substr($settings['wraphlt'], 0) == ',') {
                    array_unshift($whlt, '');
                }
                $menu_item['link']['title'] = $whlt[0] . check_plain($menu_item['link']['title']) . $whlt[1];
                $link_options['html'] = TRUE;
            }

            if (!empty($menu_item['link']['has_children']) && !empty($menu_item['below']) && $depth != 0) {
                // Megamenu is still beta, there is a good chance much of this will be changed.
                if (!empty($settings['megamenu_exclude'])) {
                    if (is_array($settings['megamenu_exclude'])) {
                        $megamenu = (in_array($mlid, $settings['megamenu_exclude'])) ? 0 : $megamenu;
                    }
                    else {
                        $megamenu = ($settings['megamenu_exclude'] == $mlid) ? 0 : $megamenu;
                    }
                    // Send the result to the sub-menu.
                    $sfsettings['megamenu'] = $megamenu;
                }
                if ($megamenu == 1) {
                    $megamenu_wrapper = ($menu_item['link']['depth'] == $settings['megamenu_depth']) ? TRUE : FALSE;
                    $megamenu_column = ($menu_item['link']['depth'] == $settings['megamenu_depth'] + 1) ? TRUE : FALSE;
                    $megamenu_content = ($menu_item['link']['depth'] >= $settings['megamenu_depth'] && $menu_item['link']['depth'] <= $settings['megamenu_levels']) ? TRUE : FALSE;
                }
                // Render the sub-menu.
                $var = array(
                  'id' => $id,
                  'menu' => $menu_item['below'],
                  'depth' => $depth, 'trail' => $trail,
                  'sfsettings' => $sfsettings
                );
                $children = theme('superfish_build', $var);
                // Check to see whether it should be displayed.
                $show_children = (($menu_item['link']['depth'] <= $depth || $depth == -1) && $children['content']) ? TRUE : FALSE;
                if ($show_children) {
                    // Add item counter classes.
                    if ($settings['itemcounter']) {
                        $item_class[] = 'sf-total-children-' . $children['total_children'];
                        $item_class[] = 'sf-parent-children-' . $children['parent_children'];
                        $item_class[] = 'sf-single-children-' . $children['single_children'];
                    }
                    // More helper classes.
                    $item_class[] = ($megamenu_column) ? 'sf-megamenu-column' : '';
                    $item_class[] = $link_class[] = 'menuparent';
                }
                $parent_children++;
            }
            else {
                $item_class[] = 'sf-no-children';
                $single_children++;
            }

            $item_class = implode(' ', array_filter($item_class));

            if (isset($menu_item['link']['localized_options']['attributes']['class'])) {
                $link_class_current = $menu_item['link']['localized_options']['attributes']['class'];
                $link_class = array_merge($link_class_current, array_filter($link_class));
            }
            $menu_item['link']['localized_options']['attributes']['class'] = $link_class;

            $link_options['attributes'] = $menu_item['link']['localized_options']['attributes'];

            // Render the menu item.
            $output['content'] .= '
' : '>';
            $output['content'] .= ($megamenu_column) ? '
' : '';
            $output['content'] .= isset($whl[0]) ? $whl[0] : '';
            $output['content'] .= l($menu_item['link']['title'], $menu_item['link']['link_path'], $link_options);
            $output['content'] .= isset($whl[1]) ? $whl[1] : '';
            $output['content'] .= ($megamenu_wrapper) ? '

' : '';
            $output['content'] .= ($show_children) ? (isset($wul[0]) ? $wul[0] : '') : '';
            $output['content'] .= ($show_children) ? (($megamenu_content) ? '
' : '
') : '';
            $output['content'] .= ($show_children) ? $children['content'] : '';
            $output['content'] .= ($show_children) ? (($megamenu_content) ? '
' : '
') : '';
            $output['content'] .= ($show_children) ? (isset($wul[1]) ? $wul[1] : '') : '';
            $output['content'] .= ($megamenu_wrapper) ? '

' : '';
            $output['content'] .= ($megamenu_column) ? '
' : '';
            $output['content'] .= '
';
        }
    }
    $output['total_children'] = $total_children;
    $output['parent_children'] = $parent_children;
    $output['single_children'] = $single_children;
    return $output;
}

/**
 * Overriding theme_site_map_menu_link()
 *
 * @param array $variables
 * @return string
 */
function YOURTHEMENAME_site_map_menu_link($variables) {

    $element = $variables['element'];
    $sub_menu = '';

    /**
     * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
     */
    if (YOURTHEMENAME_link_should_be_hidden($element['#href'])) {
        return '';
    }

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    return '
' . $output . $sub_menu . "
\n";
}

/**
 * Returns HTML for a set of links.
 * @see theme_links()
 */
function YOURTHEMENAME_links($variables) {
    $links = $variables['links'];
    $attributes = $variables['attributes'];
    $heading = $variables['heading'];
    global $language_url;
    $output = '';

    if (count($links) > 0) {
        $output = '';

        // Treat the heading first if it is present to prepend it to the
        // list of links.
        if (!empty($heading)) {
            if (is_string($heading)) {
                // Prepare the array that will be used when the passed heading
                // is a string.
                $heading = array(
                  'text' => $heading,
                  // Set the default level of the heading.
                  'level' => 'h2',
                );
            }
            $output .= '<' . $heading['level'];
            if (!empty($heading['class'])) {
                $output .= drupal_attributes(array('class' => $heading['class']));
            }
            $output .= '>' . check_plain($heading['text']) . '</' . $heading['level'] . '>';
        }

        $output .= '
';

        $num_links = count($links);
        $i = 1;

        foreach ($links as $key => $link) {

            /**
             * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
             */
            if (YOURTHEMENAME_link_should_be_hidden($link['href'])) {
                continue;
            }

            $class = array($key);

            // Add first, last and active classes to the list of links to help out themers.
            if ($i == 1) {
                $class[] = 'first';
            }
            if ($i == $num_links) {
                $class[] = 'last';
            }
            if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
                && (empty($link['language']) || $link['language']->language == $language_url->language)) {
                $class[] = 'active';
            }
            $output .= '
 $class)) . '>';

            if (isset($link['href'])) {
                // Pass in $link as $options, they share the same keys.
                $output .= l($link['title'], $link['href'], $link);
            }
            elseif (!empty($link['title'])) {
                // Some links are actually not links, but we wrap these in  for adding title and class attributes.
                if (empty($link['html'])) {
                    $link['title'] = check_plain($link['title']);
                }
                $span_attributes = '';
                if (isset($link['attributes'])) {
                    $span_attributes = drupal_attributes($link['attributes']);
                }
                $output .= '' . $link['title'] . '';
            }

            $i++;
            $output .= "
\n";
        }

        $output .= '
';
    }

    return $output;
}

/**
 * Theming links (theme_link())
 * @see http://api.drupal.org/api/drupal/includes!theme.inc/function/theme_link/7
 *
 */
function YOURTHEMENAME_link($variables) {
    /**
     * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
     */
    if (YOURTHEMENAME_link_should_be_hidden($variables['path'])) {
        return '';
    }

    return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

Substitute YOURTHEMENAME with your own theme's name.
Substitute the values of $your_paths_to_show_in_menu_only_on_their_own_pathand $link_also_visible_at_paths variables in the previous step with your appropriate values. In the previous example, I hide the "contact" AND node/9 pages' menu link by default, and let them only be visible when we are viewing these pages themselves OR when displaying node/3 or any_other_path paths (so in any other cases, I don't see the link to "contact" or node/9).
Save the file.
Clear the cache!

So the final code should look similar to this: http://pastebin.com/PzQFhykn.

BUT in your exact case, you would like to hide node/425, so your code should look like this: http://pastebin.com/DKi5aSyq

Ask if something isn't quite clear.


drupal_view or views_embed_view doesn't show translated content

I found the problem. The view is configured to be a "block" and the "rendering language" setting belongs to the "block" definition I guess. So I added the block id and now it renders in the correct language:

{{ drupal_view('ipa_projects_map', 'block_1') }}


after long investigation and test I think there is no way to make the "language module" work correctly if all the language codes have not been declared in the configuration, so that every language has the code after the base_path. Using base_path for the primary language and code for the secondary (base_path / language_code /) creates confusion to the "language module" that results in unexpected results. Alias url and url edirect can not make up for the lack. It would be necessary to create a special module to solve the situation and while having seen some code in the working web, I do not think it's a good idea to use it with the core 8 and beyond. The "language switcher" module, on the other hand, works well, but to make it integrated into the main menu, you still need to write custom code. In short, all languages, the primary and the others must be dicated in the configuration in the classic way: base_path / language_code /. There is no way out.


How to remove the caption in gallery caption module?

You can copy file galleryformatter.tpl.php from Gallery formatter module to your folder theme. And remove some code line 28->35

<?php if (!empty($data['title']) || !empty($data['alt'])): ?>

                <?php if ($data['alt']): ?>
<?php print $data['alt']; ?>
<?php endif; ?>
                <?php if ($data['title']): ?>
<?php print $data['title']; ?>
<?php endif; ?>

          <?php endif; ?>

And clear cache.


How to find all views that have "broken or missing handler"?

Yes, there is a debug option within Views's advanced settings that will print out debug statements via the Devel when a handler is broken.

Combined with Devel's Execute PHP block/form, you can use the execute the following snippet to enable debugging, evoke execution on all Views, and review the output messages for any broken handler warnings between each execution prompt.

// Capture/set debug settings.
$views_debug = variable_get('views_devel_output', FALSE);
$views_region = variable_get('views_devel_region', 'watchdog');
variable_set('views_devel_output', TRUE);
variable_set('views_devel_region', 'message');

// Execute all views/displays
foreach( views_get_all_views() as $view) {
  $displays = array_keys($view->display);
  foreach($displays as $display) {
     dpm("Executing $view->name ($display):");
     $view->execute($display);
     $view = $view->clone_view();
  }
}

// Reset debug settings.
variable_set('views_devel_output', $views_debug);
variable_set('views_devel_region', $views_region);


Views: Sort By Global Math Expression Result?

You can't sort currently by just using views but i would recommend to store
the value in the database.

Therefore create a computed field: http://drupal.org/project/computed_field
and do the logic in there to store the value in the DB. Once you have done this views will be able to sort by that.


a little clarification about contextual filter

1) Content refers to Node in Views 3.x

2) Contextual filters are filters. That means that any filter you add here is a dynamic filter fetched from context (page path arguments, node data etc). So they are filtering all the results (views data if you prefer it).

A good idea is to enable the display of the database queries (admin/structure/views/settings) so you can inspect what are you doing with every views settings.


Automatic adding of the subject to the contact form

I have created a custom module, but the form_alter can just as well be placed in the theme template file.

function MYMODULE_block_info() {
  $blocks['contact_at_webform_block'] = array(
    'info' => t('Contact Us'),
  );

  return $blocks;
}

function MYMODULE_block_view($delta = ''){
  $block = array();

  switch ($delta) {
    case 'contact_at_webform_block':
      if (user_access('access content')) {
        $block['subject'] = t('Contact Us');
        $block['content'] = l('Contact Us', 'contact', array('query' => array('subject' => drupal_get_title())));
      }
      break;
  }
  return $block;
}

function MYMODULE_form_alter( &$form, &$form_state,$form_id ){
  //dpm($form); dpm($form_id);
  if ($form_id == 'webform_client_form_5') {
    $qp = drupal_get_query_parameters();
    $subject = isset($qp['subject']) ? $qp['subject'] : '';
    $form['submitted']['subject']['#default_value'] = $subject;
  }
}

So the important part of the link in the block is to add the page title as a query parameter, so the href of the anchor will look like this contact?subject=PAGE_TITLE. If you use a block from views or created from the block UI then make sure to output the link in similar fashion.

The form alter code picks up the query parameter and inserts it into the webform subject text field. You will have to adapt the code here as your form id and text field will be different. Install devel module, then uncomment the dpm statement that is relevant. First dpm the value of your $form_id and replace mine (webform_client_form_5) with yours. Then dpm $form and inspect $form['submitted']. Look for your subject field.


Why am I getting call to undefined function after splitting module functions to two files?

files[] only works for class/interface autoloading, it won't include arbitrary PHP files. The docs say

  Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing class or interface declarations in the .info file

You can get around it by adding a line like this to the top of your .module file:

require_once DRUPAL_ROOT . '/sites/all/modules/my_module/my_module.admin.inc';


How to remove the word "New" for the new comments

copy /modules/comment/comment.tpl.php to your theme folder e.g. sites/all/themes/mytheme/(templates/)comment.tpl.php.

That theme file will override the comment.tpl.php from core, in that file you can remove this block:

<?php if ($new): ?>
  <?php print $new ?>
<?php endif; ?>

This way is perfectly fine, you are not changing/ hacking core. The theme system was meant to be used that way :)


Workflow for Entity relationship / relations

How about a content type with two Entity Reference fields?  One for each of the two blogs.

Each node of that content type will then be a connector, and you can use the workflow module or perhaps Workbench Moderation to manage the connections.


convert a cck field from integer to string (text)

You would have to change the type in field data and field revision tables and add the FIELD_NAME_format column in both the tables.
Change the type and module columns in field_config to 'text'. And change the data column in field_config and field_config_instance tables.

For more info on this you can visit this link.


Formatting Field Collection data with Views Data Export (CSV)

The solution is to implement a views_pre_render hook in a custom module.

function mymodule_views_pre_render(&$view) {
    if ($view->name == 'myview') {
        foreach ($view->result as $key => $row) {
            $line = array();
            foreach ($view->result[$key]->field_field_fruit_collection as $n => $collection) {
                $item = current($collection['rendered']['entity']['field_collection_item']);
                $line[] = $item['field_fruit'][0]['#markup'] .  ' (' . $item['field_color'][0]['#markup'] . ')';
                unset($view->result[$key]->field_field_fruit_collection[$n]);
            }
            $view->result[$key]->field_field_fruit_collection[0]['rendered']['#markup'] = implode(', ', $line);
        }
    }
}

In this example, the collection field is field_fruit_collection which is made up of two fields: field_fruit and field_color. The contents of the exported collection field will look like :

"Apple (red), Banana (yellow), Kiwi (green)"


That code doesn't enable Drupal's autocomplete (it would need the #autocomplete_path property to do so), so I guess you mean the browser autocomplete?

The standard way to do that is to set the autocomplete attribute on the element which you can do like this:

  $form['plantuser']['username'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#description' => t(''),
    '#required' => true,
    '#maxlength' => 50,
    '#weight' =>1,
    '#attributes' => array('autocomplete' => 'off'),
  );

Bear in mind autocomplete is only valid using the HTML5 doctype; if you're using another doctype you'll need to implement a JS solution to set the attribute instead, e.g.

(function($) {
  $(function() {
    $('#input-id').attr('autocomplete', 'off');
  });
})(jQuery);


A response event is possibly too late, I think at that point, you already have a built response object, and the page is just a string that will be replaced.

You're better of using a hook for this, namely hook_page_attachments(), which exists just for the purpose of adding additional libraries to the page.


How do I sort two different date content-types in a view?

Are you sure you are only have one sort field? It sounds like you are also sorting on "Type". If you are sorting on type, make sure the "Date" is the first in the sort fields. The order of the sort fields, makes the top ones dominant.


How can I use the same render cache but for json?

You have to use a cacheable response and then you can add cacheable metadata from a render array or from an object directly:

use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;

  $response = new CacheableJsonResponse($json, 200);

  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));

  $response->addCacheableDependency($entity);

If you use the core REST API this should already be implemented.


This is the site default configuration:

/core/modules/system/config/install/system.site.yml

uuid: ''
name: 'Drupal'
mail: ''
slogan: ''
page:
  403: ''
  404: ''
  front: /user/login
admin_compact_mode: false
weight_select_max: 100
langcode: en
default_langcode: en

So if you have a Minimal install, you have to go to /admin/config/system/site-information and change the default front page.

The Standard profile overwrites this config to point it to the pre-installed front page view.


You get the outputs message as an array, because you supplied $body and $title as arrays, and $form_state->getValue('author'); doesn't give you author of node test with the following code:

function test_form_alter(&$form, FormStateInterface $form_state) {
  // Custom validate function.
  $form['#validate'][] = 'validateForm';
}

function validateForm(array &$form, FormStateInterface $form_state) {
  //- Get the author id.
  $author_uid = $form_state->getValue('uid')[0]['target_id'];
  // Load the author account.
  $author = User::load($author_uid);
  //- Get the body value, if you want just the summary change value by summary.
  $body = $form_state->getValue('body')[0]['value'];
  //- Get the title value .
  $title = $form_state->getValue('title')[0]['value'];
  //- Use addMessage instead of drupal_set_message its deprecated.
  \Drupal::messenger()->addMessage('Thanks for submitting the form! you typed in the following as author:' . $author->getAccountName() . ' . body:' . $body . '. title:' . $title);
}

Don't forget to add the following use:

use Drupal\Core\Form\FormStateInterface;
use Drupal\user\Entity\User;


Drupal performance issue - too much time to establish a connection!

Finally found problem - panel templates in my theme

for those who experience same , can follow these steps

my site is optimized with APC and mod_deflate, so in pagespeed for chrome test, its 93/100
real problem was waiting time . chrome network analysis shows first GET took approx 18+ sec , then loading of other elements is real quick
after several test, i found my theme is causing delay. so i put a blank page.tpl in my theme. And you know it took 12+ sec to load that blank page! so it was not any db query problem!
so problem must be with .info, disabled css, then js, still no improvement
finally removed panel template declaration from .info , and now site took .3 sec to load!
next i tried with only one panel template in my theme, site took 1-2 sec

I have 10 panel templates in my theme.so panel templates affects site performance!


Should store input format in the database?

Yes, if you have your own form elements that are using the WYSIWYG, and are storing those results in th database, then you should also save off the input format. I did a survey of well-used modules looking into this a few weeks ago, and didn't find any that didn't do the same.

Even if you don't need it now, you will have some need in the future tho render out that input, and you will need the format to pass to check_markup.


Need to add both condition for sidebar and front page like this.

if (drupal_is_front_page() && $vars['page']['sidebar']) {
      $vars['content_classes'] = 'cool-class';
}

else {
      $vars['content_classes'] = 'super-cool-class';
}


Custom Block Class with custom Template, cache issue

The problem is not your choice of cache parameters. If you set cache max-age to 0 you don't need any other cache setting to disable the cache.

The problem is how you use the block template. You probably render only the single variables you've added and not the default {{ content }} variable. This is the reason the cache info gets lost.

Better use a custom twig template for the custom variables:

hook_theme() in mymodule.module:

function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'mytemplate' => [
      'variables' => [
        'var1' => NULL,
        'var2' => NULL,
      ],
    ],
  ];
}

build() in block class:

  public function build() {

    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $var1 = $user->field_field1->value;
    $var2 = $user->field_field2->value;

    return [
      '#theme' => 'mytemplate',
      '#var1' => $var1,
      '#var2' => $var2,
      '#cache' => [
        'contexts' =>  ['user'],
        'tags' => $user->getCacheTags(),
      ],
    ];
  };

mytemplate.html.twig:

Additional user info

Field 1: {{ var1 }}

Field 2: {{ var2 }}

The template mytemplate will be nested inside of the block template, which then, if you change it back to default, can merge the cache data to the block level and page elements on higher levels.


Ok my colleague found the solution !!

There was 2 lines added at the start of our settings.php :

This thing added lines at our downloaded files and corrupted them  !!

Ok so thank you for your time :)


Under Webforms > E-mails > E-mail template choose Custom Template.

Remove the [submission:values] token. That's what lists all the fields and their values with labels. Customize the other text as you wish.

Note the "Browse available tokens." link below the text box. This pops up a window that shows you what placeholders you can put in to build your email. You can even click on the browse tokens popup to add them to the text field. Some of them can be used as-is. Some need additional info, like the field tokens.

Field values are under the Submission header.

For your zip_code field example, you can use:

For just field:
[submission:values:zip_code]

For just label:
[submission:values:zip_code:label]

For label and field:
[submission:values:zip_code:withlabel]

You'll see there's lots of other stuff you can use, too.

Hope this answers your questions.


Breadcrumbs not showing properly translated

the first you must check the node type that is not translated then you write the code like this

function YOURTHEM_breadcrumb(&$variables) {
  $breadcrumb = $variables['breadcrumb'];
  $breadcrumb[] = drupal_get_title();
  if (!empty($breadcrumb)) {
    $node = node_load(arg(1));
    $type = $node->type;
    if ($type) {
      switch ($type) {
        case 'conventions_exhibitions_director':
          $breadcrumb['breadcrumb']= l(t('Conventions Exhibitions Directory'), 'conventions-exhibitions-directory');
          break;
         case 'event':
          $breadcrumb['breadcrumb']= l(t('Event'), 'event');
          break;
         case 'news':
          $breadcrumb['breadcrumb']= l(t('News'), 'news');
          break;

      }

    //var_dump($breadcrumb);
      if($type == 'webform'){
        array_pop($breadcrumb);
        if (arg(0)== 'node' && arg(1) == 263){
           $breadcrumb['breadcrumb'] = t('Attend an Event');
        }elseif (arg(0)== 'node' && arg(1) == 7) {
          $breadcrumb['breadcrumb'] = t('Contact Us');
        }elseif (arg(0)== 'node' && arg(1) == 263 && arg(2) == 'done') {
          $breadcrumb['breadcrumb'] = t('Attend an Event');
        }elseif (arg(0)== 'node' && arg(1) == 7 && arg(2) == 'done') {
          var_dump($breadcrumb);
          $breadcrumb['breadcrumb'] = t('Contact Us');
        }
        $output .= '' . implode(' > ', $breadcrumb) . '';
        return $output;

      }
  }
    $output .= '' . implode(' > ', $breadcrumb) . '';
    return $output;
  }
}

be careful to replace the 'YOURTHEM' to your current them name


add custom data attributes to block from block configuration page

You will need to create a custom block using hook block info, hook block view and hook block configure. That last hook will let you as a form render array (see drupal form api).

The custom block system in drupal 7 isn't very good. If you need anything but the simplest HTML code then you should create your own blocks using the above hooks.


How can I theme the markup for the labels in a set of radio options on a specific form item?

You'll need to massage the $optionsSet array so it's structured like this:

$optionsSet = [
  'option1' => 'option 1',
  'option2' => 'option 2',
];

$form['my_items'] = [
  '#type' => 'radios',
  '#title' => $this->t('Items'),
  '#options' => $optionsSet,
];


The best way to accomplish a floating image is to have some custom css: http://css.maxdesign.com.au/floatutorial/

Anyway, the drupal module Media can help you alot. Please follow this complete and well explained article: http://purewebmedia.biz/articles/2013-01-10/how-insert-and-float-inline-images-drupal-7.


node access not taken in account in views

For doing access control on views, i used the hook_views_post_execute.

For nodes with a restricted_content field set to true, the content is shown or not depending on roles

 function my module_views_post_execute(ViewExecutable $view)
 {
$VIP_member=false;
$user=\Drupal::currentUser();
$userRole=$user->getAccount()->getRoles();

if (( $user!=null )&&(in_array('VIP_member',$userRole))){
    $VIP_member=true;
}

if ($view->id() == 'articles_list') {
    foreach ($view->result as  $elementKey => $result ) {
        $node=$result->_entity;

        $VIP_restricted=$node->field_VIP_only->getValue();

        // Remove node if no rights
        if (($VIP_restricted[0]['value'] == true) && ($VIP_member==false) ){
              unset($view->result[$elementKey]);
        }
    }
}
 }


Arguments don't seem to work in the first position. So /%/product won't work, but /content/%/product will. Just move the argument to at least the second position and all should be fine.


Importing nodes from custom XML feed: how do I convert some XML fields into entity references?

Maybe a bit late...

Do you know the feeds_tamper module?

But - I think you won't get around writing your own feeds_tamper plugin.
You have to parse your input field and search for node IDs, then replace it with the ID, as you wrote. This can not be done with feeds_tamper standard plugins, because even with REGEX-replace you don't have access the node IDs.


how to use tokens as “views filter criteria” for a custom table?

We do not have token based filters, but instead what we can use is 'contextual filters', with in contextual filters you can get current logged in user.

I am assuming you are storing user information(mostly uid) to know who created what.

Now since its a custom table, the relation/join for users table with your custom table you have to define while exposing it to views. Here goes the sample code.

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

  $data = array();

  $data['custom_view_expose']['table']['group'] = t('Custom table exposed');

  $data['custom_view_expose']['table']['base'] = array(
    'title' => t('custom table exposed'),
    'help' => t('Contains records we want exposed to Views.'),
  );
  $data['custom_view_expose']['record_id'] = array(
    'title' => t('Record ID'),
    'help' => t('The record ID.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
  );
  $data['custom_view_expose']['data'] = array(
    'title' => t('Data'),
    'help' => t('The Data.'),
    'field' => array(
      'handler' => 'views_handler_field',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
  );
  // Allow views to join it with users table if needed while querying database.
  $data['custom_view_expose']['table']['join'] = array(
    'users' => array(
      'left_field' => 'uid',
      'field' => 'uid',
    ),
  );

  $data['custom_view_expose']['uid'] = array(
    'title' => t('User ID'),
    'help' => t('The record user ID.'),
    'field' => array(
      'handler' => 'views_handler_field_user',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    // Allow this field to show in relationship option.
    'relationship' => array(
      'base' => 'users',
      'field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('Users'),
    ),
    // Get this field as contextual filter option.
    'argument' => array(
      'handler' => 'views_handler_argument_user_uid',
      'numeric' => TRUE,
      'validate type' => 'uid',
    ),
  );

  return $data;
}

The above code exposes a very simple table as in screenshot

Now while creating the views within your contextual filter options will see uid as on the fields for which you can pick value to come from current logged in user, and views will automatically filter down results. Adding views screenshot

.


You haven't selected any fields:

$result = db_select('raffles', 'r')
  ->fields('r', array('foo', 'bar'))
  ->execute()
  ->fetchAll();

If you want to select all the fields, then use the following code.

$result = db_select('raffles', 'r')
  ->fields('r')
  ->execute()
  ->fetchAll();

Incidentally, the second raffles is a valid alias and not related to the problem.


I finally found a solution:I cloned the rule of the Commerce Sale module:
I created a Component:
Conditions:
-Entity has field:Parameter: Entity: [line-item], Field: commerce_product
-Entity has field:Parameter: Entity: [line-item:commerce-product], Field: field_discount_price
-NOT Data value is empty:line-item:commerce-product:field-discount-price:amount

Actions:Set the unit price to a specific amount
(Specify the numeric amount to set the price to:Price:Amount
Value:Discount

Then I created a rule:
Events:Calculating the sell price of a product
Action:The previous component
(Data selector:Commerce line items)

Then I used a price formatter and its done https://www.drupal.org/project/commerce_extra_price_formatters
Thanks!


Custom template for view with block display in a page

The correct naming is:

views-view--applications--block-1.html.twig

Also, the custom template should be based on the views-view.html.twig template, rather than on the views-view-unformatted.html.twig template.

The following are the possible template names sorted by precedence:

[base template name]--[view machine name]--[view display id].html.twig

[base template name]--[view machine name]--[view display type].html.twig

[base template name]--[view display type].html.twig

[base template name]--[view machine name].html.twig

[base template name].html.twig

(Source: http://redcrackle.com/blog/drupal-8/theme-views-templates)


I don't think length is valid for integers. size is though:

$schema['node']['fields']['show_in_inbox'] = array(
  'type' => 'int',
  'size' => 'tiny',
  'default' => '1',
  'not null' => TRUE,
  'unsigned' => TRUE,
  'description' => 'Field added by Smart_delete module',
);

Data Types


Adding JS to a Drupal 8 theme (replacement for drupal_add_js)

It seems you can use hook_preprocess_page with attached as such:

function MYTHEME_preprocess_page(&$vars, $hook) {
  $path = drupal_get_path('theme', 'MYTHEME');
     // Render the main scripts file.
  $local_js = array(
    '#attached' => array(
      'js' => array(
        $path . '/js/scripts.js' => array(
          'group' => JS_THEME,
          'weight' => 9999),
      ),
    ),
  );
  \Drupal::service('renderer')->renderRoot($local_js);
}

This works great (theme.inc uses this method), note the extra nested array around the weight.


How to override specific row classes in a view preprocess function

For Example:

function THEMENAME_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $view_name = $view->id();

  if ($view_name = 'frontpage') {
    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {
      if( in_array($id,[0]) ) { //first row only
        $attributes = $variables['rows'][$id]['attributes'];
        $attributes->removeClass('lol')->addClass('haha'); // changes "lol" to "haha"
        break;
      }
    }
  }

}


Trigger ajax callback from input field webform

I figured out you cannot attach ajax to webform components you need to add them to $form['submitted']

$form['submitted']['TEXTFIELDNAME']['#ajax'] = array(
  'callback' => 'callback function',
  'wrapper' => '#foo',
  'method' => 'replace',
  'effect' => 'fade',
);


To create something both so specific and complex, you probably won't be able to find modules that will solve this problem for you 100%. So to be able to do this you will have to develop some of this yourself (or pay some one to do it for you)

You best bet will be to start of with organic groups, rules might also help. The fact that you want users to be able to create other users complicate things, as that is something usually done by admin users. Most likely you will have to create your own custom form to handle this.


Is there a way to pass an argument to a view without using the url?

Yes, your example does exactly what you're wanting. Read the docs on views_embed_view...

  "...: Any additional parameters will be passed as arguments."


You can use javascript to add css to your page after all the other css files have been  listed.

<?php
  drupal_add_js();

  // Then in the js file you can add the css file

If you are still stuck then place a link here of your site and contact me.


Display any discounts only at cart / checkout stage

When product sell prices are calculated via Rules, they are done so in the context of either a temporary line item (for products not in the cart) or the line item on an order (for products in the cart). This means you can check to see if the commerce-line-item:line-item-id is empty or not using something like the "Data value is empty" condition. In your case, you'd want to negate that condition so that if the line item ID is empty, the discount is not applied.


Form built by Ajax commands not sending values

You need to build conditional elements in the form definition (mymodule_form) and not in the ajax callback. When the form is rebuilt using ajax, $form_state['values'] will be set, whereas it's not set on the initial form build.

Here is an example:

function mymodule_form($form, &$form_state)
{
  if(isset($form_state['values'])
  {
    // put your conditional form elements here
  }
}


Which graphs solution for Drupal 7 can be used to upgrade my Open Flash Chart solution from Drupal 6?

I've used highcharts script before, not with this module, but it might work for you http://drupal.org/project/highcharts


How do you automatically perform several back-to-back migrations in a set order?

When you activate a migration module that contains multiple migrations, they are installed in alphabetical order.  This is the order that they are executed in when you use the UI or:

drush mi --all

I have added a single letter as a prefix to my migration.  This allowed me to arrange my migrations as needed.


How to create a link to a file in a module?

file_create_url() is right choice. Check the url it generates and try to open it directly in browser. If it fails do one of these:

Check if file is exists in right folder
If yes, check if it readable (filesystem permissions). Also check permissions for files/ directory.
If file exists and is readable, check your server setup. It should allow to view files from files/ directory. Probably you have wrong mod_rewrite config (apache) or wrong nginx config.


The module 'Views Field View' that you have mentioned is very good imo. In order to use it, you have to edit a view A and add another existing view B as a field of view A.

But this is as far as it gets, it does not facilitate a 'joining' of views of any sort, for that matter I think it would be better for you to rebuild a new view with relationships etc, if Views Field View is not adequate for you.


How to use entity field as div background image in Views Slideshow?

Make sure to have a look at the Background Images Formatter module. It allows you to define a background-image (and size) for any given CSS-selector, as specified in your view (using an image field).

This actually takes care of the popular demand of using specific background images in views (and avoiding the inline-style method, which is impossible in Views)


A template file should never contain code that executes a query; that should be done in a preprocess function, eventually.

The code to get the number of rows in a table is similar to the following one.

$count = db_result(db_query("SELECT COUNT(*) FROM {mytable}"));

The table name should always be put between curly brackets, which will be replaced with the prefix currently set for database tables.