A View is basically a query builder. You need to provide it with a filter that includes the content you want to show, and excludes the content you don't want to show.

There are many different different ways to solve it, here are a few of the common ones:

Use different content types for the different types of content, and filter by "Content type" in the Views
Add a Vocabulary, "Post Type" or something, with "Current Affairs" & "Education" as terms; attach a term reference field for that vocab to the content type, filter on that instead in the Views
Add a boolean/text/numeric/whatever field to the content type, set that to a value on a node-by-node basis, use that to filter the Views.


How do I remove the "submitted by" text on node display?

You can find the option by editing the content type settings.

Structure > Content Types > Type Name

Click Edit

Then uncheck the Display author and date information. option in Display Settings.


With the help from @Clive I found a solution:

/**
 * Implements hook_node_update().
 */
function MY_MODULE_node_update(\Drupal\node\NodeInterface $node) {
  foreach ($node->getFieldDefinitions() as $definition) {
    if (!in_array($definition->getType(), ['entity_reference', 'entity_reference_revisions'])) {
      continue;
    }
    if (!$definition->getSetting('target_type')) {
      continue;
    }
    if ($definition->getSetting('target_type') == 'media') {
      $media = $node->{$definition->getName()}->entity;
      if ($media) {
        $media->groups->target_id = $node->groups->target_id;
        $media->save();
      }
    }
    if ($definition->getSetting('target_type') == 'paragraph') {
      $paragraph = $node->{$definition->getName()}->entity;
      if ($paragraph) {
        MY_MODULE_update_media_items($paragraph, $node->groups);
      }
    }
  }
}

/**
 * Set groups on all media items referenced in a paragraph.
 *
 * @param $paragraph
 *   The paragraph.
 * @param $groups
 *   The groups to set.
 */
function MY_MODULE_update_media_items($paragraph, $groups) {
  foreach ($paragraph->getFieldDefinitions() as $definition) {
    if (!in_array($definition->getType(), ['entity_reference', 'entity_reference_revisions'])) {
      continue;
    }
    if (!$definition->getSetting('target_type')) {
      continue;
    }
    if ($definition->getSetting('target_type') == 'media') {
      $media = $paragraph->{$definition->getName()}->entity;
      if ($media) {
        $media->groups->target_id = $groups->target_id;
        $media->save();
      }
    }
    if ($definition->getSetting('target_type') == 'paragraph') {
      $paragraph = $paragraph->{$definition->getName()}->entity;
      if ($paragraph) {
        MY_MODULE_update_media_items($paragraph, $groups);
      }
    }
  }
}


How can I programmatically extend the registration form?

I had this same question and it doesn't seem to be answered anywhere so I'll give the answer that I figure out, hopefully this helps someone.
First you need to add the form to the entity do this in the module file in hook_entity_type_build something like the following sample:
/**
 * Implements hook_entity_build
 */
function MYMODULE_entity_type_build(array &$entity_types) {

  $entity_types['user']->setFormClass(
    'MYMODULE_register',
    'Drupal\MYMODULE\Form\myModuleRegisterForm'
  );
}

Create a new class src/Form/myModuleRegisterForm.php to extend RegisterForm:
namespace Drupal\MYMODULE\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\user\RegisterForm;

class myModuleRegisterForm extends RegisterForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {

    $form = parent::form($form, $form_state);

    // Change the form here

    return $form;
  }

}

Then load it in your controller
public function myModuleRegister {

  $build = [];

  $entity = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->create([]);

  $formObject = \Drupal::entityTypeManager()
    ->getFormObject('user', 'MYMODULE_register')
    ->setEntity($entity);

   $build['form'] = \Drupal::formBuilder()->getForm($formObject);

   return $build;
}

That pretty much covers it, obviously you need the route to point to the appropriate function in your controller but otherwise this should do it.  Hope it helps.


SearchApiException while retrieving config files of Solr server solr_server server

