How to customize a node--type.html.twig template?

Here is some examples

Render the whole field markup

{{ content.field_text }}

Get just the value of the field

{{ content.field_text.value }}

Get a field value from authors object

{{node.uid.entity.field_gender.value}}

For field above you can get the machine name of the field as you see it for example in admin/structure/types/manage/page/fields

For multivalue fields look at some examples here

Read more about how to find more variables here


views is the module you are looking for. It will allow you to list your contents filtered by content type as links. Look at this tutorial before you start.


Not really a module there does all those things you want.

However, you might be interested in Achievements module.

"The Achievements module offers the ability to create achievements and badges similar to systems seen on Xbox 360, Playstation 3, Foursquare, Gowalla, GetGlue, and more. For a Drupal site, this could mean commenting a certain number of times, starting a forum topic, visiting the site every day of the week, or anything else that can be tracked and coded."


The i18n comments can be used for this.  From the project page:

  A very simple module which would allow you to show all/any comments
  attached to all node translations. Just a great way to communicate in
  truly multi-lingual environments.

  For example I have node in English and Spanish. Drupal natural way
  would be to show comments for en/es translation separately (attached
  to en/es content). But i18n_comments will aggregate all English and
  Spanish comments for any translations. It doesn't matter if user will
  leave a comment to any node translation.


Go to permissions settings page admin/people/permissions and search for the permission 'Import media files from the local filesystem'. Give this permission to all user roles that should be able to upload files from their local computer.


IMO there is a solution without custom coding ... Below is a synopsis (to avoid writing a manual ...) of how to get this to work ...

Step 1:

Create an additional flag, let's label it like "Ever flagged with FlagX" (whereas 'FlagX' reflects the flag for which you want to know if the entity was ever flagged).

Step 2:

Use the Rules module to create a rule like so:

Rules Event: After entity (=node or user) is flagged with FlagX
Rules Action: Flag an entity (= node or user), with parameter the flag "Ever flagged with FlagX"

Here is a sample of such rule (in Rules export format, adapt the machine name of both flags to fit your needs prior to importing it in your own site), for a flag used for flagging an entity of type "user":

