Drupal saves the timestamp of a user's last access, but by the time your can react to a user visiting the site, that value has already been overwritten with the current timestamp (that happens in sess_write()). I don't have a cut-and-paste solution for you, but there are some ideas how to store the previous timestamp for later use in this forum topic.


How to get nodes created on current using Views and Drupal 8

You can use Content: Authored on in views filter criteria and specify offset today.
I was able to achieve event date filter using below code.
I was able to achieve this using custom coding may be it will help you.

function common_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'new_page' && $view->getDisplay()->display['id'] == 'news_present_year') {
       // print_r($query->where[1]['conditions'][2]);
        $current_yr_start = strtotime(date('Y-01-01'));
        $current_yr_end = strtotime(date('Y-12-31'));
        $current_yr = 'node_field_data.created BETWEEN ' .$current_yr_start.' AND '.$current_yr_end;
        //$current_yr= 'node_field_data.created = '.strtotime(date('Y-01-01'));
        $query->where[1]['conditions'][2]['field']= $current_yr;

        /*print_r($query->where[1]['conditions'][2]);
       kint($query->where[1][3]);
        dpm($query);*/
        }
        if ($view->id() == 'new_page' && $view->getDisplay()->display['id'] == 'news_block') {
        //print_r($query->where[1]['conditions'][2]);
        $current_yr= 'node_field_data.created < '.strtotime(date('Y-01-01'));
        $query->where[1]['conditions'][2]['field']= $current_yr;

        //print_r($query->where[1]['conditions'][2]);
        }
    }


Some themes can do this for you out of the box. See AdaptiveTheme as an example -- you can float an image field inline the body field.

I believe with DisplaySuite you can also show fields inline.


You can use the image url formatter module to output the path to the image.  Then do like you tried before to Rewrite Results and add the markup.


How to avoid module specific jQuery plugin script running globally?

From my experience it's usually best to leave this check to JS and don't bother on PHP side. Of course it all depends on your definition of best, but benefits I see are:

It's easy and stable to test for div existence with $("#myid"), opposed to more mysterious tests in PHP. Now you know that this div will appear when X is true and Y == Z. Will you remember that in two months?
Sure, we have comments. But will future developer understand what you meant? Will you be disciplined enough to write them, and do it really clearly?
It's easier for caching - if you aggregate your scripts, you will use the same aggregated file for pages with and without div, so one less check / download for browser
It lessens the chance for conflict between your module and other ones.

Modules shouldn't just overwrite [#attached] array, but I encountered some that did.
If you are using drupal_add_js instead, making sure test for conditions is run when it is supposed to might be hard, if other modules will try to reorder hooks. So this isn't a sure way to avoid problem described above.
Various caching systems might miss the conditions you use. Probably nothing as severe as Boost and Mobile Tools issue, but risk is there.
Theme shouldn't need to know about blocks - if you will leave test to theme, point above will not apply, but you risk crashes whenever theme is switched or block is disabled. Testing for it on both sides will add a lot of code.
And I'm sure there are other things I simply never encountered yet.

Of course you could say most of those are bugs in other modules, and you would be right, but being right does not help if you need your site up and running.
It's easier to quickly see scripts added via .info file than to search code for drupal_add_js or attached or... you see, there are many ways to do it in code, happy hunting if you are new developer and need to find where this one script came from.


Unable to contact the Apache Solr server

Since you're able to connect to ApacheSolr I am keen to know if you set the credentials correctly on Drupal side. Make sure that you added the local server correctly here admin/config/search/apachesolr/settings/add. After that use the Test connection button to verify that you are able to contact the ApacheSolr server.


How to display a confirm box before submitting a form?

confirm_popup.info

name = Confirm Popup
description = Adds a confirm popup when saving all nodes.
package = custom
version = 7.x-1.0
core = 7.x
dependencies[] = jquery_update
dependencies[] = overlay

confirm_popup.module

<?php

/*
 * Implements hook_form_BASE_FORM_ID_alter()
 */
function confirm_popup_form_node_form_alter(&$form, &$form_state, $form_id) {

  $content_type = $form['#node']->type;
  if ($content_type == 'article') {

    $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/confirm-popup.js';
    $form['#attached']['css'][] = drupal_get_path('module', 'mymodule') . '/css/confirm-popup.css';

  }

}

js/confirm-popup.js