I found this question when I started with the same problem (in my case a Debian server we manage vs a RedHat we don't) and did not see the answer (due to how short it was). After a lot of digging I realized the problem was SELinux (which is the same given the answer I now see above).

The main reason for the puzzle was that the requests did work from command line ("wget -O - {your SOLR ping URL}" worked just fine). But we learned from a Drupal thread (https://www.drupal.org/node/1473368) that recommended to test if SELinux was running:

sestatus
getsebool -a | grep httpd

The reason for it to fail normally is that "httpd_can_network_connect" is off. You can set it on by doing: setsebool httpd_can_network_connect=1

By the way what point us in the right direction was trying to use the same API call drupal_http_request() on a different module. We enabled/used Aggregator to pull an RSS feed (which worked), but our call to the SOLR ping show result "-13 Permission denied" on the log.

Hope this helps as a shortcut for the next person with this issue!


Installing Drupal module requires ftp access - macOS localhost

Depending on how you are running this locally (native, Docker, etc) this can differ, but I will assume you are using what comes with macOS to run Drupal.
The difference here is Mac does not have a www-data or apache user like Linux does. If you are running with the defaults, the user you are looking for is _www (unless you have modified this in Apache confs).
So, you will want to do:
chown _www (directory)

Technically, this is probably better asked on ServerFault, but I can imagine there are a lot of people trialling or demoing Drupal who just use what is on Mac to do it, and will come across this post finding it helpful.


I switched to the latest dev release ob the webform module and could skip the wizard pages depending on previous values without having to code anything. Thanks for the tip @jrockowitz ;)


You can use the following code.

db_query('DELETE FROM {node_revisions} nr WHERE nr.vid NOT IN (SELECT n.vid FROM {node} n)');

You don't want to delete all the revisions: You want to delete all but the current revision.

Executing only that query is going to leave data about deleted revisions in other database tables, as modules that save information about a revisions are not notified a revision is going to be deleted. I am thinking of the CCK module, for example, which saves information about the node fields in its own database tables. The CCK module executes the following code, when a revision is deleted.

/**
 * Implementation of hook_nodeapi 'delete_revision' op.
 *
 * Delete node type fields for a revision.
 */
function content_delete_revision(&$node) {
  _content_field_invoke('delete revision', $node);
  _content_field_invoke_default('delete revision', $node);
  cache_clear_all('content:'. $node->nid .':'. $node->vid, content_cache_tablename());
}

A more complete code would be similar to the following one.

$query = db_query('SELECT nr.nid, nr.vid FROM {node_revisions} nr WHERE nr.vid NOT IN (SELECT n.vid FROM {node} n)');

while ($revision = db_fetch_object($query)) {
  if ($node = node_load($revision->nid, $revision->vid)) {
    node_invoke_nodeapi($node, 'delete revision');
  }
}

db_query('DELETE FROM {node_revisions} nr WHERE nr.vid NOT IN (SELECT n.vid FROM {node} n)');

Looking at the code of node_revision_delete_confirm_submit(), I don't see anything else that needs to be done.

The new code I wrote could take much time to be executed, depending on the number of nodes, and revisions. This means the code should be executed:

In an implementation of hook_cron()
As a batch operation
In a PHP file that bootstraps Drupal, and increases the execution time with @set_time_limit(240)
With Drush

Considering that the code is only necessary for the migration, I would avoid the first two options, which would require you to write a module you need just in this very specific case. If you have more sites, and all of them need to execute the same code, option 3 is always possible, and that is what is done from Drupal with cron.php.
About option 4, I would first check Drush doesn't have already commands that could be helpful in this case. I would not reinvent the wheel, when it is not strictly necessary. I would also check how to write Drush Shell Scripts.


Requirements issues while setting up a D7 website

Looks like you're missing some PHP components.

Try the following on the command line:

sudo apt-get install php-gd php5-common php5-mysql
sudo service apache reload

EDIT

I've just realised I've COMPLETELY assumed you're running *buntu - if you're not then please let me know!


If you modify your inline entity form by writing a small module, (for this look at README and the ..api.php) you can set your default values by loading them from the entity. So your former entries are available.


How to restrict Drupal commerce Shipping only for two provinces

If you are using the Address Field module, you definitely have Madrid and Guadalajara as options. Thereafter, you need to use rules and add conditions. I'm not sure how your shipping works but I would use the Flat Rate module to create components, such as 0-5km, which costs a set amount. Create a flat rate, give it a name: perhaps 0-5 km, and a price then add conditions. Select "Order address component comparison". Province will be available. Your operator is "equals" and then you add your values, Madrid and Guadalajara.

Here is a screenshot of a rule that restricts shipping costs being applied to a certain country, within weight parameters and restricts it to a particular product but it is possible to select a province instead of a country

Here is a screenshot of the components, I selected province here to show that it is available


It should be possible to take most relevant config files (content type, fields, displays, ...), create a module, put them in the config folder of it and install that module on any site you want. Or the same with an install profile, I made some relatively successful* tests there by throwing all config of an actual site into an install profile and was able to install it.

You can also manually edit them, as long as you're not doing in the active storage.

Problematic are for example config files that contain a mix of things. Translation settings for example, which are stored in a single yml file for all entities and bundles, or rest.module settings, all enabled resources are also in a single file. So you would have to write code that manually updates that configuration in hook_install().

* Relatively successful, which means I had some troubles with config that referenced content (custom blocks, default images of image fields) but I think that can be sorted out.


Unable to add Acquia Cloud site using Acquia Dev Desktop behind a proxy (Win 7)

Short answer is:
"Proxy configuration is currently not supported in the most recent version of Acquia Dev Desktop"

There are some workarounds, that work with varying levels of success, but nothing solid that I've found.


Is the Panels simple cache lifetime a minimum or maximum?

Simple cache, is unfortunately not very clever, hence the name "Simple".

A 7 day cache will be cleared when the first request past the 7 day mark occurs, so it is the minimum lifetime of the cache.

The reason that it isn't smarter than that, is probably that content panes can come in a great deal of forms, and it's not trivial to implement a generic solution to knowing "When something was updated".

Continuing on that, I've implemented Panels cache which attempts to be smarter, but is limited to Content panes based on an entity context. It considers the cache lifetime to be infinitely long, but clears it when the entity that is the context is updated.

It's not terribly well tested, but it was written for a paying client that had it running in production without issues or complaints at least for the months I worked with them.


#element_validate is used to provide validation for a specific element.
#validate is used for the form, and for elements that cause the form to submit (button, image_button, submit). It provides the names of extra functions to call during the validation process.
hook_field_validate() is for validating fields (not standard form elements). This doesn't necessarily take place in the context of a form submission.
There's isn't a hook_form_validate() - by convention if a function called FORM_ID_validate() exists then it will be used as part of the above #validate array for the form. This is used to validate any part of the form, not just a specific element.
hook_field_attach_validate() runs as validation when fields are attached to an entity, it doesn't run in the context of a form (see field_attach_validate())

Not all of the above are executed at any one time, or in any single context, so listing an execution order isn't possible.

Hopefully the above distinctions will make it obvious which one to use in what circumstance.


How to properly add JavaScript to drupal

If your code sample is accurate, and you are calling drupal_add_js() from outside a function in a module file, then that will be the problem.

You would want to add your js from within your hook_block_view().
This way it loads after drupal has done all it needs to do with its js and jQuery will exist.

Also, you might not want to put your map initialisation in a behavior, because you would usually only ever want your map to load once, on page load.
I don't know all the details of your setup though so I can't know exactly what is best in your case.


Custom Mult-Step Form remove next button

You could try something like this on the second form:

if (empty($form_state['values']['location']) {
    $form['next']['#access'] = FALSE
}


How to use multiple content types in a "Calendar" View sorting by the field type of "Date"?

You need to change the calendar view's Contextual Filter (Under "Advanced") to use the new date field, instead of the post date.


Finding commerce custom fields inside a rules loop

The trick for this is to use a component.

Create a new component, and check for the fields using "entity has field". Then, in the original rule, loop over the line items, and put the component inside that loop.

The kicker is that it is impossible (possibly? not I couldn't find a way) to get other product-level fields into this component.


If you're using symlinks, you'll have to allow that in your .htaccess file.


Language switcher not visible when logged out (Drupal 7)

You have to check the permissions on internationalization module; probably you have selected "administrator only".

By the way, read this: Drupal multilingual.


$content contains the renderable elements of your node (see documentation on node.tpl.php). This contains the node body, links, and other custom fields you've added to your node type. As Andrew suggested, the drupal_render() function can print individual fields or all fields (render($content)).


How one can get a field auto loaded with node title by passing nid

Prepopulate might solve your problem.

The Prepopulate module allows fields in most forms to be pre-populated from the $_REQUEST variable.
For example, the following URL,
http://www.example.com/node/add/blog?edit[title]=this is the title
will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets. For examples on usage for all of these cases, please read the USAGE.txt file that comes with the module or you can read the online handbook page.


Adding a view desktop link to mobile site

I don't know about X-AH-Mobile-Redirect, but I did this a while ago by creating a link like http://example.com/?device=desktop and on page load I would check for $_GET['device'] and for a cookie

Then I could just check

if (isset($_GET['device']) && $_GET['device'] == 'desktop') {
    setcookie('mycookie', 'true', strtotime('+365 days'));
    $mobile_browser = 0; //This forces site into desktop mode
}

Then on desktop version you just go the other way around with a http://example.com/?device=mobile

if (isset($_GET['device']) && $_GET['device'] == 'mobile') {
    setcookie('mycookie', null, -1); //Unset cookie
}

Of course you have to add whatever you need to force your mobile detector to go into mobile/desktop version, but it's pretty much it, on page loads check for the cookie and for the query strings and act accordingly.


How to avoid duplication of data using feeds module?

Use Target configuration as unique to avoid duplication


Within a View, How do i paginate the content found inside a single Multiple file field, i.e. inside one node

There are two obvious ways to solve this, the easier one is through your existing Content views, and the other is through creating a new File type view.

Content type Views

It is true that the Views type determines what will go into each new row in views results, and Pager is acting on views rows.

But if you have a multi-value field it is possible to make it display each value in a separate views row, making the same node appear many times in the views results, as many times as there are field values.

Here's how you do it:

Edit your "Videos" field and under Multiple field settings make sure you don't have the Display all values in the same row option enabled.

This will make the same node repeat as many times as you have videos, and although the Pager will still work on node rows, it will look like it's working on field values (if you're only showing that one field and not revealing the node Title, for example).

File type Views

To get the Pager to actually page through individual files you have to create File views. There are some steps how you can make that views pull data from one content type and field:

The File views starts by displaying file names of all the files on the system. To make it aware of where the file is being used (you want only the Videos) add a Relationship File: Content using Videos and make it required. This will filter out only the files that are in the "Videos field", and it will make available various Content related Fields and Filters.
Add the "Content: Videos" Field and set it so it doesn't display all values in the same row. You will still see the files repeated in the results.
Don't add any File Fields
Under Query settings enable Distinct and Pure distinct. This will make each file display only once.
Add the Contectual filter for NID, it will be available because of the Relationship you added and it will use it by default.


How do I modify a webform submission field right before it is saved?

You can use preSave method in your handler. Please check out the Webform module handler tests module which is part of Webform codebase, it has TestWebformHandler.php file which defines the submission test handler which displays a status message for every handler event.

For example:

<?php

namespace Drupal\webform_test_handler\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformInterface;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform submission test handler.
 *
 * @WebformHandler(
 *   id = "test",
 *   label = @Translation("Test"),
 *   category = @Translation("Testing"),
 *   description = @Translation("Tests webform submission handler behaviors."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_IGNORED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class TestWebformHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   */
  public function preCreate(array $values) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postCreate(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postLoad(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preDelete(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postDelete(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $this->displayMessage(__FUNCTION__, $update ? 'update' : 'insert');
  }
}

Then you can use a standard ways of modifying your $webform_submission.

See also: Way to do an action after a webform submission has been created.


How do I attach AJAX click events on  or  tags?

You need to write code for this element. Copied from d.o..

STEP BY STEP

Select the element to attach Drupal.ajax object to.
Lets create HTML element first.

/**
 * Menu  callback.
 *
 * Build container to load ajax content to.
 */
function my_module_remote() {
  $wrapper = array();
  $wrapper['#attached']['js'] = array(
    drupal_get_path('module', 'my_module') . '/my_module_ajax.js'
  );
  $wrapper['#attached']['library'] = array(
    array('system', 'drupal.ajax')
  );
  $wrapper['container'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'remote-content-wrapper',
      'title' => t('click to reload')
    )
  );
  $wrapper['container']['content'] = array(
    '#markup' => t('Loading data...')
  );
  return $wrapper;
}

This callback will create simple page with div container and text "Loading data..." on it. Pay attention to element with id "remote-content-wrapper". This div container we will be base DOM element for our Drupal.ajax object.
In JS code we select it is with #:

$('#remote-content-wrapper').once('remote-content-wrapper', function() {
  var base = $(this).attr('id');
...
});

NOTE: I use '$.once()' method here to attach behaviour only once. Read more.
So, the HTML element selected and it is div#remote-content-wrapper.

Build object of options for new AJAX element.
    ...

    var  element_settings = {
          url: window.location.protocol + '//' + window.location.hostname +  settings.basePath + settings.pathPrefix + 'ajax/remote',
          event: 'click',
          progress: {
            type: 'throbber'
          }
        };

...
    The only required keys is:

'url' - the path to make ajax call to, any drupal full path.
'event' - the javascript/jQuery event to react to, any string or one of the registered like 'click', 'change', 'keypress'
'progress' - the progress type. Object contain 'type' key, which can be either 'throbber' or 'bar'.

Other settings:

    keypress: true,
    effect: 'none', // jQuery effect.
    speed: 'none', // setting for jQuery effect.
    method: 'replaceWith', // Will be rewritten with ajax command.
    // The additional data to submit.
    submit: {
      'js': true
    }

Add the new AJAX object to global Drupal.ajax object.
It is simple easy:

Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
Drupal.ajax() function-constructor takes 3 parameters:
- element id,
- DOM object,
- settings object

NOTE: The new element should be stored in global Drupal.ajax array of ajax objects under the element id key. Every Drupal.ajax object on the page are stored in this array.

That it! The Drupal.ajax element created.
To trigger new ajax reaction we should call registered in element_settings object event:

$(this).click(); // $('#remote-content-wrapper').click();

I use here click, but you could pass as parameter any event you want, and then trigger it with .trigger() method.
    AJAX callback should return array of Drupal commands or any custom registered AJAX commands which will be executed after success ajax call.

The complete js part:

(function ($) {
  /**
   * Load remote content after the main page loaded.
   */
  Drupal.behaviors.my_module_load_remote_content = {
    attach: function(context, settings) {
      $('#remote-content-wrapper').once('remote-content-wrapper', function() {

        var base = $(this).attr('id');

        var element_settings = {
          url: window.location.protocol + '//' + window.location.hostname +  settings.basePath + settings.pathPrefix + 'ajax/remote',
          event: 'click',
          progress: {
            type: 'throbber'
          }
        };
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
        $(this).click();
      });
    }
  };
})(jQuery);

The complete PHP part:

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['ajax/remote'] = array(
    'title' => 'Data',
    'page callback' => 'my_module_remote_ajax',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['page'] = array(
    'title' => 'Data',
    'page callback' => 'my_module_remote',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Menu callback.
 *
 * Output the page with the container to load AJAX content to.
 */
function my_module_remote() {
  $wrapper = array();
  $wrapper['#attached']['js'] = array(
    drupal_get_path('module', 'submit_ajax') . '/submit_ajax.js'
  );
  $wrapper['#attached']['library'] = array(
    array('system', 'drupal.ajax')
  );
  $wrapper['container'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'remote-content-wrapper',
      'title' => t('click to reload')
    )
  );
  $wrapper['container']['content'] = array(
    '#markup' => t('Loading data...')
  );
  return $wrapper;
}

/**
 * Ajax callback.
 *
 * Load remote information.
 */
function my_module_remote_ajax() {

  $commands = array();

  $selector = '#remote-content-wrapper';
  $html = my_module_function_to_request_data_form_remote_server_and_build_html();
  // Debug messages, we can use dpm() here.
  $messages = theme('status_messages');
  $commands[] = ajax_command_prepend('body', $messages);
  // Add command with insert new requested content
  $commands[] = ajax_command_html($selector, $html);

  print ajax_render($commands);
  drupal_exit();
}


How to make a view list entities, not translations?

I think the proper filter is the following:

"Content: Default translation (= True)"


Display child terms in term taxonomy page

Set up a new view of type "taxonomy terms"
Give the view a "block" display (not a page)
In the "advanced" section of the view (on the right) you can set up a "contextual filter" based on "parent term".
The trick to making this work with a block is to select the "Provide default value" option and select "raw value from url" "path component 3". This will send in the id of the parent term from the url (works even though your term is aliased).
Go to admin->blocks and put that block in the "footer" region; set it to only appear at the url taxonomy/term/* (this will work even though your term is aliased).


How can I schedule change of the default front page?

I would add a date field to the node and then filter the view to only show the node scheduled for today. Point your front page to that view.

You'll need the date module.


Block caching when access-restricted modules are enabled

Assuming that the module that creates the block and is this performance heavy is a custom module, a simple solution would be to cache the output of the block from within the block. Take a look at the cache_set and cache_get functions on http://api.drupal.org


Drupal 7 Display legal module fieldset on user/% instead of user/%/edit

I just took a look inside the code of Legal module, what you describe is not possible by design, as of legal is hooking in existing forms:

legale.module line 223

function legal_form_user_profile_form_alter(&$form, $form_state) {

legale.module line 223

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

You might want to try out building a custom user-page form and hide the unwanted elements from profile form.

For reference in how to to that see this answer.

I also think you will need to go a bit further than views only and use Panels to add multiple views on one page.


If you check \Drupal\link\Plugin\Field\FieldType\LinkItem, you see that it supports an array of options.

LinkFormatter then passes those to the URL.

So the only thing that you need is a custom widget that allows you to select/configure classes within the options somehow.


Performance of site when loading 3000+ variables

Yes, large variable tables are a problem.

Variables should only be used for small configuration flags and settings and not to store large structures for example.

But given a large amount of modules, dynamic variables like per-content type things you will sooner or later get into trouble.

No, there is no solution to this problem. The variables system will be replaced with the new configuration system from the CMI initiative for Drupal 8 which will hopefully be better at dealing with this.


How to remove Page cached by boost message in view source

This is not possible in the 7.x-1.x version of the module (unless you patch the code). You should file a feature request in the Boost issue queue.

If you want to temporarily patch the code, open the file boost.module, around line 1145:

  $types['text/html'] = array(
    'title'           => t('HTML'),
    'description'     => t('HTML output, usually a webpage'),
    'extension'       => 'html',
    'enabled'         => TRUE,
    'gzip'            => TRUE,
    'lifetime_max'    => 3600,
    'lifetime_min'    => 0,
    'comment_start'  => NULL, // <--- set to null
    'comment_end'    => NULL, // <--- this too
    'variants'        => array(),
  );

If you would like to contribute a patch, which would be greatly appreciated, the right way to do this would be to modify the boost_exit() function, around line 315:

  // Add note to bottom of content if possible.
  if ($_boost['matched_header_info']['comment_start'] && $_boost['matched_header_info']['comment_end'] && $_boost['matched_header_info']['comment_footer_enabled']) {
    $expire = $_boost['matched_header_info']['lifetime_max'];
    $cached_at = date('Y-m-d H:i:s', REQUEST_TIME);
    $expires_at = date('Y-m-d H:i:s', REQUEST_TIME + $expire);
    $note = "\n" . $_boost['matched_header_info']['comment_start'] . 'Page cached by Boost @ ' . $cached_at . ', expires @ ' . $expires_at . ', lifetime ' . format_interval($expire) . $_boost['matched_header_info']['comment_end'];
    $data .= $note;
  }

You would also have to set the default (TRUE) in boost_boost_storage_types(), and to the $keys in boost_get_storage_types() so that it does the variable_get(). Bonus points for also exposing it to the admin interface.


I assume you're going to use the mongoDB module. This doesn't move the ENTIRE database over, just parts of it, like cache, blocks, watchdog, etc.

This works well because mongo, or any "document" oriented database is not great at relations. So you can move the data that is not very relational into mongoDB easily.

Mongo itself is cake. Easy to install, easy to understand. It's simply "JSON" data. If you don't know JSON, read up on it now. Already, many parts of Drupal's data are stored as JSON inside text fields in a regular SQL database such as MySQL.

I'd re-iterate that you probably don't want to move EVERYTHING over, like the nodes, taxonomy, etc. Those things are highly relational. Also, the mongoDB module doesn't support those for that reason.

Installation of the module is pretty straight forward and happens in settings.php. See the mongo module readme file for more info.


Redirect the anonymous users to the login page when they try to vote a node

I have installed the module that you mentioned and got the same error. It seems that even though the Vote Up/Down module allows you to give anonymous users permission to vote, internally, it does not support it and throws the specific error. I suspect - I'm guessing here - that they are using the user id to "save" what the logged-in user voted and when the user id is 0 (which means anonymous) an error is thrown.

Anyway, the way I see it, there are 2 main paths that you can follow in order to get the functionality that you want:

1) Have someone (= a drupal developer) modify the module for you. This way, you will be able to add the functionality, and even submit the changes it to the module's repository.

Pros: you help the community, you get a clean solution (depending on the developer's skill)

Cons: costly (I suspect), takes time, you get bad code and patch the problem (depending on the developer's skill)

2) Get the functionality through theming. Instead of enabling the module for anonymous users, you can just disable it, and through the node-nodetype.tpl.php file you can just show the image of the voting arrows to the anonymous users (you will have to use an if conditional to check if the user is logged in or not) and make the image point to a link like this:

/user/login?destination=/node/$node->id

This way the user will be redirected to the login form and then back to the node, but he will have to press the vote button again.

Pros: easy to implement, theme based solution = minimal interaction with code

Cons: it's really a work-around, not a solution, the user is not actually voting but he thinks he is voting (not really honest :P)


Show field label when using tokens in "Global Custom Text" field in Views?

A workaround would be to just create your own label by typing it in.

ex 1: Title: [title_field]

ex 2: Title:
[title_field]


How to get the vocabulary terms for the current language

Two issues here:

Getting the current language, and
Getting the terms for the current language

1. Getting the current language

Use the global $language variable and get its language property:

$language->language

2. Getting the terms for the current language

In theory, you'd use i18n_taxonomy_get_tree, like so:

global $language;
$tree = i18n_taxonomy_get_tree(1, $language->language,0,NULL,FALSE);

but it seems that function is buggy. Instead, you can try using i18n_taxonomy_localize_terms with taxonomy_get_tree instead:

if (module_exists('i18n_taxonomy')) { // Check if the module exists
    global $language;
    $tree = i18n_taxonomy_localize_terms(taxonomy_get_tree($VID,0,NULL,FALSE));
} else {
    $tree = taxonomy_get_tree($VID,0,NULL,FALSE);
}


Try the RPX (Janrain Engage) module.

  Using Janrain Engage, Drupal sites can authenticate new and existing
  users with popular social networks, map user profile data from these
  websites to Drupal fields, and share Drupal content with a user's
  friends on their social networks.

  This includes Facebook, Twitter, Google, Yahoo!, LinkedIn, Myspace,
  AOL, PayPal, and Windows Live (see the complete list below).


How do I delete nodes older than X days?

I had problems with D7 using Auto Expire, and ended up using HOOK_cron() in a custom module:

function mymodule_cron() {

// we only want to deal with messages (a content type)
$message_type = "message";

// grab all messages
$message_nodes = node_load_multiple(array(), array('type' => $message_type));
// set up the timestamp for the expiry
$message_search_date = strtotime("- 30 days"); // UNIX timestamp for 30 days ago

// now loop through messages, & if they are old, expire them
  foreach($message_nodes as $m) {

    $obj = entity_metadata_wrapper('node', $m);

    // when was it last updated, & is it still published?
    $last_update = $obj->changed->value();
    $published = $obj->status->value();

    // if it's still published & it's not recent, then unpublish it
    if(($message_search_date > $last_update) && $published<>0) {
        $obj->status = 0;
        $obj->save();
    }
  }
}


Add a custom form only to a particular content type

If I'm not wrong, I think you are trying to display your custom form in the node view of a particular content type. You can do this in two ways.

The first approach is to implement hook_node_view() from the module level.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        if($node->type == 'your_content_type'){
            $node->content['my_form'] = array(
                '#markup' => drupal_get_form('your_form_id'),
                '#weight' => 1,
            );
        }
    }
}

The second approach is to implement hook_preprocess_node() from the theme level.

function MYTHEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    if($variables['node']->type == 'your_content_type'){
        $variables['content']['my_form'] = drupal_get_form('your_form_id');
    }
  }
}


How to "use Search by Page as its own entity"?

If it suits your workflow you could just deny access to those two search pages using hook_menu_alter():

function MYMODULE_menu_alter(&$items) {
  $items['search/node']['access callback'] = FALSE;
  $items['search/user']['access callback'] = FALSE;
}

If you still need to provide access to those paths under normal circumstances, and just hide the tabs on the search-by-page page, you can provide a function for the access callback that does a quick check on the current URL:

function MYMODULE_menu_alter(&$items) {
  $items['search/node']['access callback'] = 'MYMODULE_search_page_access';
  $items['search/user']['access callback'] = 'MYMODULE_search_page_access';
}

function MYMODULE_search_page_access($name) {
  // Deny access when on a search-by-page page
  if (arg(0) == 'search' && arg(1) == 'search_by_page') {
    return FALSE;
  }

  // Otherwise return the default access callback
  return _search_menu($name);
}


You're asking alot of questions ... here are some general answers.

The batch api is used to take a set of data and partition out the data into workable batches. The batch api does not guarentee that timeouts will not occur. you need to find a batch size that that is the sweet spot for your dataset size.
typically you would choose a batch size of say 5, 10, 15 or 20 items. and called node_save for example 25 times before going onto the next batch (page refresh). The page refreshes per batch do slow down your import process ... due to the HTTP requests.
if you're querying data say from a Queue or something if you can try to avoid re-fetching the data and using a static php variable to store information you can save some time.
The Migrate module is designed to solve these kind of problems by using Drush.

If ordering of the data doesnt matter. I find parallelizing (eg, multiple worker threads) can help with these types of imports look at Background Process and Ultimate Cron Queue Scalar.


Structure -> Content Types -> Your Type -> Manage display-> Change the position of image field with plus icon -> Save


It works as expected - in $form_state['values'] you have validated values, and in $form_state['input'] you have raw values. If you will limit validation to title field only - only this field will be transferred into "values" array.


How do I set a Boolean config variable to false?

When setting a boolean with drush, you need to use 0, not false.
pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': true

pk@DC:~/$ lando drush config-set advagg.settings enabled 0 -y

 // Do you want to update enabled key in advagg.settings config?: yes.

pk@DC:~/$ lando drush config-get advagg.settings enabled
'advagg.settings:enabled': false


How does Drupal handle update of multiple module bundles of features without breaking stuff?

It doesn't - that job falls to the developer.

Drupal/Drush doesn't know which versions of unrelated modules work with each other; I imagine that would probably be quite complicated to describe generically.

One method Drupal offers to handle this scenario is using advanced dependencies in your module .info file. For example, when you know that the current versions of A, B and C you have installed work with one another, then lock them down in your feature module's .info:

dependencies[] = A (1.x)
dependencies[] = B (>7.x-1.5)
dependencies[] = C (>1.0, <=3.2)

That way a Drush (or other) updates won't interfere, you'll always have versions that you've manually verified are compatible.

When you're ready to think about updating those modules, download them to your dev version of the site, run all the updates, and all of your tests, and see where you're at. If things work, great, update your .info file with the new dependency versions, release the code, and you're good to go.

If not, then you need to look into whether it's something that you need to fix yourself, whether it's a known bug with the new version and has a patch, a known incompatibility between the two modules, and so on. Beyond writing an excellent test suite that you can trust, I doubt there's an automated or shortcut method for doing this.


You can do it with the following steps too :

Go to http://localhost/phpmyadmin
Select your database and drop all the tables
Go to http://yoursite.com/install.php

Or you can use : drush si

And done.. :)


Site affected by PSA-2014-003, revoke all public keys?

Short answer

You don't need to replace your SSH-keys if only their public part was stored on the server. And that's usually the case if you've only used it for logging into the server.

Long answer

Since the server may have been compromised all the data on the server might have been copied by any number of attackers. This includes everything used for authentication:

private keys (SSH, SSL, GPG, …)
passwords, if they were stored in an insecure manner
API-keys for other web-services
The mysql password

You should replace all of them.

For SSH's public-key authentication you usually copy your public key into the ~/.ssh/authorized_keys file. Your private key remains safely on your computer. Therefore there is no need to replace your ssh-keys. That's the main benefit of asymmetric encryption: Everyone can have your public key without compromising the security.


You're looking for the FileField Sources module:

  FileField Sources is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only)
  Select existing files through the IMCE file browser

Emphasis mine.


Sure.  You can use hook_preprocess_node() to do this, eg, something along the lines of:

function YOURTHEME_OR_MODULE_preprocess_node(&$variables) {

  $node=$variables['node'];

  $foo= /* get the value of this field from $node */ ;

  $variables['theme_hook_suggestions'][] = 'node__' . $foo;

  // or....

  switch ($foo) {

    case 'FIRSTVALUE':
      $variables['theme_hook_suggestions'][] = 'node__FIRSTSOMEOTHERSTRING';
      break;

    case 'SECONDVALUE':
      // etc etc etc

  }

}

and then Drupal 7 will look for a node--WHATEVER.tpl.php.

ADDITION:

If you are wanting the PAGE itself to be different based upon this field, then you would use hook_preprocess_page() with similar logic but using page__WHATEVER instead in the theme hook suggestions and page--WHATEVER.tpl.php in the template names.


Trouble accessing twig variables passed from custom block

So, block--na-fourwords.html.twig is an existing Drupal suggestion for a template name for a block with id na_fourwords. I was able to override the template file, but my theme function that was trying to talk to that file was being ignored because it already existed. It would be nice if Drupal had some kind of feedback to let you know of conflicting theme hooks like that.
Anyway, hopefully this saves someone similar frustration.


Using PHP ImageMagick with ImageCache Custom actions - Returning image

Someone might find this useful as Documentation is very sparse for this (this took me over a day to figure out). The problem was I was writing to a seperate file - Works, but ImageCache will delete it, also defeats the point of using ImageCache.

The solution is as follows, to use $image->ops[] and ImageMagick CMD's. (This is entered in the custom actions of imagecache. Distort image, apply mask, and apply overlay. This is used for creating product images for a Shop with just normal images supplied. I'll probably make a blog post in more depth at some point.

$image->ops[] = "-distort Barrel '0.0 0.0 0.16 1.0'";
$image->ops[] = "-resize 1600x1600";
$image->ops[] = "-crop 1500x1500+60+50";
$image->ops[] = "'sites/default/files/coushin-bg.png' -compose Dst_In  -gravity center -alpha Set -composite -format png -quality 90 ";
$image->ops[] = "'sites/default/files/Blank-Cushion.png' -compose Multiply  -composite -format png -quality 90 ";
return $image;


How can I stop JavaScript from being cached during development?

I'm assuming you have to clear caches because your JS file is being aggregated? Can't think of a different reason.

That has absolutely nothing to do with how you add your JS file (Most of what you tried shouldn't even work, use #attached][library).

Instead, it depends on the separate settings to aggregate JS or not. You can find them on the Performance settings page. Aggregation is also automatically disabled if you use the provided sites/example.settings.local.php as your settings.local.php, which I strongly recommend when doing development, also for the other things it does like enable verbose error logging and disabling render caching (but keep in mind to always test your code with render caching too).


field_group #states does not working with using hook_field_group_build_pre_render_alter()

After debugging I found that hook_field_group_build_pre_render_alter() is indeed working, but dpm() cannot work inside it at all.

For debugging, you can only use var_dump() or kpr() inside this hook function.


Smart quotes creating a problem with anonymos user role

Without more information it's hard to tell exactly's going on but there's a couple things that come to mind:

Copying and pasting from MS Word/other rich text editors is notoriously problematic and both TinyMCE and CKEditor have built-in settings for pasting data from Word & stripping the extra formatting
In case you're not using any WYSIWYG you should always paste your code in Notepad or another plain-text editor and then re-copy it to lose the extra formatting
Finally, I don't really think it applies to viewing content at all but the visibility thing might have to do with the text-format used in the body field, it's common to edit content using Full HTML and then users without access to it (only Filtered HTML for example) can't edit it


Select list field type as sorting order criteria

Looking for approximately the same, but I believe this isn't easily solvable. What you could do is use taxonomy instead and then sort the view by the term weight (create a relation to the taxonomy in the view and you get term weight as sort criteria).


Is There a way to search non drupal solr index?

The Sarnia module is the only solution I'm aware of. It leverages the Search API, but unlike the other SOLR modules, it is designed to expose the content of any index rather than index Drupal content. It also has some pretty decent documentation, here.

However, I'm having trouble getting it to actually work properly. Latest dev version is not working for me, at least at the moment.

[UPDATED] Most of my troubles arose because my SOLR index does not use the standard handler names, and so some manual configuration was required (hacking service.inc). Once done, it certainly works, although it does not cope with grouping/collapsing results, and I'm not sure how to expose facets.


On Unix or OS X, you can use which drush to learn the location. On Windows, it is where drush from the command line.


How to highlight new added links on front page with cookies?

You could do this in a limited way where you store each item's nid and updated date in a cookie. The cookie would get updated each time the user loads the front page by JavaScript that reads the nid and date from the DOM.

Before the cookie is updated it is used to set a highlight class on any items that aren't set in the cookie.

In order for the cookie to not grow too large the items could be pruned by date if the front page only shows most recent.

For an demo take a look at https://jsfiddle.net/rnc2eLxr/2/

I've included the code below.

JS libraries:

https://code.jquery.com/jquery-2.2.4.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js

HTML:

Google

Reddit

Javascript:

// Get cookie value.
var linksString = $.cookie('frontLinks'),
  links = [];
if (linksString != undefined) {
  links = JSON.parse(linksString);
}

// Highlight any links not found in cookie.
$('li a').each(function(i, v) {
  var $link = $(v),
    tuple = {
      "date": $link.data('date'),
      "nid": $link.data('nid'),
    },
    match = findByNid(links, tuple.nid, true);
  if (!match) {
    $link.addClass('highlight');
    links.push(tuple)
  }
});

// Find array object by nid property.
function findByNid(inArr, nid, exists) {
  for (i = 0; i < inArr.length; i++) {
    if (inArr[i].nid == nid) {
      return (exists === true) ? true : inArr[i];
    }
  }
}

// Store links in cookie.
$.cookie('frontLinks', JSON.stringify(links))

CSS:

li a.highlight {
  border: red 1px solid;
}


That sounds like a fine solution. The one thing I would suggest is to NOT use the webform module. I think you should just create the custom form with the Form API.

You'll spend more time overriding the unneeded behavior and features of webform than you would creating the form from scratch with FAPI.


For Drupal 6 you create a custom block and let the content be:

theme('user_profile', $account);

For Drupal 7 you do change the code a bit:

render(user_view($account));

In both cases $account if the fully loaded user object who's profile you want to display in the block.


Send an email when the roles are changed

To detect 'any' change to the users roles, you can use the following PHP via the condition "Use PHP code"

return (count(array_diff_key($account->roles, $account_unchanged->roles)) + count(array_diff_key($account_unchanged->roles, $account->roles))) <> 0;

The other PHP answers will not necessarily fire when a user has been 'removed' from a role.


How do I add recaptcha to a custom form programatically?

The module doesn't implement hook_element_info, so it doesn't define a new element type. The code you're using looks like it's borrowed from the traditional captcha module, which does things a bit better and provides the element type.

Looking at the code, this is all you need in your form alter hook:

g_add_captcha($form, $form_id);


"The website encountered an unexpected error. Please try again later." error show on cache clear

I was also getting the same error. The reason is given in the error message,i.e. Drupal is not able to find the specified controller. In my case, in the routing yml, the controller's path is "hello_world\Controller\HelloController", whereas my HelloController.php file was contained in the hello_world\src folder instead of the required path (**hello_world\src\Controller** folder).

My hello_world.routing.yml contents

hello_world.content:
 path: '/hello'
defaults:
 _controller: '\Drupal\hello_world\Controller\HelloController::content'
_title: 'Hello World'
requirements:
_permission: 'access content'


How to save term with term references programmatically?

If you're using the built-in term reference field type, the column is named tid, e.g.:

$term->field_realization[$term->language][]['tid'] = $another_term->tid;

If you're using an Entity Reference field type, the column is named target_id, e.g.:

$term->field_realization[$term->language][]['target_id'] = $another_term->tid;


flexslider keeps crashing when i try to change settings

I have managed to resolve this, I managed to find it on google here : JQuery Update breaks Views UI  .

Basically if you go into your jquery Update module, click configure, then change it from 1.8 to 1.7 it works


I'd guess that your custom module is called search, which would conflict with the core Search module, also named search.

There's no such thing as namespaces with regards to Drupal modules (at least out of the box, I'm not sure if there are any contrib modules that deal with this. My gut instinct is that there wouldn't be). Each module needs to be individually named, or the last module of the same name that Drupal comes across will be the one it uses.

Make sure your module is not called search; that includes making sure the folder name for the module, the name of the .info file, name of .module file, etc. are not called search.info etc. That should make sure that both modules are available in your module list.


How to add exposed form block to .tpl.php

You want to print an exposed block in tpl, right? I am using this in drupal 7

<?php
  $block = block_load('views', '-exp-VIEWNAME-DISPLAYNAME');
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>

for example

<?php
  $search_block = block_load('views', '-exp-cruise_package-page');
  $output =  drupal_render(_block_get_renderable_array(_block_render_blocks(array($search_block))));
  print $output;
?>


How to Include an ATTACHMENT to a Drupal's Entityform Submission Email?

Here is some more detailed guidance on how to solve this:

As mixerowsky states you will need to download and set up Mime Mail.

The latest version of Entity Form (7.x-2.0-rc1) comes with it's own preconfigured rules. You'll need the Entity Rules module for these. You can clone or edit these.

Alternatively you can set up your own fresh rules in the 'normal' way by using the 'After saving a new entityform submission' event.

Whichever method you go for you will need to add the 'Send HTML e-mail' element to the Actions stage of the rule (you can remove the existing actions if you cloned the packaged entity rules).

Edit the action and within the attachments section you can add a file path token, e.g.

[ENTITY_NAME:FILE_FIELD_NAME:file:path]

Check the Replacement Patterns for the correct ENTITY_NAME and FILE_FIELD_NAME and make sure you append ':file:path' as above and you will get an attachment on the HTML email.

Other file tokens include:

[ENTITY_NAME:FILE_FIELD_NAME:file]
[ENTITY_NAME:FILE_FIELD_NAME:file:url]
[ENTITY_NAME:FILE_FIELD_NAME:file:size]

You may wish to use these in the email body for example.

Here is a list of file tokens. There are other useful tokens listed on there too.

Trouble Shooting & Testing

Make sure you are using the correct token. Check the replacement patterns for the correct entity name and file field, e.g.

[ENTITY_NAME:FILE_FIELD_NAME:file:path]

Then try adding the file tokens to the email BODY to make sure that it is working correctly, e.g. Add this to the body:

Filename: [ENTITY_NAME:FILE_FIELD_NAME:file]
Filepath: [ENTITY_NAME:FILE_FIELD_NAME:file:path]
FileURL:  [ENTITY_NAME:FILE_FIELD_NAME:file:url]
Filesize: [ENTITY_NAME:FILE_FIELD_NAME:file:size]

This should output something like this in the BODY of the email:-

Filename: filename.pdf
Filepath: public://filename.pdf
FileURL:  http://website.local/system/files/filename.pdf
Filesize: 16.59 KB

If the 'filepath' is not present then there will be no attachment.

Make sure that the Drupal file system is set up correctly and files are getting saved when the entity form is submitted.

Double check your System Stream Wrappers and Token installs.

Make sure you have set up Mimemail correctly and you are receiving emails OK. Maybe set up a test using a different system (e.g. Webform) to check that file attachments are working in the first place.

If you use the correct token then it will work - however if there is an problem with the set up of the email sending or other modules then you may not get an attachment. The chain from 'entity form' to 'email with attachment' is quite long and complex so make you test every step of the journey.


Get result view with formatter programmattically

Use $view->result to get the filtered rows, $view-field for the fields, on which you can use the methods getValue() for the field value and render() for the formatted field as render array.

An example:

use Drupal\views\Views;

  $values = [];
  $view = views::getview('view_example');
  if ($view) {
    $view->execute();
    foreach ($view->result as $rid => $row) {
      foreach ($view->field as $fid => $field ) {
        $values[$rid][$fid . '-value'] = $field->getValue($row);
        $values[$rid][$fid . '-render'] = $field->render($row);
      }
    }
  }


how to use hook_cron_queue_info in a custom module?

You can look at the example code shown in the documentation from hook_cron_queue_info(), which still needs an explanation on how it is used.

function hook_cron_queue_info() {
  $queues['aggregator_feeds'] = array(
    'worker callback' => 'aggregator_refresh',
    'time' => 60,
  );
  return $queues;
}

The code show is actually the implementation of hook_cron_queue_info() made from the Aggregator module. (See aggregator_cron_queue_info().)

"aggregator_feeds" is the name of a Drupal queue that is filled with items that need to be processed; "aggregator_refresh" is the name of a function that will be called when Drupal executes cron tasks, once for each item contained in the "aggregator_feeds" Drupal queue. aggregator_refresh() gets the item taken from that Drupal queue as first parameter.

The question you would ask at this point is: When are the Drupal queue items added to the queue?

The Aggregator module does that in its hook_cron() implementation, but any function could add items to a Drupal queue, including other hooks (with the exception of hook_cron_queue_info() and similar hooks*), form submission handlers, page callbacks, or any function called from those functions.

* By "similar hooks" I mean all those hooks that return information, and that are not invoked to handle an event or after/before an event occurred/occurs (as in the case of hook_node_delete()). In the list of "similar hooks," I would add, for example:

hook_menu()
hook_entity_info()
hook_field_info()
hook_archiver_info()
hook_tokens_info()


Checkbox value incorrect in custom validation

ok, I've found the cause of the issue:
I rendered $form['t_and_c_accepted'] twice in the twig template which caused the browser to post a value that was different from the checkbox that was visible.

So it was my own mistake but I answer this question anyway in case anyone else would be wasting time solving the same issue


Panel frontpage overrides site front page after migration

Managed to solve it by rolling back the "***_d6_i18n_system_site"
So this seems to be some kind of hiccup between the panels and i18n migrations.


Load and interact with a node comments from their related node

Ok so here is one way to do it, it's not very elegant and needs improvement.

I created a comment view that has a page display which gets NID from url so when ajax calling the content with ajax my/url/89 will return the comments for node 89. This works; even Ajax_Comments are working!

Edit: Ive fixed it so it will cache the data for the user, so when traversing the gallery, it does not load the data ad-nauseum. It stores in .data and pulls it back in if the user has already viewed it.

Anyway, even though this works I feel it needs a lot of improvement and/or different approach.  Below is some of the related updated latest code.

$(function(){

  // Override the default behavior of all `a` elements so that, when
  // clicked, their `href` value is pushed onto the history hash
  // instead of being navigated to directly.
  $("a.thumb_link").click(function(){
    var href = $(this).attr( "rel" );

    // Push this URL "state" onto the history hash.
    $.bbq.pushState({ image: href });

    // Prevent the default click behavior.
    return false;
  });

// Keep a mapping of url-to-container for caching purposes.
  var cache = {

   '': $('#gall-default') // If url is '' (no fragment), display this div's content.
  };

  // Bind a callback that executes when document.location.hash changes.
  $(window).bind( "hashchange", function(e) {
    // In jQuery 1.4, use e.getState( "url" );
    var url = $.bbq.getState( "image" ); //Get State from the above push "image"

    // In this example, whenever the event is triggered, iterate over
    // all `a` elements, setting the class to "current" if the
    // href matches (and removing it otherwise).
    $("a.thumb_link").each(function(){
      var href = $(this).attr( "rel" );

      if ( href === url ) { //Mark the active thumb and launch its content!

            $(this).addClass( "current" );
            $("#gall-default").css("display","none");
            //event.preventDefault();
            var $this=this;
            $bgimg.css("display","none");
            $preloader.fadeIn("fast"); //show preloader
            //style clicked thumbnail
            $outer_container_a.each(function() {
                $(this).children(".selected").css("display","none");
            });
            $(this).children(".selected").css("display","block");
            $outer_container.data("selectedThumb",$this); //get and store next image and selected thumb
            $bg.data("nextImage",$(this).next().attr("href"));
            $bg.data("newTitle",$(this).children("img").attr("title")); //get and store new image title attribute
            itemIndex=getIndex($this); //get clicked item index
            lastItemIndex=($outer_container_a.length)-1; //get last item index
            $bgimg.attr("src", "").attr("src", $this); //switch image

            //set context for node load bits
            var node = $(this).attr( "node" );

            $("#ajax-div .inner").empty();

             if ($(this).data('comm.cachedHtml')) {
                  $('#ajax-div .inner').html($(this).data('comm.cachedHtml'));

             } else {

                var toLoad = $(this).attr('node');// Get the URL of the clicked link.
               $.ajax({ // Now load the content
                    url: toLoad,
                    cache: true,
                    beforeSend: function () {
                    $("#preloader2").fadeIn("fast");
                },
                    success: function(data) {

                      $('#ajax-div .inner').html($('#content', data));// Inject new content
                      $("#preloader2").fadeOut("fast");
                      $(this).data('comm.cachedHtml', data);
                      Drupal.attachBehaviors('#ajax-div .inner');
                    }
                });

              }

      } else { //Un-Mark Thumb & other deselecting
         $(this).removeClass( "current" );

      }
    });

    //do something  here..
  });

  // Since the event is only triggered when the hash changes, we need
  // to trigger the event now, to handle the hash the page may have
  // loaded with.
  $(window).trigger( "hashchange" );
});


What is the purpose of rerender FormState property?

The only place in core that checks for, $form_state->get('rerender') in an if statement is in:
/core/modules/views_ui/src/Form/Ajax/ ViewsFormBase.php
// If the form has not been submitted, or was not set for rerendering, stop.
if (!$form_state->isSubmitted() || $form_state->get('rerender')) {
  return $response;
}

// Sometimes we need to re-generate the form for multi-step type operations.
if (!empty($view->stack)) {
  $stack = $view->stack;
  $top = array_shift($stack);

  // Build the new form state for the next form in the stack.
  $reflection = new \ReflectionClass($view::$forms[$top[1]]);
  /** @var $form_state \Drupal\Core\Form\FormStateInterface */
  $form_state = $reflection->newInstanceArgs(array_slice($top, 3, 2))->getFormState($view, $top[2], $form_state->get('ajax'));
  $form_class = get_class($form_state->getFormObject());

  $form_state->setUserInput([]);
  $form_url = views_ui_build_form_url($form_state);
  if (!$form_state->get('ajax')) {
    return new RedirectResponse($form_url->setAbsolute()->toString());
  }
  $form_state->set('url', $form_url);
  $response = $this->ajaxFormWrapper($form_class, $form_state);
}
elseif (!$form_state->get('ajax')) {
  // if nothing on the stack, non-js forms just go back to the main view editor.
  $display_id = $form_state->get('display_id');
  return new RedirectResponse(Url::fromRoute('entity.view.edit_display_form', ['view' => $view->id(), 'display_id' => $display_id], ['absolute' => TRUE])->toString());
}
else {
  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $response->addCommand(new ShowButtonsCommand(!empty($view->changed)));
  $response->addCommand(new TriggerPreviewCommand());
  if ($page_title = $form_state->get('page_title')) {
    $response->addCommand(new ReplaceTitleCommand($page_title));
  }
}

The if (!empty($view->stack)) { part will only pass if the form is a multi-step form and you're not in the last step; otherwise, it will proceed to close the modal. Ex: when you click "Apply" or "Cancel" or "Remove". (Ex: when adding a field) it triggers the else:
else {
  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $response->addCommand(new ShowButtonsCommand(!empty($view->changed)));
  $response->addCommand(new TriggerPreviewCommand());
  if ($page_title = $form_state->get('page_title')) {
    $response->addCommand(new ReplaceTitleCommand($page_title));
  }
}

Conclusion
As it only gets checked in the views_ui module, this setting is basically a way to tell the Views UI Form:
if the setting form is a multi-step form, like when you're adding a field:

to keep the modal open and build a new $form_state for the next form

Otherwise, its like when you click apply/cancel/remove it tells it to close the modal, show save & cancel buttons, and show/refresh the live preview.


Grant permission to current user at runtime in specific environment

Yes you can but why not just remove the field ? here is a few ideas on to how to do it..

in settings.local.php

 //add
$settings['stop_captcha_from_being_stupid'] = TRUE;
// or
$settings['enviroment_name'] = 'dev';

in some hook_form_alter

use Drupal\Core\Site\Settings; // above ^^^
$stop_capcha = Settings::get('stop_captcha_from_being_stupid') ;
if ($stop_capcha === TRUE) {
  unset($form['captcha']);
}

// or enviroment with custom header ;)
$current_request = $request = \Drupal::request();
if (!empty($current_request->headers->get('shutup-captcha'))) {
  if ($current_request->headers->get('shutup-captcha') == 'somesalt') {
    $environment_name = Settings::get('enviroment_name') ;
    $environments_to_allow_bypass_captcha = [
      'dev',
      'int',
      'test',
    ];
    if (in_array($environment_name, $environments_to_allow_bypass_captcha)) {
      unset($form['captcha']);
    }
  }
}


Views returns 'All taxonomy terms' in alphabetically order; can I change to Parent > child

I believe you're looking for something like the Hierarchical Term Formatter module:

  This module provides hierarchical term formatters for taxonomy reference fields. In other words, it can display a taxonomy term reference on, say, a node as Parent > Child, rather than just Child.


There is no easy way to hide that page. If you don't use it, you can implement hook_menu_alter(), and either remove it completely, or set its access callback to FALSE.


How can I prevent placeholders to wrap the value with single quotes in db_query?

You're imploding your array into a string, so PDO will (correctly) put quotes around it. PDO can handle arrays just fine, though, no need for manual manipulation:

$nid_array = array(24,34,56,7,8);

$query = "  SELECT *
            FROM {table_name} as t
            WHERE t.nid IN (:list_of_nids)";

$placeholders = array();
$placeholders[':list_of_nids'] = $nid_array;

$result = db_query($query, $placeholders)->fetchAll();


How to get a field in a exposed filter criteria as an autocomplete?

You can use Views Autocomplete Filter for getting autocomplete exposed filter in views. Module page says :

Add autocomplete functionality to the views filter text fields.

 - It works for node titles or cck text fields.
 - The autocomplete results are actually the view results, so they are view related.

But the field which you will expose & use autocomplete should be in the views result fields as well.


How can I split the body field to insert content between the first and the second paragraph?

I resolved my issue, using solution below
    {% set Paragraphs = node.body.value|split('</p>') %}
  {% set paragraphHalf = (Paragraphs|length / 2)|round %}

  {% if paragraphHalf %}
    {% for paragraph in Paragraphs %}
      {% if paragraphHalf == 1 or loop.index % paragraphHalf == 1 -%}

      {% endif %}
      {{ paragraph|raw }}

      {% if loop.last or loop.index % paragraphHalf == 0 -%}
      {{ insert item }}
      {% endif %}

    {% endfor %}

  {% endif %}


How to include "children" content types on a content type page?

Contextual filters are part of Views, they can't be used to link content types together. If you're simulating a relationship between the two types using a contextual filter, it will only exist in the very narrow context of that View.

The standard way to link content types together is with the Entity Reference module. Something similar to the following should get you what you're looking for:

Add a multiple cardinality entity reference field to the Parent content type, referencing the Child type.
Optionally install Inline Entity Form, if creating the Child content while inside the Parent edit form makes sense for your use case. It provides a widget for the entity reference field type. I won't go into details, if you choose that widget and visit the edit form for a Parent node, you'll see what it does.
Use either the autocomplete or inline entity widget to relate the Child nodes to the relevant Parent nodes.
Visit the display options for the Parent content type, choose "Rendered Entity" for the display format of your entity reference field, and in the settings choose an appropriate view mode.

That will render the Child nodes inside the Parent node without the need to alter the template file at all.


Run callback after Views exposed filter AJAX

JS events need to be bound when the document is ready. Drupal handles this for you if you use behaviors:

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $(document).once('mymodule-ajax').ajaxComplete(function (e, xhr, settings) {
      // ...
      });
    }
  }
})(jQuery);


What is a good module that allows maintainers of nodes?

I have used Node Access Node Reference for this. You will need to install Entity Reference and create a multi-value entity reference field linking to users you want to be able to maintain your node.


Why would a new user role have default permissions that are greyed out and cannot be changed?

Under Drupal 7, assigning a permission to the authenticated user defaults that permission to all roles except the anonymous user. If you wish to have a lesser role (non-authenticated) you are going to have to remove the permissions from the authenticated user first. Then set up a post authentication role with the permissions you wish to add on authentication and set up a rule to assign that role when the user authenticates.

(I know! Not straight forward at all!) Remember that the permissions are additive. You do not have to repeat their assignment. Just specify the permissions that each role will add to the default. Then assign the roles to the users as required.


Exporting settings in a code with Features / Strongarm - how to detect right variables - config ones

Unfortunately, the Drupal variables table doesn't provide any distinction between variables used for configuration (e.g., whether anonymous pages should be cached) and variables used to store transient values (e.g., date cron was last run, which tabs are currently active in the UI), so there's no automatic way to do this.  (Fortunately, it looks like Drupal 8's configuration management system will handle this better.)

I typically export and update Features modules from the command line using Drush.  I've been using the following Unix shell script to list Features Components which haven't yet been exported to any feature — the script filters out Features Components I know I don't want in my Features modules:

drush fc % --not-exported \
    | grep -v '^ dependencies:' \
    | grep -v '^ user_permission:access devel information' \
    | grep -v '^ user_permission:execute php code' \
    | grep -v '^ user_permission:switch users' \
    | grep -v '^ uuid_node:' \
    | grep -v '^ variable:additional_settings__active_tab_' \
    | grep -v '^ variable:cron_key' \
    | grep -v '^ variable:cron_last' \
    | grep -v '^ variable:ctools_last_cron' \
    | grep -v '^ variable:date_api_version' \
    | grep -v '^ variable:dev_mem' \
    | grep -v '^ variable:dev_timer' \
    | grep -v '^ variable:devel_api_url' \
    | grep -v '^ variable:devel_error_handlers' \
    | grep -v '^ variable:devel_execution' \
    | grep -v '^ variable:devel_krumo_skin' \
    | grep -v '^ variable:devel_page_alter' \
    | grep -v '^ variable:devel_query_display' \
    | grep -v '^ variable:devel_query_sort' \
    | grep -v '^ variable:devel_raw_names' \
    | grep -v '^ variable:devel_rebuild_theme_registry' \
    | grep -v '^ variable:devel_redirect_page' \
    | grep -v '^ variable:devel_use_uncompressed_jquery' \
    | grep -v '^ variable:devel_xhprof_directory' \
    | grep -v '^ variable:devel_xhprof_enabled' \
    | grep -v '^ variable:devel_xhprof_url' \
    | grep -v '^ variable:drupal_css_cache_files' \
    | grep -v '^ variable:drupal_http_request_fails' \
    | grep -v '^ variable:drupal_js_cache_files' \
    | grep -v '^ variable:drupal_private_key' \
    | grep -v '^ variable:entityreference:base-tables' \
    | grep -v '^ variable:features_codecache' \
    | grep -v '^ variable:features_ignored_orphans' \
    | grep -v '^ variable:features_semaphore' \
    | grep -v '^ variable:install_profile' \
    | grep -v '^ variable:install_task' \
    | grep -v '^ variable:install_time' \
    | grep -v '^ variable:mimemail_key' \
    | grep -v '^ variable:prod_check_module_list_lastrun' \
    | grep -v '^ variable:simplenews_last_cron' \
    | grep -v '^ variable:simplenews_last_sent' \
    | grep -v '^ variable:simplenews_private_key' \
    | grep -v '^ variable:simplenews_source_cache' \
    | grep -v '^ variable:update_last_check' \
    | grep -v '^ variable:xmlsitemap_generated_last' \
    | grep -v '^ variable:xmlsitemap_rebuild_needed' \
    | grep -v '^ variable:xmlsitemap_regenerate_needed'


Make sure you already have the Token module  installed in your site. The Token module.

on your site go to /admin/config/workflow/rules
Select send an email on the action section of the rule
Click switch to data selection
Click DATA SELECTORS and find your select list Eg:(node:field-select-list) token and add it into To box.

Hope it help


Found the answer, the Sub-pathauto module does the job perfectly.


Drupal 7 Commerce - How do you style the Please wait loading message/icon when you select an attribute?

For example:

/* Custom ajax throbber style */
.ajax-progress .throbber {
  /* New icon */
  background: transparent url(../images/ajax-loader.gif) no-repeat 0px 0px;
  /* icon is 15px square */
  height: 15px;
  width: 15px;
  /* Alignment, may tweak to suit */
  float: left; /* LTR */
  clear:both;
  margin: 2px 2px 8px 2px;
}
.ajax-progress-throbber .message {
  /* Hide the "please wait" msg */
  display: none;
}


To convert from $tid to term name, use  taxonomy_term_load() to load the object, and then access $term->name:

$term = taxonomy_term_load($tid);
$term_name = $term->name;

Your function should look like:

function MYTHEME_preprocess_node(&$vars) {
  if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
      foreach ($content['field_photo_topic']['#items'] as $index => $info) {
        $tid = $info['tid'];
        $term = taxonomy_term_load($tid);
        $term_name = $term->name;
        $content['field_photo_topic'][$index]['#href'] = 'photos/' . $term_name;
      }
    }
  }
}

Please note that this will only work the way you intend if you use PathAlias or similar to alias the path to be accessible by  term name instead of numeric $tid.


What is the difference between the config and the settings directories?

schema
This folder is used for schema related things. This is most often used to tell Drupal how custom configurations and configuration entities will be saved.
install
The folder can contain configurations, for example a view. All configurations will be installed; if any configuration fails, the module can't be installed.
optional
The folder can contain configurations, for example a view. All configurations will be installed if possible. If a configuration has missing dependencies, it won't be installed.

Configuration installation only happens when the module itself is installed. Optional configurations can install missing configurations when dependencies are met by a new installed module.


Creating Email Sending Rules in WebForm in Drupal 7

See webform_rules:

  Did you ever want to react on webform submission using rules but
  couldn't find the proper event? Webform Rules makes it possible to
  catch webform submissions by rules and do whatever you'd like to do
  with it (meaning: do whatever rules let you do with it).

It should let you perform most of the logic you've outlined here.


Is the "size" field in file_managed used for anything?

It's used in a few places:

theme_file_link() where it's used to add microformat data to a file link (per http://microformats.org/wiki/file-format-examples).
file_space_used() where it's used to "determine total disk space used by a single user or the whole filesystem".
file_validate_size() where it's used to "check that the file's size is below certain limits".

It's probably a good idea to fill this field in if you're able, or at least run a small script to do so after you've manually entered the records. Something like this maybe:

// The filesize column defaults to 0 so it's an easy check.
$fids = db_query('SELECT fid FROM {file_managed} WHERE filesize = 0')->fetchCol();

// Loop through the files and update the file size field.
foreach (file_load_multiple($fids) as $file) {
  $file->filesize = filesize($file->uri);
  file_save($file);
}


Is it possible to host private files on remote file server in Drupal 8?

Yes, the private file system is just another folder on your server, configured in settings.php
For example, you could

Mount a separate storage volume there via NFS
Add another EBS volume (if AWS)


Nevermind, got it working by using the template_views_load_more_pager. I was just using the wrong function name. Found it in the views load more module.


How to assign credit hours to user account once the content is marked completed by admin

i managed to do it with rules and adding some action code in a custom module.

After adding a condition, i had a make a custom action and then i was able to add that action in to the created rule.

You can send value to your custom action and then load user and update its field.

$user = user_load($user_trainer_id);
$obj = entity_metadata_wrapper('user', $user);
$obj->field_earned_credit_hours = $new_custom_value;
$obj->save();


Images instead of radio buttons or dropdown list?

You can accomplish this with a combination of a little JQuery and CSS.

Here's some starting points

http://codeloaded.com/fullscreen-preview/jquery-image-checkbox
http://aaronweyenberg.com/90/pretty-checkboxes-with-jquery
http://codecanyon.net/item/jic-jquery-image-checkbox/full_screen_preview/676874
http://boedesign.com/blog/2008/06/08/imagetick-for-jquery/

Then use a custom module to load the JS when needed using drupal_add_js() typically instantiated with a hook_form_alter().

Something like this:

/**
* Add example.js to content type 'car' create/edit form for example.module
*/
function example_form_alter(&$form, $form_state, $form_id) {
if ('car_node_form' == $form_id) {
  drupal_add_js(drupal_get_path('module', 'example').'example.js');
}

You can find more examples for detecting different forms and patterns on the hook snippets page.


How do I use a theme hook suggestion in template.php?

The default theme function for all fields is (wait for it), theme_field().  You can copy this function into your own theme, and rename it to MYTHEME_field(), either to alter or to refer to as reference.

You would then name your specific version MYTHEME_field__field_video_virtual_tour__basic_drealty_listing().  Note the two underscores separating the parts.

For reference, the standard suggestions are

MYTHEME_field__FIELDNAME__CONTENTTYPE()
MYTHEME_field__CONTENTTYPE()
MYTHEME_field__FIELDNAME()
MYTHEME_field()

Also remember, these are really just to wrap your elements with some HTML.  If you want to change the way the element itself gets rendered out, you should really make a field formatter.


Changing Site Background on button (and carrying it over to all pages on site)

You could change the background with JavaScript and also save that preference in the user's Local Storage - which is basically a cookie that doesn't get sent to the server. It gets erased when cookies get erased.

First you need a JavaScript function to check that LocalStorage is available. Here is the function I use, cribbed from Stack Overflow:

function localStorageTest(){
  var test = 'test';
  try {
    localStorage.setItem(test, test);
    localStorage.removeItem(test);
    return true;
  } catch(e) {
    return false;
  }
}

You'll throw an exception if the localStorage object is not available (e.g. if cookies are completely disabled), so that's why the try/catch.

Then you need to check for a preference when the page loads. I'm using jQuery here:

if (localStorageTest()) {
  var bgcolor = localStorage.getItem('bgcolor');
  $('#page').css('background-color', bgcolor);
}

Finally, some code to set the preference - assuming here we are setting the same color as the button. You could use another attribute on the element to store the value. jQuery again:

$('#button').click(function() {
  var bgcolor = $(this).css('background-color');
  $('#page').css('background-color', bgcolor);
  if (localStorageTest()) {
    localStorage.setItem('bgcolor', bgcolor);
  }
};

Just to add some Drupal to this answer, there is a Local Storage module that doesn't quite do this yet, but could potentially work if you set up a custom form and send the color choice as an AJAX form submit.

Also consider the Session Cache API module if you are going to elaborate on this example - it won't do what this example does, but it can help perform similar tasks.

I haven't tested this code, so there may be errors - consider it at least a roadmap to accomplishing the task.


How to read JSON data from external URL and display it in a node

If the data does not have to be live and can be fetched / updated every x number of minutes, then I suggest you create a task with scheduler which loads the remote data into a local database table at a specified interval (drupal_json_decode can help converting the JSON string into an array that can be inserted in the database). After you do that you would be able to adopt that table into Drupal & Views using the Data module. This would make the data available as a view with sort handlers and filters, like any other view. Otherwise, to handle live data I would suggest integrating Angular JS to retrieve the remote JSON and to filter the results. NgApp module can help you in this regard.


How to get related nodes for node reference?

I don't know of an API function specifically for that but it's fairly simple to implement one using existing API methods:

function get_related_nodes($master_nid, $field_name) {
  // Load the 'master' node
  $master_node = node_load($master_nid);

  // Get the node reference items attached to this node
  $items = field_get_items('node', $node, $field_name);

  // Loop through and grab the nids
  $nids = array();
  foreach ($items as $item) {
    $nids[] = $item['nid'];
  }

  // Return the fully loaded reference nodes
  return node_load_multiple($nids);
}


You can use a combination of the Webform module and Views.  Create a node with the form you want using the webform module and you can then create a block with Views for that particular node.


How to set up multiple hierarchy taxonomy?

It's quite simple:

State-County-City hierarchy you have figured out
Create separate taxonomy for regions
Go to /admin/structure/taxonomy/*/fields and add a taxonomy field to terms in first tree. That way you will be able to assign cities, counties and states to regions

Later, you will have to switch to Views for display, as regular taxonomy pages will not be enough to display nodes by historical region - but that's for another question.


User email being deleted when submitting Profile 2 form

You will have to check that hook_form_FORM_ID_alter  and the callbacks inside that hook, at least at the end you can check if the $form still have all the previously data


Is there existing integration between the Salesforce and Location modules?

It's difficult to say what's the exact problem, but I think you could have unmapped property in your configuration.
So please go to /admin/structure/salesforce/mappings and verify all the objects that have the properly set mappings and the tokens are valid.

If this doesn't help, try the following options:

Clear the cache (including memcached).
Check watchdog logs for further info.
Double check your Salesforce mappings again if you didn't miss anything.
Upgrade your Location and Salesforce module to development version just to test.
Look for any existing issues.
Debug the code using xdebug.
Report the issue or bug report on Drupal site against the right module.

You may also try the following related links:

Location - Select User Primary
Support Salesforce attachment sync


How to list out Flag content User in event page in Drupal Commons

Create a head count for each flag

Refer to listing flagged content with Views for a tutorial about creating a view with flagged content.

Starting from around 6:55 (and up to around 12:05) it explains How to create a view showing flagged content. Before 6:55 it mostly shows how to create that "Sidebar" flag (skip that part if you know that already). Here are the relevant steps in it (that you want to pay special attention to):

Even though the video uses a "global flag", your case is NOT a global flag (i.e. each user can flag/unflag, not just a restricted list of users, such as those with "administrators" or "content editors" role).
The tutorial creates a view of type "block", but you probably want to create a view of type "page" (though a "block" might be sufficient also if you prefer).
Within the "Advanced" link of the Views UI, you must add a "relationship" (think of an SQL "join" if you're not familiar with Views). To add such relationship, enter "Flag" as the "filter" on the popup window (as shown in the video around 8:25). You'll then get a shortlist of about 7 possible relationships to select from. Your question doesn't say (yet) if the flags you use apply to "nodes" or to "users", but I'm about sure (and going to assume) you'll be using "nodes". So use Flags: node flag counter as relationship. You might possibly also be able to use the Flags: node flag relationship instead (which is NOT shown in the video here), because the Flags: node flag relationship brings in more data about the flagging event, such as "who flagged it, when, etc".
As shown/mentioned from around 10:20 in the video, this video is about a "global flag". If it would have been about a none-global flag, then it would count the people who have used the "flag". So with only that, you already have like a "head count" of people who have "set the flag". Something like "number of attendees" already?
After you finish the first view for (say) the first flag, then repeat what is above by cloning that first view into a 2nd (and 3rd) view, and then adapt the 2nd view to use the 2nd (and 3rd) flag, to build a similar list.
As shown/mentioned from around 11:00 in the video (up to around 12:05), if you've selected to create a view of type "block" (not a "page"), then you still have to position the block (created by the view(s)) in an appropriate theme region.

Add more details about the flagging user

Refer to Getting the flagging user into Views for a tutorial about how to add more details about the flagging user (starting from around 2:00, though the real "Views" related part starts from about 4:00). Here are the relevant steps in it (that you want to pay special attention to):

This is about creating a view op type "page" (not block), which is also what you probably want, in the format of a simple tabular display.
The "path" where this view will be shown (around 4:40), like user/%/friends, which in your case I'd suggest something to become like user/%/events.
The "menu tab" that will be created (around 5:10), like Friends, which in your case I'd suggest something to become like Events.
The 2 (not just one ...) relationships that get added here, i.e.: Flags: User Flag (around 5:40) and Flags: User, which is The user that flagged an item (around 6:55)
Note the "contextual filter" that gets added (around 7:40, up to around 9:00), i.e.: User: Uid. It's to answer questions like "what are the events that this user confirmed to be attending so far".
Starting from about 9:10, the actual user details (such as User: Name) get added.

Starting from around 9:45, you get like a summary of it all, i.e.:

Start from a user profile (such as user/1) and use the (new) tab Friends.
A recap of the "crucial part" of this view, i.e. the 2 relationships that this view is using.


You can achieve your requirement by using Audit Files module.

  Audit files is designed to perform audits of your upload directory and
  the corresponding database records. It will cross check that all files
  in the database have a corresponding physical file, or it will check
  that all files in the upload directory have a corresponding entry in
  the database.


How to debug missing default value of managed file?

First of all can you try to remove the fieldset to a different $form[] array key? Is it really necessary to make it nested like this?

I think if you want to know if the file is added or removed then you can check in the following way.

$total_image_count = $form_state['storage']['image_elements']; // The number of image uploaded elements; just as example.
for($i = 0; $i < $total_image_count; $i++) {
  if ($form_state['values']['image'][$i] != 0) {
    // File is not deleted.
  } elseif ($form_state['values']['image'][$i] == 0) {
    //File is deleted.
  }
}

However, check with this and let me know.


I see youhave a callback function beep_beep_action() but no beep_multiple_beep_action() have you forgotten it ?


Suggested theme hook doesn't get applied

EDIT, after further debugging (see comments):

Using $suggestions[] = 'page__abacus__product' and a template called page--abacus--product.html.twig works. Theme suggestions should contain double underscores.


The Panels module provides the views content panes which is a display type for views, there you can create your view easily, make it fetch input argument from context and show the results, then you can simply include your pane in the place you want.

if you are not much familiar with Panels module, then this tutorial can make you became familiar, hence this is for Drupal 7 but you can use it in drupal 8 as well.


After lots of brainstorming and googling one user Marc from drupal.org suggested me the working solutions. Thanks to Marc for the solution.

Here is the solution:

To set it up, you will need a couple of steps:
REM: This method don't use the "Infinite Scroll Module", it's a rewrite of the stuff. In this method I choosed to integrate it in the theme, you could also create your own module (wish would be probably better .... )

1) download https://github.com/desandro/imagesloaded (jquery.imagesloaded.min.js) place it in your theme folder YOURTHEME/js
This will make sure all images are loaded before activate the infinite scroll

2) download https://github.com/paulirish/infinite-scroll (jquery.infinitescroll.min.js) place it in your theme folder YOURTHEME/js
In order to make it work with Drupal search modify it as follow: Search match(/^(.*?page=)2(\/.*|$)/ replace it by match(/^(.*?page=)2(&.*|$)

3) Create a new js (ex:infinitescroll.js) with the content of the below jquery & place it in your theme folder YOURTHEME/js
Rem: You will probably have to change the img path

4) modify YOUR_THEME.info and add

scripts[] = js/jquery.imagesloaded.min.js
scripts[] = js/jquery.infinitescroll.min.js
scripts[] = js/infinitescroll.js

5) flush the cache

6) cross finger & try .... it should work if not ... it's time to debug with firebug ...

Jquery code which you should place in infinitescroll.js

(function($){
    Drupal.behaviors.viewsInfiniteScroll = {
            attach: function (context, settings) {
              $(function(){
                if (this.processed) return;
                this.processed=true;
                if ($('.search-results').length==0) return;
                var $container = $('.search-results');
                $container.imagesLoaded( function(){
                  $container.infinitescroll({
                    navSelector  : 'ul.pager',    // selector for the paged navigation
                    nextSelector : '.pager-next a',  // selector for the NEXT link (to page 2)
                    itemSelector : '.search-results',     // selector for all items you'll retrieve
                    animate      : true,
                    msgText  : Drupal.t("Loading new results..."),
                    img: '/sites/default/themes/bartik/images/ajax-loader.gif',
                    donetext:Drupal.t('No more results to load.'),
                },function(arrayOfNewElems,state){
                    //YOUR CALLBACK STUFF .. To re-attach behaviour if needed

                    })
            })
          });
          }
        };
})(jQuery);


Make sure all files are present !

The drupal way for custom js in your theme is a behavoir, so your js file should look like this:

    (function ($) {
      Drupal.behaviors.myThemeBehavior = {
        attach: function (context, settings) {
           $(context).find('.counter').once('myThemeCounter').counterUp({
             delay: 10,
             time: 1000
           });
        }
      };
    })(jQuery);

This will ensure the script is executed after the DOM is loaded and only will run once.


Why does template.php override not work?

Use my_theme_pdfpreview, because even though there's a specific function assigned to it in hook_theme(), you should use the key to override.

I admit I got confused as well at first :)


How do I remove a configuration object from the active configuration?

The easiest way to do this at the moment is to use drush php (or core-cli) to open an interactive session.

Then use:

Drupal::configFactory()->getEditable('system.menu.devel')->delete();

This functionality will be added into Drupal console as well.


How to add validation on 'next' button using fieldgroup module

Create own module and add

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

  if ($form_id == "FORM_ID") {
        $path = drupal_get_path('module', 'MY_MODULE');
        drupal_add_js($path . '/validations.js');
    }
}

Create validations.js file to the MY_MODULE folder and put this there

(function ($) {
Drupal.multipageControl.prototype.nextPage = function() {

        // Group check here, otherwise every pages required fields invoke error.
        if (this.wrapper.hasClass('GROUP-NAME')) {
       $('input.required').each(function(index) {
        $(this).rules("add",
            { required:true, messages: { required: "field is required."} }
        );
    });

validated = 1;

$('input.required').each(function(index) {
                // You might want $("#YOUR-FORM-ID") here instead of just form.
    if (!$("form").validate().element(this))
        validated = 0;
});
}

if (validated == 1)
    this.wrapper.next().data('multipageControl').focus();
else
    $('html, body').animate({scrollTop:0}, 'slow');

}
})(jQuery);

This actually checks all fields in your form that are required.


"Failed to set field" Problem with SimpleTest, testing a form

Permissions would be my first guess.

Enable debug output in the Simpletest settings and then check if your module is installed and you have permissions to visit that page.


How to enable comments on custom entities

For Drupal 7, this module should do it - https://www.drupal.org/project/comments_entity

For Drupal 8, comments are available as a field for any entity type.

Summary:

Create a new Entity Type
Create a new Bundle for that Entity Type
Create a new Comment Type and select your Entity Type
"Manage Fields" on your new Bundle and add a new "Comments" field.
Configure comments as desired in the field settings.

Wrote a blog post about it here: http://www.daggerhart.com/drupal-8-add-comments-custom-entity-type/


\Drupal::currentUser() returns admin account info instead of logged in user

hook_menu_links_discovered_alter() is not invoked right before the links are shown, but when the links need to be rebuilt. Using the code you are showing, you are getting values from the user who is currently logged-in when the links are rebuilt; until the next rebuilt, that is the value shown for every user. (This means this is not the right method to dynamically change the menu link.)
If the links rebuilt is caused from a action you take when logged-in as administrator user, that explains why the name shown is taken from the administrator user.

If you need to alter the title used for a page, you need to alter the route and set its _title_callback property. The title callback is invoked right before the title is shown, so accessing there the object for the currently logged-in user would be correct.