How to transfer webform submission ID to client side

You could start by putting the submission id into $_SESSION and add it to Drupal's js settings

drupal_add_js(array('mymodule' => array('webform_id' => $_SESSION['webform_id'])), 'setting');

Then access it on the client side

webform_id = Drupal.settings.mymodule.webform_id


What code should I use where I used db_query()?

As quick replacement for queries on the database Drupal uses by default, you can use the following code.

use Drupal\Core\Database\Database;

$db = Drupal::database();
$result = $db->query("SHOW TABLES");

Keep in mind that:

db_query() will not be removed before Drupal 9 goes off; you can still use it, even if it is preferable to refactor your code to be more object oriented
The code I shown should be used in legacy procedural code; when possible, you should consider refactoring it to be object oriented and use Drupal 8 services and Dependency Injection Container


Headless Drupal 8 - cookie authentication

It looks like maybe you are not successfully retrieving the CSRF token. The CSRF token can be retrieved from /rest/session/token.

See https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities for examples on POSTing to core entity endpoints.


Migrate date time field using migrate source csv

from_format: Y-m-d H:i:s means hours with leading zeroes, but there are no leading zeroes in your source. Use from_format: Y-m-d G:i:s (capital G)  for 24-hour-format without leading zeroes
see https://www.php.net/manual/function.date.php


Would disabling core modules, which I don't need, speed up my site?

In theory, the answer is yes, but in practice, I doubt it. It depends entirely on on the module though.

If you have badly written module that implements hook_boot, so it executes on even cached page requests, and it performs lots of logic in there, and you have no use for it, then sure, you would gain speed from disabling it.

Most likely though, the average module is going to be implementing logic that is only actually executed when it is used, so if you don't use it it's not going to cost much.

If it's a big module, you could see a small dent in memory usage, as all enabled modules are loaded into memory, and as pointed out by Mołot, a modules variables and menu router entries will consume some resources, but again, I think in practice, it's not going to make a big difference.

That said, if you don't use the module, why keep it enabled? It by definition doesn't provide you with any benefit if it's not used, and at least it's going to clean up the administrative pages.


Is there a special way to list Commerce Products?

I believe we have this captured in an issue. The main issue was https://www.drupal.org/node/2831895 and is now in https://www.drupal.org/node/2827721.

Part of our blocker has been getting tests for this. We need to build a test for the use case then work towards a resolution.

There is a pull request in progress at https://github.com/drupalcommerce/commerce/pull/582. I have not reviewed this and not sure how close it is to a final solution.

The issue is unique form IDs.


You can create one block and add the html content and place this block in the footer region. This content will place inside the  tag and after the main content. Thats mean you will get your content before the closing  tag.


How can I set a default node owner for anonymous nodes on the node edit form?

You can do this pretty quickly in a custom module by implementing a hook_form_alter().

In this example, I created a module called "anon" (you might want to use something more specific) and in my anon.module, I have the following:

<?php

/**
 * Implements hook_form_alter()
 */
function anon_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "article_node_form" && isset($form['author']['name']['#default_value']) && $form['author']['name']['#default_value'] == "") {
    $form['author']['name']['#default_value'] = $user->name;
  }
}

The above code checks to see if you are on a article_node_form (change this to the content type you are using), if the author of the form is blank (which is representative of an anonymous user) and then sets the author name to the currently logged in user name.

Note that by default a new form will always set the author value to the logged in user, so this would only apply for existing nodes.


Content profile + rules. Problem with action, when user is created a profile then logged in

Where do you want them to go?

  Redirect to profile creation page, if users have no profile.

If a user already has a profile node, they won't be directed to create one (as stated in the rule itself) so when the user logs in, he/she should be taken to your default front page (or whatever page he/she was trying to access if access was denied to anonymous users.

EDIT

If you want users to be directed to the user page if they already have a profile, simply create another rule to do so.  Below is an example of a rule to do this for you:

Create a new rule, give it any title you like, for the Event select User has logged in and click "Save changes"
Now click "Add a condition", choose User has content profile and click the "Next" button
On the settings page for the condition, you may choose what content type to use for your content profile condition.  Choose one (or leave it if using default Profile) and click "Save"
Now click "Add an action", choose Page redirect (under the System heading) and click the "Next" button
On the settings page for the redirect, in the first textbox for To: enter user,  click the "Force redirect" checkbox and click "Save" (as seen below):

Make sure the rule is enabled and your users should be directed to the correct pages.


How can I avoid saved configuration settings to be exported?

If you don't want to export configuration you should use State API.
From documentation:

  It is specific to an individual environment.
  You will never want to deploy it between environments.
  You can reset a system, losing all state. Its configuration remains.


Is it possible to trigger an Ajax CallBack Function After a Link is Click

Yeah you just need to use use-ajax class for this.

$form['myid_print']['myid_print_search_idnumber_wrapper'] = array(
  '#type' => 'item',
  '#markup' => l(t('Test Ajax'), 'admin/ajax-url/nojs', array('attributes' => array('class' => 'use-ajax'))),
);

Checkout this blog : http://www.computerminds.co.uk/drupal-code/make-link-use-ajax-drupal-7-its-easy.


How to delete a scheduled task using Rules Scheduler?

Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder" for an illustration about how to delete scheduled tasks, using the "schedule_delete". As explain in that answer: the schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).

To make this work (that you actually indicate the exact scheduled task to be deleted), you need to specify an appropriate "identifier", like "[account:name]" in my example. To understand how I know what in my case the identifier is of the task to be deleted, look at the way I specified my (new) scheduled task to be created: it is "identifier" : "[account:name]", which  is what I used as my identifier to schedule a task.

In your case, I think "[account:name]" would be a pretty good choice for such identifier. But your questions states "... users then gets 4 emails over the next four weeks, sent by the scheduler ...". So if the 2nd email only gets scheduled after the first email (and not schedule all 4 emails upfront together), and similar for the 3rd and 4th email, then you should be fine using this identifier also.

Note: Specifying an "identifier" like "[account:name]" is what you'd do in your Rules Action (similar to my "step 3" in the above sample). While you'd probably want to create a Rules component similar to my "step 2" in the above sample to actually send an eMail.

Update: The "integrity check" problem shown near the end of the updated question, is probably because in your rule, as shown in the updated question, does not specify the date to schedule your component. Have a look again at my answer I mentioned above: the rule there specifies a date via this part of it:

  "date" : {
    "select" : "account:field-next-article",
    "date_offset" : { "value" : 2592000 }
  },


Differences between Location and Location CCK?

Location: provides the Location API; handles address storage and geocoding. Essentially the base of the location module to which the other modules rely upon.

Location CCK: provide a Location behavior as a CCK field. This module uses the field API properly rather than its legacy node location module which implemented its own fields and storage.

If you are evaluating which one to use, I would recommend the cck one. The others are being deprecated soon.

Via the project page:

  Location 7.x-4.x is planned to be a stripped out version of location
  7.x-3.x, which has no node location, user location, location taxonomy (at least in its curren form), location add another sub-modules. It
  will only have location field, which will essentially be the current
  location cck module.


I made a similar patch to the Amazon S3 module: "New variable to override file field URI scheme per environment"  https://www.drupal.org/node/2422977#comment-9602981
This patch was adopted by the module, and is now the approved way of solving the OP's problem using the Drupal 7 Amazon S3 module. This is the issue I wrote on Drupal.org.

Problem/Motivation
When using Features (or hook_field_default_field_bases() directly) to export file field definitions, the Upload destination is included. This can already be handled in a custom module by implementing hook_field_default_field_bases_alter(), and checking $conf (set in env-specific settings files, etc). But it would be nice to include support directly in amazons3.module.
Proposed resolution
Implement hook_field_default_field_bases_alter(), and check for a namespaced variable amazons3_file_uri_scheme_override. This variable can be added to environment-specific sites/*/settings*.php files to allow certain environments to upload to S3 while other environments upload to whatever the defined/exported (public or private) URI scheme is.
User interface changes
The only change in the UI would be that the field settings reflect the URI scheme defined either by the exported field bases or the variable (on environments where that's present).
API changes
No API changes, but the patch documents usage of the variable.

Note the module's README.md also now contains this additional line:

When using Features to export field definitions, the Upload destination is included. If you want to override this (for example, in a multi-environment workflow), use the 'amazons3_file_uri_scheme_override' variable. See amazons3_field_default_field_bases_alter() for documentation.

Here is the relevant documentation of amazons3_field_default_field_bases_alter that README note is referring to:
* Allows a variable to override all exported field bases to use 'Amazon S3' as
* the Upload destination. For example this can be added to environment-specific
* Drupal settings files, to allow certain environments to upload to S3 while
* other environments upload to the exported (public or private) URI scheme:
* @code
* $conf['amazons3_file_uri_scheme_override'] = 's3';
* @endcode

Also note the variable is not deleted by amazons3_uninstall() because it's only valid use case is being defined in $conf (otherwise just change the field setting).


Basically after examining the code example from the example module, I've found that the vertical_tabs are the container of the different fieldsets, and the title of the fieldset is the vertical tab's title.
All tabs are connected to the vertical_tabs through the  #group attribute. It's that simple...

$form['additional_settings'] = array(
         '#type' => 'vertical_tabs',
         '#weight' => 99,
      );

      $form['vertical_tabs_example2'] = array(
      '#type' => 'fieldset',
      '#title' => t('Example vertical tab2'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      // The #group value must match the name of the vertical tabs element.
      // In most cases, this is 'additional_settings'.
      '#group' => 'additional_settings',
      // Attach the javascript for vertical tabs.
      '#attached' => array(
        'js' => array(
          'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
        ),
      ),
      '#tree' => TRUE,
      '#weight' => -2,
    );

      $form['vertical_tabs_example'] = array(
      '#type' => 'fieldset',
      '#title' => t('Example vertical tab1'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      // The #group value must match the name of the vertical tabs element.
      // In most cases, this is 'additional_settings'.
      '#group' => 'additional_settings',
      // Attach the javascript for vertical tabs.
      '#attached' => array(
        'js' => array(
          'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
        ),
      ),
      '#tree' => TRUE,
      '#weight' => -2,
    );


How do I initialise store in-app-purchase?

In a DrupalGap Custom Module, you'll use hook_deviceready():

/**
 * Implements hook_deviceready().
 */