{ "rules_set_the_ever_flagged_with_flagx_flag" : {
    "LABEL" : "Set the ever flagged with FlagX flag",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "ON" : { "flag_flagged_flagx" : [] },
    "DO" : [
      { "flag_flaguser" : {
          "flag" : "ever_flagged_with_flagx ",
          "user" : [ "flagged-user" ],
          "flagging_user" : [ "flagging-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Step 3:

"To know if an entity was ever been flagged before" (as in your question), all you need to do now is to check for the entities that have been flagged with the "Ever flagged with FlagX" flag. Obviously, it should be straight forward to use the Views module to create an appropriate list of those entities (like users) for which the "Ever flagged with FlagX" flag is not yet set ... which would then be the actual answer to your question, i.e. the entities (like users) which were "Never flagged with FlagX".


How do you disable the CSS from a core module in Drupal 8 using libraries-override?

Seems you are missing a starting / on the full path. And the name of the overriding library looks wrong as well. There's no library core/layout_discovery. It must be layout_discovery/twocol instead.

libraries-override:
  layout_discovery/twocol:
    css:
      theme:
        /core/modules/layout_discovery/layouts/twocol/twocol.css: false

Source: Overriding and extending libraries

Alternatively, unsetting libraries via hook_page_attachments_alter() does the trick as well. Here comes a working code snippet to be placed in your theme's *.theme file. Replacy MYTHEME with the machine name of your theme.

/**
 * Implements hook_page_attachments_alter().
 */
function MYTHEME_page_attachments_alter(array &$attachments) {

  foreach ($attachments['#attached']['library'] as $key => $library) {

    // Install the Devel submodule Kint for debugging.
    // Check all libs:
    // ksm($attachments['#attached']['library']);

    // Here I disable the core base library.
    // Looks pretty ugly afterwards.
    if ($library == 'system/base') {
      unset($attachments['#attached']['library'][$key]);
    }

    // So for you it must be like following.
    // Simply try to find the right name via ksm($library);
    // or the other ksm() command from above.
    if ($library == 'layout_discovery/twocol') {
      unset($attachments['#attached']['library'][$key]);
    }
  }
}


How to replace metatag description using views argument?

I found that in the available tokens for the metatags while configuring the view, I can access the url arguments with this token [view:url:args]


Copy the file your_site/modules/search/search-result.tpl.php to your theme and modify the code.

You can read more about this in:

Customizing search-results.tpl.php and search-result.tpl.php


Difference between creating a Rest endpoint and a route&controller with jsonResponse

The main difference is the authentication and authorization,  is Rest Solution  you should provide different way to authentication and authorization to access to the endpoint. but in Controller,route solution is MVC base solution that drupal and it's ACL  ( role and permissions) hanle the access to the results not REST authorization methods like basic_auth, oauth2  etc.


Creating Multifield Search with Apache Solr Search

You can use Custom Search module. Create a search block with your custom filters (taxonomy list). And enable "Allow user input using the URL" in your Apache-solr settings page (ADVANCED SEARCH PAGE OPTIONS section).


Is translation an option in Drupal 8's logger?

No, don't use t() for logger messages. The messages are going to be translated already and you don't want to translate twice.

Example for the cron message:

    $logger->notice('Starting execution of @module_cron(), execution of @module_previous_cron() took @time.', [
      '@module' => $module,
      '@module_previous' => $module_previous,
      '@time' => Timer::read('cron_' . $module_previous) . 'ms',
    ]);

This is the same as in a t() function. The difference is that the messages are stored untranslated and will only be translated on runtime so that the message can be displayed in each user's language.


Where does drupal store LDAP server information?

By default Drupal doesn't store any LDAP server information.
If anything is stored by other modules, it's stored in the database.
Depending on different modules, these data is saved in different tables.

If you're using LDAP module for Drupal 7, you can find the settings in ldap_servers table.

If you're using LDAP module for Drupal 6, you can find the settings in ldapauth table.


You can provide node level content type templates with the pattern node--node_type.html.twig.

So, for an article it would be node--article.html.twig.

In your case, it would be node--recette.html.twig. You can also provide view mode level twigs the same way, with node--node_type--view_mode.html.twig files.

Lets say you wanted to customize the teaser display markup:

node--recette--teaser.html.twig

If you enable twig debugging, you can see in your HTML source (comments) which template is being used, and what other template pattern names are available to you:

https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

Going any further than that, you would need to implement hook_theme_suggestions_alter to get more custom template names based on some sort of logic.


Image / ImageField / ImageCache (automatic thumbnails)

Here is a tutorial that will walk you through adding images.

http://www.youtube.com/watch?v=l0I5f9YmmI0


Installed D7 with Minimal profile and root user do not have any role set to it. How to create a locked role for root?

Navigate to /admin/config/people/accounts#edit-admin-role and select from the list which role should be treated as "Admin role".


I cannot delete Devel generated content because I get an error about a not existing table

Solved the issue by updating module Pathauto to 1.6 apparently the version I was using (1.3) had a compatibility issue with Drupal 8.8.0 on how path aliases are being handled now.


Content type with taxonomy in single exposed filter

Finder module will filter both of the fields, You can select taxonomy term, node title, body, fields, ..etc to perform the search.

  There are many ways to put together finder's functionality to get the
  sort of search form you need. There are also many hooks and theme
  functions allowing full customization of finder's output.

It is used for these purposes:

As a search tool to find a group of nodes or users.
As a way to navigate to a specific node or user page that matches criteria.
As an alternative to exposed filters for a Views module display.


Have a look at the Field Translation module, a submodule (i18n_field) of the i18n module. Some more details about it (from the Community documentation):

  ... allows for translation of text associated with a field's settings including the label, help text, default value, and list options. Translation of these field settings can be added through the 'Translate interface' pages (Administration > Configuration > Regional and language > Translate interface).

Especially the "list options" mentioned above seem to be what you're looking for.


How to attach external js to Drupal.behaviours

You can use .once available in Drupal.

Drupal.behaviors.Newsletter = {
    attach: function (context, settings) {
      $('#cd-sso-newsletter-form').once('form-Newsletter', function () {
        // Your Code.

        });
      });
    }
  };


enable dd() for drush - temporary://debug_drupal.txt call fails

As of a recent change to Drush (March 30, 2013), Drush is aware the  environment variables TMP and TEMP.  So the solution (on Ubuntu) is:

export TMP="/tmp/"

and

sudo chmod g+w /tmp/drupal_debug.txt
sudo usermod -a -G www-data DrushUser


Change Image Alternative text on select box change

I don't think it can be done using AJAX with php, image field doesn't expose the alt as field with value to change it.
But there is a way to do it by using custom Javascript in an AJAX callback like the following:

/**
 * Implements hook_form_alter().
 */
function MODULENAME_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['field_custom_language']['widget']['#ajax'] = [
    'callback' => 'AltChange',
    'event'    => 'change',
    'wrapper'  => 'edit-field-image-wrapper',
    'progress' => [
      'type'    => 'throbber',
      'message' => t('Loading...'),
    ],
  ];
  // Add library.
  $form['#attached']['library'][] = 'MODULENAME/alter-alt-image';
}

and the callback function should be like:

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
function AltChange(array &$form, FormStateInterface $form_state) {
  // Get the language value.
  $lang_code = $form_state->getValue('field_custom_language')[0]['value'];
  $response = new AjaxResponse();
  $response->addCommand(new InvokeCommand(NULL, 'AltChange', [$lang_code]));
  return $response;
}

and Then create the library:
MODULENAME.libraries.yml

alter-alt-image:
  version: 1.x
  js:
    js/script.js: {}

and your Js script:
MODULENAME/js/script.js

(function($) {
  // Argument passed from InvokeCommand.
  $.fn.AltChange = function(argument) {
    // Set alt value to the passed arguments.
    $('input#edit-field-image-0-alt').attr('value', argument);
  };
})(jQuery);


How to add css immediately (display:none) to a block created through hook?

A block can have a content element when created in code. This content element can be raw HTML or a drupal render array. If you use raw HTML for your block you can just put <style type="text/css">#your-block-id { display: none;}</style> directly into your block output.

Or if you use a render array you can do something similar with the #attached key on the render array. This is outlined in the API usage of drupal.org and a comment provides an example:

$block['content'] = array(
  '#markup' => mymodule_testblock_content(),
  '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    ),
  ),
);

Obviously the render array approach is a cleaner, more elegant solution. You can even have the CSS inline when using #attached.


how to make a form field be required with hook form alter

this was the answer:

$form ['revision_log']['widget'][0]['value']['#required']=TRUE;

thanks for the tip about the widget Kevin


A view where a user doesn't have a certain content type

I am pretty sure what you need to do is set in the access permissions of the view to be permission: Publish Content


View/Page with form to insert data and display it

Sounds like you need to create a content type and add some fields to it.

After that configure permissions so authenticated users can create that content.

The follow up display of that content can probably most easily be done with the Views module.


Block form send email to recipients from a view

You can use Views Send module for that.

  Views Send enables you to send mass mailing from a View.


This problem is related to using blockify, which is a requirement for Aurora. It is fixable with a patch.

There is a full explanation along with the patch here:  https://drupal.org/node/2074249

If you're new to drupal like me and haven't installed a patch before here is a guide with links to a video that explains how to go about doing this:  https://drupal.org/patch/apply


Authcache Caching Cancelled due to php error

Ironically there is an error in the error-reporting code of Authcache 7.x-2.0-beta2. Apply the patch from issue #2161095, after that the PHP error message will be displayed correctly by the debug widget.


Can a product support recurring and not recurring payment at the same time?

If you take a look at this page, you can see that what comes out of the box is that you create a seperate product variation for the recurring products and then create seperate products.

Instructions from the docs:

  Download and install the Commerce Recurring Framework and Advanced queue Drupal modules.

  Create a variation for the recurring products
  Go to admin/commerce/config/product-variation-types

  Add a product variation type with the “Allow subscriptions” trait
  Create a product type for recurring products

  Go to admin/commerce/config/product-types
  Add a product type that uses the previously-created product variation

  Create one or more billing schedules. The billing schedules will become options when configuring your product.

  Go to admin/commerce/config/billing-schedules
  Create a new billing schedule with the desired options

  Fixed (specific day of month) or rolling (from creation date)
  Dunning options to remind users for expiring credit cards

  Create a product

  Use the previously-created product type, with the recurring variation
  Use the desired billing schedule

A possible solution would be to create a custom block that switches between the two products on the product page.

If you want to fetch data from the recurring product on the normal product, you might want to create a reference field to the recurring product on the normal product.


I'd definitely go for field_attach_update.

The idea is simple. Just load the node and save it using field_attach_update.

Ex:

$node = node_load($nid);
$node->field_name[LANGUAGE_NONE][0]['value'] = 'New value';
field_attach_presave('node', $node);
field_attach_update('node', $node);
  // Clear the static loading cache.
entity_get_controller('node')->resetCache(array($node->nid));

This will not changed any timestamp or any other hook that node_save usually invokes. Loading the node will also invoke some hooks so probably it's not that efficient.

If you have the nid and if the node structure is dead simple, you can do it like this as well:

 $node = new stdClass();
 $node->nid = $nid; // Enter the nid taken. Make sure it exists.
 $node->type = 'article';
 $node->field_name[LANGUAGE_NONE][0]['value'] = 'New value';
 field_attach_presave('node', $node);
 field_attach_update('node', $node);
  // Clear the static loading cache.
 entity_get_controller('node')->resetCache(array($node->nid));

Anyways, if you are trying to update anything other than than fields, this will no work (comment status, published status, etc). Also If you are using node_save, cache for the particular node will be cleared automatically for different methods we need to clear it with 'entity_get_controller'.

Update:
It appears that you should also call field_attach_presave() to let other modules process the field input properly. File module, for example, uses it to set the file status to permanent using this hook. I have updated my 2 examples above.


If you've got the calendar views setup already, there's a few ways to show them all together

Views attachment displays ( maybe )
views_embed_view in a template ( ok, if comfortable with PHP )
Panels ( recommended )

For example, using Panels, you can create a page with a particular layout and simply embed the View displays into the Panel page via the user interface.


Need a current page's "Content Type" passed to a node.html.twig template (for a different content type) on page load, AND after ajax call

Well, here's what I came up with... and it's working as needed. If there are issues with this approach, please feel free to critique. My backend skills leave much to be desired. Thanks!

function custom_mods_preprocess_node(array &$variables, $hook) {

// Get the current page's content type on page load
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  $variables['pageNodeType'] = $node->getType();
}

// Keeps the type available if an AJAX call happens
if (\Drupal::routeMatch()->getRouteName() == 'views.ajax') {
  $previousUrl = \Drupal::request()->headers->get('referer');
  $fake_request = Request::create($previousUrl);
  $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
  if ($url_object) {
    $route_params = $url_object->getRouteParameters();
    $ent_id = $route_params['entity_id'];
    $node = \Drupal\node\Entity\Node::load($ent_id);
    $variables['pageNodeType'] = $node->getType();
  }
}


How to create a view that lists one post per user

The solution was to use Rules and Views bulk operations (VBO) to change the 'promoted to front page' property of that users blog posts when they submit a new post. The triggered rule simply removes 'promoted to front page' from all their posts and then adds it back to the newly submitted node. Thus, each user will only have a single blog post with this property, which makes the blog homepage easy as you simply create a view sorted by date and filtered with the 'promoted to front page' property. Johan Falk has done some excellent tutorials on using rules and VBO. Well worth a watch.


There is an error in your SQL so you're getting the column not found error.  If you break up your query, you should be able to get it.
Since this question has 1k views and no answers, and I just had to do this myself, here are some helpful resources for anyone looking to build their own Views custom sort plugin in Drupal 8/9.
First, this blog post on Medium by Oleksandr Trotsenko has a detailed tutorial on writing custom sorts and filters for Views.  The example is to take a product weight and weight unit fields to sort all products by weight, regardless of whether that weight is recorded in lb or kg. There are code examples for hook_views_data() and the views sort plugin.
There's another tutorial by Clare Ming on how to extend a datefield to add a sort that shows dates in the future first, and then dates in the past in reverse chronological order. It also has code examples.


How to export user's content via features to new site in Drupal 7

You can use Data export import module
Here ls the link of module - https://www.drupal.org/project/data_export_import


Performance using location based information and proximity filters

I'll answer the first part of your question about caching with a gentle warning and a tip...

I've tried caching location-based searches and it's a fast way to a HUGE (slow) cache_views_data table.

The reason is the same as the need to cache; there are lots of permutations of latitude and longitude, so every new request will add to the cache. Depending on the speed at which you have new content or updates, the cache will either:

become immense as the queries are stored for many different lat/long combinations. This will happen with long cache times.
be quite big but rarely hit because the cache times are suitably short to keep the pages showing fresh data.

Super-huge cache tables can quite possibly be as much of a performance hit as having the database just calculate what's nearby. Lookups might be ok but inserts and expunging old data will certainly slow your database server down.

One approach I considered but haven't yet implemented is to make the latitude/longitude arguments less granular by rounding the values to fewer decimal places. This way, you can have much higher cache hit rate at the expense of a little accuracy. For example, there's much more chance of (51.1, 0.9) being hit by multiple users than (51.123456, 0.887744). The number of decimals, and therefore accuracy loss, is entirely up to you.

You can either implement a views hook to change the views arguments, or use Views PHP to add custom code to your arguments which allows them to be rounded within the view itself.


Add a Canvas Form Control in Drupal Custom Module

The form api does not support every tag in HTML. For special cases use a form key of #markup to embed raw HTML. Scan the form APIs for that keyword for examples.


hook_flag_access and hook_flag_multiple_access() do seem to be the way to go. You will need to write a small custom module for that, which you can read more from here.

An example implementation is below:

<?php

function MYMODULE_flag_access($flag, $entity_id, $action, $account) {
  if ($flag->name == 'NAME' && $flag->entity_type == 'node') {// Change flag name with your flag's machine name.
    $node = node_load($entity_id);
    if ($node && $node->uid == $account->uid) {
      return FALSE;
    }
  }

  return NULL;
}

function MYMODULE_flag_access_multiple($flag, $entity_ids, $account) {
  if ($flag->name == 'NAME' && $flag->entity_type == 'node') { // Change flag name with your flag's machine name.
    $nodes = node_load_multiple($entity_ids);
    foreach ($nodes as &$node) {
      $node = $node->uid == $account->uid ? FALSE : NULL;
    }
    return $nodes;
  }
  return array();
}

You will need to change "MYMODULE" with a module name of your choice, and use the same name and save it as MYMODULE.module. Accompany with the MYMODULE.info, drop in a folder and activate the module. Above is a sample code for you to start with the module. It checks if the Flag's entity type is node. If it's node, the relevant node(s) will be loaded, and the user ID will be matched against the provided account's user ID. If they match, it returns FALSE, indicating access should be denied. It does not explicitly return TRUE, to allow the basic Flag access checks and potential other modules to determine the access.


Show datetime value in views with entity api

You won't need to define a custom getter callback for known data types with a schema field since it can use entity_property_verbatim_get as it's getter callback, which is used by default if no 'getter callback' property is set.

$properties = &$info['foo']['properties'];
$properties['created'] = array(
  'label' => t('Date created'),
  'description' => t('The date the foo entity was created.'),
  'type' => 'date',
  'schema field' => 'created',
);

For maximum control, I would suggest you try describing your entity to views. Assuming you have an entity type called foo, stored in the table foo with a created field, you can:

/**
 * Implements hook_views_data()
 */
function foo_views_data() {
  $data = array();

  $data['foo']['table']['group']  = t('Foo entity');

  $data['foo']['table']['base'] = array(
    'field' => 'foo_id',
    'title' => t('Foo entity'),
    'help' => t('The foo entity.'),
  );
  $data['foo']['table']['entity type'] = 'foo';

  // Expose a timestamp (e.g. created date).
  $data['foo']['created'] = array(
    'title' => t('Created'),
    'help' => t('The date the foo was created.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );
}

Then, you can also do things like:

// An argument handler accepting year and month
$data['created']['created_year_month'] = array(
  'title' => t('Created year + month'),
  'help' => t('In the form of YYYYMM.'),
  'argument' => array(
    'field' => 'created',
    'handler' => 'views_handler_argument_node_created_year_month',
  ),
);

For more info on integrating with views, you can install Advanced help module, and check out the included Views documentation.


Checking for User Role in Views Field with Twig

First, you should not do security by role.  It should be done by checking for a permission.

In general...Twig gets passed a user variable from Drupal that can be used for this.  There is a hasPermissions method.  Here's a sample code snippet.

  {% if user.hasPermission('administer eck entities') %}
      Add tab
  {% endif %}

If you must use roles, there should be an hasRole() method on the user object that is passed in.  (See User Object api docs)

For Views:

Views has limited twig like support in the GUI but does not support all the functions of the underlying twig functions.  To check for user permissions in a header, you will either need to use the hook_preprocess_views_view() or create your own view specific template, e.g. views-view--view-name.html.php in your theme. You will need to process the header (or footer) variables in these to get the permission specific info into the view.

If you want to limit specific fields, you can use the field specific hook and templates as well.


Modal notification box on the screen of every authenticated user

Drupal does not provide a way to send notifications to all site users by default. The action you are trying to use will only notify the user who triggers the action (you). Messaging can help you achieve what you want. You may also need the appbar module.


What is the execution sequence of functions while rendering a form?

Here's a diagram of the form build workflow in Drupal 7

More info: https://drupal.org/node/165104


Programmatically loaded taxonomy form ajax errors

This function worked for me:
Please try to use form_load_include() and drupal_build_form() instead of drupal_get_form() to generate form

  $form_id = 'taxonomy_form_term';
  $vocabulary = taxonomy_vocabulary_load($tid);

  $form_state = array();
  $form_state['build_info']['args'] = array($vocabulary);

  // use form_load_include() and drupal_build_form() instead of drupal_get_form()
  form_load_include($form_state, 'inc', 'taxonomy', 'taxonomy.admin');

  $form = drupal_build_form($form_id, $form_state);


How do I show the publishing date instead of the creation date?

I think that this module should be fine for Drupal 7:

Publication Date

It adds a field on every node that says Published on: and then the date.


How to send hidden field value to db on webform submit

You also will need to write a hook_form_submit for your form. In the _form_submit() you will take the hidden value and store it where you like.

That is the simple answer for your question. If you provide more details there could be other ways of handling the data. What is your form action?


How can i use taxonomy name in url page using a view

The PathAuto module allows you to easily change the URLs for the default taxonomy listings (which do what you describe).

Install the module and go to Administration > Configuration > Search and metadata > URL aliases.

You can set a pattern for your vocabulary that is just [term:name] BUT there are good reasons not to do that (for example if a category overlaps with a default path).  Something like holiday/[term:name] is likely a better choice.

For more options on PathAuto see the recipes from Drupal.org.

If you need more control over the display you can override the view that generates term pages.


can we add two search form in single site?

You can use the Custom Search module so it only searches in your specific content type.

1) Enable custom search and custom search blocks

2) Now go to admin/structure/block and configure Custom Search 1

3) Scroll down a bit and click on the blue CONTENT text

Then at the bottom, in Content exclusion, check mark the content types that you do not want to show.

4) In region settings, select the region you want this block to show up in.