(function($) {
Drupal.behaviors.confirmPopUp = {
  attach: function (context, settings) {

    $(document).ready(function() {

      $("#edit-submit").attr("type", "fake");
      $("#edit-submit").attr("id", "fake");

      $(document).on("click", "#fake", function(){
        var box = $("
Are you sure you want to save your changes?
SaveCancel

");

        $("#overlay-content").prepend('

').prepend(box);
        $("#overlay-content").addClass('transbg');
        $("#overlay-titlebar").prepend('

');
      });

      $(document).on("click", ".save-btn", function(){
        $('#fake').attr("type","submit");
        $('#fake').attr("id","edit-submit");
        $('#edit-submit')[0].click();
      });

      $(document).on("click", ".cancel-btn", function(){
        $(".blackbg").remove();
        $(".popup-box").remove();
      });

    });

  }
};
})(jQuery);

css/confirm_popup.css

.blackbg {
   height: 100%;
   width: 100%;
   position: absolute;
   overflow: hidden;
   z-index: 10;
   background-color: rgba(0, 0, 0, 0.5);
}
.transbg{
   background-color: rgba(0, 0, 0, 0.0) !important;
}

.popup-box{
  width: 350px;
  height: 120px;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 20;
  background-color: white;
  padding: 10px;
  font-size: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  font-family: "Lucida Grande", Verdana, sans-serif;
  line-height: 1.2em;
}

.btns-wrapper{

   position: absolute;
   bottom: 15px;
   text-align: center;
   font-size: 15px;
   display: block;
   margin: auto;

}

.save-btn,
.cancel-btn{
  padding: 10px;
  width: 70px;
  cursor: pointer;
  border-radius: 5px;
  display: inline-block;
}

.save-btn{
  background-color: #6bc711;
  margin-right: 10px;
}

.cancel-btn{
  background-color: red;
}

#fake{
  width: 34px;
}

Result


How to get all node ids from same content type

This is a basic query that returns last 10 changed nodes (published) of type 'article'. Modify for your needs.

$query = \Drupal::entityQuery('node')
  ->condition('status', NODE_PUBLISHED)
  ->condition('type', 'article')
  ->range(0, 10)
  ->sort('changed', 'DESC');
$nids = $query->execute();


If you customized a default view provided by the calendar module, you can revert it back to the default by clicking on "revert" (Click on the pointer behind edit).


Where to input hook_element_info_alter() to remove format description in date_popup form field?

You need to create a custom module.

You can follow this guide to creating your first module.

However you won't need any form code... just your element info alter, and process function. After enabling and clearing cache, you should see the desired behavior you are after.


A little bit late, however, hope this will be of use.

When defining an admin path for each bundle, path provides the path that should be used in hook_menu for the Field UI´s pages. For resolving the '%event_type' placeholder in admin paths, you need to provide a loader function that, in your case, should be 'event_type_load' and it must return a single type object.

/**
 * Event type loader function.
 *
 * param $type string
 *  The name of the event type as it appears in the admin Path placeholder
 *  of a bundle. By convention, all Drupal paths use dashes instead of underscores.
 *
 * return $type stdClass object
 *
 */
function event_type_load($type) {
        $types = enf_get_types();
        // We need to replace dashes that may appear in $type with underscores.
        // By convention, bundle names needs to use underscores, not dashes.
        $type = str_replace('-', '_', $type);
        return isset($types[$type]) ? $types[$type] : FALSE;
}

You may need to modify as well the line that reads,

'real path' => 'admin/structure/enf-event-types/manage/' . $type,

and replace it with the following one:

'real path' => 'admin/structure/enf-event-types/manage/' . str_replace('_', '-', $type),

NOTE: to be consistent with the name of the module that defines your custom entity, you may want to rename the admin path placeholder '%event_type' to be '%enf_event_type', and thus the loader function would be 'enf_event_type_load'.


How to check for view mode in twig template?

In a field.html.twig, how can we detect the view mode?

In a field template there is no top level variable for the view mode like in the node template. You can create one and then your twig code should work:

{% set view_mode = element['#view_mode'] %}

Another option is to add a template name suggestion, see Field template for display mode.

Both are valid options. There are many projects heavily depending on Twig logic while other projects prefer PHP in preprocess and template name suggestion hooks.


Override a node template suggestion with template in custom module

Isn't your array key wrong? It should be:

 $theme['node__property__full'] = [
    'template' => 'node--property-display--full',
    'base hook' => 'node'
];

If you're wanting to target the "full" display and your content type has a machine name of "property"

I'm doing something similar targetting a node of type "news" and display node "teaser":

function mymodule_theme($existing, $type, $theme, $path) {
  return [
   'node__news__teaser' => [
      'template' => 'node--news--teaser',
      'base hook' => 'node'
    ],
  ];
}

And my folder structure is:

/modules/custom/mymodule/templates/node--news--teaser.html.twig


Submit handler doesn't work after theming the form

I know you've found an answer to your question, but I just want to explain why did you get that problem.

Drupal adds form_build_id, form_token, form_id (hidden fields) for security reasons and it's some purposes, while you're theming the form with template file and render its fields manually usually miss to include those fields, after that you form submission stops working. Recently this problem happened in my Symfony project (I'd found the solution) and after few days in my Drupal project, the solution was the same;

If you render the fields manually and also call drupal_render_children function, you will find that fields can be duplicated, my solution was rendering those fields also, like this:

print render($form['form_build_id']);
print render($form['form_token']);
print render($form['form_id']);

In my case for some reason drupal_render_children duplicated my form fields (I think this is normal, because I manually rendered the fields plus called drupal_render_children), that's why I ended up with this solution.


What's the data structure that needed by services for posting new node with drupal7 services?

Corrected JSON format and tested on my local environment.

{
    "body": {
        "und": [
            {
                "value": "IamShen"
            }
        ]
    },
    "type": "shen",
    "field_shen_image": {
        "und": [
            {
                "new": 1,
                "display": 1,
                "fid": 541
            }
        ]
    },
    "title": "justalittletitle"
}


Enabling a custom module after uninstalling it

I found out that you have 2 issues with your hook_install code.

You're adding body field first then saving the node type. It should be the opposite.
There's no such function called node_add_date_field in Drupal package, unless you've created it yourself in your custom module.

Your hook_install should be as the following code:

function bachecanews_install() {
  $t = get_t();
  $node_bachecanews = array(
    'type' => 'node_bachecanews',
    'name' => $t('Bacheca News'),
    'base' => 'node_content',
    'description' => $t('Usa Bacheca News per inserire le notizio sul sito.'),
    'body_label' => $t('Contenuto della News')
  );
  $content_type = node_type_set_defaults($node_bachecanews);
  $status = node_type_save($content_type);
  node_add_body_field($content_type);
  $t_args = array('%name' => $content_type->name);
  if ($status == SAVED_UPDATED) { // in caso di modifica
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato modificato.', $t_args));
  }
  elseif ($status == SAVED_NEW) { // in caso di creazione
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato creato.', $t_args));
    watchdog('node', 'Creato il nuovo tipo di contenuto %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
  }
}

If you want to add additional field to your custom content type and this field is not body field, you use field_create_field()

As an example, you can look at standard_install().


I think you need a proper inner join.

Tweaking your snippet to:

$currentTIDs = db_query("SELECT tn.tid, td.name
                         FROM {term_node} tn
                         INNER JOIN {term_data} td
                         ON tn.tid = td.tid
                         WHERE tn.nid = 22640");

while ($cTids = db_fetch_object ($currentTIDs)) {
   array_push($currentTIDsArray, $cTids);
}

drupal_set_message('<pre>' . print_r($currentTIDsArray, TRUE) . '</pre>');

I digress, but worth mentioning Drupal coding conventions on variable names etc.. can be found here: http://drupal.org/coding-standards#naming


Why call javascript behaviour within its own function?

You're reading that wrong - the return from once() isn't Drupal.behaviors (it's a collection of jQuery elements), and Drupal.behaviors.behaviourName isn't a function that will do anything by invoking it, anyway. You would need

Drupal.behaviors.behaviourName.attach();

To get anything meaningful, but that's not synonymous with the code you're referencing.

So that code is not calling a javascript behaviour within its own function. It's calling a jQuery extension function on the elements returned from once(). Most commonly when code needs to do what you're describing in Drupal, you'll see Drupal.attachBehaviors(); instead.

What you have is a convention used by the developer who wrote the script, nothing more; you'll need to ask them for their motivation for doing so, and how/where they're attaching the $.fn functions of the same names as the behaviours.


Why does simpletest report a missing schema for my Drupal 8 module?

I see several errors, not sure which one trips you: you missed a type for riddles and tried to define a mapping immediately under. But riddles is a sequence and each element in the sequence is that mapping. So:

riddler.settings:
  type: config_object
  mapping:
    riddles:
      type: sequence
      sequence:
        type: mapping
          question:
            type: label
            label: 'Question'
          response:
            type: label
            label: 'Response'

At least that's what I would attempt...


Manage custom modules across multiple installations

The Drush make approach, as you've already mentioned, is the version my team is using.

Even though you are not currently using drush make for your sites, it should be relatively straightforward for you to move to this workflow if you want as drush also provides drush make-generate which will generate the make file from an existing site. Thus no need to feel like it's only worth it for new sites. :)


Additional validation after successful login

If You want to abort login I think You should try to add own validate function to user_login whith hook_form_alter (https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7)

<?php
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') { // or $form_id = 'user_login_form'
    $form['#validate'][] = 'check_username_against_ad_hoc_service';
  }
}

function check_username_against_ad_hoc_service($form, &$form_state) {
  $name = $form_state['values']['name'];

  if($name == 'NoGo') {
    form_set_error('name', 'You're an Ad-hoc!');
  }
}
?>

You can also use function hook_form_FORM_ID_alter (https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_FORM_ID_alter/7)


Create basic field data in template like node for custom entities {{ custom_entity.id }}

Why does {{ custom_entity.id }} produce this error message?

Exception: Object of type Drupal\Core\Field\FieldItemList cannot be
printed.

If your entity defines id for the entity ID then {{ custom_entity.id }} is ambiguous. It can mean the object property (the ID field) or the method EntityInterface::id().
So use parentheses to make it clear it is a method:
{{ custom_entity.id() }}

Or retrieve the field value when you have already a field as the error message shows:
{{ custom_entity.id.value }}

What are they doing special for node?
The node entity is using nid as ID field, so id and nid are unambigious.
Method id():
{{ node.id }}

Field nid:
{{ node.nid.value }}


My hook_menu_alter() and page callback don't get triggered

You haven't passed $items into the function ;)

function material_menu_menu_alter (&$items) {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_menu_taxonomy_page_callback';
}

Without that you're not actually altering anything as $items doesn't exist in a global scope.

You'll also need to clear the caches again once you've made the change.

UPDATE

Working code that I've just verified:

material.info:

name = Materials
description = Redefine the path for materials menu
package = CR-Hub
core = 7.x
; Includes
files[] = material.module

material.module

function material_taxonomy_page_callback($term) {
  // Calling drupal_goto() here will result in an infinite loop.
  // This is the page callback for pages with a URL like taxonomy/term/1 so
  // there's no need to redirect...you're already where you need to be.
  // This function is used to build up the new page content for the taxonomy page

  // As a test just output the name of the term related to this page.
  return $term->name;
}

function material_menu_alter (&$items) {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'material_taxonomy_page_callback';

  // You don't need to return anything from this function as $items is passed in by reference...anything you change in that variable will be reflected in the $items var in the calling function.
}

Once installed if I go to any taxonomy page the content region contains just the name of the taxonomy term for that page (using return $term->name). If it's not working for you the only thing I can advise is to clear Drupal's caches, or check what custom/contributed modules you've got installed that might be overriding your code.


Primitive Error when saving a custom field with a text_format widget

Here is what solved the issue:

I used messageFormValues in my Widget.php to override the Array with the text value, so it could be stored in my database.

public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
  foreach($values as $key => $value) {
    $values[$key][date_text] = $value[date_text][value];
  }
  return $values;
}

To unescape the html for my twig template(so it is displayed as html and not as text on the site) I used the raw attribute.

With this solution no Text-Format will be saved, but it was not necessary for my custom field anyway.


Create a view with user filter by default and all users after reset

This is possible. What you want to look into here is the concept of Views Contextual Filters. So you'll set this up something like this:

This will allow you to have a default view that works on the currently logged in user. Then you can setup another Exposed Filter which shows all authors. Hope this helps.

Thanks to this somewhat related post for the image.


Pass parameter from a custom php function to hook_block

I'm not sure how this would be expected to work consistently; if your block relies on arguments built up from a particular page callback, then the block will only work on that page.

Having said that, if the page callback arguments are based on a known value, for example a node ID, then I can see how it might work for a particular path/set of paths.

Let's say this is your menu item in hook_menu():

$items['my/path/%node'] = array(
  'title' => 'A title',
  'access arguments' => array('access content'),
  'page callback' => 'MYMODULE_some_function',
  'page arguments' => array(2)
);

And this is your code for MYMODULE_some_function():

function MYMODULE_some_function($node) {
  $the_value = do_something_to($node);
}

In your hook_block() function you can grab the node ID out of the URL, load the node manually, and perform the same function on it that you have in MYMODULE_some_function(). For example:

function MYMODULE_block($op = 'list', $delta = 0, $edit = array()) {
  // I've omitted the 'list' op, obviously you'll need to implement that yourself

  if ($op == 'view' && $delta == $the_delta) {
    // Check that we're on an appropriate page
    if (arg(0) == 'my' && arg(1) == 'path' && is_numeric(arg(2))) {
      $nid = arg(2);

      $node = node_load($nid);

      $the_value = do_something_to($node);

      $block['content'] = $the_value;
    }
  }
}

You might want to centralise the code that runs $the_value = do_something_to($node); into it's own function so you're not repeating yourself.


You can add a file to your module at src/Plugin/Block/YourBlock.php

namespace Drupal\your_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides a block.
 * @Block(
 *   id = "your_block",
 *   admin_label = @Translation("YourBlock")
 * )
 */
class YourBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $nid = 2;
    $entity_type = 'node';
    $view_mode = 'teaser';

    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $storage = \Drupal::entityManager()->getStorage($entity_type);
    $node = $storage->load($nid);
    $build = $view_builder->view($node, $view_mode);

    return $build;

  }

  ...

I'm sure with a little effort you can continue this by using blockForm, blockSubmit to set the node id/type/view_mode etc.


How can I embed a view in an email sent by Rules without resorting to the PHP filter?

Using Insert View, Mime Mail and Mail System module, you can send views in emails.
After installing and enabling the above modules, you will need to configure Mail System settings and Text Format settings.

In the Mail System settings,
Change all settings to use MimeMailSystem class to send mails.
Note: Site-wide default MailSystemInterface class should be MimeMailSystem.
In the text formats settings,
Enable Insert View Filter in each text format you require.

The problem for you isn't with the rules. It should be the Mail System settings.
I hope this would work.


drupal_add_js settings and working around the anonymous page cache

You can avoid the cache by calling your file using

drupal_add_js(drupal_get_path('theme', 'themeName') .'/js/branding.js', array('cache' => FALSE));


drush status only showing drush info, not drupal info

If the drushuser account doesn't have read permission to the directory, it won't be able to run and bootstrap Drupal to get information, so it falls back to displaying the status it can which is Drush status.

If drushuser isn't the same as accountname above, it's very unlikely that drushuser will have access to the home directory of accountname. The root user can read files in every directory, so that is probably why it works as root.

You should be able to run drush as accountname or if you can put the public_html files into a shared location and make sure that the permissions are set so that both users share a group that has read access.


That code should work in both in Drupal 6, and Drupal 7.

If you edit an already enabled module, you should clear the Drupal cache, as the list of hooks implemented by modules is cached by Drupal; that means that changing the code of an enabled module doesn't cause Drupal to notice the new added hook.

As alternative, you can go to the page listing all the enabled modules (admin/modules), disable your module, click on the "Save configuration" button you find at the bottom of the page, re-enable your module, and click again on the the "Save configuration" button. This will force Drupal to clear the cache where it saves the list of hooks implemented by the enabled modules.


The latest releases of Drupal 8 are "supported but not recommended" on Drush 8. Drush 8 is still necessary if you are not using Composer to build your site. Composer is recommended for all Drupal 8 sites because sooner or later you are likely to need a module that requires Composer. If your site does not yet need such a module, though, then it is possible to continue to use Drush 8 and the pm-update command.

A few months back drupal.org changed all of the URLs used to download Drupal images; in order to continue to use Drush 8, you need the latest version, which has been updated to use the new URL scheme. Please update to Drush 8.3.0, and you should be fine.


<?php print render(block_get_blocks_by_region('region_name')); ?>


why does drupal_get_path() not work in my code?

You've spelled vacanies_manage wrong....  (same with your js file, too [and titel in your permissions])


How can I check to see differences across my multisites?

That's a task for the Features module. Before Drupal 8 and its superb configuration management the Features module was used to track and deploy changes to entities or settings from local to prod or to your coworkers. Nowadays you can use it to track changes and sync features across multiple instances of Drupal.

Let's say you have two Drupal 8 sites or two Drupal 8 multisite instances and both of them have a content type "Foobar". Then there's Features that lets you export the whole content type into a so called Features module. Which is just another module but also holds the whole config for this "Foobar" content type in it. Now you activate this Features module on both sites or instances and both will have the same content type with the same fields in it.

From now on when you change something in this content type on either instance Features will recognize the changes and offers you to recreate the Features module. Do that and the other instance will recognize the Features module had been recreated and offers you to import these changes.

And that's what you can do now. Go to the instance you consider being the master. Use Features to export the content type in a Features module. Enable this module in this instance and also in the other instance which you think got overridden or which you think is missing the changes and use Features to explore the differences and to maybe sync the changes.

  The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it contains additional information in its info file
  so that configuration can be checked, updated, or reverted
  programmatically.


How to write page.tpl.php where the HTML files is more than one?

Actually you may have to create a page--front.tpl.php for index page of your website and a page.tpl.php to have all other pages.

you could also use theme debug mode too. it can be enabled by including the following in settings.php,

$conf['theme_debug'] = TRUE;

The ablove will include theme suggestions as html comments, that helps you theming your pages.


Webform Validation to the rescue!

  This module adds an extra tab to each webform node, allowing you to
  specify validation rules for your webform components. You can create
  one or more of the predefined validation rules, and select which
  webform component(s) should be validated against those.


How to change the date on which a user was created?

Here's a link to expose the creation date for drupal 6 - someone more knowledgeable with the conversion might be able to help you change it over to 7.
Otherwise, if there are not too many users, you could do it manually via database manipulation.

https://drupal.org/node/857846


You'll need a custom module with the following function:

function yourmodule_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
 // Do something here
}

You'll probably want to add a dpm($form); (assuming you have Devel installed) to get the exact item, but the array you'll probably want to target is:
$form['commerce_payment']['payment_method'] by perhaps setting the #access to FALSE if you only have one choice. In other words, add the following:
$form['commerce_payment']['payment_method']['#access'] = FALSE;

Be sure to clear the cache after adding this function.


You can't change the template in preprocess, there's a separate hook for that, hook_theme_suggestions_template()

This is what node is doing for the node template:

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function node_theme_suggestions_node(array $variables) {
  $suggestions = array();
  $node = $variables['elements']['#node'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'node__' . $sanitized_view_mode;
  $suggestions[] = 'node__' . $node->bundle();
  $suggestions[] = 'node__' . $node->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'node__' . $node->id();
  $suggestions[] = 'node__' . $node->id() . '__' . $sanitized_view_mode;

  return $suggestions;
}

You can provide something similar. Note that when you do this in a template, you have to use the alter hook, like this example from the bartik theme:

/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 */
function bartik_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if ($variables['element']['#form_id'] == 'search_block_form') {
    $suggestions[] = 'form__search_block_form';
  }
}


How to get the template file using hook block view?

Try doing it this way, you need to separate your template name from the filepath.

/**
* Implements hook_theme().
*/
function tgs_user_theme() {
  $theme = array();

  $theme['user_list'] = array(
    'path' =>  drupal_get_path('module', 'my_module') . '/templates',
    'template' => 'my_template'
  );

  return $theme;
}


How 2 set up a bunch of modules for sell per node access?

I have done it successfully. Resolving my problem on https://www.drupal.org/node/2407311


Change the tweet.info.yml file as follows.

name: 'tweet'
description: 'A twitter Bootstrap starter theme'
core: 8.x
type: theme
base theme: false

libraries:
  - 'tweet/bootstrap'

Put the following in the tweet.libraries.yml file.

bootstrap:
  version: 3.3.6
  css:
    theme:
      css/bootstrap.min.css: {}
      css/bootstrap-theme.min.css: {}
  js:
    js/bootstrap.min.js: {}
  dependencies:
    - core/jquery

Also, be sure you have a tweet.theme file in the same directory. This file is necessary for Drupal to recognize the directory contains a theme.


How to retrieve a term tree for a specific vocabulary given the machine name?

The vid field is the machine name for a vocabulary in Drupal 8.

You just need to pass the the string you have to TermStorage::loadTree, it doesn't need to be altered. For example:

$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree("myname");


What versions from the Symfony components are used from core?

It is more accurate to say that Drupal 8 uses Symfony components, rather than all of Symfony.  If you look at 'core/composer.json' you will see all of the individual components that Drupal uses listed out.  The precise versions that get installed are listed in the 'composer.lock' file.

Drupal 8.2.x uses the 2.8 versions of these components.

For Drupal 8.3.x, there are issues open for updating to 3.1 and 3.2, but these are still works in progress. (I think there may be a 3.3 issue, but I can't find it).

The goal is to start tracking the 3.x versions, but the conversion has not been straightforward.


How do the $node modifications in hook_node_presave persist?

Objects are (mostly) passed by reference in PHP. The $node variable is a stdClass object so any changes you make will be reflected on the original object in memory.

You don't need to do anything special to implement this yourself, just accept an object as an argument to a function as usual and let PHP take care of the rest.


mysql errors after upgrading php and mysql

I added the following items to my.cnf which fixed my PDO broken pipe issues.  I am using a homebrew installation of mysql on a macbook pro with 16GB RAM:
key_buffer_size = 384M
max_allowed_packet = 100M
table_open_cache = 512
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 8M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size = 32M
query_cache_size = 128M
query_cache_size = 256M
Try number of CPU's*2 for thread_concurrency
thread_concurrency = 8
innodb_buffer_pool_size=512M


Remove email validation from Feed Import

The validation logic for the email is embedded within the user feeds module in FeedsUserProcessor.inc which means the best way to go about this is to create you own, almost identical, feeds processor in your own custom module. Read up on how to create a custom processor.

After reading that documentation you'll need a processor class and you can use FeedsUserProcessor.inc within the feeds module as a starting point. Copy that file into your own module where necessary, rename it and also rename the class name defined within the file. In this file you should see this implementation of the entityValidate function:

/**
 * Validates a user account.
 */
protected function entityValidate($account) {
  if (empty($account->name) || empty($account->mail) || !valid_email_address($account->mail)) {
  throw new FeedsValidationException(t('User name missing or email not valid.'));
  }
}

Remove the !valid_email_address($account->mail) bit in that if statement and configure your feeds importer to use the custom processor you just created.

FYI, I would not recommend importing users with invalid email addresses as this will cause major problems with your users trying to use your site properly.


Seems to definitely be an APC issue, there's a post about it on StackOverflow which links through to a bug report on PHP.net for precisely this issue.


How to display number of pageviews on articles and pages

Have you tried with Node view count module ?

  Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.


Remove HTML Markup from YouTube RSS Feed Import

The simple answer is to configure the Text format setting Node Processor section of the Feed Importer found at admin/structure/feeds/[importer name]/settings/FeedsNodeProcessor, but there has to be more to your configuration that may be impacting this.  HTML tags/brackets are not allowed in the description of YouTube videos.

So I'm not even sure what HTML you are referring to.  I'm only aware of 3 options to get access to a list of YouTube videos formatted as RSS.

1) https://gdata.youtube.com/feeds/api/users/UC194cPvPaGJjhJBEGwG6vxg/uploads?v=1

2) https://gdata.youtube.com/feeds/api/users/UC194cPvPaGJjhJBEGwG6vxg/uploads?v=2

3) Using version 3 of the API as described in https://www.drupal.org/node/2181067.  That configuration requires OAuth.