function my_module_deviceready() {
  // Place your initializeStore function's code here...

  return true; // Let DrupalGap know it is OK to continue.
}


You put the menu in the folder config/install of the module.

An example from the devel module:

/config/install/system.menu.devel.yml

id: devel
label: 'Development'
description: 'Links related to Devel module.'
langcode: en
locked: true

Then you can place the menu link items for this menu in *.links.menu.yml in the root directory of the module.

Edit:

As mentioned in the comment from @mradcliffe, some background info might be helpful. Menus are configuration entities. The storage of the configuration is for performance reasons in the database, but they were at the beginning of D8 in yaml files. If you sync the configuration to the harddisk you will find the configuration in a set of yaml files. You can put any of these yaml files in the config/install folder of your module. But you have to remove the uuid line, because the uuid is only valid for the installation you have exported the yaml file from. The menus are in system.menu.*.yml.


drupal 7 default table to store form values

You can use Drupal variable system, please read the following article: https://www.drupal.org/node/1111260

You can create you own table, just use hook_schema for it: https://api.drupal.org/api/function/hook_schema/7

If you to get information from your users by form and store it, please check the module webform:  https://www.drupal.org/project/webform

Node table used for storing main information about nodes (it's some type of content). Node can by "Article" or "News", etc. More you can read here: https://www.drupal.org/documentation/modules/node


Predefined webform configuration for specific content type

Yes, You can able to do it using admin UI.

Follow below instruction.

Add new field (boolean type) at webform content type.

Make this field as a checkbox.

Add "Entityreference" module

enable it

Create entityreference view using views UI for webform content type and add above created boolean field in FILTER CRITERIA  select operator > is one of "yes"

I have attached snapshot for views UI

Now edit manage field on job content type

Add new field on job content type give the name and select "Entity Reference" in data type.

Now select "select list" option for widget click on next button.

Next page will be shown Entityreference option at there you need to section "view" for the first drop down "Views: Filter by an entity reference view" and second "View used to select the entities" pick you entity reference view which you have created prviously and save it.

Snapshot for above description

Now you will able to select created webform on job node.


How do I build Breadcrumbs for a certain node?

I eventually solved it by creating my own subclass of the PathBasedBredcrumbBuilder from core. This class unlike core's version actually uses the passed in route_match and returns breadcrumbs based on that which makes it possible to get breadcrumbs for a certain node (or any other given route).

I still need to calculate the route match from the current node to pass to the build method (as shown in the question). It feels a bit awkward since the route_match is converted back into a url object in the build method but  it works and it is the cleanest solution i've come up with so far.

Below is the subclass:

namespace Drupal\contextual_breadcrumbs;

use Drupal\system\PathBasedBreadcrumbBuilder;
use Drupal\Core\Routing\RequestContext;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;

class ContextualPathBasedBreadcrumbBuilder extends PathBasedBreadcrumbBuilder {

    /**
    * {@inheritdoc}
    */
    public function build(RouteMatchInterface $route_match) {

      /// Set request context from passed in $route_match
      $url = Url::fromRouteMatch($route_match);
      if ($request = $this->getRequestForPath($url->toString(), [])) {
        $context = new RequestContext();
        $context->fromRequest($request);
        $this->context = $context;
      }

      // Build breadcrumbs using new context ($route_match is unused)
      return parent::build($route_match);
    }

}


How to load .css file only on your custom 404 Not Found page?

As mentioned by @Yogesh, you should use drupal_add_css. Your code cannot work because you have missing slash. Please use below code.

function themename_preprocess_page(&$vars) {
 // Adds a Custom 404 page
 $header = drupal_get_http_header("status");
 if($header == "404 Not Found") {
   $vars['theme_hook_suggestions'][] = 'page__404';
   drupal_add_css(drupal_get_path('theme', 'dev') . "/css/404/bootstrap.css");
   drupal_add_css(drupal_get_path('theme', 'dev') . "/css/404/custom-style.css");
 }
}


To maintain the sessions configure htaccess to run site with consistent protocol like www, https, if urls for pages are not with same protocols they login issues comes.


How do I overwrite Facet API tokens for active items?

I didn't need the "Facet API Bonus" module, I wrote a module to implement THEME_facetapi_link_active (included in facetapi.theme.inc)
then i simply replaced the label's text using the function str_replace like this:

$variables['text']=str_replace("Price » Amount (decimal)","Price",$variables['text']);


Showing two colorbox windows side by side...or within one main frame?

One simple approach would be to just create a content type that includes both items. For instance, "songs". Then, you could:

Embed each youtube video within their corresponding tabs node.
Then, you could use a module such as Display Suite to display one next to each other (E.g. video on the left column and tabs on the right column).
After this, if you want the tabs to be "scrollable", just set a fixed height in CSS and a "scrolled" overflow. E.g.

.views-field-body pre {
    height: 300px;
    overflow-y: scroll;
}

That should do the trick, the colorbox will open one node, instead of 2 as currently.


Form Ajax not working when rendered from Ajax callback

I have fixed the issue I was having by just returning the render array of the form rather than trying to get the form's HTML. So my AJAX callback function now looks something like this:

public static function OnPanelSwitch(array &$form, FormStateInterface $form_state) {

   $ajax_response = new AjaxResponse();

   $AddChartForm = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddChartForm');

   $ajax_response->addCommand(new HtmlCommand('#formarea', $AddChartForm));

return $ajax_response;


LoginToBoggan + Don't use set password mail

I use the same type of setup as the one you describe:

Register and login with username and email.
Login using the email address.
User sets password upon registration (i.e. no email confirmation required).

I've found that the process where user receives a one-time link to set password is a huge stumbling block in the registration process.

Drupal let set up the site to have user sets password upon registration (Uncheck "Require e-mail verification when a visitor creates an account" on Administration » Configuration » People » Account settings).

However, I do not use LoginToBoggan to allow the users to login using the email address.

Instead, I use Realname Reg.  Please note that this is a sandbox project, but it is actively maintaned (by me), and it has been tuned specifically for the use case you describe.  I've used it on a dozen production sites for about a year with no issues.


Suppose that the machine name of your vocabulary is: test.

Then you can use the following code

$vid= 'test';

$vocabulary= taxonomy_vocabulary_load($vid);

$vocabulary->set('name', trim('newmachinename'));

$vocabulary->save();

  change the newmachinename by your machine name.

Note. you must be careful when using this code, because those configurations that you have with the previous machine name will be affected


Why adding '--create-db' to sql-sync command throws the access denied?

Try:

drush sql-sync @alias1 @alias2 --create-db --db-su=adminuser --db-su-pw=password

Substitute the appropriate username and password for your mysql admin user.  Note that if @alias2 is a remote alias on a shared server, it is possible that other users on that same server might be able to observe your mysql credentials if you use this command.  You might therefore prefer to use drush @alias2 sql-drop prior to sql-sync as an alternative method to dump your sql tables.

Of course, most of the time the remote alias will be the production db, and typically you will only sql-sync from production to dev, not the other way around, so the credentials leak is not usually a problem.


Is it possible to POST values to next page with a Drupal URL?

To prepare links in Drupal, use the l() function:

$options = array('query' => array('orange_id' => $row['orange_id']));
$link = l('Edit', 'node/17', $options);

You can also add 'absolute' => TRUE to your options array to get the full URL; full options are on the docs page.

Using l() you can ensure that your URL is valid at all times.


Why are values in Entites obtained directly and sometimes by using getters?

Ok, trying to answer this. This could get a bit long :)

First, to have that out of the way, Drupal\Core\Entity\Entity::id() is not TypedData relevant, only content entities (subclasses for ContentEntityBase) are typed data at the moment. So that implementation is for example used for config entities.

Now about the different methods that you mentioned.

getValue() is part of TypedDataInterface and it's not strictly defined what it returns, but it can be understood as the raw value of that typed data object. For anything that is not a so called primitive value (like a string or integer), getValue() returns an array. So if you call getValue() on the first field item of the node body ($node->body[0]), it will return array('value' => ..., 'format' => 'text_plain'). If you call it on the field item list, you get array(0 => array('value' => ..., 'format' => 'text_plain')). So for all complex data (another typed data term, it defines an objects that consists of sub-properties, like an entity or field item), think of getValue() as toArray().
Content entities no longer have public class properties. $entity->id->value goes through $entity->__get('id')->value, which is almost identical to $entity->get('id')->value, with the following differences:

get() currently only supports defined fields. _get()/_set() allow to set anything on an entity, mostly due to BC reasons, because a lot of code still sets tons of random stuff on $node. So print $node->bla works, $node->get('bla') will throw an InvalidArgumentException('Field bla is unknown.'). This could be changed if we want to.
Before PHP 5.4, $node->get('body')[1] is not supported (while $node->body1 works fine), so you have to use the rather weird $node->get('body')->offsetGet(1) (this is ArrayAccess, #2110467: Add first(), get($index) and possibly other methods to ListInterface will hopefully soon change that to a $node->get('body')->get(1)). Now that D8 will require 5.4, this isn't much of an argument anymore and the referenced issue makes it easier too.
get() is faster than __get(). On the large scale, there's not a big difference I think (other things are worse), but relatively speaking are magic method calls considerably slower than non-magic ones.

The ->value part involves more magic methods. To explain that, I first have to mention that all entity fields (including base fields like the ID) now have a fixed structure enforced: Entity : Field item list : Field item : Field properties (like value, format, target_id). If you write $entity->id->value then ContentEntityBase::__get() gives you the field item list for the id field. Then you call $field_item_list->value, which points to FieldItemList::__get() which assumes that you want to access the first field item, so it passes the call through to FieldItemBase::__get(), which then returns the value. I suggest that's enough detail for that question, if you want to know more about FieldItemBase, I'm happy to answer that in a separate question.
Now, $entity->id->getValue() and $entity->id->value are often mixed up, but they are not actually related in any way, it's just an unfortunate naming conflict. value happens to be the pseudo-standard main field property name, especially for those that only have a single value. Reference fields use target_id, and if you want to name the property of your own field type banana , then all you have to do is set it up accordingly in your FieldTypeItem::getPropertyDefinitions() implementation and it will be $entity->your_field->banana.
There are (at least) two remaining issues that will affect these API's. That is #2002134: Move TypedData metadata introspection from data objects to definition objects and #2002138: Use adapters for supporting typed data. The main goal of those combined is that entities and field items are no longer typed data objects themself but can be used as typed data through adapter classes. That in turn means that those classes do not have to respect (and poorly implement in case of entities) the TypedDataInterface/ComplexDataInterface interfaces but can define method names that make more sense in their context. For example, we can hopefully rename getValue() to toArray() or something else that has no naming conflict with value, we can rename $entity->getPropertyDefinitions() to $entity->getFieldDefinitions() and so on.

So, to come back to what your actual (I think) question is, $entity->id->value and $entity->get('id)->value are almost identical, both are currently supported, but I usually prefer and recommend get(). __get() could still change (although I consider it unlikely, as nobody is pushing there), so if you use get(), you're on the safe side I think.


hook_menu_get_item_alter() needs to give a 404

I was able to do this in hook_menu_get_item() by getting the status of the node from a simple query, and, when status isn't NODE_PUBLISHED, I change the router item's load function from node_load() to is_null(), which will always return FALSE when a node ID is passed to it. A FALSE from a load function will result in a 404 response from Drupal. This is a bit dirty, but it uses the Drupal API properly, and it seems to work!

/**
 * Implements hook_menu_get_item_alter().
 */
function mymodule_menu_get_item_alter(&$router_item, $path, $map) {
  if ($path == $_GET['q']) {
    if (isset($map[0]) && $map[0] == 'node' && isset($map[1]) && is_numeric($map[1])) {
      $status = db_query('SELECT n.status FROM {node} n WHERE n.nid = :nid', array(':nid' => $map[1]))->fetchField();
      if ($status != NODE_PUBLISHED) {
        // Replace node_load() with is_null() as load function, to ensure the
        // output of the load function is FALSE, so we get a 404 response.
        $router_item['load_functions'] = array('is_null');
      }
    }
  }
}


Question field in the user registration process

Go to admin/config/people/accounts/fields and add the field. In field settings enable "Display on user registration form." - you can hide it everywhere else if is only for your eyes.


Display Ubercart sell price in Apache Solr search results

You can index it using solr's dynamic fields (see your schema.xml in the solr conf directory) and a custom module hook, namely hook_apachesolr_update_index().

Then you can, at search time, add the field you have indexed into the fields being fetched. For this you have three hooks or 'hooks' to choose from: hook_apachesolr_prepare_query(), hook_apachesolr_modify_query() and CALLER_finalize_query().

For further information on the hooks, see the README.txt in the apachesolr module directory.

Then in your search-result.tpl.php you'll have available the custom indexed field as $result['fields']['your_field_name'].


The "Comments block" module was the cause of this.  The module appears to be functioning as intended.  I just hadn't encountered this contributed module before, and didn't realize the project made use of it.

Because the "Comments block" module is installed, the "Comment form" block must be added to a region (e.g. "Content") in the theme.  This explains why the comment form was appearing in some themes but not in others.


The currency data lives in the commerce_order_total field by default. You can extract that information easily using field_get_items(), though an entity_metadata_wrapper() is just more fun:

$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

$currency_code = $order_wrapper->commerce_order_total->currency_code->value();


How do i use Webform API to submit my Custom Module form?

You want to use hook_schema() in your module.install file to make a database table to store your values. A small stupid logging schema I wrote is as follows:

function idprocessing_schema() {
  $schema['idprocessing_log'] = array(
    'description' => 'webextract process logging',
    'fields' => array(
      'id' => array(
        'description' => 'id of entry',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'created' => array(
        'description' => 'The Unix timestamp when the entry was made.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'msg' => array(
        'description' => 'whats going on in the processing',
        'type' => 'text',
        'size' => 'medium',
        'not null' => FALSE,
      ),
      'num_students' => array(
        'description' => 'number of students from xpath query',
        'type' => 'int',
        'not null' => FALSE,
      ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

You then insert into the table as needed with say db_insert() a Database API function of drupal.

  db_insert('idprocessing_log')
    ->fields(array(
      'msg' => $msg,
      'num_students' => $cnt,
      'created' => REQUEST_TIME,
    ))
    ->execute();

You would want to insert $form_state['values'] by the way in your my_module_my_form_submit function.


You first let Drupal's theme system know about your "theme" functions. You just create a function called mymodule_theme and that should return an array with your theme functions defined. See hook_theme for more details.

Example:

function mymodule_theme() {
  return array(
    'funstuff_output' => array(
      'variables' => array('node' => NULL),
    ),
  );
}

Now the 'funstuff_output' function does not exist... so create it!

function theme_funstuff_output($variables) {
  $node = $variables['node'];
  $output = '<h1>' . $node->title . ' is fun stuff</h1>';
  return $output;
}

Now you can call taht theme function anywhere like so: print theme('funstuff_output', array('node' => $node));

In Drupal 6, I think variables is called arguments and there are some other differences. But that's the basics.


Behat @javascript test can not login user - incorrect username or password message

It was a pain to track down but I traced it to the Security module.  It encrypts the password field on form submit - disabling the module allows Behat @javascript tests to run fine.


Modify the error message about the maximum upload file size

As far as I know, there is not a way to add a validation handler for the file field type in general. You'll need to set a hook form alter and add a custom form validate handler for the edit forms, webforms, etc that you want to override.

Refer to: How do I add a custom validation handler to an existing form/field?

Alternatively, if your site is a multilingual site configured for internationalization, you can probably override the english version of the message in the. po file. I would advise against installing and enabling internationalization just for this use case, as it adds several pieces of functionality to the site and can bloat your database.


Is it possible to put a single field of views in panels?

Yes, you can add a single field directly from panels using Add Content, for this you may need to add a context with your entity.

use Arguments option to pass an entity id from url argument and load dynamically context based on that entity;
use Context option to manually specific a entity id to load its context;

You can check node view page as example, which has node context by default.


Module for floating vertical and customizable image menu

You can use Floating block module

Floating Block Module page says

  The Floating block module allows you to keep html blocks, selected
  using jquery selectors in a fixed position on the page as you scroll.
  It works in a similar way the table header fixer in Drupal Core. This
  means that when the user scrolls their browser selected parts of the
  page can stay in the users view.


What is the right way to force a session start?

Okay, found the answer from this change record: https://www.drupal.org/node/2228871

The session can be force-started like this:

// Force session start if we don't already have a session.
$session = \Drupal::service('session');
if (!$session->isStarted()) {
  $session->migrate();
}


How do I avoid checking for updates for a specific module?

You need to implement hook_update_projects_alter().

  Alter the list of projects before fetching data and comparing versions.

  Most modules will never need to implement this hook. It is for advanced interaction with the update status module: mere mortals need not apply. The primary use-case for this hook is to add projects to the list, for example, to provide update status data on disabled modules and themes. A contributed module might want to hide projects from the list, for example, if there is a site-specific module that doesn't have any official releases, that module could remove itself from this list to avoid "No available releases found" warnings on the available updates report. In rare cases, a module might want to alter
  the data associated with a project already in the list.


This is not possible natively. You could write a Drush commandfile, and call drush_set_context('DRUSH_LOG_CALLBACK', 'my_log_function'); to intercept log messages. See drush_log() for details.

A pull request could be considered; it would need to fail gracefully if someone attempted to use it on a system that did not have syslog. Drush avoids platform-specific features where possible, though, which is probably why this has not been added as a standard feature to date.


Sanitizing User Input using Form API - Creating Nodes

Filters are used for output, not input. It's the Drupal way; save the raw, un-sanitised data in storage, and filter (and cache) when it's being rendered.

You shouldn't run check_plain() on your node title before saving it, as it will be run through the same function by core/contrib when the node is being rendered, hence the double-encoding you're probably seeing.

If you're responsible for rendering the node title yourself at any point, you should always run it through check_plain() first:

echo check_plain($node->title);

But always on output, never on input.


Is it possible with Drupal Views to have AND and OR in a filter set?

Looks like this is entirely possible with the Views 3.x branch. You can create custom Filter groups directly in the Views UI itself, and set the AND/OR for each group separately.


How to show only an image of the YouTube video while using Media: YouTube module?

If you can grab the id of youtube video then you can use following pattern of url to get  a bigger youtube thumbnail.

http://img.youtube.com/vi/[your video id]/0.jpg


HTML special characters changed to foreign characters

It should work in a proper Drupal environment

  Several people have asked how to specify the character encoding that
  Drupal uses. The short answer is: you can't.

How can I change Drupal's character encoding

  Drupal uses UTF-8 for encoding all its data. This is a Unicode
  encoding, so it can contain data in any language. You no longer need
  to worry about language specific encodings for your website (such as
  Big5, GB2312, Windows-1251 or 1256, ...). Also, when Drupal imports
  external XML data (such as RSS or XML-RPC), it is automatically
  converted into UTF-8 (iconv support for PHP will be required for most
  encodings).

From Stackers


Entity form Submissions automatic numbering over 1000

Okay after searching it was probably the 12 forum post I found another module that helps with this issue.

Install this module along with Pathauto.
https://www.drupal.org/project/pathauto_entity

The URL Alias is: [entityform:type:label]/[entityform:entityform-id]

Hopefully that helps someone.
Peace


Webform Error Occurs During Configuration Import

Ad 1)
I guess the proper workflow is never do any config changes on prod, completely disable all config UIs on prod and do only one-way forward-syncs from stage to prod. But I'm also working for small businesses, who do their work directly on the prod server, so I also can't use the "proper" workflow.

My personal workflow is

Prod always is the source of truth (no config ignore).
Before development, always pull config from prod.
drush @prod site:ssh drush_cex_and_git_push.sh "Backsync"
git_pull_and_drush_cim.sh
During development, don't change config on prod to avoid merging troubles.
After development, push to repository and pull changes on prod.
drush_cex_and_git_push.sh "New awesome feature"
drush @prod site:ssh git_pull_and_drush_cim.sh

This workflow is NOT safe for concurrent config changes, so this will not work well if you have frequent config changes on prod or long-term or multi-person development jobs!

Prerequisites:

SSH access on prod. Add dev machine's SSH key on prod's ~/.ssh/authorized_keys.
Create drush site environment entries for @dev and @prod in ~/drush/sites/self.site.yml to execute drush commands on prod environment while working on dev machine. (doc)
Use git with SSH keys for quick syncing config between environments without password prompts.
Use some bash scripts for single-command syncs between environments

git_pull_and_drush_cim.sh

#!/usr/bin/env sh
echo ""
echo "PULL and IMPORT all updates..."
echo ""

git pull
echo ""
echo "DELETING unused config files"
echo ""
git clean -fd config/sync
echo ""
./composer.phar install --no-dev
./vendor/bin/drush state:set system.maintenance_mode 1 -y
./vendor/bin/drush cache:rebuild
./vendor/bin/drush updatedb -y
./vendor/bin/drush config:import -y
./vendor/bin/drush core:cron -y
./vendor/bin/drush state:set system.maintenance_mode 0 -y
./vendor/bin/drush cache:rebuild

drush_cex_and_git_push.sh

#!/usr/bin/env sh

if [ -z "$1" ]; then
  echo "Usage: drush_cex_and_git_push.sh <commit message>"
  echo ""
  exit 1
fi

echo ""
echo "EXPORT and PUSH all updates..."
echo "Commit Message: $1"
echo ""

./vendor/bin/drush config:export -y
git add -A
git commit -m "$1"
git push

I'm also using those scripts as part of my semi-automated maintenaince script running composer updates for all my projects.

Ad 2)
drush config:import deletes all existing configs from the DB that are not present in the sync directory. Since you cannot delete an entity config while there are dependent entity instances in the database, you get this error message.
It would be the same as if deleting node.type.article.yml config while still having article nodes in the database.

There are a lot of blog posts on large enterprise projects with a strict dev --> stage --> prod workflow. I'd love to see more info on how to handle a small dev <--> prod workflow.


The twig function url() returns a render array, when you render it with the twig filter |render you get a markup object and when you render it again you get a string, which you can check whether it contains a substring:

{% set url = url('<current>') %}
{% if 'test' in url|render|render %}

url contains "test"

{% endif %}


How to add a functionality to views bulk operations?

VBO comes, out of the box, with some predefined (hardcoded) operations that can be applied to each row selected in the view. The available operations are shown within "Selected bulk operations" when configuring the VBO field. Obviously, something like Edit taxonomy terms isn't one of them.

However using Rules (Conditions and/or Actions) you can execute a VBO operation which you define using a Rules Component. To get the idea, have a look at the video about Using Rules components with VBO" uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video. This video actually shows how to (also) add a term to a node, so it should be pretty forward to use a similar technique.

For an example in which this technique is used, refer to the answer to "How to implement the mass operations on the Group's members page using Views?".

Note: to process thousands of nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!


how to resend email to new created user with wrong email

_user_mail_notify() is the underlying Drupal function that does the work of sending out a user account creation email. You can reference the API doc link on how it's used, then call the function in the appropriate code context (e.g. menu callback, submission function, drush eval, etc.) for your situation.


It sounds to me that you should have a look at the Entity Registration module as an alternative to simplify your current setup. Some more details about it, from its Community documentation:

The Entity Registration module provides the ability for users to register for any entity in Drupal. Registrations are fieldable entities and can collect any information you need from your registrants. By attaching a Registration field to any entity, you enable users to fill out a form containing customized fields to register for that entity.
Entity Registration currently has the following features:

Registrations are fieldable entities, so collect any information you need from your registrants
Unlimited types of registrations, or bundles.
Enable registrations of a given type/bundle on any entity type or individual entity through a registration field.
Per entity registration settings like capacity, reminders, etc.
Send broadcast emails to registrants.
Allow a single user to register multiple registrants.
Integration with Views and Rules via Entity API.


How do you get the nid from an entity id?

It's important to understand that if all you have is the id of any entity, then there is no way to load a specific entity with that id. Since entity_id's are not unique across entity-types, it is necessary to know both the entity type, and the entity id.

See Developers need an $entity->entity_type property for a discussion on changing this for D7, as well as info about how this will be likely be handled in D8.

On the other hand, as pointed out in a different answer, if you already know that the entity id is a node id, then you can call an entity specific load function like node_load($nid). Since most entities will have such a load function to support named arguments, such a "shortcut" function will be almost universally available.

Examples: node_load(), taxonomy_term_load(), commerce_product_load().


Using Views to filter images based on taxonomy of page node

Create a views block.
Under Contextual filters, add Content: Has Taxonomy Term ID
Provide Default Value -> Taxonomy Term ID from URL
Tick on 'Load default filter from node page, that's good for related taxonomy blocks' and tick your proper vocabulary.


How do I amend roles for the Administer Users by Role module?

A possible scenario to implement what you're looking for is like so:

Use the Flag module to allow a Publisher (any other roles also?) to flag users to indicate that they "want to amend the role for that user" (say you label such flag as "Amend User").
Then use the Rules module to react to (Rules Event) "A user gets flagged with the Amend User flag", combined with a Rules Action to "grant a role to the flagged user" (which could be multiple roles also if needed).
If you need more granularity to be able to do so for multiple roles (like role A for user X, role B for user Y and role A and B for user Z), then just use multiple flags (1 for each role individually).

True, this would require 2 more modules, but pretty sure you'll find lots of other use-cases for these amazing modules (which should be part of pretty much every Drupal site).


How do I include a custom class file in a module?

You don't use file[] = ... anymore. Instead, classes are autoloaded. For example, I have a module with the following file structure:

views_hybrid/

views_hybrid.info.yml
views_hybrid.module
src/

Plugin/

Field/

FieldFormatter/

HybridFormatter.php

HybridFormatter.php defines a class called HybridFormatter.

In my .module file, if I start typing in my IDE (NetBeans in this case) HybridFormatter it autocompletes to \Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter:: because it is autoloaded. Since I don't want that whole path littering my module, at the top I have placed the line,

use Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter;

along with use directives for other classes I am including for use with my module.

The namespace is defined in HybridFormatter.php like so:

namespace Drupal\views_hybrid\Plugin\Field\FieldFormatter;

class HybridFormatter extends FormatterBase { ... }


Drupal constructs the pages you see using blocks and nodes through a template file. To find that text, look in menu option "website information", next if not found look in the block list for a block placed in copyright or footer area.

Drupal will depend on block/regions; learn that too. Finally, when that doesn't work, in /sites/all/themes/ you'll find the PHP and HTML files delivering the themed page.


For anyone else that stumbles on this.  I found a solution.  So remember my example is "How Many Players" [i used select option 1-5].  If user selects 1, fieldset 1 appears only, if he/she selects 2, FS1 and FS2 appear, select 3, FS1, FS2 and FS3 appear.  To prevent the error I use and or statement for allow the fieldset and worked my down down.  See image.


How do i change date format in View Exposed Date filter?

To make it easy let's disable Drupal datepicker and make it with javascript.

First disable jquery ui datepicker from exposed filter (like picture below)

Then create a module with libraries in file my_module.libraries.yml like below

d8_datepicker:
  version: 1.x
  js:
    https://code.jquery.com/ui/1.12.0/jquery-ui.min.js: { type: external, minified: true }
    js/datepicker.js: {}

And in our my_module.module let's alter the exposed form and add line below :

  function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
     if ($form_id == 'views_exposed_form') {
      $form['field_date_value']['#type'] = 'textfield';
      $form['field_date_value']['#attributes']['class'][] = 'datepicker-text';
      $form['field_date_value']['#attributes']['placeholder'] = 'yyyy-dd-mm';
      $form['#attached']['library'][] = 'd8/d8_datepicker';
      $form['#validate'][] = 'my_exposed_validate';
     }

In our validate form function we will change date from our custom format to format needed by drupal :

function my_exposed_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  if(!empty($form['field_date_value']['#value'])) {
    $dt = date_create_from_format('Y-d-m', $form['field_date_value']['#value']);
    if($dt!==FALSE) {
      $value = $dt->format("Y-m-d");
      $form_state->setValue('field_date_value', $value);
    }
  }
}

And finaly in our file datepicker.js add this line :

(function($) {
    $('.datepicker-text').datepicker({ dateFormat: 'yy-dd-mm' });
})(jQuery);

Hope this helpful and if you wan't to go further, alter a form validation to check if the format sended is date or not ;)


How do you remove the "user login" block?

You may disable block on admin/structure/block page, but users can create new accounts from /user page. It's best practice disable creating new accounts by visitors.

For drupal 7 go to configuration -> people -> account settings -> registration and cancellation and set "Who can register accounts?" -> "Administrators only".
For drupal 6 go to administer --> user management --> user settings and set "Public registrations" --> "Only site administrators can create new user accounts."


Customizing menu link output (add badge)

This is the function you'll need:
https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7

That allows you to overwrite the standard theme function. You could do an if statement to check for that specific menu link ID and do a custom output.

You'll need to put that in template.php within your custom theme and replace "theme_" in the function name with the name of your theme


Organic Groups "create post" content link needed with posting content type specific to group

I solved this problem. I am not sure if this is the best way. If a better way exists, please do inform me.

To solve this problem I create 2 "Content Create Links" panels within the page.  Each added panel references the group audience specific for the Group Posting content type for the group.
At first both will probably show up, but you have to go to the global "OG Permissions Overview" and for each group type make sure that create content for that Groups posting content type is checked.  For all other type on the page you should not have "Create ____ Content" checked otherwise that content type (a posting type) will also show up as a "Content Create Links" for the wrong posting type for that group.

Do that for each Group type you have created, allowing "Create__(groups post content type) Content" and not having the "Create__(other groups post content type)__ content" for all other group posting content types for the other groups.

Now when I open up "Amigos" groups, I only get "Amigo Group Post" as the posting content type, and NOT "Authenticated Group Post" as well.

If this is too "hacky" I welcome other suggestions on how to configure this properly.


Try Views Slideshow

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


Change theme_image_widget in other theme

I found it myself.
If made a subtheme of seven (named sevensub) with just this special function in template.php

function sevensub_image_widget($vars){
    $vars['element']['alt']['#title'] = 'Foo';
    return theme_image_widget($vars);
}


Remove the link "add comment" if the user has already commented on the node

If you are OK with custom modules, you can make the module below.
If you have never made a custom module before, just make a folder called single_comment and create 2 files inside called single_comment.info and single_comment.module then add the code below into the respective files.

single_comment.info

name = Single Comment
description = Allow users to only add one comment to a node.
core = 7.x

single_comment.module

function single_comment_node_load($nodes, $types) {
  global $user;
  if (user_is_logged_in()) {
    foreach ($nodes as $node) {
      $comment_arr = comment_load_multiple(comment_get_thread($node, COMMENT_MODE_FLAT, 100));
      foreach ($comment_arr as $comment) {
        if ($comment->uid == $user->uid) {
          $node->comment = COMMENT_NODE_CLOSED;
          break;
        }
      }
    }
  }
}

You can call the module whatever you like but just remember to replace anywhere single_comment occurs. That includes the folder, file names, name in .info and the function name.


How do I separate multiple values for "print render($content['field']);" with a comma?

For example, I am fetching the texonomy vocabulary terms :

$terms = taxonomy_term_load_multiple(array(), array('vid' => '12'));
foreach ($terms as $temsaccess) {
$name[]=$temsaccess->name;
}

<a href="javascript:void(0);" id="<?php echo $term_name; ?>" Click="javascript:showProduct('<?php echo $term_name; ?>', this );"  data-filter="<?php echo $temsaccess; ?>">
<?php echo $temsaccess; ?>
</a>

Or refer to this link.


Send email when a user has finished watching something

Create an end point for your ajax request to call using hook_menu(). In this example I'm passing the UID of the user as an argument.

E.g:

/**
* Implementation of hook_menu().
*/
function myModule_menu() {
  $items['mymodule/send-email/%user'] = array(
    'page callback' => 'myModule_ajax_send_email',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}

The callback for your menu item will be responsible for actually sending the email. See this question: How to send email in drupal

E.g.:

function myModule_ajax_send_email($user) {

  // Here you put the code to actually send the email
  $status = some_logic_to_check_email_sent();

  drupal_json(array('status' => $status));
}

So then once your video has finished playing you just need to make an ajax request to your new end point, passing any information required as parameters.
E.g:

(function($) {
    Drupal.behaviors.myModule = {
        'attach': function(context) {

            jwplayer('some-id-of-video').onComplete(function(){
              //$.ajax or .post whatever to send email to a person to let them know without refreshing page
              var UID = 1; // actually set UID here
              var url = 'mymodule/send-email/' + UID;
              $.get(url, null, emailCallback);
            });

        }
    }
    var emailCallback = function(response) {
        var result = Drupal.parseJson(response);
        if(result.status !== 1) {
          // Some code to let user know there was an error
        }
    }
})(jQuery);


Uncaught TypeError: Only on Drupal edit pages

I had installed the dev version of jQuery Update 7.x-2.3+15-dev, which allows you to specify different versions of jQuery for normal and administrative pages:

I'd done this because I had previously required jQuery 1.5 for something in the backend. It appears /edit/ pages are considered 'administrative' pages - (which seems odd to me)  and therefor were using 1.5 which broke the bigSlide.js menu.
Changing the admin pages back to 1.7 fixed the issue.


Commerce Kickstart - items won't float side by side

AAAAh!  The answer is to shut down the site, shut down localhost, and re-start everything back up again.  It must have been a memory issue!


Return your renderable page build with 2 entries, one for the node and one for the form:

return array(
    'node' => $page,
    'form' => $form,
);


Force capitalization of terms on entry with Autocomplete Deluxe module

The Taxonomy dupecheck module would probably help for most of that (I'm not entirely sure about the case-sensitivity issue but give it a try; MySQL queries for term names will be case-insensitive so my gut instinct is this would work)

  Taxonomy dupecheck module prevents Drupal administrators from adding duplicate taxonomy vocabularies and/or terms. It's helpful when entering large amounts of terms or vocabularies in situations where each value must be unique. This saves time by preventing administrators from having to enforce a unique value policy through later cleanup of duplicate terms.

To force title-case on the term you could implement hook_taxonomy_term_presave() in a custom module and force it like so:

function MYMODULE_taxonomy_term_presave($term) {
  if (some_condition_applies_to($term)) {
    $term->name = ucwords($term->name); // Or ucfirst() depending on your requirement
  }
}


.htaccess 301 redirects breaking clean URLs

No idea how acquia hosting works, but I doubt they respect your .htaccess and possibly don't even use Apache.

Maybe they have their own configuration settings for that, I know that platform.sh (which uses nginx) does.

If not, then you don't really have a choice but to do it in Drupal.

You could also try the latest redirect release which has a new submodule that supports domain and wildcard based redirects.


what is the difference between a load callback and list callback in the i18n hook_i18n_object_info() function?

A list callback is a callback that returns all the objects of a specific type; for example, for content types, the list callback is node_type_get_types().
A load callback is a callback that loads a single object of that specific type; for content types, the load callback is node_type_get_type().

Reference

hook_i18n_object_info()
i18n_node_i18n_object_info()


Guess log means watchdog here. Generally, you only have what the developer passed to the watchdog.

You can try to parse the code for (a part) of the error message. There's a good chance that this points you to the code sending the watchdog, which in turn gives you more information about the problem.


How can I override with my module the existing commerce_file_field_access function?

hook_field_access() implementations are invoked by field_access() using the following code:

  foreach (module_implements('field_access') as $module) {
    $function = $module . '_field_access';
    $access = $function($op, $field, $entity_type, $entity, $account);
    if ($access === FALSE) {
      return FALSE;
    }
  }

The hook is not invoked for the module implementing that field, but for any module implementing the hook.

If you want to override what done by commerce_file_field_access(), you just implement hook_field_access() in your own module.
As field_access() immediately returns FALSE when a hook_field_access() implementation returns FALSE, you can only override what returned from commerce_file_field_access() if your hook is executed before commerce_file_field_access(). This means that your module, when it is installed, should alter the weight associated with it, and assign it a lower value than the value assigned to the Commerce File module. The following is an example of hook_install() implementation for achieving that; it is similar to the code executed in block_install().

function mymodule_install() {
  db_update('system')
    ->fields(array('weight' => -5))
    ->condition('name', 'mymodule')
    ->execute();
}

The same can be done in hook_update_N().

Any value lower than 5 actually works, as the Commerce File module uses the following code:

/**
 * Implements hook_install().
 */
function commerce_file_install() {
  // Make module weight heavier than field module
  db_query("UPDATE {system} SET weight = 5 WHERE name = 'commerce_file'");
}

The alternative of changing the weight of your module, which would influence when every hook in your module is executed, is to alter the order used for that specific hook implementations, using code similar to the following one.

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'field_access') {
    // Move mymodule_field_access() to the top of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations = array('mymodule' => $group) + $implementations;
  }
}


Display success message after submitting form

The code you are showing is the same code Drupal core uses, for example in BanDelete::submitForm().

public function submitForm(array &$form, FormStateInterface $form_state) {
  $this->ipManager->unbanIp($this->banIp);
  $this->logger('user')->notice('Deleted %ip', [
    '%ip' => $this->banIp,
  ]);
  drupal_set_message($this->t('The IP address %ip was deleted.', [
    '%ip' => $this->banIp,
  ]));
  $form_state->setRedirectUrl($this->getCancelUrl());
}

As drupal_set_message() is used from Drupal core in submitForm(), that is expected to work. I cannot say why it doesn't work in your case, since you don't show the full method code. It could also be there is a module that is interfering.

As for more OOP code, starting from Drupal 8.6, drupal_set_message() has been replaced with a service. the same code I showed (which is Drupal 8.4 code) has been changed to the following.

public function submitForm(array &$form, FormStateInterface $form_state) {
  $this->ipManager->unbanIp($this->banIp);
  $this->logger('user')->notice('Deleted %ip', [
    '%ip' => $this->banIp,
  ]);
  $this->messenger()->addStatus($this->t('The IP address %ip was deleted.', [
    '%ip' => $this->banIp,
  ]));
  $form_state->setRedirectUrl($this->getCancelUrl());
}


How to synchronize my Drupal site with content pulled from a Wordpress site?

Wordpress exports its content using RSS.  The standard way of pulling this content on a regular basis is to configure the core RSS Aggregator module (disabled by default) to pull the content from the WordPress RSS.  It is highly configurable, you can pull daily or by the hour.
Here is a link to an introduction to the Drupal Aggregator - quoting:

Aggregator is a key part of Drupal that is often ignored.
I blame it on the confusing name. No, Aggregator is not an animal in Florida that eats people. Aggregator is a module that imports content from RSS feeds into Drupal.
Because it has a name starting with "A", Aggregator is the first module that people ever see on the Modules page. In this tutorial, we're going to show you what Aggregator does and how to use it.


Setting up video for Drupal- to play in popup

Video is hard. One thing to think about is that if you are going to use Vimeo then you don't need to worry about formats since Vimeo will handle that on upload (and the player, and the HTML5). My personal preference would be to use embedded media field, and the media:vimeo module.

Then you end up with the video as a cck field and you can use something like colorbox to give you your popup.


Form value not submitting for a function called from ajax

Your mistake is a misconception about AJAX callback function. In Drupal, all permanent changes to a form needs to be done in form creation function, in your case iks_beaches_create. Function pointed in ['#ajax']['callback'] has the only purpose to determine what part of form is supposed to be updated. It can change $form, but these changes are one-time only, and preparing form to save values counts as a second time. Move all your form assembly logic to iks_beaches_create, so you could trim callback to

function countryDisplay($form, &$form_state){
  return  $form['countryDisplay'];
}

and it will work.


How to use views to display different information sources

It seems there are many ways to achieve the same result in Drupal. In the end I went for 'Context'. By using 'Panels', it does not appear to be flexible enough to easily add extra blocks when needed.

Set the condition to <front>
In reaction add blocks
Then drop in all the required views into content


If you want to run Drush, you need ssh access to the server.  This means you need your sysadmin to make an account in the server for you.

To run the "pm-" commands, and a few others, this account will need to have both read and write access to the DOCROOT.  There are a few ways to do this; let your admin pick which is best for your setup.

You will also need PHP available from the command line, preferably with the same php.ini that the website uses.


So after a little investigation I realised I had a folder called drush in my home directory as well as something added by composed inside my home directory/.composer/vendor/bin/. I deleted these drush directories and ran composer again after which drush works fine.

[ec2-user@ip-... ~]$ ls
composer.json  drush  vendor
[ec2-user@ip-... ~]$ sudo rm drush
[ec2-user@ip-... ~]$ cd .composer/
[ec2-user@ip-... .composer]$ ls
cache  composer.json  composer.lock  vendor
[ec2-user@ip-... .composer]$ cd vendor/
[ec2-user@ip-... vendor]$ ls
autoload.php  composer  drush          nikic  psr  symfony
bin           dnoegel   jakub-onderka  pear   psy
[ec2-user@ip-... vendor]$ ls -la
total 52
drwxrwxr-x 12 ec2-user ec2-user 4096 May 12 07:25 .
drwxrwxr-x  4 ec2-user ec2-user 4096 May 11 20:59 ..
-rw-rw-r--  1 ec2-user ec2-user  183 May 12 07:25 autoload.php
drwxrwxr-x  2 ec2-user ec2-user 4096 May 11 20:59 bin
drwxrwxr-x  2 ec2-user ec2-user 4096 May 11 20:59 composer
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 dnoegel
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 drush
drwxrwxr-x  4 ec2-user ec2-user 4096 May 11 20:59 jakub-onderka
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 nikic
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:58 pear
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 psr
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 psy
drwxrwxr-x  6 ec2-user ec2-user 4096 May 11 20:59 symfony
[ec2-user@ip-... vendor]$ sudo rm -rf drush
[ec2-user@ip-... vendor]$ cd ../
[ec2-user@ip-... .composer]$ cd ../
[ec2-user@ip-... ~]$ composer global require drush/drush
Changed current directory to /home/ec2-user/.composer
Using version ^8.1 for drush/drush
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing drush/drush (8.1.2)
    Loading from cache

    Skipped installation of bin drush for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.launcher for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.php for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.bat for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.complete.sh for package drush/drush: name conflicts with an existing file
drush/drush suggests installing drush/config-extra (Provides configuration workflow commands, such as config-merge.)
Generating autoload files
[ec2-user@ip-... ~]$ drush
Execute a drush command. Run `drush help [command]` to view command-specific help.  Run
`drush topic` to read even more documentation. ......rest of output ommited


How to get field collection values from user object?

I find =)

With :

use Drupal\field_collection\Entity\FieldCollectionItem;
...
$test = FieldCollectionItem::load(3);

Where "3" is, by example, a value returned by $user->get('field_houses')->getValue();


Field value not coming in template.php for published node

The right way to doing this is hook_node_view_alter(&$build) where you can alter teaser link or any other $links. You reference from here


How do I get a parent-group alias as token for the Pathauto module?

Not possible at the moment (unless you make it yourself), there is an issue in the module's issue queue though that also has a patch that might work:

https://www.drupal.org/node/2774827


The access to menu settings/revision information, etc. is controlled by permissions. For example the user will require 'administer menu' permission in order to choose what menus their content will go in.

You just need to find the permissions the relate to whatever task you're trying to deny access to, and make sure the users in question don't have that permission (at http://mysite.com/admin/user/permissions).

Failing that, you should use a hook_form_alter() function in a custom module, and set the field/fieldset #access to FALSE:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['the_field']['#access'] = FALSE;
  }
}

In case you need to control access to certain CCK fields that you've created, the Field Permissions module is available for Drupal 6 and Drupal 7 and will do just that.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.


In a template, is it possible to get the content of a block by the block ID?

Yes take a look at this module :

  Twig Blocks

https://www.drupal.org/project/twig_blocks

After module install just call the block like this in the template :

{{ render_block('machine_name_of_your_block') }}

Or in a hook :

function hook_preprocess_page(&$variables)
{

    $block = \Drupal\block\Entity\Block::load('id_block');

    $variables['myBlock'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);

}

Then in your twig template :

  {{ myBlock }}


How can I make the label text on a Views Exposed Filter inline?

You may give a top margin to the label:

#edit-field-acc-gender-value-wrapper label{
margin-top: 5px;
}

It is not the best way but it will work.


Prepopulate new Taxonomy Term's Parent via the URL

I found out that the fieldset name must also be included, and for whatever reason the "[]" is also not required. To get it to work, I used the following:

?edit[relations][parent]=24


Try this:

if (typeof Drupal.geolocation !== 'undefined') {
            Drupal.geolocation.googleCallbacks.push({'callback' : function () {
                Drupal.geolocation.maps[0].googleMap.addListener('tilesloaded', function() {
                    $('.geolocation-common-map').on('click', function() {
                        console.log('Clicked on the map.');
                    });
                });
            }});
        }


Change Entity Value In hook_feeds_presave()

Can you mention your Drupal version?

For Drupal 7, your code looks good enough at a first glance.
If it's Drupal 8, all you need is $entity->field_email = ''.

If that doesn't work, leave a comment and I'll take a detailed look.


How to set value after the page redirecting?

You need to pass the term_id along with the $form_state['redirect']
like   $form_state['redirect'] = $base_path . '/example/other/redirect-1/?tid='.$term_id;
and
get the term_id in /example/other/redirect-1/ page  write something  like below

 $term_id = $_GET['tid'];
 $term = taxonomy_term_load($term_id);
 print render($term->description);

I am giving you an idea some modification may need on code. You need to check.


New Account, change Duplicate E-mail error

You can do a couple of things. One, I would advise installing the Username Enumeration Prevention module:

https://www.drupal.org/project/username_enumeration_prevention

This will stop forgot password form abuse.

Secondly, hiding this fact on the registration side is hard. You can't have duplicate email or usernames in Drupal (not easily), and if you get an error on that then it is pretty apparent it is already in use. Giving a vague error here could also confuse actual users who are trying to register.


White screen of death when uploading a file attachment

mod_fcgid have to do with FastCGI.

There are actually a few PHP settings you may need to investigate and modify.

Reference: Increase upload size in your php.ini

In short though, you will need to up your upload_max_filesize as well as your post_max_size

Also, I would recommend watching your /var/log/apache2/error.log (Default location in Ubuntu 10.4) while debugging.  Generally running sudo tail -f /var/log/apache2/error.log will show you 'white screen' errors in real time.


Overwrite field theme function from within form alter

Your question itself the answer, inside
 hook_form_alter use the following

$form['field_job']['und'][0]['#prefix'] = 'yours html'

and $form['field_job']['und'][0]['#suffix']='yours close tags of html' this html will wrap field.


How to properly use contextual filter on group content fields

Alright, I found the solution to my issue.

These are the steps I come up and followed.

Add taxonomy term relationship to the view.
On the Contextual filter, search "Name" with taxonomy as description
Under "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED", tick "Specify validation criteria"
Choose the desired vocabulary.
Save and test in the Preview section.


How do I change the label and help text of the publishing status checkbox?

You can use hook_form_alter() to change label and help text
Use devel module to debug the label and help text change accordingly.

/**
 * Implements hook_form_alter().
 */

  function hook_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if($form_id == 'node_page_form'){
   kint($form);
   kint($form['status']['widget']['value']['#title']);
   $form['status']['widget']['value']['#title'] = t('Published status label changed');
  }
}

After applying above code for basic page node form i was able to see the change in label of published text to Published status label changed


Authenticated REST requests becoming anonymous user

(Answering my own question, and trying to sound like a third-party so it makes better sense when read...)

It looks like it definitely has something to do with the session/cookie/etc., as subsequent calls seem to be coming from a different client (from the REST server's perspective.) I'm guessing bare PHP has no way of maintaining that cookie, like how a browser would. After looking here, it looks like the cookie needs to be formatted as such in the header of the request:

Cookie: session_name=sessid

(The cookie could also be retrieved from the response's headers->set_cookie variable. The latter will include all the expiration/link info in the string as well. While either method seems to work, I'm not sure if there are any ill-effects from one or the other. I just used the first method because it was the first solution I came across.)

Both session_name and sessid can be taken from the data area of the response after a user/login request. So the  request would ultimately look something like this for a user/logout

POST /api/user/logout HTTP/1.0
Content-Type: application/json
Accept: application/json
X-CSRF-Token: igHUQD11Y8LYdyzHi8m5t33U_tCVZNHE6BbptE4mrwQ
Cookie: SESSd3a1acd26f95229c67cd0a9a1e455bd4=rv-Kbyb8znaGlYBBU5Dn7M2GzkYdWnun5aXcVYLVfvY
User-Agent: Drupal (+http://drupal.org/)
Host: mysiteurl.com
Content-Length: 0


Why not make two importers that you run on the same CSV dataset? Run it first on the first imported setup and then again on the next. Each imported can be configured to create the needed content type.


How to use entityform and ajax_form_entity in a modal window?

There is a sandbox module called Modal Entity Forms https://drupal.org/sandbox/andreymaximov/2058521

It depends on the Modal Forms module and will work in the same way, but for entity forms. I have tested the module and it works fine for now, although I want to submit 1 or 2 patches to extend it's functionality.

EDIT:
There is now a new module called Modal operations: https://www.drupal.org/project/modal
It's currently dev only (still better than sandbox) and so far it seems to work fine.


Override function image_style_path doesn't work?

I find a way to modify/rewrite the url for each files image style with s3fs module for amazon S3.
It's not really easy to explain, but it work, so i try :

In module s3fs :

Edit file S3fsStreamWrapper.inc line 310 in function getExternalUrl
line 331 replace :

if ($path_parts[0] == 'styles' && substr($s3_key, -4) != '.css') {

by :   if (substr($s3_key, -4) != '.css') {

This will stop checking whether the first path element is the 'styles' folder.

Line 337 replace:

array_unshift($path_parts, 's3','files');

by : array_unshift($path_parts, 't','f','s');

The listening url for creating the derivatives image will be changed from s3/files/ to t/f/s in part to not signal at any time that we are working with an S3. But it's url is not show to normaly user. We can not delete these folders because Drupal expects in 4th position the name of the style like s3/files/style /your-style-name we will see later why I added a folder "s".

Edit file s3fs.module :
line 116 replace :

$items['s3/files/styles/%image_style'] = array(

by : $items['t/f/s/%image_style'] = array(

We changed the listening url in the S3fsStreamWrapper.inc file so we need to modify the listener.

In function _s3fs_image_style_deliver :
Line 206 replace :

$scheme = array_shift($args);

par : $scheme ='s3';

In the previous modification we no longer send information on the scheme. That is read normally through the s3/files url which is now t/f/s. So here we have to say manually what is the scheme.

Line 210 replace :

if (!variable_get('image_allow_insecure_derivatives', FALSE) || strpos(ltrim($filename, '\/'), 'styles/') === 0) {

by : if (!variable_get('image_allow_insecure_derivatives', FALSE) ) {

Another line that check that in first position we have style but we change it afterwards so we change that.

Edit directly Core module image in module/image/image.module.
Rewrite function image_style_path line 1096 :

function image_style_path($style_name, $uri) {
  $scheme = file_uri_scheme($uri);
  if ($scheme) {
    $path = file_uri_target($uri);
  }
  else {
    $path = $uri;
    $scheme = file_default_scheme();
  }
  $tabpath=explode('/', $path);
  $namefile = array_pop ($tabpath); //array_pop delete the last element of array $tabpath and put is value to $namefile
  $path=implode('/', $tabpath);

  $total= $scheme . '://' . $style_name . '/' . $path . '/' . $namefile;
  return $total;
}

The new variable $total allows to rewrite the address of the image by keeping the name of the style first so that the drupal core recognizes it. This is the final address. I did not want it to be like /styles/your-name-style/path but directly /your-name-style/path. As a result, this requires the previous changes in the derivatives creation url so that the style name is in the same location.

Save the files and create the new images for each style:
Empty the Drupal cache with command : drush cc all

And flush the old file to create the news :

Execute this dursh function and when it ask choose all :  drush image-flush

I hope it help someone !


views exposed filter select list users with specific role

You need some custom code in order to do something like this.

You can put #access on any form element, and along with hook_form_alter you are able to alter the views exposed form and require a permission that the two roles have, making it so that only users with those roles can see and use the exposed filter.

The same technique can be used for the 2nd field you want alter.

In code this could look something like this:

module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['exposed_filter_1']['#access'] = user_permission('special permission role 1 and 2 have');
  }
}

This is example code. You need to find out the form id, and maybe do other checks. Also You need to do a SQL query to figure out if the user has created a node of that type.


View: show title of field where user is entity-referenced

So you can print the user reference fields, but that will show all users and their roles, and you only want to show the one?

This might seem a little hacky, but it should work.

First of all, add all three user reference fields, and add them to the same table cell using the views table settings.
Next, you need to hide the user reference fields that do not contain the current logged in users name. To do this, we will be overriding the fields with a tpl.php template. In your view, click on "advanced" and at the bottom, click on "theme: information". In the relevant row, you will find something like views-view-field--course--professor.tpl.php. Note that this is overriding the field, and has the view name type in it (which will not override any other views with the same field).
In your FTP, go to the views module folder. Click on the "theme" folder, and find the file views-view-field.tpl.php. Copy this file to your themes template folder, and rename it views-view-field--course--professor.tpl.php, or whatever your field name was in step 2. Then flush your cache. This should now be overriding that field in the view. (To make sure, you could edit that file, and add some text below the <?php print $output; ?> to see if it worked.)
Now that we are overriding the field, we can influence what will be shown in that field. I would replace <?php print $output; ?> with the following....

<?php
global $user;
$username = $user->name;

if (strpos($output, $username) !== false) {
  print $output;
}
?>

I haven't tested the above, but something similar to that should print the fields output, only if the current logged in users username matches the output.


How do I delete files attached with media entity?

You have to delete old versions of entities (articles etc.) where you used the files for the files to get the "used in 0 places" under /admin/content/files. After that status should be changed to temporary with option make_unused_managed_files_temporary set to true.


Creating SearchAPI searches without using Views

Realized I never added a follow up. Search API Page does not solve all the cases, and this is possible in Drupal 8 as well.

A query string was added on form submission, redirecting to my url + query string args. These prefill form values (sanitized of course) and modify the initial Search API query. Extra work was done to store some data in session, so that the query could be repeated on detail pages for sidebar results (prev/next navigation in the same result set).

Using the normal Drupal pager worked fine as well.

As part of this work, a module was born: https://www.drupal.org/project/search_api_view_modes

Here is an example of doing it in Drupal 8: https://gist.github.com/kevinquillen/cad07541347385744b161a26690ab75d

Taking this route allows you to create and provide a very tailored, controlled experience.


Create view with path relative to taxonomy term

The way to influence filtering Views through URL arguments is to use Contextual filters. For each URL sensitive Contextual filter you get one argument in your URL (separated by /).

In your case you need to add a new Contextual Filter of type Content: Content type and configure it:
    When the filter value is NOT in the URL
    Provide default value
    Raw value from URL
    Path component: 4
    When the filter value IS in the URL or a default is provided
    Specify validation criteria
    Content type
    Single ID
    Case in path: Lowercase
    More
    Transform spaces to dashes in URL

Change the Path of your Page from taxonomy/term/% to taxonomy/term/%/%.

Now when you visit taxonomy/term/1/article it will list all articles tagged with the term 1 (I'm assuming you have cloned the default Taxonomy term Views).

Show term names instead of TID in URL

It is possible to pass term names to Views from URL, instead of using term ID numbers. So the URL might look something like: taxonomy/term/tag1/article

To achieve that we have to introduce the term name into Views. In this example we cloned the default  Taxonomy term Views, and they only have term ID available.

To introduce more information about the taxonomy term we add a new Relationship. In this case we add Taxonomy term referenced from field_myvocabulary (use your Entity reference field referencing the term from the relavant vocabulary).

There are no consequences of this step visible from the outside, but from the inside we have more choices to choose from when adding new Contextual Filters. One of those new choices is Name from Taxonomy term Category. Add that as a new Contextual Filter and configure it:
    Relationship: field_myvocabulary: Taxonomy term
    Provide default value
    Raw value from URL
    Path component: 2
    When the filter value IS in the URL or a default is provided
    Specify validation criteria
    Taxonomy term name
    Vocabulary: My Vocabulary
    Transform dashes in URL to spaces in term name filter values
    More
    Transform spaces to dashes in URL

Rearrange the Contextual filters to have that Name filter first, then the Content type second and you can ignore or remove the original "Has taxonomy term ID" in third place.

Now you can enter tag1/article into the Preview and you'll see the results, all with using human-friendly URL bits. or visit /hub/tag1/article on your site.

Relationships can introduce duplicate results. If this happens make sure your filters have turned on "Reduce duplicates" option, although you'll probably have to edit your Views Query settings and set them Distinct.

Be careful about the Case settings and converting spaces to dashes and vice versa. Your term name might be "Best term", and depending on your Contextual filters settings you might need to enter "best term" or "Best-term" etc.

The default Taxonomy term Views renders Taxonomy term in Views Header area. I haven't been able to make it work with the Taxonomy name though. It does work if you keep the ID as the third filter and use path tag1/article/1.

But you can solve it (if you need this feature of rendered Taxonomy term in Views Header) with the help of an additional module: Views taxonomy term name into ID and the patch mentioned there.

You can also use this module to get term name in URL, instead of using a Relationship like explained above ;)


How to prevent users (except for admin / editors) from viewing canonical page for content type?

In Drupal 7, I believe you could do this with Rules. The Rules module is technically available for Drupal 8, but I couldn't figure out how to use it, so I'll show you how to wire up a custom module that redirects manually based on whatever your criteria is.

The basic idea is, in order to do custom redirects, you have to register an EventSubscriber service, subscribe to REQUEST KernelEvent, and then you have access to the entire request object.

In my company's case, I wrote a custom module called "redirect", so that's what this example will use.

First, create a redirect.services.yml file.

services:
  redirect.subscriber:
    class: Drupal\redirect\EventSubscriber\RedirectSubscriber
    tags:
      - { name: event_subscriber}

Then, create the class referenced above (Drupal\redirect\EventSubscriber\RedirectSubscriber) in src/EventSubscriber/RedirectSubscriber.php.

<?php

namespace Drupal\redirect\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\node\Entity\Node;

class RedirectSubscriber implements EventSubscriberInterface {

  public function redirect(GetResponseEvent $event) {
    $request = $event->getRequest();
    $baseUrl = $request->getBaseUrl();
    $attr = $request->attributes;
    $roles = \Drupal::currentUser()->getRoles();

    if ($attr !== null) {
      $node = $attr->get('node');
      if ($node !== null && $node instanceof Node) {
        $type = $node->get('type')->getString();
        if ($type == 'seel_lesson_plan' && !in_array('administrator', $roles)) {
          $event->setResponse(
            new RedirectResponse("$baseUrl/url-to-404-page")
          );
        }
      }
    }
  }

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

}

To get a better idea of how this works, read an explanation of registering event subscribers, the official Events API page, and this other Drupal SE question about redirecting content pages.


How can I use Twig Tweak to show a token in a Webform template in Drupal 8

Currently, it looks like the Twig Tweak module's drupal_token Twig function does not support passing in the $data argument, which would contain the webform entity.

You might want to create an issue in the Twig Tweak module's issue queue.


If used from inside the Drupal 6 Block UI Admin Page use php area:

$whereami=menu_get_object();
if (isset($whereami->type) && $whereami->type=='TYPEYOUARELOOKINGFOR') {
  return TRUE;
} else {
  return FALSE;
}


Is there any way to set a node to be shown in 2 menus?

Use the Multiple Node Menu module

  This module modifies the "Menu settings" in standard node editing form
  to allow managing multiple menu links to a node.


Complex view based off of Node Reference

First add the node reference field as a relationship. That will enable the node reference field to be added as a contextual filter.

You can use EVA module to attach the view to your node page, which will automatically pass the node ID to the view (which your contextual filter should pick up and show only images referencing that node).

You can checkout Is there a good tutorial for "Entity Views Attach Module"? for more info on EVA


Sounds like you just want a taxonomy term view. Then output the name field and and use the Rewrite Results, "Output this field as a link". You'll want to make the links for the other view predictable by using arguments like TID. Then you can set your link to use tokens like seminar/tid. I think you can use term name as well with a little bit of magic on the contextual filter.

If you just want to display all categories and seminars on the same page, create a view that outputs seminars and add the taxonomy term field. Then group by the term.


How can I filter sensitive data being recorded in calls to Watchdog

Assuming you're dealing with the dblog module, this is a workable solution:

Disable the dblog module
Copy dblog_watchdog into your own module's hook_watchdog implementation
Wrap each of the appropriate database field entries with your function to sanitise the string, e.g.

Database::getConnection('default', 'default')->insert('watchdog')
  ->fields(array(
    'uid' => $log_entry['uid'],
    'type' => mymodule_sanitise(drupal_substr($log_entry['type'], 0, 64)),
...

If you have other watchdog modules in use, you'll need a copy/edited hook_watchdog version for each of them too.


Access denied to all users after migrating site to new server

I finally figured it out!

We are enforcing secure flag on our cookie and therefore had to disable the corresponding rewrite rule from IIS, as we didn't have a SSL certificate in new server.


What is needed to keep parent menu element active while browsing subpages (Bartik Theme)

There are differences in how to handle navigation levels between Drupal 7 and 8.

It's customary in both versions to create one menu even when you have "sub-items", you just indent the sub-items so they "belong" to another item as a "child-parent" relationship (use the Edit > Parent Link and Show row weights if you're not using drag and drop (javascript) in your interface).

Use Menu settings in Drupal 7

In Drupal 7 you have Menu settings where you can choose which Menu to use as Main links and which to use as Secondary links. In the case where you created one menu for both you select the same Menu for both options:

Use Block Menu levels in Drupal 8

In Drupal 8 there are no Menu settings for navigation levels. Instead, you configure the Blocks for your Menu with the Menu levels options:

Initial visibility level
Number of levels to display

Add the same Menu Block twice, but configure the levels differently.

For the first level of navigation those Block Menu level numbers should be:

1
1

and for the Secondary level that only shows up when the "parent" is active they should be:

2
2

You can read a bit more in this article: Primary and Secondary Navigation in Drupal 8


When passing a variable from a render array to JavaScript how do you reach that variable in your Javascript

When you need to use a variable in the JavaScript you have set from the backend and added to the drupalSettings, you can access that variable using the drupalSettings object like tried in the example code from the question but then without adding drupalSettings to the js function, like so:
(function($, Drupal, drupalSettings) {
  Drupal.behaviors.portalCore = {
    ...
    console.log(druaplSettings.someVar); // "Hello World"
  }
}(jQuery, Drupal, drupalSettings));


Value of plid is the menu link id of the item you want your new item to be a child of (=parent id).

To create your link, simply use something like:

$item = array(
  'link_path' => 'node/' . $node->nid,
  'link_title' => $node->title,
  'plid' => 426,
);
menu_link_save($item);


Can I run the 'Toolbar' and 'Admin Menu' at the same time for different roles?

I recommend you to disable Toolbar module and use Administration Menu Source with Administration menu and enable Admin Menu Toolbar which will give you the same look as Drupal Toolbar.

Administration Menu Source:

  Use a different menu as the Administration Menu. Configurable per role.

Custom Solution:

Create a custom module add the following hook_page_alter function:

function mymodule_page_alter(&$page) {
  global $user;

  if(!in_array('editor', array_values(array_map('strtolower', $user->roles))) &&
     !empty($page['page_top']['toolbar'])) {
    $page['page_top']['toolbar']['#access'] = FALSE;
  }
}

The above code will check the role of current user and will hide toolbar if current user is not editor.

Note: make sure to replace editor to whatever editor role you named.


You are altering user_profile_form. By doing this

$form['actions']['profile'] = array(
      '#type' => 'submit',
      '#submit' => array('MY_MODULE_redirect_submit'),
      '#value' => t('Save and go to Profile'));

you have dissconnected default submit handler which save the data.

// Add the final user profile form submit handler.
  $form['#submit'][] = 'user_profile_form_submit';

So you need to append your submit handler with default submit handler


First of all, you have way too many questions in here. I recommend breaking this problem up into smaller chunks and trying to solve them each, rather than dumping this whole novel into stack exchange for someone to solve all your problems for you.

Maybe that sounds harsh, but there's a reason you don't have any replies yet.

I can point you toward the Drupal's once function, which will help you address at least your onLoad conundrum. (Hint: you should not be using onLoad, ever.)

In general if you're building a site in Drupal, and you can't find a module to do what you want, and you find yourself writing a lot of PHP or javascript or custom what-have-you, you might want to consider a new approach.

There are lots of front-end frameworks that probably offer libraries to accomplish the behavior you're trying to achieve. Try finding one that comes close to solving your problem, performs well under load, and then adapt it for your use.


If the Contact module doesn't suit your needs (comes with Drupal core and can be enabled on the Modules page), then your best option is to use the Webform module.


Is there a way sort View by results of "Options" Rate/Voting API widget?

You have to add a relationship Content: Vote Results with proper data filters

Value-type: Points
Vote-tag: Your rate widget vote tag
Aggregation-function: Number of vote

Then in views sort criteria add

(Vote results) Vote results: Value (desc/asc)


Basically, the EVA module is getting called with a bundle 'advertising_block' that it doesn't know how to handle. If you used to have a block named 'advertising_block', that would be a suspect.

The way to solve this is to (with devel installed) use the approach in webchick's Quick and Dirty Debugging. Right before line 41 of/.../sites/all/modules/eva/eva_plugin_display_entity.inc, make a temporary hack.

First, install and enable the devel module.

The code there is:

  foreach ($this->get_option('bundles') as $bundle) {
    $bundle_names[] = $entity_info['bundles'][$bundle]['label'];
  }

so we'll change it to

  foreach ($this->get_option('bundles') as $bundle) {
    if ($bundle == 'advertising_block') {
        dpm(debug_backtrace(), 'Bundle advertising_block being requested');
    }
    $bundle_names[] = $entity_info['bundles'][$bundle]['label'];
  }

Now when we hit that page, we'll see the backtrace (who called this thing, maybe why), and will have a path forward.

When you're through with this debugging code, don't forget to revert to the original code and disable devel module.

And remember that debugging like this should be done on a local dev site, not on production. Some more strategies are at randyfay.com/debugging