Failed to connect to your database server

Change the settings in your settings.php file.
For remote server you should change this like below;

$databases = array (
  'default' => array(
    'default' => array (
      'database' => 'name of database uploaded on remote server',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

'username' and 'password' are for the remote server
'host' is the hostname of the hosting server


How to expose votings (such as in rate or voting api) to views?

Alright, I found a workaround by accident.
Just add a new view that queries for the node bundle that the vote is attached to. No go to "Advanced" and add a relationship to "Rate" such that the relationship is required and not restricted to the current user. Don't apply any averaging or summing. Like that, it will spit out every node several times, once for every vote cast.


There is no special trick to posting to Drupal Forms.
But, the way that form is set up, at least for validation errors, is ajax-based. Which means that you need to post to this URL instead:

https://www.modelaircraft.org/membership/verify?ajax_form=1&_wrapper_format=drupal_ajax

with the following parameters

_drupal_ajax    1
_triggering_element_name    op
_triggering_element_value   Submit
ajax_page_state[libraries]  classy/base,classy/messages,core/drupal.ajax,core/html5shiv,core/jquery.form,core/normalize,extlink/drupal.extlink,google_analytics/google_analytics,nt_ama/nt_ama,omega/omega,responsive_menu/responsive_menu.javascript,responsive_menu/responsive_menu.styling,system/base,tb_megamenu/theme.tb_megamenu
ajax_page_state[theme_token]
ajax_page_state[theme]  nt_ama
ama_number  123
form_build_id   form-pqXufm7ga3qhXz5_dpM6_AiGcgcExovHqBG6kkqcIIE
form_id membership_verify_form
last_name   smith

That should give you a json response, similar to this:

[{
    "command": "update_build_id",
    "old": "form-pqXufm7ga3qhXz5_dpM6_AiGcgcExovHqBG6kkqcIIE",
    "new": "form-_2pgVtOL0WW10yWGP8iS1o95GyJ5pMxo5M1Mk3Jy90c"
}, {
    "command": "insert",
    "method": "html",
    "selector": "#messages-wrapper",
    "data": "    \u003Cdiv role=\u0022contentinfo\u0022 aria-label=\u0022Error message\u0022 class=\u0022messages messages--error\u0022\u003E\n          \u003Cdiv role=\u0022alert\u0022\u003E\n                  \u003Ch2 class=\u0022visually-hidden\u0022\u003EError message\u003C\/h2\u003E\n                    No match found for AMA 123 and last name smith. Please verify.\n                \u003C\/div\u003E\n      \u003C\/div\u003E\n    ",
    "settings": null
}]

which contains the message you mention.

Good luck!


How to add a field for each taxonomy term or entity reference chosen in Content Type?

Answer is Field Collection Module (https://drupal.org/project/field_collection). There is another called Multifield, you could try (https://drupal.org/project/multifield).

After installed, edit your content type and add an field with field type Field Collection. Go to Structure>Field Collection and there add fields to the Field Collection created in your content type.

After that it is equal to adding a field with reference term to content type.

What this Video https://www.youtube.com/watch?v=1V1ofpgUw-Y


Use something like
 foreach ($result as $node)
{
    $rows[] = array('data' => array("".  $node  ."..."));
    $html = theme('table',array('header' => $header,'rows'=>$rows,'caption' => '','sticky' => FALSE,'empty' => 'No details found...','attributes'=>array('class'=>'table-class'),));
    $html.= theme('pager',array('tags' => array(),'quantity'=> 10));
}


Views Bulk Operations Checkboxes check on click

This is due to the JQuery in views_bulk_operation.js :

    // Set up the ability to click anywhere on the row to select it.
$('.views-table tbody tr', form).click(function(event) {
  if (event.target.tagName.toLowerCase() != 'input' && event.target.tagName.toLowerCase() != 'a') {
    $('input[id^="edit-views-bulk-operations"]:not(:disabled)', this).each(function() {
      var checked = this.checked;
      // trigger() toggles the checkmark *after* the event is set,
      // whereas manually clicking the checkbox toggles it *beforehand*.
      // that's why we manually set the checkmark first, then trigger the
      // event (so that listeners get notified), then re-set the checkmark
      // which the trigger will have toggled. yuck!
      this.checked = !checked;
      $(this).trigger('click');
      this.checked = !checked;
    });
  }
});

Commenting them will solve it but instead of hacking the core. In your custom js file add something like:

$('.views-table tbody tr').off();

This will disable all event handlers!!


How to supress the second sidebar in Zen theme?

Go to structure => blocks, and move those blocks in another region, voila second sidebar suppressed. You may want to change the regions altogether but that gets into theme templates and such...


Create or use an existing content type for your nodes.
Add a field (field_ext_id) on the content type to track your external content id.
When building your page, use EntityFieldQuery (note that it may have performance implications on very large sites) to look for a node with field_ext_id = your id.
If no node found, create one:

$node = new stdClass;
$node->type = 'your_content_type';
$node->status = 1;
$node->uid = 1;
$node->title = 'my node';
$node->created = REQUEST_TIME;
$node->updated = REQUEST_TIME;

// set your other field values (including field_ext_id), as necessary

node_save($node);

// your new node's id is now available as $node->nid

For working with fields, have a look at Rendering Drupal 7 Fields The Right Way and Entity Metadata Wrapper.


The simplest method is to use the Aggregator module included in core.

Enable the 'aggregator' module in core
Add your RSS feed in Configuration > Web services > Feed aggregator
On the same page, click 'update items' for your feed to retrieve the RSS feed and parse the items
Create a view that will show 'Aggregator items'
(Optional step for multiple feeds) Add a filter criteria for 'Aggregator feed: Title' to only show items from the specified feed

To do more advanced functionality you will need to use the Feeds module from contrib. That module will parse the fields from a feed into content nodes.


How to create HTML Tooltips using the Charts module's API with Google Charts?

The most recent Charts version does not yet support "tooltips" as such. However, have a look at Pass library-specific options via existing #raw_options, which provides an alternative (using #raw_options) to what you're trying to get to work. For charting engine Highcharts it's already supported (and committed to the most recent dev version), while for charting engine Google Charts you'd need to apply the RTBC-patch attached to comment nr 9 (from about 6 months ago). Obviously, after that patch is committed, my recommendation here to use the #raw_options will continue to work (for either charting engine). And rest assured, this patch will make it (so it's not a patch that might make it).

With this #raw_options solution, we have a solution for using options that are specific for either of the supported charting engines (Google Charts or Highcharts). While still not deviating from a key design concept of the Charts module, which is that all supported charting options should work for either charting engines (you should be able to easily swap from one to the other charting engine, without your charts being affected).

Disclosure: I'm a co-maintainer of the Charts module.


How to log actual SMTP Authentication module communication with server?

I guess a simple answer would be to change the SMTP module's debugging output to use the watchdog, in addition to/instead of to the screen.

Unless the module offers a hook to do that you'll probably need to patch it temporarily, but if you need to debug on the live server you don't really have another option (not an easier one that I can think of, anyway).

The usual advice would be "get it reproduced on dev, then relax devel permissions temporarily for anon users to test", but of course with emails, getting problems reproduced is often hit and miss between different servers.


How to display og group visibility in a view, even if user can't change it

I've found a solution - probably not the most elegant solution and quite "hacky", but it's working so far.

Even though some users are not allowed to see the group's visibility, the information is still provided to the view, but with a marker '#access' set to false. It's possible to alter the data displayed by the view by using the hook hook_views_pre_render. An implementation, for example in a custom module, could look like this

function MY_CUSTOM_MODULE_views_pre_render(&$view) {
  // $view is a reference to the view object

  // alter only the data of the view we want to change,
  // not every view on the website
  if($view->name == "MY_VIEW_NAME" && $view->current_display == "MY_CURRENT_DISPLAY") {
    // iterate over the list of entities, in this case over the list of groups
    foreach($view->result as $index => &$result) {
      // again, have $result as a reference
      // so changes are applied to the "original data", not just to a copy

      // change '#access' field deep in the field data structure
      $result->field_group_access[0]['rendered']['#access'] = true;
    }
  }
}


Is the rules event "Before saving a user account" applied every time a user edits their account?

Before saving a user account will react before you make a change in the user account.

And After saving a new user account will react After you create the user account.

But if you have the 2 events once you create a new user account you will trigger first the Before saving a user account event and after the After saving a new user account event.

If you go to create or update a user account always you need to call the user_save() function. The difference is in the first param. See this question with an example:

Create a user programmatically and give they a role


I'm not 100% sure but I think you need the IMCE Wysiwyg Bridge module.


Simple UI solution:

Add a condition of "Data Comparison"
Data selector - commerce-line-item:type
Value equals - "Modification" (or whatever your custom line item type is called)

Now when you add a condition that checks for a field, all the fields on that custom line item type should appear. Example, "Data value is empty - commerce-line-item:custom-field".
Thanks to trevorkjorlien comment at Drupal.org


if instructor is a user entity (or reference), you can add a contextual filter in your view for your field, like this:


Are CCK shared fields loaded on node_load()?

They definitely should be attached to the node object via content_nodeapi() and content_load().


Change max length of title in a custom block added via a template file

Turns out the setting was hidden block display -> preview -> edit directly in preview.


You can do this with a callback, so that it will work whereever you use it in the form tree:

Add this to your form element:

'#element_validate' => [[get_class($this), 'validateNumber']],

And put the callback in the form class:

public static function validateNumber(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = $element['#value'];
    if ($value === '') {
      return;
    }

    $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];

    // Ensure the input is numeric.
    if (!is_numeric($value)) {
      $form_state->setError($element, t('%name must be a number.', array('%name' => $name)));
      return;
    }
}

(for the callback I've used some of the code from the html5 number element)


I haven't checked the rest of the code but

if ($block_bundle = 'my_block_bundle') {

should be

if ($block_bundle == 'my_block_bundle') {

// you could also use
$suggestions[] = 'your_suggestion' // instead of the splice


The fact that you use header() and exit is most likely the problem.

You need to use response objects that you return to properly terminate the request and write the session data.

You can't do this anywhere, I'd recommend implement a Request event subscriber. \Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber is a simple example for this:

class RedirectLeadingSlashesSubscriber implements EventSubscriberInterface {

  public function redirect(GetResponseEvent $event) {
    $request = $event->getRequest();
    // Get the requested path minus the base path.
    $path = $request->getPathInfo();

    if (strpos($path, '//') === 0) {
      $path = '/' . ltrim($path, '/');
      $qs = $request->getQueryString();
      if ($qs) {
        $qs = '?' . $qs;
      }
      $event->setResponse(new CacheableRedirectResponse($request->getUriForPath($path) . $qs));
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirect', 1000];
    return $events;
  }

}

And then register that in yourmodule.services.yml:

redirect_leading_slashes_subscriber:
  class: Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber
  tags:
    - { name: event_subscriber }


"Unable to send email" error shown to anonymous users in Workflow action

I'm assuming you're using a Rules Event "Before saving content (optionally limited to selected content types)", or some variation of a node related Rules Event.

Try to add a Rules Condition like "Entity has field" (related to that node:field-email field). After you do, that field will be available as a token you can use in any subsequent Rules Condition and/or Rules Action (where a field of that data type can be used). Your 2nd paragraph appears to me like a confirmation you don't have such Rules Condition yet (so Rules has no clue you're interested in using that eMail field).

With that, you should be able to just get it to work with the Rules module, due to which your "note" probably doesn't apply/matter anymore.


{{ content.field_title }}

This should work if you've got a field with that machine name.  If you're trying to print the title, the current syntax is:

{{ label }}

An easier way to figure out if the variables that you are trying to use is actually usable is to download the Devel module and enable Kint. Then in your .html.twig template file, you can enter:

{{ kint(content.field_myCustomfield) }}

and you would get an array with all the available variables.  If you don't want to install the devel module, you can just use:  I would recommend Devel/kint, it makes everything prettier and easier

{{ dump() }}

You're only going to need to dig into the array if you're trying to do something really custom. Eg: I used the following code in one of my projects to dig down into a link field so that i can output the exact url into an A tag inorder to wrap an entire region in a link.

<a href="{{ content.field_card_custom_link[0]['#plain_text'] }}">

You can read more about outputting Variables in twig templates here:
https://sqndr.github.io/d8-theming-guide/twig/twig-debug.html

and on drupal.org here: https://www.drupal.org/theme-guide/8


How do I rewrite the ID of an exposed filter field element?

EDIT:

I'm leaving the code below but just for kicks I went into my dev theme and did a hook_form_alter() to test another way of achieving what you want to do. What you are when you do the dpm() isn't the full output of what can possibly be changed in the HTML. You can do the following to change the ID.

<?php
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  dpm($form); // Print out before change.
  // The 'created' was my form element, yours would be which checkbox you wanted to change.
  $form['created']['#id'] = drupal_html_id('my-new-id');
  dpm($form); // Print out after change.
}
?>

The images below show the changes in the ID and the dpm() output. They are for a select box but it should work the same for any form element.

Before Change:

After Change:

The HTML Change:

Original Thought:

I think you have to use hook_theme_form_element() for this.

<?php
function <theme_name>_form_element($variables) {
  $element = $variables['element'];
  // Do something with checkbox
  if ($element['#type'] == 'checkbox' {
    // do something with element array like $variables['element']['#id'] = 'new value'
  }
  return theme_form_element($variables);
}
?>

The code above isn't tied to a certain form ID so you may have to do a little more processing to get to that piece but it should be a good starting point. Don't forget to make the ID's unique as they are originally.

Checkout the API docs for more information.

Or you can try preprocessing the form element as well, I have done this with other elements but not sure if I changed the ID's.

<?php
function MYTHEME_preprocess_form_element(&$vars) {
  $vars['attributes']['id'][] = 'another-id ';
}
?>


Avoid admin users editing other admin users

Just use the User Protect module.

This module provides various editing protection for users. The protections can be specific to a user, or applied to all users in a role.

Note: User Protect has a complicated configuration -- please take the time to read the very extensive module help before using it!

The following protections are supported:

username
e-mail address
password
status changes
roles
deletion
OpenID identities
all edits (any accessed via user/X/edit)

When a protection is enabled for a specified user (or the protection is enabled because the user belongs to a role that has the protection), it prevents the editing operation in question that anyone might try to perform on the user--unless an administrator who is permitted to bypass the protection is editing the specified user. The module will protect fields by disabling them at user/X/edit.

User administrators may be configured to bypass specified protections, on either a global or per-administrator basis.

These protections are valid both when trying to edit the user directly from their user/X/edit page, or using the mass user editing operations.

The module also provides protection at the paths user/X/edit and user/X/delete, should anyone try to visit those paths directly.


How do I import attributes with the feed mapper?

You need 'UC Feeds Product Importer' a sub module built to import all the product related fields.

check this: https://drupal.org/node/1802908

Create an importer (at admin/structure/feeds/create). Or try my default importer module, which creates a csv importer from all Ubercart fields - including attributes - automatically. If you use it, please leave feedback on the issue!
Download the template from the import page (if you use the default importer above, it will be at /import/uc_feeds_product_importer/template)
Fill in the template. For each attribute option you want enabled, fill in at least one of the cells for weight, price, or cost (a zero value works). If you fill in at least one of the three, any unfilled will default to zero. If you leave all three blank, that option will not be enabled on the imported product.
Import the completed csv at /import/uc_feeds_product_importer (if you're using my module above), otherwise go to /import and choose the importer you created.


String overrides doesn't override certain Commerce components

It's a field label, meaning it doesn't get passed through the basic string translation system. You'd need to use something like the i18n Field module instead.


Try the IMCE for FileField module. I've tested this module and working fine. It seems this is the module what you're looking for

  IMCE for FileField allows users to select files from IMCE File Browser. It supports FTP uploaded files by automatically registering them as IMCE files thus making them usable in a FileField.

Step-1:

Go to your filefield settings and Enable 'Allow users to select files from IMCE File Browsers for this field

Step-2:

Go you Manage Display settings of your content type and select FORMAT as URL to file

Step-3:

In node add / node edit form you can browse the previously uploaded files (from server) by clicking on 'Open File Browser' link.

So the file link will be displayed at node output for the uploaded file.


Resending webform submission doesn't use custom mail template

Site was using two different themes and webform was submitted from the front end theme(first theme) and back end theme(second theme)
The problem was that the webform template was present in the front end theme and not in the back end theme. So that's why when the user submitted the webform once the email uses the custom template.and when the user edit the webform under the back end theme the webform custom template is not present in this theme so the webform was using the default template.
Fix : Keep the similar custom template in both themes.


How can I get and format the node created date in field.html.twig?

Having a field template you always can get the parent entity via element['#object']. And from there you can get everything else, also the creation timestamp. You then can format it using Twig's date() filter or with format_date() in a predefined Drupal date format.

In any variation of field.html.twig (field--field-myfield.html.twig etc.) do:

  {{ element['#object'].getCreatedTime | date('F j, Y') }}

  {{ element['#object'].getCreatedTime | format_date('html_datetime') }}

Source: Sample taken from Accessing the original entity in field templates is hard.


How do I create hierarchical taxonomy terms on import nodes?

First make 3 taxonomy feeds importers for each of the tree taxonomy vocabularies separately

Import the terms from the same source file you got - you need only to specify Term Name and matching the right columm under Mapping for "Taxonomy term processor"

In case you want to import taxonomy with the hierarchy, use Taxonomy CSV import/export to put the taxonomy terms.
Sample import file with terms&hierarchy should look like this:

BMW;BMW 5;

BMW;BMW 7;

Audi;R8;

Audi;A1;

After you run these  imports, make the final node importer.
Change the settings to node processor. Remember under Mapping for Node processor when you map taxonomy terms to have "Search taxonomy terms by: Term name" checked on these three columns


Display comma-separated list of taxonomy terms?

You could try theming the field using field.tpl.php or theme_field().

As an example (using field.tpl.php):

Copy field.tpl.php to your theme directory from "modules/field/theme"
Make a copy of that file and rename it to field--field-channel.tpl.php
Edit the file however you like.

As a quick/dirty example for this to work, field--field-channel.tpl.php could look like:

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <div style="display:inline;" class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
        <?php
          print render($item);
          // Add comma if not last item
          if ($delta < (count($items) - 1)) {
            print ',';
          }
        ?>

    <?php endforeach; ?>

There are probably multiple ways to accomplish this using the .tpl file, but this is just one option.  I recommend adding a class to the DIV instead of a style and make the changes in your stylesheet instead of using inline styles.


How do I make batch callbacks as class methods?

When I use a callback function what live in a class I use, for example:

'finished' => array('\Drupal\my_batch\Form\MyBatchForm', 'finish_function'),

The same with 'operations':

'operations' => array(array('\Drupal\my_batch\Form\MyBatchForm', 'operation_function'), array($node->id())),


How can I format the date like this in search-result.tpl?

I find it is generally best to do things in a consistent way and since the drupal template_preprocess_search_result() function uses Drupal's format_date() function I recommend also using that when overriding things.

So to leave the date in the default info variable but change the format I would do this, in my template.php file of my theme (or a custom module, depending on my requirements):

/**
 * Variable preprocessor for the search result template.
 *
 * @see search-result.tpl.php
 */
function MODULE_OR_THEME_NAME_preprocess_search_result(&$variables) {
  $result = $variables['result'];

  // Override the date format.
  if (!empty($result['date'])) {
    $variables['info_split']['date'] = format_date($result['date'], 'custom', 'l, \t\h\e jS \o\f F Y');
  }
  // Reset the info variable based on the new date.
  $variables['info'] = implode(' - ', $variables['info_split']);
}

If I wanted a date variable available in my template that was separate from the info variable I would do this:

/**
 * Variable preprocessor for the search result template.
 *
 * @see search-result.tpl.php
 */
function MODULE_OR_THEME_NAME_preprocess_search_result(&$variables) {
  $result = $variables['result'];

  // Add a custom date variable for use in the template.
  $variables['custom_date'] = '';
  if (!empty($result['date'])) {
    $variables['custom_date'] = format_date($result['date'], 'custom', 'l, \t\h\e jS \o\f F Y');
  }
}

Then to use that variable in the template file you would do something like this:

<?php if ($custom_date): ?>
  <div class="date">
    <php print $custom_date; ?>
  </div>
<?php endif; ?>

Something I recommend to make things even a bit better again is instead of using the 'custom' date formatter, make a preset for "l, \t\h\e jS \o\f F Y" in the Drupal UI at admin/config/regional/date-time, then use that preset like this:

format_date($result['date'], 'preset_name');

Then you can easily change the format in future via the UI.

In this case I would recommend calling the preset "Search result date" or something along those lines so that you know what it is used for when looking the the UI and you know what will be affected if you change it.


Language fallback to site default in internationalization

I think what you need is this module: Select translation

  The options are : Use current language ; if not available use original language

I've used it before and it works pretty well.


How can I move a view from one feature to another?

I was able to do this by editing the respective view and causing the feature to go overridden.

Once the feature is overridden (aka. view settings/config saved in DB) we can recreate the respective feature w/o the view and drop that feature back into our site. Revert it, clear the cache (although when I did this, I didn't need to do either...still never a bad idea).

If all went according to plan you will now see the view is available to use in another feature, add it in, drop it back into your site and off you go!

This can also be done solely in code...
Navigate to your feature module via the CLI, you will notice 2 files: .info and views_default.inc

Find the declaration in your .info file for the respective view and move it to the .info file of the feature you want it a part of.

Next you will want to find the section of code in the views_default.inc defining your view and move that to the views_default.inc file of your new feature. It will begin with $view = new view(); and end with $export['your_view'] = $view;

You will want to revert your features to put the ordering correct in the files.


If this is an activity that you'll be repeating, like hosting events on a regular basis, I would step it up a notch and add CiviCRM to the Drupal installation. It will increase the complexity of your site by adding a new administrative area where you would manage the CRM components (at this point events and Payment Processors) but that additional complexity will simplify managing them.

Out of the box it's set for managing events with PayPal; During setup you're prompted to go through a checklist. One of those items is Payment Processor. Set it to PayPal, follow the prompts and it just pretty much works.


The "Cache pages for anonymous users" setting is stored in the variable table (as a 0 or 1), you can get it like this:

if (variable_get('cache', 0)) {
  // Cache is turned on
}

If you're interested in the "Cache blocks" setting it's also in the variables table and you can get it like this:

if (variable_get('block_cache', 0)) {
  // Block cache is turned on
}

Just for reference the first is defined in system_performance_settings() and the second in block_form_system_performance_settings_alter().


Is there anything inherently wrong with mutually reliant custom modules?

From wikipedia on "modular programming"

  Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules

If you have two modules, and they depend on each other, they are no longer independent, and in fact, are no longer two modules, but one.
At least in theory, that's a bad thing, because you can no longer make changes to one, without changing the other.

Sooner or later, you'll also likely find that this becomes a practical problem, because as the module grows, it becomes increasingly difficult to keep up appearances of an external interface. Both modules are calling functions in both modules, and again, you can no longer change one without also updating the other.


Fatal error - Class 'context_condition_node' in date_context module

It means this module is missing or registry is broken.

Can you check if the date module does exist?

If not you may try to download a copy of date module and put it in the exactly the folder.

Use Drush drush cc all to clear the cache.

In Drupal 7 you can also go to admin performance page to clear the cache. Sometimes this is still available by admin/config/development/performance.

If it still does not work, you may want to have a go with registry_rebuild module to rebuild the registry totally.


How do I replace a string when altering the output of a view field?

Remove the __value part.
{{ field_recipe_prep | replace({'pancakes': "waffles"}) }}


use node-type-"node-type-machine-name" class from body, it appears in body, and then apply inherited CSS on child classes or on elements. e.g. if you are using a content type conference use

.note-type-conference{
//style
}

or

.note-type-conference .any-other-child-class{
    //style
    }

open your developer console of browser and check body element it contains many unique and specific classes.


How to hide certain fields on the User Edit form?

You need to replace form id user-profile-form with user_profile_form

Your code should look like the following:

function profile_change_form_alter(&$form, &$form_state, $form_id) {
    // changed form id
    if ($form_id === 'user_profile_form') {
        // Use var_dump  to dump the $form array to see the fields.
        var_dump ($form);

        hide($form['account']['pass']);
        hide($form['account']['current_pass_required_values']);
        hide($form['account']['current_pass']);
    }
}


How to count the number of votes for each star in fivestar?

Once i tried to find some function that could do it. But i found just
 fivestar_get_votes($entity_type, $id, $tag = 'vote', $uid = NULL). It returns full voting score.

You can get some info here or on other sites.

I think it is possible with some sql queries EG:

   $query = db_select('votingapi_vote', 'vote');
   $query->condition('vote.entity_type', 'node');
   $query->condition('vote.entity_id', $nid);
   $query->condition('vote.tag', 'vote');
   $query->condition('vote.value', '60');
   $query->addField('vote', 'uid');
   $three_stars = $query->countQuery()->execute()->fetchField();

Here $nid is your your node's nid and 60 means three stars (20 - 1 star, 40 - 2 stars etc), vote.tag is tag that you assigned for your votes.


Display event on click of Date with drupal fullcalendar module

Have you done this with the Drupal Full Calendar Views module?

If yes, then its quite simple...

Add another field for "event date" and format the date in the format
you wish to use in the url , e.g., Y-M-D , then hide that field
using "exclude from display".
In the field you want to have as the
link, click re-write results.
Enter the path you wish to link to,
using the event date pattern rewrite pattern you created in step 1.
Your url should look like Link

As for highlighting the colour depending on event type, create another field for "node:type", and use that in the same rewrite results field as above, so your rewrite field is...

Link

Which will render out as...

Link

Then in CSS, declare classes for your node type, for example...

.event {background:red}


How do I get the node ID from the taxonomy term ID?

Use loadByProperties():

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties(['field_tags' => $tid]);


Drupal 7 different urls with same information

Whenever you need to link to a node or a term (or something else in which might have an URL-Alias), use the l() function. The link to the term will then be rewritten to the given URL-Alias (as long as there is one).


You can do it like this:

if ($foo = taxonomy_get_term_by_name($term_name)) {
      $foo_keys = array_keys($foo);
      $node->your_taxonomy_field_name[LANGUAGE_NONE][]['tid'] = $foo_keys[0];
    }
    else {
      $node->your_taxonomy_field_name[LANGUAGE_NONE][] = array (
        'vid' => 1,
        'tid' => 'autocreate',
        'name' => $term_name,
        'vocabulary_machine_name' => 'machine_name'
      );


You can disable node_access check for the view (Edit the View → Advanced → Query settings → Disable SQL Rewriting).


Logout user programmatically without redirect

The logout controller (UserController::logout()) does this in a separate step.

  public function logout() {
    user_logout();
    return $this->redirect('<front>');
  }

You can alter the controller class for the user.logout route to replace this with custom code.

What do you want to do instead? Building an anonymous response a redirect seems to be the most straightforward solution.


How to troubleshoot edit node page timeout errors?

I'd guess that a module is performing some task in either form processing or Node API Hooks. It might be communicating with a remote service, or simply taking a long time to perform some action. It might also just be that the DB communication is slow. If such an action takes too long, you'll hit the PHP timeout and the script will terminate.

You could identify which module by several means -

Debugging (eg add debug code with times to module_invoke_all() to see which hooks take a long time)
Understanding the purpose of your modules (I wonder if "Submit To Myspace" module is slowing things down?)
Process of elimination (turn off likely candidates until the problem goes away, turn them back on one by one until it recurs)

Note that the last approach is not the most dependable; if you have a 180s timeout, and module A takes 160s, module B takes 15s, and the rest of Drupal takes 6s, you could easily be mistaken in seeing the issue go away when you disable module B, despite A being the guilty party.

If the issue affects a single page, then sit back and study what might make that specific page different. Eg LinkChecker module (if installed) tries to retrieve linked images or URLs; and if those sites timed out, your node edit might also.


How do I safely get the internal path to the current site in a multisite setup?

You can use conf_path to get the path root to the current site - then append the rest of your path to that.

  Returns the configuration path based on the site's hostname, port, and
  pathname.

e.g:

$apple_icon =  array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => base_path() . conf_path() . '/apple-touch-icon.png',
    'rel' => 'apple-touch-icon',
  ),
);
drupal_add_html_head($apple_icon, 'apple-touch-icon');


Where does Drupal 7 store custom user account fields?

Assuming you're using the SQL storage backend they're stored in the field_data_field_FIELDNAME and field_revision_field_FIELDNAME tables. The field system in Drupal 7 is generic across all entities so field data for nodes/users/all entity types is stored in the same tables.

Rather than input directly into those tables, though, I'd suggest using the Drupal API to load, alter and then save each user instead. The code might look something like this:

// Grab all the uids in the users table
$uids = db_query('SELECT uid FROM {users}')->fetchCol();

// Load the users
$users = user_load_multiple($uids);

// Loop through and edit each user
foreach ($users as $user) {
  // Load the extra data from whatever source you're using
  $extra_data = my_function_to_get_extra_data_by_user_id($user->uid);

  // Update the fields
  $user->field_FIELDNAME1[$user->language][0]['value'] = $extr_data['FIELDNAME1'];
  $user->field_FIELDNAME2[$user->language][0]['value'] = $extr_data['FIELDNAME2'];
  // etc...

  // Save the user object
  user_save($user);
}

You'll probably want to change this code to process the users in batches as it's likely to take a long time to run.


So I managed to figure it out myself. It just seems that you need to build up the whole new form state manually and then rebuild the form with that state again. Here's my modified code for the ajax submit handler. But if anyone still has a better solution please post your answer here.

function MYMODULE_finding_node_form_submit_ajax($form, &$form_state){
  $commands = array();
  $commands[] = ajax_command_remove('.l-messages');
  if(form_get_errors()){
    $commands[] = ajax_command_replace(NULL, drupal_render($form));
  }
  else{
    $node = $form_state['node'];
    $new_form_state = array();
    $new_form_state['build_info']['args'][] = $node;
    $new_form_state['no_redirect'] = TRUE;
    $new_form_state['input'] = array();
    $new_form_state['values'] = array();
    $new_form_state['method'] = $form_state['method'];
    $new_form = drupal_rebuild_form('finding_node_form', $new_form_state);

    $commands[] = ajax_command_replace(NULL, drupal_render($new_form));
  }
  $commands[] = ajax_command_prepend('.page', '

' . theme('status_messages') . '

');

  return array('#type' => 'ajax', '#commands' => $commands);
}


How to theme single node differently to nodes in taxonomy list?

You have access to the $page variable in your template file; if the node is being displayed in a full page this variable will be TRUE, and FALSE otherwise.

If you look at the core node.tpl.php file you can see it too takes advantage of this:

<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>

That's used to only display a title on the node if it's not the main page display.

You also have access to a $view_mode variable if you want to be more specific about the particular view mode, e.g.:

<?php if ($view_mode == 'teaser'):
<?php // print something ?>
<?php endif; ?>


You have to do this while defining the header array like

$header = array(
     array(
       'data'  => t('Url'),
       'field' => 'd.path',
       'sort'  => 'asc',
     ),
     array(
       'data'  => t('Text'),
       'field' => 'd.text',
     ),
    );

So, this table will have two columns, Url & Text. And it will be sorted in ascending order by column Url.


template.php hook to add variable to view

I think you want to use views hooks, not template preprocess functions. The views query will be run before the template is processed. You can find a list of views hooks here: https://api.drupal.org/api/views/views.api.php/group/views_hooks/7.x-3.x

and from that link, and alex.designworks the hook firing order:

- hook_views_pre_view
 - hook_views_pre_build
 - hook_views_post_build
 - hook_views_pre_execute
 - hook_views_post_execute
 - hook_views_pre_render
 - hook_views_post_render


Using hook_form_alter to set default values for multiple-value CCK fields

I think you may need to use #after_build, to ensure that your alter code runs after CCK has completely built the form element. Try something like this

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['field_myfield']['#after_build'][] = 'mymodule_after_build';
}

function mymodule_after_build(&$form_element, &$form_state) {
  // Have a look at the element with devel's dsm
  dsm($form_element);

  // Code to adjust your form element here...

  return $form_element;
}

I'm not 100% on the above syntax. I'd sugest you have a look at this article entitled hook_form_alter() and CCK fields


Need to refresh in admin/config/regional/translate/i18n_string.


Is it possible to convert separate (matching) managed files to a single shared file?

For small scale issues of this nature, the Duplicate Images module may be exactly what you need to step through the process of identifying and removing duplicates. (At the moment it bogs down and fails with huge numbers of duplicate images).

  What does this module do?

  In a multi step form (like update.php) this module executes the
  following steps:

  1) Search for duplicates

  Searches are done on the public and/or private file system
  It searches for file names ('filename' as used by pathinfo) that end with _{n} and whose part before that also exists as separate file
  name.
  It compares file size and md5 hash (see md5_file) to determine if these are real duplicates or possible duplicates.
  The results are presented as a list whereby for the possible duplicates clickable thumbnails are shown so you can visually compare
  them. For documents just a clickable icon is shown.

  2) Search for usages

  Look if a managed file record is defined for the duplicate (and the original).
  Searches for references to the managed file in user pictures, all image and file fields, all fields that according to their field schema
  have a foreign key to the file_managed table.
  Searches for URI references to the file or a(n image style) derivative in selected text and link fields.

  3) Update usages

  Found references to the managed file record are updated to refer to the managed file record of the original (or if that does not yet
  exist, the uri field is simply updated).
  Found textual usages are changed to refer to the URI of the original document.
  Note 1: this phase uses the entity_save() function of the entity api (contrib and thus a dependency) to ensure that caches are cleared,
  hooks are called, file_usage is update, rules are executed, etc.
  Note 2: this phase does keep track of failed updates so that the next phase can skip managed file records or files that are still being
  referred to.

  4) Delete duplicates

  All managed file records that are no longer referred to are deleted.
  All duplicate files that ar no longer referred to are deleted.


How to override template for a Profile2 page

You need to put user-profile.tpl.php in your theme  directory.


Search API- Force taxonomy terms to be indexed as one language

One workaround: since I didn't need the translations in my case, I could go to the Translate UI screen and search for them and delete them one-by-one.  A real pain, but at least it cleared up the problem.


Putting multiple Add to cart links / buttons on a page

jQuery is our friend.

Create a DIV for every product that will perform an ajax request (on click) to a path that will update your cart and then retrieve the cart contents. Ex. /ajax/cart?op=add&pid=idOfProduct

Create a path (hook_menu) where you will send the add to cart message or other messages that you want to send to the cart (item removal for example).

This path will update the cart to your needs based on the parameters you send it.

The response of the path could be in full HTML for simplicity, with the updated and already rendered cart.

Replace the current cart with the new contents. It's not simple but it will work.

Hope that helps!


How to dynamically make a field visible?

You miss ] in the selector ':input[name="field_type[und]"' code test with the following it will work.

':input[name="field_type[und]"]' => ['value' => 'interne'],

Update:
The state work with any valid JQuery selector, so if you looking to target it with select selector instead of :input you can use this:

 'select[name="field_type[und]"]' => ['value' => 'interne'],


broken blocks after Drupal 7 Windows to Linux migration

Have you checked your block regions? Sometimes when I migrate a site (though for me it's between servers running different OSs), blocks disappear from the site. However, it's just a matter of them getting thrown out of their regions, and the solution is to just go to Structure -> Blocks and put them back into their appropriate regions.


How to add recurring to all product by default monthly?

Finally its solved by changing the code in rules

<?php
    //Recurring
    $data = array(
   'pfid' => ' ',
   'nid' => $node->nid,
   'fid' => 'recurring',
   'description'=>'When this product is purchased, add a fee for the same amount as the product selling price charged first after 0 days and every 1 months after that 99 times.',
     );
   drupal_write_record('uc_product_features', $data);

   $q = "SELECT pfid FROM {uc_product_features} WHERE fid= '%s' AND nid = %d";
   $result = db_query($q, 'recurring', $node->nid);
   $num = db_result($result);

  // Build the recurring fee's product object.
   $product->pfid = $num; //pfid
   $product->model = '';
   $product->fee_amount = 0.000;
   $product->initial_charge = '0 days';
   $product->regular_interval = '1 months';
   // If number intervals is negative, it means that it's unlimited intervals.
   $product->number_intervals = 100;
   $product->nid = $node->nid;

   uc_recurring_product_feature_save($product);
 ?>

I am not sure whether its a proper way..


How to change "add to comment" in comment form?

Create a seperate .tpl file for comment-wrapper named comment-wrapper.tpl.php.

To create a seperate template file for node specific comment wrapper you can create using
comment-wrapper-contenttype.tpl.php copy the code from core comment-wrapper.tpl.php and change the title in the code given below.

While copying from core comment-wrapper.tpl.php don't forget to remove the validation which is meant for forum node types only.

<?php print t('Add new comment'); ?>


How do I add taxonomy terms and vocabularies to an exportable deployment plan?

I seem to have stumbled my way through to a solution. Vocabularies don't need to be exported via UUID, as they already have their own machine name, but any terms within those vocabularies still need to be added to a deployment plan so they can be exported (inadvertently adding a vocabulary to the plan throws errors).

Using the latest development snapshots (as of March 14, 2012) of UUID, Deploy, Entity Dependency API, Views and Rules, it is possible to stitch together a UI for adding taxonomy terms to a plan. First, a managed fetch-only deployment plan must be created.

Next, a Rules component must be created using Rules, with a taxonomy term as a single parameter and a single action that adds the entity to the selected deployment plan. Note, however, that the current development snapshot of Deploy does not allow you to use Rules to add to a fetch-only managed deployment plan (I had to write a trivial patch that allows this behavior).

Next, one should create a view of all taxonomy terms, adding a Bulk Operations checkbox using Views Bulk Operations. If you have created your Rules component as above, VBO will allow you to select your component as a task to perform on all checked entities.

Now that your form is configured, all that's left to do is visit the view and add the necessary taxonomy terms, and select the relevant components to export via Features. Gotcha: There is no dependency checking in Features after adding the taxonomy terms via uuid_entities. You have to remember adding the vocabulary yourself, or tragedy and error messages will ensue.


If server does not provide content-disposition,  especially filename part of it, browser is free to choose suggested name. FF defaults to what appears to some kind of UUID, IE to domain, Chrome bases it's guess on the script being called, as far as I can tell. On the other hand adding content disposition can prevent inline viewing of PDF files, and confuse browsers in a few more ways.

You can use hook_file_download to conditionally add header with a file name where it needs to be added:

  If the user has permission, return an array with the appropriate headers.


From the qd help output:

$ ./drush.phar help qd
Download, install, serve and login to Drupal with minimal configuration and dependencies.

Examples:
 drush qd                                  Download and install stable release of Drupal into a
                                           timestamped directory, start server, and open the
                                           site logged in as admin.
 drush qd --profile=minimal --cache        Fire up dev release of Drupal site with minimal
 --core=drupal-8.0.x --yes                 install profile.
 drush qd testsite devel                   Fire up stable release (using the cache) of Drupal
 --server=:8081/admin --browser=firefox    site called "testsite", download and enable devel
 --cache --yes                             module, start a server on port 8081 and open /admin
                                           in firefox.
 drush qd commercesite                     Download and install the "Commerce Kickstart"
 --core=commerce_kickstart                 distribution/install profile, display watchdog
 --profile=commerce_kickstart --cache      messages on the server console.
 --yes --watchdog
 drush qd --makefile=mysite.make           Create and install a site from a makefile.

It should be inferred that drupal-<Sematic Version Piece> would be the project name you're downloading from the --core=drupal-8.0.x example provided.

So the following should work I believe:

drupal-7
drupal-7.x
drupal-7.N.x

Actually Drupal 7 doesnt follow semantic versioning. So D7 would require either drupal-7 or drupal-7.NN. The above drupal examples would apply to drupal 8 and beyond as of 06-01-2017 due to semvar usage in drupal.


EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids()

I had similar issue. In my case I was using following line in node.tpl

$field = field_get_items('node', $node, 'field_foo');
$sponsored = field_view_value('node', $node, 'field_foo', $field[0]);

And field_foo was not in all content type.
In Drupal 6 or 5 approach was different to get field values. That's why it was not happening.

Solution was:

if($node->type=='story'){
 $field = field_get_items('node', $node, 'field_foo');
 $sponsored = field_view_value('node', $node, 'field_foo', $field[0]);
}


How give users ability to change their blog pages theme?

Take a look at the Switchtheme module.

  Adds a block to allow users to switch between enabled themes.

Read the readme.txt of the module for the instructions.

If you wish to have different themes according to roles, take a look at the Role Theme Switcher module.

  Useful Drupal module to assign separate themes for different roles (including anonymous) in your system.


Accessing taxonomy custom field values (Drupal 7)?

If you load the taxonomy term with taxonomy_term_load(), you will get any custom field you added to the vocabulary.

I created a vocabulary to which I add a boolean field (field_test_boolean); I added a taxonomy term to that vocabulary, and then executed the following code. (22 is the taxonomy term ID for the taxonomy term I created.)

$taxonomy_term = taxonomy_term_load(22);
dsm($taxonomy_term);

The output shown by dsm() is the following one.

If you want to get the field value for the language currently set for the field, you should use the following code.

$values = field_get_items('taxonomy_term', $taxonomy_term, 'field_test_boolean');

If you need to find the taxonomy terms for which the custom field contains specific values, you should use the EntityFieldQuery class.

  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', 'fields_test')
    ->fieldCondition('field_test_boolean', 'value', 1, '=')
    ->execute();

  if (!empty($entities['taxonomy_term'])) {
    $taxonomy_terms = taxonomy_term_load_multiple(array_keys($entities['taxonomy_term']));
  }

Note

As noticed in a comment, there is a bug that doesn't allow to use the EntityFieldQuery class for taxonomy terms. The code seems fixed in the Drupal 7 development snapshot, but Drupal 7.14 is affected by the bug.


Force Language Path Prefix For Default Language

You can configure it from (admin/config/regional/language/edit/en) if English language is the default and change (Path prefix language code) field from empty to en for example


This can be done without installing module , simply you will use aggregation and group by Project .

Here is a great tutorial from nodeone.se of how to use agregation in drupal 7
See also this blog post , in the left image he is Grouping by the room(nodereference)


I found the solution to my problem:

$field_source = $entity->get('field_source')->getValue();
$url_link = $field_source[0]['uri'];
$parse = parse_url($url_link);
$value = $parse['host'];


Discount and coupon 100% off of for only 1 item in shopping cart

You could use the Flag module to get this to work, by configuring an appropriate (non-global) flag, which you should then use to (automagically) flag a user after such user applied (for the first time) the coupon code at checkout. To actually flag such users, you should use the Rules module, which integrates extremely well with the Flag module. All that's left is to find the appropriate Rules Event for such rule to be triggered (somewhere along the lines of "checkout completed" I would assume).

Any time a user tries to apply such coupon code, you can then verify if it is the very first time, or yet another time. For this verification, all you'd have to do is use a Rules Condition to check "has this user yes or no been flagged already (by the flag you created for this purpose)".

If you're not familiar with the Flag module, checkout either of these:

The set of 8 video tutorials about the Flag module.
Flag's Community documentation.


Can I use fewer modules for implementing my newsletter?

I think that with 6000+ emails to send you need to use an external mailer like MailChip or MailUp. Remember that these services have the correct infrastructure to support massive send email and dashboard report.

We have written a module for 1 of our clients that permits to create NewsLetters in Drupal and send it via MailUP for example.

However 7 modules to send an email are not a big number because in Drupal each module exec a single work:

Simplenews is the module that manages the newsletter (user subscribe,
unsubscribe, check, etc etc).
Mimemail, htmlmail and Mail system permits to create correct HTML
email and send it in correct way. And in this case you can reuse all
for the internal mail (wellcome, lost password, etc.).
Rules manage "the" rules of sending email (in this case).

In other systems you have a big module that manages all but not so good like single modules for single works. And in many cases the big module is not compatible with other modules. In Drupal I have found only very few cases where a module is not compatible with other modules.


To load a node, use

node_load($nid);

This requires that the node is saved and that you have it's nid.

To give a better answer more details are needed


It is possible, but not currently in the queue for Drupal 8 core.  There is nothing stopping it from being a contrib module, though, or being added to the Datetime Extras.

Essentially, the internals of Drupal are based around the PHP \Datetime class1, which uses the Gregorian calendar.  Custom code would have to convert back and forth between this system.

I think two places would need to be updated:

Widgets would need to be created for timestamps and datetime fields to convert to the Gregorian calendar when a user enters a date.   These widgets could then be configured every place fields are used (eg, via Manage Form Display).
A new date formatter service would need to be created to convert Gregorian dates to the other calendar system for when dates are rendered.  The glitch here is that the date placeholders are baked into the field formatters in several places.  New field formatters may also be needed to handle these cases.  It would also be possible to just use new field formatters, but there are places in code that call out to the date formatter service directly (for non-field uses).  Also keep in mind that there are places in core that don't use the date formatter service and call format_date() or date() directly (this is a known issue that will be addressed).

Also keep in mind that some things need to stay in the Gregorian calendar, and render out that way.  The main place that pops into my head are where the ISO 8601 format is used, which happens in the RDFa module and when things like the HTML5 <time> element gets rendered out with the datetime attribute.

1 This is a huge simplification from how datetime and timestamps are handled by core, but the heart is still the native \Datetime class.


Views - Filter "Content: Authored by" to show only content by anonymous users


Take a look at file_save_upload() and the functions which call it.

The function will handle the validation of the file, and save it to a new location. In Drupal 7 this also adds the file to file_managed table.
Note that the file will be stored as a temporary file, so make sure to set the status of the file to permanent afterwards.

You will probably want to implement the file_save_upload function inside your form's validation hook (before the submit handler), so you can alert the user if the file upload failed, or did not meet your validation requirements.

If the name of the image field you are trying to validate is image, then the first parameter of file_save_upload should be image, as such:

$path = file_save_upload('image', ...);

This function will then return the path on the server to which the image was uploaded (so you can for example store that path in a custom database field).


Help with a dynamic select list of flags for webform

It is not webform_hook_select_options_info() it is webform_hook_webform_select_options_info().
(If your module name is webform_hook)
The MODULE parts are the places, where you should enter your modul name.
Inside the foreach you need to enter valid fields from your content that listed inside the view.
Be sure that the Flag Modul is working.


PHPUnitTest is missing the file_managed table?

Ugh... Forgot to install the entitySchema.

This is how to do it in the setup method

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->installConfig('system');
    $this->installConfig('graphql');
    $this->installConfig('file');
    $this->installConfig('image');
    $this->installConfig('user');
    $this->installEntitySchema('user');
    $this->installEntitySchema('file');

    Role::load(RoleInterface::AUTHENTICATED_ID)
      ->grantPermission('execute graphql requests')
      ->grantPermission('create media')
      ->grantPermission('view media')
      ->grantPermission('access content')
      ->grantPermission('bypass node access')
      ->grantPermission('create url aliases')
      ->save();
  }


Rewrite results for user picture to except tokens

Please take a look at these two solutions:

https://www.drupal.org/node/2396813#comment-11571515

and

Getting user photo url and profile url using views_json


You might want to look at the Flag Page module which expands on the Flag API, or the Bookmark module.

For the Flag API, look at the Flag Lists module which will allow your user to create multiple private lists of nodes.


Stab in the dark, but I think your problem is probably stemming from the fact that you're building the form from within a theme function, which in turn calls another theme function, then so on and so forth. Logically theming should be after you've built the form.

Replace drupal_get_form('mkl_variousTest_form') in hook_theme() to NULL and in your page callback add the following code.

$form = drupal_get_form('mkl_variousTest_form');
return theme('formPage', array('form' => $form));


You can easily customize your theme depend upon your requirement

Open up your theme's .info file and you should see some regions like this:

regions[featured] = Featured

regions[content] = Content

regions[sidebar_first] = Sidebar first

regions[sidebar_second] = Sidebar second

to add a new region just type in a new one in that .info file. I'd be careful of replacing any though as there are several regions in D7 that are required.

Then you'll need to print out your new region in your page.tpl.php file which goes something like this now:

<?php if ($page['sidebar_first']): ?>

        <?php print render($page['sidebar_first']); ?>

    <?php endif; ?>

Don't forget to clear your cache or you won't see the new region. It really helps to poke around in some other D7 themes and see how they've done things also.

taken from this source http://drupal.org/node/1088718


The Drupal for Firebug module (which can be used with Chrome or Firefox) has a firep() function built in which will log a print_r of any variable passed to it into the Drupal for Firebug widget. That might be an option.

If you really want a console log, though, I think you'd have to write the functionality yourself. It isn't too hard though, here's a quick module I knocked up that works well for me:

File: js_debug.info

name = JS Debug
core = 7.x

File: js_debug.module

function js_debug_log($var = NULL) {
  $log = &drupal_static(__FUNCTION__, array());

  if ($var) {
    $log[] = $var;
  }

  return $log;
}

function js_debug_page_alter(&$page) {
  drupal_add_js(drupal_get_path('module', 'js_debug') . '/js_debug.js', 'file');
  drupal_add_js(array('js_debug' => array('messages' => js_debug_log())), 'setting');
}

File: js_debug.js

(function($) {
  $(function() {
    if (Drupal.settings.js_debug.messages) {
      for (var i = 0; i < Drupal.settings.js_debug.messages.length; i++) {
        console.log(Drupal.settings.js_debug.messages[i]);
      }
    }
  });
})(jQuery);

The above code is obviously very bare, and doesn't check to make sure console.log() is available, etc. But it will work fine in Chrome/Firefox for any var (including arrays and objects).

To use, simply call js_debug_log($var); from code; the variable you pass will be logged in the console as you'd expect.


How to redirect to external URL upon form submission

You'll want to use $form_state->setResponse() instead to utilize the TrustedRedirectResponse you're creating.

Something like this should work:

public function submitForm(array &$form, FormStateInterface $form_state) {
  // Do form stuff...

  $myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
  $response = new TrustedRedirectResponse(Url::fromUri($myurl)->toString());
  $form_state->setResponse($response);
}

This response may be cached depending on your page cache settings. If you need to change this behavior, you can modify the caching metadata. This should disable this type of caching completely for the response (not tested):

public function submitForm(array &$form, FormStateInterface $form_state) {
  // Do form stuff...

  $myurl = "https://example.com/my/path?amount=33&gift=0&product_id=1";
  $response = new TrustedRedirectResponse(Url::fromUri($myurl)->toString());

  $metadata = $response->getCacheableMetadata();
  $metadata->setCacheMaxAge(0);

  $form_state->setResponse($response);
}


Okay, here is how I did it. Hopefully it will help someone else. After uploading the new drupal core, I went to the settings.php and set the $update_free_access = TRUE;. This will allow you to apply the update without being logged in by going to site.com/update.php.

Once that was done, in the database, I truncated the cache tables and I was able to log in and fix everything.

Hope this helps.


Downloading custom module with drush make

Add a line to the make file to make it look like so:

core = 7.x
api = 2
projects[cs_all][type] = "module"
projects[cs_all][subdir] = "contrib"
projects[cs_all][download][url] = "git@bitbucket.org:myrepo/cs_all.git"
projects[cs_all][download][type] = "git"
projects[cs_all][download][branch] = "master"

So add the line to indicate 'type = git' . That would make it look closer to what is documented on https://www.drupal.org/node/1432374 ...

Curious to hear what results you'd get then.


I have followed this and disabled the css/js aggregation. Css were applied.


How often i should re-build and re-submit xml sitemap for news website?

Depending on your server configuration you can setup your site to run cron more often.

You can also use Rules module, To write a rule for resubmitting site map  which can be trigger after certain time or on new content published.

It is also important to mention that search engines takes time to index - no matter whether through external links, internal links or sitemaps.

So don't think submitting site map more often will help.


How to retrieve datetime from database in Drupal?

If you want the benefits of a SelectQuery, but with the more fine-grained control over the SQL, you can always use the where() method to inject (sanitised) raw SQL into the WHERE clause. e.g

$query = db_select('Project', 'p');
$query->fields('p', array('submissions', 'date_time'));
$query->condition('p.user_id', $user->uid);

// Fetch only records where date_time is greater than 30 days ago
$query->where('date_time > DATE_ADD(NOW(), INTERVAL -30 DAY)');

$results = $query->execute()->fetchAll();
foreach($results as $r) {
  $rows[] = array(strtotime(date("Y-m-d", $r->date_time))*1000, $r->numberOfPackages);
}

I don't know of any 'structured' way to get those sort of advanced conditions into a SelectQuery object so resorting to plain ol' SQL is necessary sometimes.


Drupal 7 doesn't use the '%' place holders.  Try this:

$primary_key = db_query("SELECT `COLUMN_NAME` FROM `information_schema`.`COLUMNS` WHERE (`TABLE_SCHEMA` = 'mydatabase') AND (`TABLE_NAME` = :tbl_name) AND (`COLUMN_KEY` = 'PRI')", array(':tbl_name' => $mytable));


How to install a text filter for plain_text input format

Do it in GUI. http://example.org/admin/config/content/formats/plain_text

Check it in Enabled filters section and then make sure it's the last one in Filter processing order section. If you'll put it before Display any HTML as plain text, your tags will get added and then in the very next step removed.

Also,  tag may be removed by HTML cleaning modules. Modern way is to make it like  and then style it in CSS. Actually, it might be a wise idea to add  as well, and maybe "card" class for both, and respective classes for clubs, spades, hearts and diamonds. That way you will be able to style them differently or even use image substitution, if you wish - all in CSS.

You can provide default CSS in your module. In mymodule.info add line:

stylesheets[all][] = css/cards.css

Create that file in mymodule/css directory and place all styles there. That way they will be there, and themes will be able to override them in their own CSS files.


Is a DB transaction executed when it is committed?

Copied from my comments:

That depends on where and how you are calling cache_set(). A transaction only exists if someone explicitly started it. If you're in a node, user or other entity insert/update hook for example, then yes, then you are in a transaction.

If there is an active transaction that it will only get committed at the end. Nested transactions are supported but only to rollback to a certain step. Does the external request need to happen immediately? Doing external requests from a entity crud hook is always a bit problematic for performance (imagine a bulk resave or import of nodes) too. Consider moving the HTTP request to a shutdown function or a queue.