In option 1 and 2, replace UC194cPvPaGJjhJBEGwG6vxg with account name you want a feed for.  In both those options, the description text is in the element...

 <media:description type='plain'>

That element cannot be mapped with just Feeds, Media and Media: YouTube.  You'd need something like https://www.drupal.org/project/feeds_mediarss

There may be another way to access the RSS, but without knowing what you are using it's impossible to provide a better answer.  As long as the Feeds Parser and Processor acknowledge the text format setting in the Feed Importer, the resulting nodes should only have plain text in their body fields.


Getting Node Field Values from Referenced Entity within a Paragraph

If you're doing this in a node template you could access it like so

{{ node.field_paragraph.entity.field_in_paragraph.value }}

Obviously replace field_paragraph with the machine name of the paragraph field and field_in_paragraph with the machine name of the field inside the paragraph you want.


How to selectively import and export content between 2 Drupal websites?

You could always write a couple of migration classes with the Migrate module, and hook up Site B as the datasource (the module would live in Site A).

You can do this by adding Site B's database credentials to the settings.php as another configuration, then calling on that in your script.

Here is an example of what a Migration class might look like:

class YourMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $query = Database::getConnection('connection_name', 'connection_key');
    // other query arguments to execute
  }
}

Where the Database::getConnection arguments are the names of the items in your $databases array in settings.php. With a working script, you can then write other scripts (or a cron job) to periodically run the migrate job.

Others will say to use Feeds, but I've always been a big Migrate fan (not Drupal2Drupal migrate module, the main Migrate module itself).

  I've noticed that backup migrate can have manual selection of what to
  export, but it will overwrite destination right?

Pretty much. Site A would get wiped out. It also isn't as simple as moving MySQL data around, unless every data model in Site B is identical or exists in Site A even then its a fairly large technical challenge not to screw anything up. I would not do anything with SQL at this level - it needs to go through the API.


How do I get the node URL in a Twig template?

According to Functions - In Twig Templates you can use is simple by

 {{ path('entity.node.canonical', {'node': node.id}) }}


Adding something like this to the template.php of your subtheme should get you in the right direction.

function MYTHEME_alpha_preprocess_region(&$vars) {
  $menu_object = menu_get_object();
  if (isset($menu_object->type) && $vars['region'] == 'content') {
    $vars['theme_hook_suggestions'][] = 'region__content__'.$menu_object->type;
    $vars['attributes_array']['class'][] = 'region-content-'.$menu_object->type;
  }
}

Then you just need to create .tpl files for them in the same way you would for other content type based tpl files (example: region--menu--page.tpl.php)


You can use path('entity.node.canonical', {'node': dd.nid}) in the template file.

The markup in the template file would look like this.

{{ 'About Us'|t }}

I haven't tried it, but it should work.


how to make product with attribute which select admin and only this attributes be visible for user

You should create a Vocabulary : Color . In the voacabulary list all terms with the list of colors: blue, red , green etc
. In your Product Display field add a Term Reference field and include vocabulary color to the product display.
For Red Shirt you should select the color Red  in term reference field autocomplete or checkbox.
Similarly for other colors you should do the same.


bypass a character limitation rule (webform)

you will need to write your own validation function - borrowed from here:

Adding custom validation rules - Webform Validation hooks

Last updated January 7, 2014. Created by svendecabooter on September 11, 2010.
Edited by Liam Morland, wundo, crystaldawn. Log in to edit this page.

This page describes how to write custom validation rules for your webforms. This requires installation of the Webform and Webform Validation modules.

The following code should be implemented in your own custom module.

Adding custom validation rules
The following steps will let you add custom validators through your module:

1/ Implement hook_webform_validation_validators().
This hook implementation should return an array of validator key => options array entries.
The options array can contain the following configuration keys:

name (required): name of the validator

component types (required): defines which component types can be validated by this validator. Specify 'all' to allow all types

custom_error (optional): define whether a user can specify a custom error message upon creating the validation rule.

custom_data (optional): define whether custom data can be added to the validation rule

min_components (optional): define the minimum number of components to be selected for creating a validation rule

max_components (optional): define the maximum number of components to be selected for creating a validation rule

description (optional): provide a descriptive explanation about the validator
See function webform_validation_webform_validation_validators() in

webform_validation.validators.inc for a live example

2/ Implement hook hook_webform_validation_validate($validator_name, $items, $components, $rule).
This hook gets passed 4 parameters, which will allow you to react to your custom validator (or any other validator for that matter).
Explanation about these parameters:

$validator_name: this is the validator name (i.e. array key as entered in hook_webform_validation_validators)

$items: array containing user submitted entries to be validated.
$components: this array contains the definitions of the webform components in your form

$rule: this array contains the details of your validation rule
See function webform_validation_webform_validation_validate() in webform_validation.validators.inc for a live example

Additional hooks
The hook hook_webform_validation($type, $op, $data) can be used to react on various webform_validation based actions.`

$type - possible values: 'rule'

$op - possible values: 'add', 'edit', 'delete'

$data - array with rule data in case of $op add/edit, rule id in case of $op delete.

The hook hook_webform_validator_alter(&$validators) can be used to alter the array of validators that is being generated by hook_webform_validation_validators().

$validators - array of validators as supplied by modules implementing hook_webform_validation_validators().
Example

<?php
/**
 * Implements hook_webform_validation_validators().
 */
function idvalidation_webform_validation_validators() {
  return array(
    'validate_id' => array(
      'name' => "Validate ID",
      'component_types' => array(
        'textfield',
      ),
    )
  );
}
/**
 * Implements hook_webform_validation_validate().
 */
function idvalidation_webform_validation_validate($validator_name, $items, $components, $rule) {
  if ($items) {
    switch ($validator_name) {
      case 'validate_id':
        $valid_ids = array(1, 2, 3); // get this from database source instead
        foreach ($items as $key => $val) {
          if ($val && (!in_array($val, $valid_ids))) {
            $errors[$key] = t('%item is not a valid ID', array('%item' => $components[$key]['name']));
          }
        }
        return $errors;
        break;
    }
  }
}
?>


What is the name of your template file? Depending on what template you use,

{% if view.total_rows > 6 %}
  <div ...
{% endif %}

should work.


Unable to get all the sub-menu's in the data compare

As a temporary way around I have done the reinstall of 7.34 and installed all the modules from the start.This got me back the menu but I cannot do the un-install every time this problem comes.
I will be losing a lot of time


Special type of nginx redirect: redirect only if $request_uri is empty

Ok, I've found the solution. I'm adding this to my existing nginx config:

location = / {
  rewrite ^ http://subdomain.domain.com permanent;
  break;
}

This redirects the top level domain but leaves all the existing "deep" links intact. If anybody wants to know why I'm doing this, it's good for SEO. I'm keeping the old URLs intact (as an archive) but redirect the domain to my new website.


Add a new role using the Drupal Services Rest api

First of All you could create the custom resource in a custom module and enable it, for doing that follow that tutorial

Second in the callback function use that code to create a new role

$role = new stdClass();
$role->name = 'editor';
// $role->weight = 10;
user_role_save($role);

Let the role name be an argument taken from the request.


Access Denied even if permission is given

Your implementation of hook_perm() (which is not valid for Drupal 7), only defines the trial_balance permission, not the akuntansi permission your code is trying to use.
The fact the user #1 has the permission to see those pages is just because the user #1 by-passes all the permissions; in fact, user_access() returns TRUE for that user.

  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

To make it clear, without explicitly setting an access callback, the access arguments are expected to be an array with the user permission string, which in your case would be trial_balance.

If the module is for Drupal 7, then hook_perm() is not even used; instead, Drupal 7 uses hook_permission(), which is not a simple renaming of the previous hook. It is expected to return a differently structured array; using the same array as Drupal 6, will cause it to not properly work.


Nevermind, I managed to do this via a module I wrote.

To whom it may concern, the idea is to create a hook override for the hook field formatter.


Drupal redirects after form submissions. So you are effectively making two requests, one for the form submission and one as a consequence of the redirect.

See Wikipedia: Post/Redirect/Get for details about why Drupal redirects after form submissions.

Set $form_state['redirect'] = false to prevent redirection.


How do I show a field value of a referenced field separately?

I Think found the solution.

I Create a views and add a relation to entityrefence field , So in field of the view I can add another field of referenced content.

for example if we added reference field to users,in a view can add relation to that reference field (go to relations part of views settings) and add another user fields like email or user picture in our views (from fields part of the views settings).picture and email of referenced user show to ours.

Sorry for bad english typing.I hope solve problem of somebody.


Is json_decode parse-ability proof of a safe string?

TL;DR: You should check_plain it.

Because the json-enoded string itself can contain insecure code.

This is our example. $data[1] and $data[2] should not be executed.

$data = array(
  'Hukana Matata',
  '',
  'CLick here',
);

You encode this with json_encode. If you json_decode($data_str), and it's a perfectly valid JSON.

$data_str = json_encode($data);

Now, if you print this:

print $data_str;

Now, you will see that the forward slash is escaped.

["Hukana Matata","',
      'CLick here',
    );
$data_str = json_encode($data, JSON_UNESCAPED_SLASHES);
print $data_str;

Notice how the script tag sneaked in:

["Hukana Matata","","CLick here"]


Show views display based on exposed filter value

I find out two methods here.

Method 1: Use set_display function

function mymodule_views_pre_view(&$view, &$display_id, &$args)
{
 //To get the query string to find out the field value
$query = drupal_get_query_parameters($_GET, array('q', 'page'));

if( $query['viewby'] == 'photo')
 {
  $view->set_display('view_photo');
 }
}

Method 2: drupal_goto (if the two displays are not sharing the same exposed filter)

function mymodule_views_pre_view(&$view, &$display_id, &$args)
{
 //To get the query string to find out the field value
$query = drupal_get_query_parameters($_GET, array('q', 'page'));

if( $query['viewby'] == 'photo')
 {
  //build up the the query string here
 $query['filter_a'] == 'xxx';
 drupal_goto('viewphoto_path',array('query' => $query));
 }
}

To my case, i used Method 2.

I am really new to drupal, and not sure are these methods will cause any problem or not.
Let me know if they are ok.


How to remove the div surrounding the view block?

Enable Twig debugging as per this https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates
Then, see which template file is currently outputting your block view
Create a new twig template file in your theme with the same name
Copy the content of the original file
Edit accordingly


Did you force Drupal to rebuild the menu, after you changed the code? If you don't do that, Drupal will use the previously defined menus.

To force Drupal to rebuild the menus, you just need to visit the modules page (the administration page showing the list of all installed modules), disable a module, and re-enable it. The last two operations are not strictly necessary; you would probably get the same effect if you click on the "Save" button present on that page without to enable or disable any module at all.
Drupal will call any implementation of hook_menu() and hook_menu_alter(), and it will grab the last menu callbacks defined from your module.

Alternatively, you can call menu_rebuild() from code, or install Devel, which has a block containing a link that allows to force Drupal to rebuild the menu list it caches.


I think I've just used $form_state['redirect'] in the submit handler in the past.

However I'm not sure what order your submit handlers are firing in, maybe it would work if you added the after_build function to the form array as opposed to the button array. (If your custom submit handler is firing first then your redirect could get overwritten.)

E.g: $form['#submit'][] = 'he_helper_custom_redirect';

If that doesn't work then this post suggests using rebuild with redirect:

$form_state['redirect'] = 'where-do-you-want-to-go-today';
$form_state['rebuild'] = TRUE;

This code shows how to add a new custom submit handler without overwriting the original one:

function he_helper_after_build(&$form, &$form_state) {

  // add to the existing submit array to not override the default submit handler
  $form['actions']['submit']['#submit'][] = '_he_helper_custom_submit';

  // change the button text
  $form['actions']['submit']['#value'] = '2hello';

  return $form;
}


How to get grid items to align center in Bootstrap views?

If you can create div tag, you can use css as show below.

Example:

html:

.....

css:
.secLayerContainer { display: inline; float: left; width: 100% }
.secLayerContent { display: block; float: none; width: 200px; margin: 0px auto}

note: 200px also can change 20%. (your preference)


Create table while installing my custom module

In your schema your setting pid  as primary key. You are setting '' value for primary key. Remove that default value for pid and try.

Then your code should be:

<?php
/**
 * Implementation of hook_install().
 */
function person_install() {

  drupal_install_schema('person');
}

/**
 * Implementation of hook_schema.
 */
function person_schema() {

// Static (meta) tables.

$schema['person'] = array(
  'fields' => array(
    'pid'            => array('type' => 'int', 'length' => 11, 'not null' => TRUE),
    'name' => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
    'city'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE),
    'country'        => array('type' => 'varchar', 'length' => 50, 'not null' => TRUE)
  ),
  'primary key' => array('pid'),
  );
return $schema;
}

After edit the code don't disable and enable the module, hook_install will only call at module install process, so you should first disable the module, unistall the module and then install the module again.


How can I send an e-mail whenever user registration fails?

Not sure how deep you want to go, but here's what I would do.

Create a custom module, "mysite_utils" (I always make at least one
custom module to do some custom tweaks.)
Create a mysite_utils_form_alter(&$form, &$form_state, $form_id)
function.
In that form_alter function, look for the user registration form_id.
Add a custom validation handler mysite_utils_user_register_validate().
Put your validation checks in that function. If the validation fails,
send yourself an email.

This process will require a lot of custom coding, not sure what your Drupal level is.


Best way to add fields to the output of a View

Basically you have two options to do this elegantly.

Use the computed field module (it also includes the storing of the results in the database to save on heavy SQL queries as mentioned in the comments). It comes with a lot of documentation and examples at the bottom of that page.

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

Write a custom views field handler (example is for Drupal 7 only!). In drupal 8 some functions like hook_views_api() have been removed and the info file has changed.

This is less flexible and will result in a specific field to choose when building a view. However sometimes less flexible can be desirable.

In order to do this you need to write a custom module. Consisting the following folder and files:

module_name

module_name.info
module_name.module
views

module_name.views.inc
module_name_handler_field_custom_field.inc

The .info file describes the module:

name = Custom Views field
description = Provides an additional field to Views
core = 7.x
package = Views
dependencies[] = views
files[] = views/module_name_handler_field_custom_field.inc

The .module file contains the module, which in this case is only a function to let Views know where to look for its files.

/**
 * Implements hook_views_api().
 */
function module_name_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'module_name') . '/views',
  );
}

The file module_name.views.inc performs the logic for Views. If you define a new entity, use hook_views_data(). If you alter an existing entity such as a user or a node, use hook_views_data_alter() but also look at the example code of hook_views_data().

In order to create a new field based on another field, you can do something like this:

/**
 * Implements hook_views_data_alter().
 *
 * Defines a new field with content built by the module_name_handler_field_custom_field class.
 * @see hook_views_data()
 */
function hook_views_data_alter(&$data) {
 // This example adds an example field to the users table.
  $data['node']['example_field'] = array(
    'title' => t('Example field'),
    'help' => t('Some example content'),
    'real field' => 'field_existing_base_field', // Enter the base fields system name here.
    'field' => array(
      'handler' => 'module_name_handler_field_custom_field',
    ),
  );
}

Finally the handler, which composes the field. Here we can alter the output of the field using the real field we defined above as input.

class module_name_handler_field_custom_field extends views_handler_field {
  /**
   * Render a computed field value (multiplied by 5).
   */
  function render($values) {
    // Load real field value.
    $real_value = $this->get_value($values);
    // Generate new value.
    $value = function_to_substitute_complicated_value($real_value);
    return $this->sanitize_value($value);
  }
}


How to send data like NAME[]=value via POST request and simultaneously redirect user to 3rd party server?

Try setting the name directly:

$form['order_price'] = array(
  '#type' => 'textfield',
  '#title' => t('Amount'),
  '#size' => 10,
  '#required' => TRUE,
  '#name' => 'ORDER_PRICE[]',
);


How to create a link with l() function that jumps to specific part of page?

The last parameter of l() accepts also the same options accepted from url(). This means you can use the following code since Drupal 6.

<?php print l(t('About Me'), 'node/55', array('absolute' => TRUE, 'fragment' => 'FIRST')); ?>

On my test site, the output is the following one.

About Me


Showing each node's creation date but in the content-list (instead on in each node)?

I believe the purpose of this module Administration Views is exactly what you are asking for.
Once you install it, it will allow you to override your "content" page.
This way you can add extra columns, sorting and filters to that page, using the Views UI.

The View you are looking for is called Administration: Nodes (at least in D7) and if you edit that and add fields, they will show up on the content overview page. (comment by @Neograph734)

You would need to edit this view, by navigating to the admin/structure/views/view/admin_views_node URL.
Add the "Content: Post date" to the field of that view
Configure the new field; set the Date format to "Short" and possible renaming its label to sth like "Created".
You can optionally rearrange your columns and also make the new "Created" column Sortable in the Table format setting
Save your view and visit the admin/content URL, it should now look similar to this:

Hope this helps!


Function in template.php to override Profile2

I have crossed checked the suggested way on my local and I can see it working.Here are some pointers.I copied the profile2.tpl.php present inside profile2 module and paste it inside site default theme templates folder and finally clear the caches.In order to see what profile is working I added some test content on both templates and found content from profile2.tpl.php from my theme is working.

As a side Note:You can make theming experience far more easy using Theme Developer module,

  Firebug for Drupal themeing.Note that this module injects markers into
  the DOM to do its magic. This may cause some themes to behave
  erratically and less capable browsers may make it worse (especially
  IE)/. Enable it when needed, and disable it afterwards.


Try the Pathauto module to do this. I found it helpful for auto-aliasing URLs in bulk, and you can also customize it by using

function MyModule_pathauto_alias_alter(&$alias, array &$context) {

}

it works pretty well.


Can't Remove Image from CCK File Field when editing node (Throbber just spins)

I was going to say it was probably permission-related (no delete permission) but if you managed by turning off javascript than its definitely not that.

Turn on firebug, enable the console & turn javascript back on.

If its an ajax error it will show up in the firebug console.


Is there any problem with the way I attach the library to AjaxResponse
that may cause the broken layout?

I guess so. This is how core does it when its an AJAX response, it attaches it to the form like this:
$form['#attached']['library'][] = 'my_module/library_name';
$ajax_response->setAttachments($form['#attached']);


How to add current user field to view field list, when it has no relation to the content?

This is an answer for Drupal 7.

You can

use Views template system and rewrite output of the field (will work only for Views) or
create own formatter for file field (will work everywhere for fields with this formatter) or
alter any file path in hook_file_url_alter (will work everywhere without settings)

I will show how to create field formatter. It will correctly work with standard node rendering, Views, Panels, etc.

/**
 * Implements hook_field_formatter_info().
 */
function YOURMODULE_field_formatter_info() {
  return array(
    // Our own formatter for 'file' field
    'YOURMODULE_file_link' => array(
      'label' => t('Special download link'),
      'field types' => array('file'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function YOURMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  global $user;
  // Now just hide field if user not logged in
  if (user_is_anonymous()) {
    return;
  }

  switch ($display['type']) {
    case 'YOURMODULE_file_link':
      foreach ($items as $delta => $item) {
        // Some title
        $title = isset($item['description']) ? $item['description'] : $item['filename'];
        // Theme link (http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_link/7)
        $element[$delta] = array(
          '#theme' => 'link',
          '#text' => $title,
          '#path' => 'download.php',
          '#options' => array(
                        'attributes' => array(),
                        'html' => FALSE,
                        'query' => array('u' => $user->uid, 'document-fid' => $item['fid'])
                      )
        );

      }
      break;

  }
  return $element;
}

Add this code to your module (replace YOURMODULE with your module name), enable module, clear the cache if needed. New formatter will be available in Views field settings and in standard content type display settings.


What module does this site use to handle its great badge system?

This site (stackexchange.com) is not built with Drupal, but if you're looking for similar features in Drupal, check out User Badges, possibly in combination with Userpoints and/or Rules.


How to apply an image style based on a condition?

If you want to do it in template file, you can access your boolean variable using $node object. You can do following way :

if ($node->field_boolean[LANGUAGE_NONE][0]['value']) {
  print theme('image_style', array('path' => $node->field_image['und'][0]['uri'], 'style_name' => 'style1_name'));
}
else {
  print theme('image_style', array('path' => $node->field_image['und'][0]['uri'], 'style_name' => 'style2_name'));
}

Or :

If you are using panels, then you can use visibility rule to the fields by adding it twice with different image style.


How to make custom template for search results

By using the theme function I have got it working. Here is how it looks like:

/**
 * Implements hook_theme().
 *
 * Create custom theme and template files.
 */
function mymodule_theme() {
  $themes = array(
    'my_search_result' => array(
      'variables' => array('result' => NULL, 'module' => NULL),
      'file' => 'mymodule.pages.inc',
      'template' => 'my-search-result',
    ),
    'my_search_results' => array(
      'variables' => array('results' => NULL, 'module' => NULL),
      'file' => 'mymodule.pages.inc',
      'template' => 'my-search-results',
    ),
  );
  return $themes;
}


The clean URL test failed Drupal and Openshift

It's a little hard to answer your question without knowing your setup, e.g. operating system, drupal version and the location, where your site is hosted (are you trying to view it on localhost or on a remote host?).

If you are running Drupal 7, clean urls should be enabled by default.
So, maybe the following does help:

If the url you are accessing is

http://www.your-site.com/?q=admin/config/search/clean-urls

change it to

http://www.your-site.com/admin/config/search/clean-urls

... and test again. Does it still fail?

source:  https://drupal.org/node/1572984#comment-6751806


Quick tabs module change title to bottom

I would recommend you to start by downloading the excellent devel_themer module from Drupal.org and install it on your site. It will also require that you install the devel module.

Once you install it and enable it, devel_themer will tell you what template (*.tpl.php) is being used. You can then go to that template and alter the order of the HTML elements directly. You will also find devel_themer to be a great tool for learning Drupal theming.


It was hard coded in the settings.php file. This will override any settings you do in the UI.


Here is how I used exposed filter to filter content with date (assumed you have the Date Views module enabled).

I just create a view with all fields and the in the "Advanced > CONTEXTUAL FILTERS" section, I add a new contextual filter and I select Date : Date (node). In the next box, I can select the date field to filter (publication date or any date field). I can also give a default value if no date parameters is passed through the url : for example, the current date.

And that's it, I just pass the date as URL parameter : I have something like

http://mydomain.com/agenda/all/2012-03

where /all is my first parameter, I us it to match a country for my posts, and the second parameter is the month of the post.

I hope that helps.


First thing you have to do is to move the form into it's own block. That will require a hook_block_info(), to define the block, and hook_block_view(), to create the content of the block.

https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_info/7.x
https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_view/7.x

Define the block:

function my_module_block_info() {
  $blocks['your_block'] = array(
    // info: The name of the block.
    'info' => t('Your Block Name'),
  );

  return $blocks;
}

Then create the content. You can use another function that contains the form.

function my_module_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();

  switch ($delta) {
    case 'your_block':
      $block['subject'] = t('My Form');
      $block['content'] = drupal_render(drupal_get_form('my_module_myform_form'));
      break;
  }
  return $block;
}

function my_module_myform_form() {
  // Your form will go here.
  $form['my_value'] = array
  (
    '#type' => 'select',
    '#options' => array('' => '---', 1 => t('One'), 2 => t('Two'), 3 => t('Three')),
    '#required' => TRUE,
  );
  $form['submit'] = array
  (
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

Next is to create a submit callback which redirects to your page. You don't need to register the callback. Drupal looks for the form function name with '_submit' appended.

function my_module_myform_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'some/path/' . $form_state['values']['my_value'];
}

And then we need to create the page:

function my_module_menu()
{
  $menu['some/path/%'] = array
  (
    'title' => 'My form submitted values',
    'page callback' => 'my_form_submitted_value_callback',
    // array(2) will pass the value of the wildcard to the callback function
    'page arguments' => array(2),
    'access callback' => TRUE,
  );
  return $menu;
}

function my_form_submitted_value_callback($submitted_value)
{
  return t('The value you submitted was: @value', array('@value' => $submitted_value));
}

If you need more than one value, there are more methods on this page like using $_GET and session variables:
https://www.drupal.org/node/1990276

Sources:

Form within a block
https://www.drupal.org/node/2064545
https://www.drupal.org/node/1990276
How to create a new block programmatically?


All my blocks are gone. Even the block menu entry is gone

If you have a module and theme with the same name, this will happen (regardless if you do/don't have hook_block in either of theme).


Get language path prefix code as contexual filter parameter

In Views with i18n there is also a filter available for that matter:

  Content: Language

You can set this to 'Current user's language' in order to filter your content based on the selected language.


Use Rules to give users a discount on their order after a few days (Commerce)

I haven't done anything date related, but I have made some rules to apply discount based on various specifications. You should checkout the Commerce Discount module, it integrates in with rules.

So you would just need to create a rule to add a scheduler item for each of the time periods that you are interested in when the user adds an item to their cart, or whatever event you need.

Then when each scheduled item goes off, you would have a rule to apply a discount to their order, and do whatever else you want (maybe notify them by email).

Then a final rule that would delete any additional scheduled items once the order is marked at complete.

You should be able to accomplish all this with a few rules.


How to set default value of select list field on add node form?

If you need "code" way you need set default value like this.

$form['field_name']['und']['#default_value'][0] = "1"

"1" -  its number of element which you want set default.

I use that when i need set programaticaly default value for field which use term reference.


How do I embed a view as a form field and pass the information on

I ended up doing this with hook_form_alter() and views_embed_view you can also add html to a form this way.

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

if ($form_id == 'your_form_id') {

       $form['what do you want'] = array(
         '#type' => 'textfield',
         '#title' => t('Question'),
         '#description' => t('Here is a question ?'),
         '#default_value' => $form['#node']->something ? $form['#node']->something : 'itis',
         '#required' => FALSE,
         '#suffix' => '
html test here
',
         '#weight' => 0,
       );

       $form['contact_information'] = array(
         '#value' => "
some html
",
       );

       $form['choose_an_image'] = array(
         '#value' => views_embed_view('my_image_view', $display_id = 'default'),
         '#weight' => 0,
       );

      return $form;
   }

}


Preprocess image: how to get parent entity?

Here is the the "real" code counterpart to the pseudecode from the question:

function THEMENAME_preprocess_responsive_image_formatter(array &$variables) {
  // get the imagefield's parent entity
  $fieldParent = $variables['item']->getEntity();

  // this line is only needed if using media entities (= entity references)
  // must disable entity view caching to work correctly
  $fieldParent = $fieldParent->_referringItem->getEntity();

  // get the image width from the custom field
  $myImgSizes = $fieldParent->get('field_image_size')->getString();
  // can't change attribute here => store it temporarily
  $variables['responsive_image']['#attributes']['data-overridesizes'] = $myImgSizes;
}

function THEMENAME_preprocess_responsive_image(array &$variables) {
  //override sizes attribute with my calculated value
  if (key_exists('data-overridesizes', $variables['img_element']['#attributes'])) {
    $variables['img_element']['#attributes']['sizes'] = $variables['img_element']['#attributes']['data-overridesizes'];
    unset($variables['img_element']['#attributes']['data-overridesizes']);
  }
}

If using media (=entity references) you also have to disable view cache for entites (see this question)

function MODULENAME_entity_view(&$build, $entity, $display, $view_mode) {
  if ($entity->getEntityTypeId() == 'media' && $entity->bundle() == 'image' && $view_mode == 'my_uncached_viewmode'){
    unset($build['#cache']['keys']);
  }
}


Trying to add a class to a menu in a preprocess function

To add class in navigation's
 element, include below code in template.php

function THEMENAME_menu_tree__menu_MENUNAME($variables) {
return '
' . $variables['tree'] . '
';
}


Creating a view with 2 content of different content types

"2 specific contents" .. if it's very specific / admin decides, add an extra field with code. Fill 2 nodes with something like 'promo' or '1234 Hide this field in the display, so you only see the code when you're editing. In the view, filter on this field (only nodes with this and this code) and voilá.

-edit: in this way you can re-use the view for different codes. Maybe use the URL (like foobar.com/promo shows the 2 nodes with promo in the code field). Tbh, i don't know how to use the URL in Views ;-)


Drupal 8, very simple hierarchical form doesn't work

You need change type $form["planet"] to fieldset or container. Don't use text field in this case:

$form["planet"] = array(
  '#type' => 'fieldset',
  '#title' => '1 : '.$this->t('planet'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);


Does service module expect Base64 encoding for file uploads through http-post (drupal 7)?

Short answer yes it does. There is a create raw method but unfortunately, it doesn't work very well b/c drupal 7s file handling is a joke.

Ive created a patch that will allow you to attach files to  a node and it uses multipart form, but its a work in progress.

http://drupal.org/node/1484992


Installing on CentOS 6 with Apache 2.2.15

If you are sure that mod_rewrite is enabled and working you could try to get past the system requirements check if you change the url during the step "Verify requirements" like this:

Standard URL like this:
core/install.php?langcode=de&profile=standard
change it to:
core/install.php?langcode=de&profile=standard&rewrite=ok

You add

  &rewrite=ok

to the url. This will normally be done through .htaccess. Then reload the page or click try again and you should get past this warning.

But it seems that something is not working as expected with your mod_rewrite, so you might encounter trouble later on.


How to get url and description of FileFieldItemList's items in node template

I am able to access the uri, and I can generate url from it by a Twig filter.

{{ content.field_document.0['#file'].uri.value|urlFromUri }}
{{ content.field_document.1['#file'].uri.value|urlFromUri }}
{{ content.field_document.2['#file'].uri.value|urlFromUri }}

and the description:

{{ content.field_document.0['#description'] }}
{{ content.field_document.1['#description'] }}
{{ content.field_document.2['#description'] }}

the Twig filter:

<?php

namespace Drupal\something_general\TwigExtension;

use Drupal\Core\Url;

class Custom extends \Twig_Extension
{

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters()
  {
    return [
      new \Twig_SimpleFilter('urlFromUri', array($this, 'UrlFromUri')),
    ];
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName()
  {
    return 'custom.something_general.twig_extension';
  }

  /**
   * @param $uri
   */
  public static function UrlFromUri($uri)
  {
    $realpath = drupal_realpath($uri);
    $path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $realpath);

    return $path;
  }

}

I am also able, to get the number of the items of the FileFieldItemList:

{% for index in 1..node.field_document.getValue|length %}
{% endfor %}

And finally the iteration in the node--publication.html.twig file:

{% for index in 1..node.field_document.getValue|length %}
  {% set document = content.field_document[ (index-1) ] %}

  {{ dump(document['#file'].uri.value|urlFromUri) }}
  {{ dump(document['#description']) }}

{% endfor %}


There are always different ways to do things in Drupal. Drupal Commerce (DC) is the shining example of this. DC allows for project attributes out of the box using fields on product types that are set to be attributes (this creates an AJAX field as a select option in the add-to-cart form). This is an example of attributable fields. You will notice the price and the photo changes when you change the video type. You can also handle some attributes with line items added to an entire order (this is how shipping is done). If you have global attributes, the best way would be a line item added to the entire order.

You list delivery and background color; I am going to assume these would be global attributes that would apply to any order in your store. These would be prime candidates to use line items added to the order. But this also depends on how you are going to allow your customers to purchase products.

I would need more infomration about how you want to setup your shopping experience to be able to completely answer the question.

DC is an extremely powerful and flexible shopping cart. But it is complex.


You're not supposed to change the $form element in the AJAX callback, only in the form_alter function. Otherwise,

  when the form is submitted (ajax or not), the submitted form does not
  match the cached form, which causes Drupal to fail


Use views calc to achieve this behaviour, This module adds simple calculations to a views table: https://www.drupal.org/project/views_calc


How to capture bank payment info to store for payment processing using Drupal Commerce?

Commerce Card on File

Commerce Card on File provides an API and user interface for storing
and reusing credit card data on subsequent orders within Drupal
Commerce. The module does not retain full card numbers locally but
instead stores the remote ID of the full card data from the payment
gateway used to validate and process your credit card transactions.
This means card on file data will only be good for a single payment
gateway; if you change payment gateways or accounts, your stored card
data may no longer be usable.

How this module is PCI compliant
This module is safe as it does not retain the full card number. Only the last 3 numbers and expire date are stored in your DB. So if your DB gets hacked, you'll be fine.
Furthermore, when this module connects your payment processor, it uses a token to represent the persons card. Only you can use that token to deposit funds to your account. So even if somehow they intercept the token value, they can't do anything with it.
source: David Kitchen

You should also get Commerce Dunning to deal with expired card numbers.
Commerce Dunning

Dunning management (Delinquent User Notification) is the automated
process that's kicked off when a charge attempt of a recurring order
fails. This process involves periodic customer communication and
payment retries.

Dunning Video Tutorial


(Disclamer: As usual with legal questions, I am not a lawyer, only a lawyer can give you a definitive answer).

Every Drupal module that is written and every javascript code that directly interacts with Drupal (or any other GPL code, but note that jQuery is dual-licensed and also available under the MIT License, this is not relevant when used with Drupal, though), automatically falls under the GPL. That's why GPL is also called a viral license. Everything it "touches" is GPL'ed automatically.

If you give the source code to someone, then he has every right the GPL grants him, including giving the source code to anyone he wants to, modify it and so on. However, viewing a website alone does not distribute your PHP code. JavaScript is a tricky question, see for example https://softwareengineering.stackexchange.com/questions/125955/using-gpl-licensed-jquery-scripts-on-website-with-ads and http://www.gnu.org/philosophy/javascript-trap.html. As far as I understand these, you always distribute the JS code.

So, obfuscating the JavaScript without providing a way to get the unmodified source code or adding a statement like the one you suggested above is in fact a direct violation of the GPL and someone could attempt to sue you.

Also note that there is an extended version of the GPL, the Affero General Public License, which explicitly includes viewing of a website as distribution. CiviCRM for example uses that license, so if you are required to allow visitors access to your custom adjustments/extensions of your website, when using a software like that.

Given the way the Ajax system in Drupal works, most relevant things usually happen on the server side, so that is usually not a big problem. Also, most GPL related lawsuits are usually related to companies selling products which run GPL software (e.g. routers) which don't provide access to their customized source code. I've never heard of a lawsuit against a website violating the GPL, but that could just be ignorance on my side, don't count on that ;)


problem migrating my drupal site PDOException: SQLSTATE[42000] [1044] Access denied for user

With JustHost you need to assign the user to the database from the Database Maintenance drop down page. Instructions are on their site too. I did this, and it fixed my problem.


How to get comment cid in hook_comment_insert?

All entities have an id() method:
$cid = $entity->id();


The function would be get_browser. But you should be using Javascript to detect this instead of PHP.

There are a variety of ways it would fail/be incorrect from the PHP layer, caching, spoofing, etc. Once it gets cached, it would show up for the next person regardless of what browser they are using.

Plenty of JS libs out there can detect it as close as possible, but there is also a module ready to roll here as well that will just solve this for you more than likely, one such module being Browser Detect. There are a few modules for this actually, try them out and see what one suits you best.


Custom Path Alias with Initial Letter as Token

There are many ways to achieve this, as you said.

The less-coding way I see is to use Custom Token and create for each node a token using the following code :

return substr($node->title, 0);

Then you use this token in your URL alias pattern like [yournewtoken]/[node:title].

If you have a multi-lingual site, the first letter might not be the same in all languages, you may update this code to fit this.


Inherit all styles from base theme expect a few

As noted on the sub-theme page, a sub (or child) theme will inherit all the parent's css files "as long as you declare at least one stylesheet in your sub-theme's .info file".

You can override a stylesheet simply by declaring one of the same name in your sub-theme's .info file. If there is a stylesheet you don't want in your sub-theme, just add an empty file with same name to the sub-theme's .info file.


programmatically get bundles from field collection?

What about:

$bundle = db_query("SELECT bundle, entity_type FROM field_config_instance WHERE field_name = :field_name", array(':field_name' -> $field_name))->fetchAll();

If you know the enity_type then you can use field_info_instances().


How do I populate an address field in php?

But what are the address field element and how do I get a list of them?

You can get a list of the available field columns from addressfield_field_schema():

country
administrative_area
sub_administrative_area
locality
dependent_locality
postal_code
thoroughfare
premise
sub_premise
organisation_name
name_line
first_name
last_name
data

  Can they be anything I want?

Not by default, but as the addressfield module uses ctools plugins, it's easy to extend to add your own if necessary (see the Address Field Phone module for inspiration).

  Does the create content form create the array when the form is submitted and therefore the form labels are just a guide

Exactly right, the addressfield module provides labels and fields based on the currently selected country. They can be whatever suits the locale, but if you look at the names of the form elements, or inspect the field array on form submissions, you'll see they always match the keys from the field schema hook above. There's an excellent answer to a question on SO which goes some way to explaining the reasons for this implementation.

For a UK address specifically, you would populate it roughly like this:

$node->field_address[LANGUAGE_NONE][0] = array(
  'organisation_name' => 'Company',
  'first_name' => 'Joe',
  'last_name' => 'Bloggs',
  'country' => 'GB',
  'thoroughfare' => 'Street address 1',
  'premise' => 'Street Address 2',
  'locality' => 'Town/City',
  'administrative_area' => 'County',
  'postal_code' => 'SW1 1AA',
);


In Drupal 7 there isn't a specific hook to alter the URL associated with a taxonomy term, but you can use the generic hooks for altering URLs, which are hook_url_inbound_alter(), and hook_url_outbound_alter().

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('|^taxonomy/term/([0-9]*)|', $path, $matches)) {
    // Alter $path; $matches[1] contains the term ID.
  }
}

function mymodule_url_inbound_alter(&$path, $original_path, $path_language) {
  // Revert the change done in mymodule_url_outbound_alter().
}

hook_url_outbound_alter() is invoked for URLs output from Drupal, hook_url_inbound_alter() is invoked for URLs Drupal is receiving.

In Drupal 6, it is possible to implement hook_term_path(), but that is invoked only for the module associated with the taxonomy term. The code invoking that hook is in taxonomy_term_path().

  if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
    return $path;
  }

If you want to use a third-party module, then there is the Pathauto module, which allows to automatically set the alias for users, nodes, and taxonomy terms.

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


clean_class is a filter which invokes the \Drupal\Component\Utility\Html::getClass() method on the string, which:

  Prepares a string for use as a valid class name.

Basically it removes invalid characters from HTML classes in preparation for rendering. clean_id is the equivalent for HTML IDs.

There are other filters registered by core too, see TwigExtension::getFilters for more details.


How to update user fields from a custom module form?

you are not saving the user correctly, you should call:

$user->save();

This is an example how to change the username:

$user->setUsername('new-username');
$user->save();

Here is another example to add a role to a user:

$user->addRole('administrator');
$user->save();

Can you try the following:

/**
 * Submit the register form
 *
 * @param array $form
 * @param FormStateInterface $form_state
 * @return array|RedirectResponse
 */
public function submitForm(array &$form, FormStateInterface $form_state)
{
    // Create a new user
    $values = $form_state->getValues();

    // User from Drupal\user\Entity\User;
    $user = $this->ctrUserManager->getCurrentUser();

    if($user){

        $user->set('mail', $values['mail']);
        $user->set('field_last_name', $values['field_lastname']);
        $user->set('field_first_name', $values['field_first_name']);
        $user->set('field_civility', [$values['field_civility']]);

        $violations = $user->validate();

        if (count($violations) === 0) {
            $user->save();
            drupal_set_message('Your profile has been updated');
        } else {
            drupal_set_message('Error during user profile update', 'error');
        }
    }
}


Display hierarchical entity reference fields inside node

You could render this with four different display modes:

1.) The Event view mode to start with:

Event Title
Event Date
Event Description
Reference field for Organization, configured to render the view mode logos1
Reference field for Organization, configured to render the view mode logos2

2.) The Organization view mode logos1 contains one field for the Organization logos:

Image field logos

3.) The Organization view mode logos2 contains one field for the User logos

Reference field for the content type User, configured to render the view mode userlogos

4.) The content type User view mode userlogos

Image field for user logos

To implement two instances of the reference field you need the module Display Suite. Or combine logo1 and logos2 in one view mode with two fields, but then the logos will get mixed. Or use for the second reference field a View, with the help of EVA.


Not as much of an answer as it is a recommendation. You should be doing this at the price calculation (per product) level, not order level. Not doing this can mean you're taking into account the taxes, shipping, other coupons/discounts, etc.


If the filter not Full HTML, you will need to edit the filter format and enter the attributes on the anchor tag in the settings. If not, they will be stripped out (for security reasons).


Remove superfluous divs from views fields output?

There are several ways to strip HTML. You can under rewrite results Strip HTML tags or under style settings Customize the HTML. If you have tokens enabled you can exclude a bunch of fields then add a Global text markup field. Most of the wrapping markup will be removed and you can use the your own markup or not by typing HTML into the Global text field placing the placeholder tokens where in the HTML the field should be rendered. Another way to clean up Views markup is to create override theme templates by clicking on theme templates for the theme override template title and copying the default code changing anything you don't want in them before you save.


Status updates in organic groups disappear after a period of time

In /admin/settings/activity_log there is just the field to control this.

Note: Though each time we run a cron job, entries over 30 days still disappear. This is perhaps a bug? So our makeshift solution is to click the Regenerate Activity tag. This seems to behaves predictably.


If you just need to add the classes I believe it can be done like so
$url = Url::fromRoute(
  'entity.node.canonical',
  ['node' => $record->nid],
  ['#attributes' => ['class' => ['btn', 'btn-default', 'use-ajax']]]
);

 $title_link = Link::fromTextAndUrl($record->title, $url);

At that point $title_link should be able to be rendered in the template as is!
// php
$variables['title_link'] = $title_link;

// twig
{{ title_link }}


Conference registration form/site with limited places available

Session = content_type.

One session = one node of type session

Every session has a field "available spaces"

Create a custom form programatically which you pass the session id in a field of type "value".
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#val

In the validate function of the form check if the field "available spaces" for the session with that id is greater than 0, otherwise decrease it and in the submit function store the user id with this session id.

Regards.


Site-wide altering of access behavior in Drupal site

Here's one way to do it:

Set up your permissions to reference a taxonomy.
Add a hook to change the view_mode of a node you don't want a user to see.

Ours looks like this, we are using a taxonomy called 'Access Level' to control what level of access a node should be shown at (field_access_level).  Roles can be given permission against any, all or none of the various taxonomy terms, really useful for segregating products on a Drupal site.

/**
 * Implements hook_perm().
 */
function i_security_access_permission() {
  $permissions = array();
  $terms = taxonomy_get_tree(11);
  // Define permissions using taxonomy Access Level vocabulary
  foreach ($terms as $term) {
    $permissions[$term->name] = array(
      'title' => t($term->name),
      'description' => t('Access content from '. $term->name),
    );
    $permissions['Edit Role Names'] = array(
      'title' => t('Edit Role Names'),
      'description' => t('Allows users to edit role Names'),
    );
  }
  return $permissions;
}

/*
 * Implements hook_entity_view_mode_alter
 *
 * Sets the view mode to full or teaser based on user access rights
 */
function i_security_access_entity_view_mode_alter (&$view_mode, $context) {
  if (array_key_exists("field_access_level",$context['entity'])) {
    $access_tid = $context['entity']->field_access_level['und'][0]['tid'];

    $access =  taxonomy_term_load($access_tid);
    // Checks if user has access to content
    if (!user_access($access->name) && $view_mode != 'search_index') {
      $view_mode = 'teaser';
    }
  }
}

You can improve upon it by adding a test for view_mode in your node template and displaying a login button and/or your exhortation to upgrade when the node is shown in teaser mode.  Same applies for views.

Some things to note:

If you're using a taxonomy and programmatically mapping it to permissions, make sure users can't change the taxonomy terms because all of the permissions get lost
User can however, add new taxonomies and remove unwanted ones with impunity.  Especially since if you remove a term and then add it back in, the permissions you have set for your roles magically reappear (at least they have in my experience).
The && $view_mode != 'search_index' near the end is because I found this was interfering with Apache Solr indexing the site: it was only indexing teasers!  I'm not sure what other view_modes there are, so be careful with this.

I wonder if we have the makings of contrib module here?


Change drupal standard messages like "You have just used your one time login link"

Try the String Overrides module. If you have more strings to change.

Provides a quick and easy way to replace any text on the site.
Features

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the
Locale module
Note that this is not a replacement to Locale as having thousands of
overrides can cause more pain then benefit. Use this only if you need
a few easy text changes.


Views breadcrumbs can be tricky. You can create a module and a class that implements BreadcrumbBuilderInterface and do:

class MyBreadcrumbBuilder implements BreadcrumbBuilderInterface {

  use StringTranslationTrait;

  /**
   * The AdminContext service.
   *
   * @var \Drupal\Core\Routing\AdminContext
   */
  protected $adminContext;

  /**
   * The AliasManager service.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * The EntityTypeManager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    AdminContext $admin_context,
    AliasManagerInterface $alias_manager,
    EntityTypeManagerInterface $entity_type_manager
  ) {
    $this->adminContext = $admin_context;
    $this->aliasManager = $alias_manager;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) : bool {
    if ($this->adminContext->isAdminRoute()) {
      return FALSE;
    }

    // Using route_match, check if the current route is a view and which view id
    // and return true or false
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) : Breadcrumb {
    $breadcrumb = new Breadcrumb();

    // create your breadcrumbs...

    return $breadcrumb;
  }

}


Have a look at the "Usage statistics" page of any module on drupal.org, which includes all sorts o relevant information.

As an example, checkout the Rules module, for which you can find those statistics at https://www.drupal.org/project/usage/rules . Apart from a nice chart, it also gives you the statistics by Drupal Release (D6, D7, D8), and this for each Drupal Release for which the module does have some release. If you scroll to the bottom of those statistics, you even get more details (for the last 5 weeks) of every (minor) release of the module.

Attention: don't confuse "using a module" with "number of dowloads of a module"! E.g, for the Rules module, there are currently 296,819 sites reporting that they are using this module, while there have been 2,642,716 downloads so far. Open question: does that mean that only (about) 10% of sites for which this module was downloaded actually still use this module? Answer: I don't think so ...

PS: Replace "rules" in the above URL by any other module's name to find similar statistics.


Custom module and template.tpl.php files

There are a lot of examples of use of the Drupal API for module developers in the Drupal documentation. In particular, you may find the Examples for Developers module handy, especially the "theming_example" sub-module. This is not an actually functional module, but just a container for a lot of example code that new developers can test, manipulate and learn from.


Loading a form via AJAX with drupal_get_form()

Try just to do echo render($return); exit();.

Otherwise, you should change de delivery callback from the path of your page, and I'm pretty sure that exists one one Drupal for Ajax.


Block value in a view row design template

You can use the following code.

$block = block_custom_block_get($block_id);
$content = $block['body'];

But be advised that it would generally contain html which would be difficult to parse.

If you are looking to store a value and then use it to check in the theme layer I would suggest creating an admin page for that and storing the value in the variables table, which you can later access by

variable_get('my_setting', 3);