Some basic questions about creating a webform handler from the module webform_example_handler

Could someone please tell me what key thing(s) I need to do to make
  that connection

There are 4 ways that you can tell Drupal that your plugin exists.

You can read about the other 3 at D8 Plugin discovery

In this case Webform uses:

  AnnotatedClassDiscovery

  The AnnotatedClassDiscovery class uses name of the annotations that
  contains the plugin definition, e.g., @Plugin, @EntityType, in plugin
  docblocks to discover plugins, minimizing memory usage during the
  discovery phase. The AnnotatedClassDiscovery class takes an argument
  in its constructor, $subdir, which specifies the
  sub-directory/sub-namespace for this plugin type. The
  AnnotatedClassDiscovery class scans PSR-4 classes inside those
  sub-directories of Plugin folders to find plugins (see a
  "Annotations-based plugins").

Side Note: Entities and blocks also use this "annotation" method.

This "annotation" is seen in webform_example_handler/src/Plugin/WebformHandler/ExampleWebformHandler.php

Yes, this info is inside a comment block, weird, but that's just how it works.

  In webform_example_handler.schema.yml the first line is:
  webform.handler.example. Is this a standard Drupal construct of
  <webform>.<handler>.<my_module>, or something specific that must be
  followed set by the webform module or am I completely off base on how
  this is derived?

Wrong, otherwise it would've been named webform.handler.webform_example_handler.

It's actually webform.handler.<WebformHandler_id> (The ID you use in the annotation).

This is because your module can have multiple plugins, so it makes no sense to use the module's name here.

The webform.webform.webform_example_handler.yml file: could someone explain the parts? In my module would it be: webform.webform.dis_doc_gen.yml ?

Assuming your module is named dis_doc_gen, correct.

  Last: I have built my webform through the interface so I assume that I
  don't need the file webform.webform.webform_example_handler.yml as
  that would only be for creating a webform from a yml file upon
  installing the module as far as I can tell

Correct, anything inside the /install folder, runs on install and that file is creating a form. Since you created one via the UI, you don't need this in your use case.


Ubercart Recurring Payments and Subscriptions:Charge automatically?

You can use this module.

UC Recurring Payments and Subscriptions

Features:

New/improved API for payment gateways to interface with uc_recurring - see hook_recurring_info().
Ability to treat a recurring fee as a new order - so it gets access to everything a new order gets at the time of renewal e.g separate invoices, apply roles etc...
Option for unlimited renewals (ie: renew until canceled).
Option for recurring payments to be set that same as product price (this means that the recurring payments can be based on adjustments of a products from things like attributes).
Conditional action support - sending emails on failed renewals.
Extension API - administrators can configure what will happen on a failed payments, e.g order can be extended and re-attempts as many times as required.

Take a look at discussions here

PayPal community

x.com

Please note module is not stable yet


How to make #states work when dependant element is modified with JS .click()

Drupal states are bound to the change event, therefore you need to trigger that one too. The following snipped should do what you want:

$('#id-of-radio-button').trigger('click').trigger('change');


How can I add HTML ASCII codes into menu link items?

Yes. Menu HTML.

  This very simple module adds a checkbox to the menu item edit form and allows the admin to add html to the menu item title. The idea is to use this for external links for which you want to display a logo of the visited site or simply to add strong on some words.


You can override the menu wrapper in this manner:

function YOURTHEME_menu_tree__MENU_NAME($variables) {
  return '<nav class="menu'.$variables['delta'].'">' . $variables['tree'] . '</nav>';
}


Constraint handling for @DataType (Typed Data API)

In abstract class PrimitiveBase that uses PrimitiveInterface... which StringData entends you can see the PrimitiveInterface use of PrimitiveInterface methods:

getValue(); , setValue($value);, getCastedValue();

so you can safely do ether however ... Personally as your data is realy a string  I would go with the extend StringData option

and call
parent functions like

 public function getValue() {
   return parent::getValue();
   or
   $this->parent->getValue();
 }

 public function setValue($value) {
    // CRAZY REGX HERE
   $new_value = $this->getREGXCRAXY($value);

   return $this->parent->setValue($new_value);
 }

 public function  getREGXCRAXY($value) {
    do the things.
  if value !== valid
 throw new \Exception('Invalid data dude must be in format xyz');
  return $new_formated_value;
 }

no i think it is proper to throw the exception because then the person can catch it in an event subscriber .. or learn the right way to set the data.


Using twig, how to show a message on the frontend if a field is empty?

The fact that you are in the field template is proof for a non-empty field. So you need code outside of the field template to show a message. This can be PHP like the module you've linked or TWIG in a different template.
For example:
node.html.twig
{% if node.field_example.isempty %}

Field is empty

{% endif %}


Display root terms based on child in a view

Try this:

You can use relationship, and add "Taxonomy term: Parent term" field relation in it. Now make relationship with city field. It will give root term name based on child term name.

I have recently done this, it works.

Hope it will works for you.


The actual class has to be included in the use statement.

use Drupal\book\Plugin\Block\BookNavigationBlock;


there is a module for that node view count, from module page:

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

This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.


In D7 default theme bartik, you can see the main menu is rendered using a theme hook links__system_main_menu:

    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>

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

Drupal will use MYTHEME_links__system_main_menu(), if you define it in your theme.
Thus, you could implement the hook_links__system_main_menu as follows. Probably you will do that in the template.php file in your theme folder.:

function mytheme_links__system_main_menu($variables) {
  $html = "
\n";
  $html .= "
\n";
  foreach ($variables['links'] as $key => $link) {
    $html .= "
".l($link['title'], $link['path'], $link)."
";
  }
  $html .= "
\n";
  $html .= "
\n";

  return $html;
}

This will override the links__system_main_menu theme and customize HTML output for the main menu.

[Edit]

If you are looking for the quickest way, you just need to tweak your page.tpl.php by adding an extra wrapper to the menu ul.
For example, in the Bartik theme,

    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>

Then, you can access it using #your-id ul{ } in CSS or $('#your-id ul') in JS.
But, the above code is just for example, you should not hack the core themes or modules.
I assume you have your own theme.


Add a button that when clicked adds the user to the entity reference field

You can create a custom module dealing with the subscriptions. Implement hook_menu(), and create a callback url that gets the NID (I suppose your content type is derived from the node entity, but it would work for custom entities as well) as parameter, e.g. 'node/%node/subscribe'.

Within the callback function you check whether the current user has already subscribed for this job and create the reference programmatically if not.

In your view make sure to read the NID property. You may hide it from display. Then you can easily add another field, and rewrite its output as link using the [nid] token from the previously hidden NID, in the above example, the URI would be 'node/[nid]/subscribe'.

Last not least you can CSS style your link to look like a button.


The empty anchor target might be the problem. The browser may be having a "problem" fixating the empty (non-visual) target as the page loads.

Ideally, you would attach the id to something. eg. an Hn tag.

The name attribute on the anchor is deprecated in HTML5 if that is of concern. Reference: https://www.w3.org/TR/2008/WD-html5-diff-20080610/#absent-attributes


Where to put #Ajax Callback in webform twig file

You can create a form alter function in your module file and then add the callback property to the respective field

$form['actions']['submit']['#ajax'] = [
  'callback' => 'callback',
  'event' => 'click',
];

See also

Alter Ajax callback on Webforms
How do I add an AJAX action on a select element in a ContentEntityForm to change the value of another select element
Update webform field value using AJAX realtime


The webform_civicrm module does this (actually it disables it rather than hiding it)

You can see the relevant code here (note this function runs in the context of hook_form_alter).

You could hide it by doing something similar but setting $form['form_key']['#type'] = 'hidden';


How to manage contrib modules composer dependencies on drupal 8

At the moment this is not possible, and it does not look like this will make it into Drupal 8, as Drupal is in code freeze.

Instead, try to manage your dependencies using your module's *.info.yml file (this is for depending on other modules) or using http://drupal.org/project/libraries, which is for third party libraries.

To elaborate on why using Composer for Drupal 8 contributed modules is not a good idea right now:

You cannot expect site builders to know composer and do a "composer install" after having downloaded Drupal to their computer, as Drupal is not just for people who are familiar with the command line.
Because of that, you would have to do the composer install yourself and commit all code to your repository. While this is legally possible for any third party code that complies with the GPLv2, this makes maintenance harder, and if someone downloads two modules that both use the same library through Composer, they'll end up with duplicate code. This in turn makes class loading and debugging a whole lot less fun.


Can I install Drupal Commerce as a site in a multi-site architecture, preferably using Commerce Kickstart?

After much research, I've found out the following:

Can Commerce Kickstart be added to a multi-site installation?

The answer is No.

As Clive pointed out, CK ships with patches to Drupal core, so it's definitely not unmodified.  Additionally, CK will break if one tries to migrate an already existing, stand alone installation to be one of the sites in an existing multi site setup. CK depends on the installation profile to be present to continue to function correctly. Finally, Bojanz, a contributor to the project, points out, CK is a distribution and has to stand alone.

Can Drupal Commerce be added to a multi site installation?

The answer is Yes.

In that same answer above, Bojanz also points out that Drupal Commerce can be added to a multi site architecture. The caveat is that it has to be built out a la cart with modules as needed that make up the Commerce Kickstart distribution.


Webform calculator (I need to delay the result)

Well, this is how I managed to delay the calculation results in
webform_calculator.js
line 12, 13, 14

setTimeout(function(){
  Drupal.webformCalculator.evaluateAllFormulas();
}, 3000);


How to pass default values on node form through form_alter when using confirm_form?

This is my dirty solution of the problem, I use $form_state['complte form'] instead $form:

$refill_fields = array(
  'form_build_id',
  'form_id',
  'form_token',
  '#id',
  '#token',
  '#build_id',
);
foreach ($refill_fields as $refill_field) {
  $form_state['complete form'][$refill_field] = $form[$refill_field];
}


Programmatically translate taxonomy terms

Basing on Using the i18n API from other modules, the code should be the following one.

$term = taxonomy_term_load($tid);
$translated = i18n_string_translate("taxonomy:term:$tid:name", $term->name);


Is a block changed programmaticaly with hook_block_view_alter cached?

hook_block_view_alter() isn't going to affect the cache settings for the block automatically, though you can find a way if you really want to as Molot points out below; typically you use hook_block_info_alter() to change the cache settings for a block:

function mymodule_block_info_alter(&$blocks, $theme, $code_blocks) {
  $blocks['block']['my_block_id']['cache'] = DRUPAL_CACHE_PER_PAGE;
}

Here, DRUPAL_CACHE_PER_PAGE will cache your block for each page, which could be quite a bit better than not caching at all and creating the content dynamically for each page. If you need dynamic content every time, choose DRUPAL_NO_CACHE. Clear the block cache to make Drupal aware of your new settings.

But! If you are prepared to have a custom module to run alter hooks, consider writing a block from scratch. If you are going to have a custom block, I feel that it helps if it is impossible to accidentally delete in the Drupal UI.

To implement a basic block you need hook_block_info and hook_block_view.

hook_block_info is where you tell Drupal that the block exists and how to cache it:

function mymodule_block_info() {
  $blocks['myblock'] = array(
    'info' => t('My Awesome Block'),
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  return $blocks;
}

Next, hook_block_view does the work of generating the content. I find that assigning the content to a callback makes my code easier to read, but do what works for you. Using switch() makes it easy to add more blocks to your module later on.

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

  switch ($delta) {

    case 'myblock':
      $block['subject'] = t('My awesome block');
      $block['content'] = mymodule_some_function_to_build_the_block_content();
      break;

  }

  return $block;
}


You're in the correct place (html.tpl.php) to modify the doctype assuming you're using Drupal 7, thats the default theme implementation for altering the basic page structure (documentation). In Drupal 6, you're looking for the page.tpl.php file.


You should use the template_preprocess_node() function. Add this to your template.php in your theme and do whatever you have to do.


Rules condition to check if user is a member of a specific group type?

The is a rule action "Rules has role" this should do it.


all modules that use the field api module

You can find all the info to format fields in the field API

If you want to know how core modules implements the Field Api, you have to enter in every hook info page and there you will find the modules that implement this concrete hook. You can also follow the links to see the code.
Here an example of hook_field_delete and the location on web page:

On the other hand, if you want to know what contributed modules have implemeted the field API, you will have to look in the contributed modules page and make a filtered search with core = 7.0 and module categories = Fields.


You can use the Rules module.

  Example use cases

  Build flexible content publishing workflows changes Send customized
  mails to notify your users about important Create custom redirections,
  system messages, breadcrumbs, ... And many more...

To use that go to admin/config/workflow/rules/reaction/import and import this
it will redirect user to admin/dashboard path after user logged in :

{ "rules_redirect_after_login" : {
    "LABEL" : "redirect after login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [ { "redirect" : { "url" : "admin\/dashboard" } } ]
  }
}

You may also build a custom module and use  hook_user_login and do something on the lines of :

function hook_user_login(&$edit, $account) {
     $_GET['destination'] = 'node/25';
 }


How to set one variable for each link on a views un-formatted list

I accidentally left the quotes in when entering the variable path so it didn't work. I was entering:

<?php print l(' a', "$view->style_plugin->row_tokens[$id]['[path]']", array ('html' => TRUE)); ?>

And the I should've been putting in:

<?php print l(' a', $view->style_plugin->row_tokens[$id]['[path]'], array ('html' => TRUE)); ?>

When you're calling a value in an array, it won't work if you put the path in quotes.


Adding javascript to drupal 7 is giving error

I would try to pass the $ alias to your mobilizeCustomInit() function.

Either way, the easiest way to solve your problem would be to just use "jQuery" directly in your code instead of the $ alias if its still giving you problems!


Missing edit tabs on only one content type

If you have a dsm($tabs) at the top of your page.tpl.php and it's showing it's set, nothing should be unsetting it by the time it is output later on in the template.

For example, in the default D6 page.tpl.php, it does this...

<?php if (!empty($tabs)): ?>
<?php print $tabs; ?>
<?php endif; ?>

and in D7 it does this...

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

...so, I'd take a look at the page source and see if css or something else is causing it to be hidden. For example, perhaps your theme is doing stuff like cascading a class in the body with the tabs class.


How to programmatically set the color scheme for a theme?

No - this is not possible in 6.x due to how color is intended to work. Its meant to be a simple way to change a very basic theme, not for advanced users. In 6.x, when you change your color settings, it is doing the following:

Replaces hexidecimal colour values in CSS files
Creates sliced images with the new colours for use as CSS background images
Copies unchanged images without alterations

This creates a dump of 'color files' that looks like this in your files directory (for the Garland theme)

bg-bar-white.png
bg-bar.png
bg-content-left.png
bg-content-right.png
...
style.css

It also creates a random number for the folder each time, so the folder is getting deleted and recreated each time you save the changes.

All of this is to make it easier for novice users to change their colors, with I assume the understanding that if users could configure their own CSS and theme in code, they wouldn't be using the color module to begin with. This approach is also confirmed here on D.O by Jeff Burnz

  Currently there is no way in Drupal core to export your custom color
  scheme to file, i.e. no way to capture the configuration

Conversely, there is no way to import an existing dump of colors files into your site.


Which backup system is good for my local project?

First of all, let me just state the obvious: the solution that I'm about to propose is not going to bring your files back; it is a measure that you'll have to take from now on in order to prevent similar disasters in the future.

Basically, since you are working in your local machine (if you were working in the cloud you could automate a snapshot-taking process) you will have to keep a backup of 2 different things: the files and the database. Assuming that you are following the "drupal best practices code" and you are keeping every new file in the sites folder of your drupal installation, all you have to do is keep a regular backup of this folder and the database. So:

1) Regarding the "sites" folder: you can create a simple cron job that will compress and archive the folder regularly (even though it is out of the scope of this answer, you can find more information on crontab here)

2) Regarding the database: the solution here is actually pretty simple: "Backup and Migrate" module. It gives you the option to schedule your database backup and save the file through FTP in a remote server, send it through email or save it in your local machine. It's basically more than you'll ever need for this purpose.

P.S: I'm pretty sure that you will get some answers that you should be running a version control system to avoid things like that in the future. It's true that a version control system would be the ideal way to make sure that your files will not be lost in the future (the database is another story). However, the solution that I mentioned above is considerably faster and can get you up and running in no time. If you have time though, I would strongly suggest that you take a look at SVN or GIT (or any subversion control system that you like for that matter).

P.P.S: If the data that you lost is important, you can do a google search for data recovery software. A very quick search that I did gave me this.


I think the advice from Choosing a Drupal version is probably the best to follow:

  At any given time, there are two major release series of Drupal which are supported. Currently, these are Drupal 6 and Drupal 7.

Essentially, official support for Drupal 6 will stop when Drupal 8 is officially released.

You can find further discussion on the So long, Drupal 5.x (End of Life Announcement)


While the page.highlighted variable contains the block data (mytheme_messages) for message display, the block rendering data doesn't contain the messages themselves, so there's no way to check for message existance there.

However, you can inject a custom variable based on the current message queue from drupal_get_messages().

For example, in your MYTHEME.theme:

/**
 * Implements hook_preprocess_page() for page.html.twig.
 */
function MYTHEME_preprocess_page(array &$variables) {
  // Inject a flag based on the current message queue.
  $variables['available_messages'] = !empty(drupal_get_messages(NULL, FALSE));
}

And within your page.html.twig:

{% if available_messages == true %}
   <!-- TODO: Add custom markup when there are messages -->
{% endif %}


Remove default configuration on uninstalling module

I know that we can set all the configuration to have the module as dependency, but that is tedious to do; is there a better way to let Drupal uninstall all the configuration on the module in the config/install folder?

Not really. Deleting the configuration is just as tedious, as you need to know what's yours. you could solve it using a naming pattern and list all node types, fields, views, .. starting with yourmodule_ I guess.

There's been some discussion to automatically add the module providing the configuration as an enforced dependency, but that's actually also not always what you want.


How to change the existing images embedded in Views Twig template to S3 bucket URL

Try adding

$settings['s3fs.use_s3_for_public'] = TRUE;

After that clear cache, now your site images will render form Amazon S3 bucket.


Register the user from the login form itself

I had a similar use case in the past and i am giving some snippet, hope will help you. The key was user_login_finalize and then redirecting internally to the same page.

Load the user if already present or create and then load him

$user = user_load_by_name_and_password($username, $password);
if ($user == FALSE) {
  $newuser = array(
    'name' => $username,
    'pass' => $password, // some password
    'mail' => $email, // some email
    'status' => 1,
    'init' => $email, // some email id
    'roles' => $roles, // some roles
  );
  // New user is saved and loaded
  $user = user_save(drupal_anonymous_user(), $newuser);
}
user_login_finalize();
drupal_goto(get_current_url_with_query_params());

http://api.drupal.org/api/drupal/modules!user!user.module/function/user_login_finalize/7
Finalize the login process. Must be called when logging in a user

drupal_goto must be called as user_login_finalize() bootstraps the currently logged in user too late and hence will throw 'access denied' even for the page for which the user has permission. drupal_goto() makes sure that the user is properly bootstrapped and then is made to access the page again.

It is equivalent to reloading the page after the user has logged in but this is the only way i got my external login work. Refer User login using a token or ID (no password)


I can't see any potential issue with using Keep-Alive unless it is not properly configured. e.g

KeepAliveTimeout value is not ideal. For example, if the site is high traffic the value should be higher to make sure there is no frequent tcp connection re-initiated.
MaxKeepAliveRequests should be tweak according to number of assets the server is serving.

It is recommended to use this feature to:

Reduce latency
Reduce the use of server resources such as CPU and memory

For HTTPS you might want to check SPDY.

  SPDY is a protocol developed by Google to increase the speed and
  efficiency of delivering web content. SPDY modifies parts of the
  HyperText Transfer Protocol (HTTP) to improve web performance.


Show calculated value at the bottom of every node for a specific content type

Computed Field module will do for you.

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

if you need this through views, you can check this link there are answers which might help you.

also this module will help you,

Views Custom Field

  Now that the Views module has incorporated the rownumber and markup
  fields, only the PHP field is left for this module. I started a new
  project called Views PHP. It also includes support for PHP filters and
  sorts.


You can define a theme function that uses a template file, and then use theme function to for the menu callback output.
The following is example code for Drupal 7; similar code can be used for Drupal 6.

function mymodule_theme() {
  return array(
    'mymodule_oath' => array(
      'variables' => array('id' => NULL), // This is the list of the variables that will be passed to the template file.
      'template' => 'mymodule_oath', // Change this to the template file name.
    ),
  );
}

function mymodule_oath() {
  // Does some stuff, authenticates the user, etc.

  print theme('mymodule_oath', array('id' => 10));
  return NULL;
}


Add the field to the content type; check your node/page template, and add some code to print the new image field. If there is no custom template for your content type, create one and customize the output to your wishes.
You might also check the display settings for the content type, and make sure your image is displayed.


How to get notifications in a new window when using the Mentions module?

You could also use the Message module for this. So that you expand the rule you already have (or clone it in a variation of it) to have the Rules module create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages that got created in the format you need (page, block, etc).

Here is a blueprint of what you'd need:

Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to Nodes. I'd imagine that the message text you'll  want to use is similar to the eMail or messages your existing rule already produces.
Enhance your rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in Which user related token(s) can be used to create a Rule for setting up a message type? for some examples, which are related to these variations of using Mentions:

A user gets flagged (using Flag).
A user is mentioned (using Statuses (Social Microblog)).

Make sure to also add a Rules Action to pass any relevant tokens from Statuses, via Rules, as Replacement tokens that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
Use Views to display the created messages in the format you prefer.


Where do I find the "Security code" to test "Commerce PayPal WPP Credit Card" with my "sandbox buyer account"

Just put in any number that matches the card type - e.g. 111 or Visa / Mastercard / Discover or 1111 for American Express. As far as I know, the PayPal API will accept any value. It should just be the card number and expiration date that have to match your sandbox test card details.


You have to firstly install imagemagick in your operating system.
for Ubuntu please follow below procedure:-

(1)https://medium.com/@sanjaywrites/install-latest-version-of-imagemagick-in-ubuntu-16-04-c406ddea1973

(2) https://www.enovate.co.uk/blog/2015/12/16/how-to-install-imagemagick-from-source-on-ubuntu-14.04

For window download imagemagic exe file.
https://imagemagick.org/script/download.php

once your Operating System have magicmagick  then install these module pdfpreview https://www.drupal.org/project/pdfpreview

and do a needful change as shown in image

and on your view  do a needful change as shown in image


setContainer Error When Registering an EventSubscriber Service

The problem is the logging line in getSubscribedEvents:

\Drupal::logger('debug')->debug('get sub events');

Drupal::logger queries the container for a service, but the container hasn't been set at the point the event subscriber discovery happens.

By the time the event handler is invoked, the container has been initialised, so the logging in checkForRedirection should work fine.


In Views field settings add &nbsp; to No results behavior. Your View  will then display a space and a field label if the field is empty.

If you're using Unformatted list format for your View block, then in Format -> Fields -> Settings make sure that Hide empty fields checkbox is unchecked. See screenshots below.


Drupal -> User error: Failed to connect to memcache server

You need to check how mem cached was run on your hosts. You can check this like so:

ps -Af | grep memcached

Check if it has -l 127.0.0.1 in arguments. If it is the case then just restart memcached with correct IP address instead of 127.0.0.1.


How do I get hex value for field categoryhex on creating category?

That hexadecimal value of the color. You can get the hex value of the color from here - http://www.w3schools.com/html/html_colornames.asp
http://www.color-hex.com/color-names.html


Is it possible to display Entityform Types using Page Manager and Panels in D7?

What we have done so far, is to reference an Entity-Form in an node type with entityreference.
This works so far.
The Form will be displayed in the panelized theme and the preview will show up too in the correct context.
But!

The Preview will not show the labels of empty fields
The submission Page will not show in the correct layout and is still loosing context (even with pm-existing-pages)
List fields are broken, if core Patch https://www.drupal.org/node/1677598 is applied they don't break the form submit, but are empty in the preview and not saved.
Date fields with time are somehow broken too. Time is not safed, Date only when using the PopUp Calender

We decided to use the redirect option instead of the submission page to workaround the layout problem with the submission.
The Preview is still broken and we are trying to get it fixed.

Conclusion: Entityforms and Panels do not play well together. If we would have know this before we would have built a custom module or used Webform 4.x instead (we are still using webform 3.x in this site but there you don't have the option to use views to manipulate submitted data without loading another bunch of buggy modules!)

Hopfully Drupal 8 and YAML-Forms do a better Job in the future.


displaying content using entityfieldquery

I think this is the right way because it works for me. Error was in below line.

$query->fieldCondition('field_product_sub_cat', 'tid', $all_children[$i],'=');

Correct way to compare with array is:

 $query->fieldCondition('field_product_sub_cat', 'tid', array("$your_array_variable"));


Edit settings.php and add:

$conf = array(
  'clean_url' => 0,
);

Use drush:

drush vset clean_url 0

You can also edit the database as well.


I think you are correct. You should be able to create a view block, set the field to be "rightcol" and then use contextual filters (under advanced features) to filter what is in the view depending on URL.


Try the Drush Composer Generate project. If you have your composer.json committed to a vcs, you can run composer-generate and then compare the results and fix up anything that it might mis-apply.


Create entities when user account created

After doing my due diligence, I chose to use the hook_user_insert() to extend my logic for the entity creation. It fires when a new user is verified and added to the users table/entity.


Goto http://YOURSITE/admin/config/system/site-information and under "ERROR PAGES
" change "Default 404 (not found) page" to your search page. In this way, Drupal will redirect all 404 pages to the page that you have provided.


How do I enable rich text editing on all my long text fields?

Now they are all working. I think what happened is that since I have posted the question I have rebooted Apache and MySQL (as well as I may have cleared a cache or two) and that fixed the problem. I've tested a few editors, and now they all seem to work across multiple text areas.


There is an update "REGENERATE MARKER CACHE" option in gmap settings.

By pressing "Regenerate" button Drupal will update JS file stored in

/sites/default/files/js

Make sure you have access to that file.


Probably it is the difference between if field['und][0]['value'] is set or not. Even if field['und][0]['value'] is empty, it's different with not instancied field.

Try a default value on this field and add an other visibility condition on this default value


How to display specific button for certain user?

To hide and show buttons by role you can use the $GLOBALS to get the user and check on user role, something like.
 <?php if (in_array('role 1', $GLOBALS["user"]->roles)): ?>
    <button value="button 1">button 1</button>
  <?php else: ?>
    <button value="button 2">button 2</button>
    <button value="button 3">button 3</button>
  <?php endif; ?>


How can I set the help text as an input placeholder on the user login form?

unset($form['pass']['#description']);

or

hide($form['pass']['#description']);

is probably sufficient for the description element. I wouldn't use both above on form fields/controls though, because that may lead to unwanted validation errors and so forth.

$form['name']['#description']['#access'] = FALSE;

does not work for 'description' element as it is not a form control(field).

If anybody knows of better ways for removing description element, please chime in.


Using Webform Hooks to submit and display custom module forms?

Webform has nothing to do with your form if you created it in a module.Your form is a form not a webform type node.
Form API! reference is what you need and to install Devel module

Then

dpm($form)

inside your form builder function to check which function is your #submit which is your #validate and add[] your own if you like

form values are stored in $form_state array
dpm($form_state) it also in your submit function and do whatever you want with these submitted values.

Store them in drupal database using variable_set() , mail them using drupal_mail() etc.

Some links

http://drupal.org/node/717740
http://api.drupal.org/api/examples/form_example%21form_example_tutorial.inc/7


How to get count in views when group by some field?

You can try using this module

Term Node Count


Creating a Youtube block using Views for Embedded media field module

You should use the formatter, that's how it works. You just change the Option of the field to Image Thumbnail.


PDO exception error [database].semaphore doesnot exist

This question is duplicate. I already answered this in here. this is because of your database engine which must be converted to MyISAM from InnoDB. go to that link for more detail.


you are almost there. Just set "Use aggregation" to yes. Also, make sure there is not other field in "sort criteria".


You will want to use the pathauto module. This will also required for you to install the token module.
Once you have those two modules install you will want to head over to the pathauto settings path at admin/build/path/pathauto.  You will see there's a field-set for Taxonomy. There is also replacements patterns which contains various different tokens you can use to generate your path.
In your case the pattern you want to use looks like this:
category/[catpath-raw]

This will automatically generate the path for those taxonomy terms based of these categories.
I assume most of this is for 6.x but the same concept applies for 7.x


How to update fields of a new node created using Rules?

In Rules you have to add those fields as conditions - "Entity has x,y,z field" - then they will become available for your actions


How to filter with all outputs when using Rewrite results option in Views

To filter on both the Firstname and Lastname, when you want to add a filter, select  Global: Combine fields filter, and then click add. The next step tells you to select the fields to filter. Select your firstname and Lastname field


Solution how to import contents of a .txt file into a body field?

I believe you can accomplish this with Feeds Tamper and a custom plugin.

Take one of the existing text plugins and clone it to a new one.  Then inside the plugin callback, take the cell value (your text file name), build up a proper path, do a file_get_contents(), and stuff the contents into the result.

If you end up going this route, it may be a decent patch to Feeds Tamper for inclusion in the project itself.


How to integrate captcha to multi page webform

One thing that may work is altering the form using HOOK_form_alter() and than modifying the form to show the captcha only on the last step something as below:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Get the form id through dpm() or print_r().
  switch ($form_id) {
    // Add the form id as here.
    case 'webform_client_form_form-id':
      // Get the value of step number and the total number of steps in form.
      $page_num = $form['details']['page_num']['#value'];
      $page_count = $form['details']['page_count']['#value'];

      // Check if its not the last step and catcha present in form.
      if (($page_num != $page_count) && (!empty($form['captcha']))) {
        // Remove the captacha from the form.
        unset($form['captcha']);
      }
    break;
  }
}


Exposed filter or facet for a vocabulary listing select list

Facets are usually used for a lot more complex examples with many properties to narrow down your search by.

Both facets and the usual Views with Exposed filters form create paths that hold search parameters entered by users.

The simplest case would probably be to add the textual filter for the Body field, and the Filter for the Taxonomy reference field, and Expose them (so that the users can choose values for them and narrow down the search results). You can use Exposed form settings to change the way the form fields display, drop-downs sometimes aren't the most usable options.

You can use Better Exposed Filters module if you need more options for the exposed form display.


Drupal 8 devel dpm does not expand Drupal\node\Entity\Node

dpm() does not print any protected properties and it also doesn't know about methods. That's especially bad for content entities but applies to most objects in 8.x now.

The issue referenced in the answer from Daniel Wehner adds Kint, which is already much better, as it will give you protected properties and methods.

However, for content entities, it still won't be that helpful as the values are all within ->values and ->fields and it's not trivial to understand how those work, especially with multiple languages.

That's why we're also working on better integration for content entities with Kint, so that it will display the fields and their values, see the screenshot in that issue.

Until then, you can also always use the following to debug what's inside a node or other content entity:

<?php
dpm($node->toArray());
dpm($node->getFieldDefinitions());
?>

At least the first one also works well with debug(), which has the advantage that it also works when running tests.


Avoid drupal bootstrap for each image styles in private filesystem

No because it are separate http(s) requests. Every requests needs to redo the check.


Image File Upload via REST case Error 500 response due destination directory not set

The missing property was destination "uri"
"uri": [
   {
      "value": "public://" + media_name + ".jpg"
   }
],


Here is the place http://drupal.org/node/418616, Provides the list of modules with similar functionality you can choose something better and as per your need,


Changes in the way Drupal 7 handles JavaScript and jQuery

I think you misunderstood the changes.

JavaScript code should be wrapped in (function ($) { ... })(jQuery); to allow usage of $ as shortcut to jQuery. This is to allow jQuery to play nicely with other libraries. In this function, you still have to wait for the DOM to be loaded if you want to alter it. That's what wrapping your code in jQuery.ready(function(){ ... }) does.

But instead of using jQuery.ready(function(){ ... }), you should use behaviors to let Drupal's JavaScript knows that your code wants to process anything added (or removed) from the DOM.

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function(context, settings) {
      $(context).find('#edit-apiusername').append('test');
    }
  }
})(jQuery);


Javascript code appears in search results

Since the javascript code is actually part of the node content it would take a bit of work to get it to be ignored.

An easier solution would be to use implement hook_db_rewrite_sql() and excludes from appearing in search results. Here is a great tutorial: Hiding content from Drupal's search system.

That said, there is a module out there that does this, Search Config. However it is marked as obsolete and not being maintained anymore, therefore you might want to think twice before using it.

For the record it does indeed work as designed, and works well! (I use it on my website with no problems).


How to add "Agree to terms" checkbox in Drupal 8 form

Your code was D7 and what should a checkbox do with #size and #maxlength? :)

This answer presumes you have the Devel submodule Kint installed.

/**
 * Implements hook_form_alter().
 */
function THEME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  ksm($form_id); // Remove when done.

  if ($form_id == 'MY_FORM_ID') {

    $form['tos'] = [
      '#type'          => 'checkbox',
      '#title'         => t('Terms and Conditions'),
      '#required'      => TRUE,
      '#default_value' => TRUE,
    ];
  }
}

Check out this Introduction to Form API.


regex works in PHP fiddle but not in Drupal

Yep, the issue was I couldn't use the <> symbols. Have to use &lt and &gt instead.


Drupal 7 field widget - allowed values list

This would be hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta = 0).

The example code for the hook, reported in the documentation is the following one.

function hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => $instance['widget']['type'],
    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
  );
  return $element;
}


Why not render in a tpl so you can control the look of it?

I see you already used hook_block_info() so you can complete this using hook_block_view() with a custom callback function to use hook_theme()

Here is a complete example of it:

function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => 'user/',
  );

  return $blocks;
}

then:

function openid_connect_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'openid_connect_login':
      $block['content'] = openid_connect_login();
      break;
  return $block;
}

then:

function openid_connect_login() {
  return theme('openid_connect_login_tpl', array('data' => NULL));
}

last thing here:

    function openid_connect_theme($existing, $type, $theme, $path) {
      return array(
        'openid_connect_login_tpl' => array(
          'variables' => array('data' => NULL),
          'template' => 'openid-connect-login',
          'path' => drupal_get_path('module', 'openid_connect') . '/theme',
        ),
);
}

create your file inside you module under the name we gave openid-connect-login.tpl.php and put it in a folder I named theme ..

I hope I understood it right and was helpful for you issue ..


How do I get the active theme path in a view?

You can do by

global $base_url;
$theme = \Drupal::theme()->getActiveTheme();
$default_image_url = $base_url.'/'. $theme->getPath() .'/images/image.jpg';


Why does the favicon sometimes not show up and generate "page not found" errors, and other times does show up

Some browsers search for favicon under http://example.com/favicon.ico without checking. But they are minority now.

Most respect:

<link rel="icon" href="http://example.com/img/icon.png">

as described by W3C.

If your site tries to use <link> approach but fails on some pages, like admin pages rendered using different template, and you do not have favicon.ico in default location, you will get exactly described effects.

If browser is looking for  http://example.com/favicon.ico when you have proper <link rel="shortcut icon"> it is a browser problem, not yours. It means browser (or at least that part of it's code) is outdated, unless it looked under correct URI first and got another error, but then you would see two errors in log, one for right place, second for outdated one. In Mozilla's queue there is a number of reports about improper favicon detection by FireFox - in example this one. It shows how even modern browsers can sometimes fall back to old methods.


How to clear the a block cache programmically

When displaying information from a config object add it also as cache dependency to the render array.
For example in a preprocess hook:
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config->get('some_field');
  $variables['some_field'] = [
    '#markup' => $config_value,
  ];
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')->addCacheableDependency($variables, $config);

See How to clear cache for config entity after making changes?
You don't need to change form submit because saving a config object automatically invalidates cache entries having this cache dependency (cache tag).

Another example based on the block code from your answer and using a different method to add the cache tag:
  /**
   * Config settings.
   *
   * @var string
   */
  const SETTINGS = 'uw_cbl_special_alert.settings';
  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = \Drupal::config(static::SETTINGS);
    return [
      '#markup' => $config->get('message'),
      '#cache' => [
        'tags' => $config->getCacheTags(),
      ],
    ];
  }

Access caching
As asked in the comments, you can add cache dependencies to access results as well:
AccessResult::allowed()->addCacheableDependency($config)
AccessResult::forbidden()->addCacheableDependency($config)


You can easily configure drush aliases for this.

Having properly configured drush brings so many benefits, especially if you work with multiple environnements for your sites.

As an example, say you have aliases defined for example.com as follows:,

@example.local, @example.staging, @example.prod

See a status of all 3 sites:

drush @example st

Clear the cache on local env:

drush @example.local cc all

Dump production database and load it into local:

drush @example.prod sqldump | drush @example.dev sqlc

Anyways, you get the idea. Packing your drush.rc file with your project in git (shove it in /sites/all/drush/drushrc.php ) will allow anyone working on those projects to have those aliases fully defined on every code checkout.
Happy codings, cheers!

Lots of examples on drush aliases via google, here is a pretty well written one: https://www.monarchdigital.com/blog/2012-10-10/drush-aliases


ckeditor loads all the page html while editing not only the body field

I had this problem some month ago, one solution with disabling search module was good, but now i've needed search-box working, so i've made a research and found another thing.
In my case the problem was Plugin for inserting drupal teaser and page breaks. I've had this plugin switched off, but button "DrupalBreak" was added to Used button list.
solution 1:
Go to CKEditor profile settings page at '/admin/config/content/ckeditor/edit/[profile_name]'
Switch of "Plugin for inserting Drupal teaser and page breaks" in appearance settings.
Make sure, that "DrupalBreak" button is not in use.
solution 2:
The problem most likely lies within the search-module's cronjob to index the page. This cronjob kind of views the nodes it wants to index. If you use hook_node_view() anywhere in your modules and the cron-user gets an error or gets lead anywhere by a drupal_goto(), the behaviour you described is the result.
Solution: Disable the search-module if you don't need it. If you need it though, check the $view_mode in your hook_node_view()-implementations. If it says "search_index", no redirects should be made. (the easiest way is to just return $node if($view_mode == "search_index")


How to move Drupal 8 with composer, to another server

As already said in the comments composer does not have a way to help with transfering a site.

With a site build with composer I usually zip the composer directory (which includes the drupal directory) and get a database dump.  On the receiving server just copy the files on a similar directory structure and import the database.

For going from plesk to cpanel you probably have to set the document root correctly.  In plesk its usually httpdocs/docroot but in cpanel it should probably be set to public_html/docroot

Also I don't suppose you will need but it does not hurt to run composer update

NOTE: this is a quick and dirty way of transferring from on host to the other assuming that php version and other parameters stay the same, this is by no means a best practice in transferring a site to a new host.

For best practice you should follow the advice in the comments and see the guide on Use Composer to manage drupal site dependencies and the section for Managing existing sites using Composer might come in handy.


How can set a custom action with a custom attribute selected in form?

It is possible to use the $_POST array in the custom php code, which can be called in the action, which is assigned to the vbo action!
The page to show the view with the vbo fields is: /node/%node/add_person_to_event, so arg(1) is the nid of the event.

So my custom action code is:

$status = $_POST['status'];
$event = arg(1);
foreach ($_POST['views_bulk_operations'] as $key->$vbo_nid) {
   build_relation_person_event($event, $vbo_nid, $status);
}


You should create a custom Controller rather than hook on page load. This way you won't have an overhead on every page load. In the Controller (accessible under movie/{movie_id} route) try to load movie by movie_id (entityQuery), and if it does not exists simply create one based on data from 3rd party service and display in a display mode of your choice.


MigrateSQLMap how to instantiate if table has no primary key

To migrate content into Drupal taxonomy terms, use the MigrateDestinationTerm class, not MigrateDestinationTable. Here is example code

    $this->map = new MigrateSQLMap(
      $this->machineName,
      array(
        'term_id' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'Term ID',
        ),
      ),
      MigrateDestinationTerm::getKeySchema()
    );


How to filter views block by content type

Add a filter of content:type in one of your display Also,
You can select this block override at the top when you do any specific block related changes. check the screenshot http://i.imgur.com/vdu0wqg.png


Ensure atomicity of user_save within hook_node_delete

user_save() itself is likely to be guaranteed atomic. You're running innodb or equivalent, right?

However, you have no guarantees that the user isn't altered between your user_load() and user_save(), which can cause a race condition. There lock.inc for that.

  A database-mediated implementation of a locking mechanism.

This is very unlikely though, and if this happens to you often and regularly, you likely have a problem elsewhere in your code.

However, not even that can protect you from other parts of the code, in a parallel request, loading up the user, modifying it, and saving it back, in between your calls. For better or worse, you can't reasonably guarantee that no other piece of code, such as contributed modules, modifies your users.

Suggested options:

Modify the field value directly like UPDATE [table] SET [field] = [field] +/- [value]. Then you can rely on the DB's underlying mechanisms for atomicity.
Accept a small risk of failure. Run a hourly cron job to recalculate values, correcting for mistakes.
Don't use a user field for this data. Either use a custom entity, or directly manage a custom table. Force all updates through a lock mechanism.


How can I use 'format_type' => 'custom' for a datetime field?

I'm pretty sure you need to use the datetime_custom display type vs datetime_default. You won't need to pass the format_type parameter in your settings array. You will end up with something like:

...
->setDisplayOptions('view', [
  'type' => 'datetime_custom',
  'settings' => [
    'date_format' => 'd/m/Y',
  ],
...

That should work how you'd like. The datetime_custom formatter is defined in core's datetime module.


I'm waiting for this one, too. Conditional Fields module.
But it's not yet available in D7.


Way to programmatically add string translations?

Put the following helper function in your custom module:

use \Drupal\locale\SourceString;

function mymodule_add_translation($source_string, $translated_string, $langcode) {
  // Find existing source string.
  $storage = \Drupal::service('locale.storage');
  $string = $storage->findString(array('source' => $source_string));
  if (is_null($string)) {
    $string = new SourceString();
    $string->setString($source_string);
    $string->setStorage($storage);
    $string->save();
  }
  // Create translation. If one already exists, it will be replaced.
  $translation = $storage->createTranslation(array(
    'lid' => $string->lid,
    'language' => $langcode,
    'translation' => $translated_string,
  ))->save();
}


How to change the path in which are stored the media modules files and images?

i have found the radio button for selecting private in

/admin/structure/media/manage/file/fields/media.file.field_media_file/storage

how to change folder path , using possibly tokens?


How to create programmatically multiple URL alias of same taxonomy term?

If you use pathauto module:

You can use hook_pathauto_alias_alter  like the following:

/**
 * Implements hook_pathauto_alias_alter().
 */
function YourModuleName_pathauto_alias_alter(&$alias, array &$context) {
  // Change tags here by your term name
  if ($context['module'] == 'taxonomy_term' && isset($context['type']) && $context['type'] == 'tags'){
   // Get the current user the location for example australia
    $user_location = 'australia';
    // Change the alias to be
    $alias = $user_location. '/cars/[term:name]';
  }
}


Copying a CiviCRM/Drupal install from one server to another (got error)

If you have Drush installed, you can also use the following command to update some of those settings:

drush civicrm-update-cfg

It will try to update the URL and directory settings, which is pretty equivalent to the URL: "http:///index.php?q=civicrm/admin/setting/updateConfigBackend&reset=1".

After that, you can use the API to flush various CiviCRM caches which may be using that data:

drush civicrm-api system.flush


What bundle and entity_type do I use in field_create_instance to add a field to a taxonomy vocab?

The taxonomy module doesn't define any bundle types for taxonomy_vocabulary (see taxonomy_entity_info()) so Drupal's entity/field system assigns it a default one with the same name as the entity type (taxonomy_vocabulary).

field_create_instance(array(
  'field_name' => 'category',
  'label' => 'Some label',
  'required' => true,
  'widget' => array('type' => 'autocomplete_deluxe_taxonomy'), // I've also tried options_buttons
  'entity_type' => 'taxonomy_vocabulary',
  'bundle' => 'taxonomy_vocabulary'
));

I have to ask though, are you absolutely sure you want to add a field to the vocabulary rather than the term entity? I haven't come across many use cases where adding fields to the vocabulary itself is necessary. Drupal doesn't even have a UI to manage the fields (but I guess that could be why you're going this in code!)


There is no permission in a default D7 configuration to only delete one's own comment. To get this you must install Comment Access (or another contributed module with a similar function).

If you add the permission "Administer comments and comment settings" (navigate to Administration » People » Permissions), to a role, that role get access to a "Delete" tab for comments, but that lets the user holding this permission delete everbody's comments - not only his/her own.

Installing a module is no big deal in Drupal.  If you want this, I am afraid you need to install a module.


Drush scripting fails on call to drush_pm_enable()

The Drupal and Drush bootstrap processes are fairly complicated things; it is best no to try to figure out how to call them yourself.  If you want to bootstrap and call arbitrary PHP code, you can do so using Drush via drush @mysite ev 'php code here'.

As for calling Drush code directly, you should use drush_invoke_process, just as you are for the site-install command.  So, instead of drush_pm_enable(), instead use drush_invoke_process("@self", "pm-enable", array('ctools', 'views', 'views_ui')).

However, if you are running site-install on an installation profile, you should not need to call pm-enable, as the installation profile should take care of that for you.  If you're not sure how to build an installation profile, you can have Drush generate one for you.  You'll need to use the prototype generate-profile command, which can be found at http://drupal.org/node/1368242.  It does not work for D6 sites yet, but works fine for D7, so should be good for your purposes. Take a look at the list of modules generated in your profilename.info file; these will be enabled for you during site-install.


To do this you could use a popular module http://drupal.org/project/flag.
There is also documentation here http://drupal.org/documentation/modules/flag.


How to configure the default visibility to "Only the listed pages" when adding a block?

Nope. The block add admin form is hard-coded to use BLOCK_VISIBILITY_NOTLISTED (i.e. "All pages.." option) as the default option; there's no configuration setting there. The only way around this is to form alter it with a module.


How to enable Submit Button after filling out the required fields?

check out #states visible #states invisible in drupal.

http://api.drupal.org/api/examples/form_example!form_example_states.inc/function/form_example_states_form/7

http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_process_states/7


This:

function mymodule_form_user_register_form_alter($form, &$form_state) {

needs to be this:

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

Notice $form is by reference in the second snippet.


How to add an html element (BODY) class based on taxonomy from logged in user?

In your custom module implement hook_preprocess_field().In the given code I am adding a taxonomy term field with uid as class,you can change to your requirement.

function mymodulename_preprocess_field(&$variables) {
  global $user
  if($variables['element']['#field_name'] == 'your_taxonomy_term_name') {
    dpm($variables);
    dpm($variables['classes_array']);
    $variables['classes_array'][] = $user->uid;
  }
}


How to track user node views and quiz results

I'd use the Goals module (disclosure: I'm its maintainer) to "track wether user has visited particular node" (as in your question). No need for custom coding. Read on for details how to do so ...

Configure a goal

Navigate to the relative path admin/config/goals/manage and use the link "Add a goal" to define just 1 goal, with a description (say):

View some node, only 1 time.

Configure a task

To achieve the above goal, define the Task(s) to be completed. Even though there could be multiple tasks to be completed for a single goal, in your case you just need 1. It's simply View a node (assume we use a machine name like view_a_node).

Track progress while performing tasks

To track the progress made by a single user to complete this task, you only have to write an appropriate rule, using the Rules module, to record relevant events happening in your site, which are related to the completion of the task to reach the goal.

For the goal/task described above, you'd only need 1 (extremely basic) rule, which would look like so:

Rules Event: Content is viewed.
Rules Events:

Check user has role "authenticated" (how else would you know which user it is ...).
Check the node id of the node being viewed (eg: node=123).

Rules Action: Record a task for Goals (obviously, the task to be recorded is "View a node"). This is where part of the Goals magic happens, such as verifying the requirements in the optional task configuration options for a task (only once an hour, etc).

Here is a rule which you could probably use for this (if you have a "task" defined with the exact machine name view_a_node, just use the Rules UI to import it in your own site to get you going, if not adapt that machine name prior to starting such import):

{ "rules_record_task_view_a_node" : {
    "LABEL" : "Record task view_a_node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "rules", "goals" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "data_is" : { "data" : [ "node:nid" ], "value" : "123" } }
    ],
    "DO" : [
      { "goals_task_record" : {
          "task_name" : "view_a_node",
          "user_to_save_for" : "[site:current-user]",
          "task_id" : "Node ID of viewed node = [node:nid]"
        }
      }
    ]
  }
}

The above gets you started for a single node like node/123. To enhance it to also verify node/124, node/125 and node/126 (it doesn't matter in which order they are viewed ...), this is how to do so:

Add 3 similar tasks to be tracked (for the 3 other nodes), with a machine name that includes the relevant node id.
Duplicate the above rule for each of the other nodes (only difference is the node id in the Rules Condition and the machine name of the Task in the Rules Action). As an alternative, use the Conditional Rules module to consolidate those 4 rules in a single rule.


Were you using clean URL's before the migration?  If this is the case, than you may need to set up mod_rewrite only for nginx. I have not used the server but found this article on how to achieve the same.

http://wiki.nginx.org/NginxHttpRewriteModule

Not sure if this is your problem though, although it might be.


"Disabled" regions re-enable after navigating away and back from module page

I believe I resolved my issue. Both the page callback function and mymodule_page_alter function were in a mymodule.pages.inc file that is linked to in the mymodule_menu function. Drupal doesn't like the hook being in the .inc file, so I moved it to the .module file, cleared cache, and reloaded the page. The form's page seems to be loading the content I want to see and nothing else, even after navigating away from the page and coming back to it later.

Lesson learned -- I'll just keep all API hooks in the module file unless taught to do otherwise. Or, unless hooks being outside of the .module file isn't possible anyway.


To find out what is missing, implement hook_views_data_alter() and dsm($data) in the function to find the right path for your field.


Enable CSS files in Omega 3 sub theme with Drush?

I'm only a bit familiar with Omega 4. In order for your css files to be "enabled" by default, you need to transfer the theme settings from the database into the theme's .info file and make sure this is enabled also in the live site. So if you have css/style.css and its declared in the .info file, Omega 4 will just follow the .info file.

Hope this helped. :)


hybridauth module - redirect problems after connect

We had the same exact issue using the above configuration.

It turned out that I had a rule enabled to redirect the user to a page upon login.

When I disabled the above rule everything went back to normal

Probably a conflict between modules.

Thanks,
Leonidas


The reason you're getting the error "Undefined variable: nid" in some cases is obvious. You're only assigning a value to $nid if the following is TRUE: arg(0) == 'node'. If arg(0) is something else, $nid never becomes defined, causing the error.

Since it doesn't make sense to use $nid unless it is defined, you can get rid of error by moving the construct where you use the value of $nid inside the if-test, like this:

<?php
if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid);
  $value = $node->field_price['und'][0]['value'];
  return $value;
}
else {
  return FALSE;
}
?>

Note that this will return the value stored in the field field_price if arg(0) is equal to the string 'node', and return FALSE otherwise.

You write:

  What I want is getting the field_price's value, changing it for negative and returning it for Rule.

Please note that your original code does not do that.  Nor does mine.  I just told you how to fix the bug. The business logic is still up to you.

Please also note that this has nothing to do with Drupal - it is Programming 101.


The browser is likely crashing because most of the views objects have circular references in them, and the output can be huge.

$variables['field'] is the field handler object for the field being rendered.  I am 97% sure these are all derived from \Drupal\views\Plugin\views\field\FieldPluginBase() (3% uncertainty because it is the end of the day and I am really tired).

You best bet is to do a debug(get_class($variables['field'])) to get the fully qualified class name, and then typehint in your preprocess, eg:

function MYMODULE_preprocess_views_view_field(&$variables) {
  /** @var \Drupal\views\Plugin\views\field\Boolean $field */
  $field = $variables['field'];
}

and then use your IDE to navigate through what you need to do.

To see what is in $variables, just do a

debug(array_keys($variables));

and go through a similar exercise to get the types; it's just a boring associative array where the keys are all strings.


You are getting 404 error because actually there is no page in your site with that url.

In your referenced tutorial the following statements can found as a note:

"
Note: The sample callback URL above is incorrectly shown. The callback URL should be an URL on the client side. When Drupal has authorized the consumer, it will call this URL with the access token as a parameter."

So you have to define a page call back with path as you want. You can define in your custom module.  OR You can give a valid site path as callback url. So When Drupal has authorized the consumer, it will call this URL with the access token as a parameter.


How to place a role-aware "Add new" link at the top of a Views listing of media

A quick views only way you could:

Create an attachment with your link in a custom text or however you'd like to do it. Set the access permission for that attachment to your role and attach it to your main page display

If the user doesn't have that role the attachment should be empty/show the no results content


How can I change the value of a field in node / [id] / edit?

I alter my forms with the following:

function mymodule_form_test_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // code here...
}


Depending on the type of code that you need to run, and from the Drupal version, AHAH and AJAX could be the answer.

On Drupal API, there is example code for AHAH (Drupal 6), and AJAX (Drupal 7 and higher).


In a Linux environment, this is done for NFS drives by creating a symbolic link under your Drupal webroot.

In the Windows environment, you can also create a symlink to a network drive path (e.g. \xx.xx.xx.xx\my\content\folder ).


It could be as simple as just clearing cache or just visiting the 'modules' page in your admin. The content of .info files is cached and isn't reloaded with every page visit.


How to configure Workbench to allow author to publish own content without moderation?

Have a look at this issue, it discusses this topic: https://www.drupal.org/node/1338750


hook_theme_suggestions_page() provide default template file inside module folder

This issue got resolved by adding hook_theme(). Normally theme suggestion templates are only picked up when they are in themes. So We need explicitly define theme suggestions using hook_theme() inside a module. Then only it takes templeate from your modules templates folder.

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'page__ajax' => array(
      'render element' => 'elements',
      'base hook' => 'page',
    ),
  );
}


Adding class to image-link in render array

To get your class on the image's link you'll need to set it in the path options:

$my_image['#path']['options']['attributes']['class'][] = 'colorbox-load';


Print custom HTML between Exposed Filter Area and Results in Views

This can easily be achieved using themeing.

In the edit view for your view click on advanced
At the bottom of the section is "theme information"
Look for the line "Display output" and from left to right the themeing becomes more specific
Decide how specific you want the themeing to be (hint if unsure go to the right)
Copy the theme file name (which should be something like views-view--example--page.tpl.php) and create a new file in your theme folder with that name
Click on the display options link and copy the contents of the file from the <?php through to the bottom of the fixed width text and paste that into the new file
Add your text after the code block that looks like this:

  <?php if ($exposed): ?>

  <div class="view-filters">

  <?php print $exposed; ?>

  </div>

  <?php endif; ?>

Save the file
Click the "Back to theming information" link
Click the rescan template files link
Save your view
Visit the page your view is on


Where do I store classes and ids that the user inputs in my custom module?

Of your three options, 2 would be a huge burden to a site in performance, and 3 will likely be a security issue. So I'd go with 1.

For reference, see the Block Class module.


What's the proper use of EntityFieldQuery?

EntityFieldQuery uses a set of hooks to interface with field storage modules, such as Field SQL Storage, in order to work for fields as well as other node properties. Long term, EntityFieldQuery is a much more reliable way to query any type of entity, and in some situations it can perform cross entity queries (see field_has_data or _list_values_in_use() for an example.

Here's a simple example of using EntityFieldQuery to get a list of all nodes published before a specific timestamp:

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('status', 1, '=')
  ->propertyCondition('created', '1294694496', '<');

$result = $query->execute();

$results from that query would look something like this:

Array
(
    [node] => Array
        (
            [1] => stdClass Object
                (
                    [nid] => 1
                    [vid] => 49
                    [type] => article
                )

            [2] => stdClass Object
                (
                    [nid] => 2
                    [vid] => 2
                    [type] => page
                )

        )

)

You could then use that array as input to node_load_multiple:

$nodes = node_load_multiple(array_keys($result['node']));


Theming two instances of an input field in one form

Is there a reason having the class on the input would be better than having it on the block? e.g. does it make some CSS/JS awkward by not being able to target the input directly?

If not, having the class on the block seems like the ideal solution both in terms of ease-of-development and semantics...you want the search input to be styled based on where it is. That feels like a natural separation for a hierarchy of selectors: .block .input

If the blocks are in different regions, you could use the region class instead, which is there by default in most themes; that would avoid even having to alter the blocks themselves.


How to use conditional not to print a field if empty in user profile?

Have you thought of using Entity Metadata Wrappers?

You can wrap the user profile using $user_profile_wrapper = entity_metadata_wrapper('user', $user_profile);, and then you can find out if the field has a value with:

if (isset($user_profile_wrapper->field_myfield)) {}

This should tell you if the user profile HAS the field, and then you might use:

$value = $user_profile_wrapper->field_myfleid->value();

to actually get the value and test if it's empty or not.

Sources:

https://www.drupal.org/documentation/entity-metadata-wrappers
Checking for existence for a field on an an entity_metadata_wrapper


Add empty links from a BreadcrumbBuilder

Drupal 8 has now a special <nolink> route to define empty links:

$breadcrumb->addlink(Link::createFromRoute('Empty link', '<nolink>'));

See issue (patch commited to 8.2.x): https://www.drupal.org/node/2693725


The comments and example code in the documentation: achievements.api.php show how to create a new achievement.

There is no administration interface, you must create a module and use the hooks described in the above link to create new achievements.


Create taxonomy reference field programatically in Drupal 8

I did it by following method. If any other better way to achieve this, please suggest.

$tag_terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('tags');
$tags = array();
foreach ($tag_terms as $tag_term) {
    $tags[$tag_term->tid] = $tag_term->name;
}

$form['custom_tags'] = array(
  '#type' => 'select',
  '#options' => $tags,
  '#title' => $this->t('Preffered Tags'),
  '#default_value' => $this->store->get('custom_tags') ? $this->store->get('custom_tags') : '',
);


Drupal + Solr, how to boost search results with updated date?

This module may be a solution https://www.drupal.org/project/search_api_sorts

Otherwise using you method above - According to this post http://www.metaltoad.com/blog/date-boosting-solr-drupal-search-results

then you need to add an extra []

$call_args['params']['freshness'][] = 'recip(abs(ms(NOW/HOUR,ds_changed)),3.16e-11,10,1)';

However after testing I still can get the result I want.

For example the value 3.16e-11,10 ; as far as I understand it means a year of milliseconds that gives a score of 10 inside that time span. and then decrease after.

For testing I used

call_args['params']['qf'][] = 'recip(abs(ms(NOW/HOUR,ds_changed)),86400000,21,1)';

which should give Posts added/changed on the day a score of 21 and then decreases daily.

Testing with 3 identical listings.  And only title set at a boost rate over 1.  I cannot get the articles to listing in date. order. Have i missed something obvious.


If you are using D6, you need to install the cck module to add custom fields to nodes.

But, if you are using D7, cck has been migrated into drupal core. You can easily create custom fields for each content type at the path admin/structure/types/manage/{content-type-name}/fields. For your page content type, go to admin/structure/types/manage/page/fields.

I think your case is not concerned with the views module. You can generally check what is views here.

AFAIK, there is no module to create different custom fields per node. We can only create custom fields per content type.
If you are sure you have static numbers of page ( such as page, about, etc. ) and if you will not allow your client to add a new page content, it is possible to create and display different fields upon NID.
You will need to write hook_preprocess_field in your theme template.php and hook_form_alter in your custom module to show/hide different field upon NID.
Here are some example code snippet.

In your theme template.php,

function yourtheme_preprocess_field(&$vars){
    $element = $vars['element'];
    // let's say nid=1 is for your home page
    if($element['#object']->nid == 1){
        // hide custom fields for the other node 2
        if( in_array($element['#field_name'], array('field_1_for_nid_2', 'field_2_for_nid_2')) ){
            $vars['classes_array'][] = 'invisible'; // make display:none in theme css file for the class .invisible
        }
    }
    // let's say nid=2 is for your about page
    elseif($element['#object']->nid == 2){ // do same things for nid=2
        // hide custom fields for the other node 1
        if( in_array($element['#field_name'], array('field_1_for_nid_1', 'field_2_for_nid_1')) ){
            $vars['classes_array'][] = 'invisible'; // make display:none in theme css file for the class .invisible
        }
    }
    // and so on.
}

In your custom module yourmodule.module,

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

    if($form_id == 'page_node_form'){ // for the content type 'page'
        $nid = arg(1);
        if($nid == 1){ // when your client edit the page "home", let's say it is nid=1
            // hide custom fields for the other node 2
            $form['field_1_for_nid_2']['#required'] = FALSE;
            $form['field_1_for_nid_2']['#type'] = 'hidden';

            $form['field_2_for_nid_2']['#required'] = FALSE;
            $form['field_2_for_nid_2']['#type'] = 'hidden';
        }
        elseif($nid == 2){ // when your client edit the page "about", let's say it is nid=2
            // hide custom fields for the other node 1
            $form['field_1_for_nid_1']['#required'] = FALSE;
            $form['field_1_for_nid_1']['#type'] = 'hidden';

            $form['field_2_for_nid_1']['#required'] = FALSE;
            $form['field_2_for_nid_1']['#type'] = 'hidden';
        }
        // and so on
    }

}

If you don't know about how to write custom module, here is a good start point.
If you don't want custom coding, the best way is to create different content types with different fields for your pages.


Field format display options are components of view modes, stored in the config entity EntityViewDisplay.

For example, load the default view mode for the user and extract the configured image style of the user_picture field:

use Drupal\Core\Entity\Entity\EntityViewDisplay;

  $component = EntityViewDisplay::load('user.user.default')->getComponent('user_picture');
  $image_style = $component['settings']['image_style'];


How to debug views_handler_field_node_revision handler?

I had this problem when the "Content revision: Title" field on my view was set to "Link this field to the original piece of content" however it wasn't using the relationship to the content.

I set it to use the "Content revision: Content" which fixed the link and the error.

I think this error is displayed with problems regarding a node_revision view and an error in the relationship, as Nels mentioned.


Send data from a Drupal site to a web service

Well, it probably depends on the type of web service you want to send data to, but there is this module, REST API Query, for REST web services (http://drupal.org/project/rest_api_query).

This week we needed to send an issue report form data from a Drupal site to a Redmine issue tracker, using the Redmine web API. We played around with the above module, but finally decided to do it in plain PHP, using CURL.

Here's the code we are using (inside the custom Drupal module we made), so you can get a general idea. You can easily adapt to your specific needs.

$url = {The API url here};
$userpasswd = {api-user}:{api-pass};
$xml = {XML payload};

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_USERPWD, $userpasswd);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
curl_close($ch);

UPDATE: There is a drupal core function that performs the same task, drupal_http_request. I guess it would be better to use that one, doing it the drupal way and all :-) I have not yet tried it out though.
http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_http_request


Having trouble making Views treat external content as nodes/entities

I would probably not go down the the road of using Views (or Ctools) plugins at all here. (And I'm a big fan as well as proponent of Ctools and it's plugin architecture.)

I would create a new entity type, or a dummy content type of a node, and then take over the loading of said entity/content type with hook_entity_load.

Why integrate with Views only, when you can integrate with Core instead, possibly even with less effort?


I have used the following code to fix my problem.
keywords:
    - plugin: sub_process
      source: keyword
      process:
        value: Name
    - plugin: entity_generate
      value_key: name
      bundle_key: vid
      bundle: keyword
      entity_type: taxonomy_term
      ignore_case: true

I put it in the nodes migration file.


Drush updates core successfully to 7.32 but is still 7.31

Try drush up drupal. That may do the trick.


Implement hook_field_create_instance(), hook_field_delete_instance() and hook_field_attach_rename_bundle()

These two drupal resources should get you there:

https://www.drupal.org/node/2054619
https://www.drupal.org/node/2012896

As an aside, here is how I found the changes: Drupal Changes


You can use Google Analytics Event Tracking module to track mouse click and other events. This module provides a hook where you can track click events.
From module page:

Event Tracking is a way to track user interaction with out registering a page view.
This module allows an interface for Google Analytics event tracking capabilities. It provides a hook for other modules or "glue code" and also has some handy drush commands.


From the Login Toboggan config page:

  LoginToboggan automatically performs basic password validation for
  illegal characters. If you would additionally like to have a minimum
  password length requirement, select the length here, or set to 'None'
  for no password length validation.

If you check the logintoboggan_validate_pass you see:

  if (preg_match('/[\x{80}-\x{A0}'.          // Non-printable ISO-8859-1 + NBSP
                   '\x{A1}-\x{F7}'.          // Latin punctuations
                   '\x{AD}'.                 // Soft-hyphen
                   '\x{2000}-\x{200F}'.      // Various space characters
                   '\x{2028}-\x{202F}'.      // Bidirectional text overrides
                   '\x{205F}-\x{206F}'.      // Various text hinting characters
                   '\x{FEFF}'.               // Byte order mark
                   '\x{FF01}-\x{FF60}'.      // Full-width latin
                   '\x{FFF9}-\x{FFFD}]/u',   // Replacement characters
                   $pass)) {
    return t('The password contains an illegal character.');
  }

So your problem comes from Login Toboggan.

I think this automatic validation is only performed when user can set the password int he register process.


Use the hook_form_alter hook, check which form you're on and what the current action is, then remove the node and redirect to where you want to go.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7.x

Here's my D8 code, should be fairly similar in D7:

<?php

function my_module_name_form_alter(&$form, $form_state, $form_id)
{
  if ($form_id == 'node_mynodename_delete_form') {
    // write code here to delete the node and redirect
  }
}

This code goes into the .module file.

Replace my_module_name with the name of your own custom module.

Replace mynodename with the machine name of your node.

There are plenty of examples out there on how to programmatically remove a node and redirect.


append values to drupal7 cck link field entry

You can use the Media: Youtube module.

You would then create a file field with a Media file selector widget. Make sure you configure the field to use the Youtube URI schema.

You can configure the size of the video through the field display settings.

When you create a new node, you will need the share url, like http://youtu.be/n1yxNjU7u_8 to embed it.


why and how the view is putted in the sidebar first block

resolved it
use context module.
Conditions select view
Reactions select block - sidebar first


trouble with a checkbox on the user registration pages

Found the answer. The problem was that I selected the wrong field type. I think because it is only one field you need to select a Boolean type. Now it's working!


How do I edit serialized values in "config" and "key_value" tables?

Don't edit the serialized config, edit the config as YAML. Try for example
drush cedit
See other options (UI and command line) here: https://www.drupal.org/docs/configuration-management


"Administer Taxonomy" is needed to make a user select a term

You don't need to give an user the permission to Administer Taxonomy in order to use a vocabulary. Assuming you are using Drupal 7, as the name implies Administer vocabularies and terms it's a permission that allows one to edit and/or *delete a term from any vocabularies. It can also be specified per vocabulary.


Which hook to use for updates of all nodes of a particular type

I would like to know if there is a way to target only that node type directly from the hook and not to have the hook triggered for all nodes and then checking the node type.

Node hooks aren't that granular, they're invoked for all nodes and there isn't a system in place to make that selective based on the type. If you're worried about performance, don't be; the difference between the hook being invoked for all nodes, and a system to allow it to be selective would be negligible.

If you want to react to existing nodes being update, hook_node_update() is definitely the right choice.

You just need to test the type in that function:

function MYMODULE_node_update($node) {
  if (in_array($node->type, ['book', 'article', ...])) {
    // Do something.
  }
}


Customise Recent Content block to show only 1 content type

A custom View (as a block) would solve your problem.

You can make it replicate the functionality of the 'Recent Content' block but minus the the Content Type that you wish not to include.


I have an idea!  How about if you add an additional field to your Job content type called 'Time at job' that's simply a text field.

Then, create a new rule with the rules module that fires off when a Job node is saved or modified.  In that rule, you can simply set the 'Time at job' field by calculating its value from the values of the two date fields (using php).

For the php code calculating the length of time between two dates, there are countless of tutorials online.  Here's just one that's quite comprehensive: https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php.

Would that fit your scenario?  Calculating a third field upon node save/edit and displaying that instead?


How to assign the user login block to header region

The Drupal core User login block doesn't display a login/logout link; it only displays a form for logging in an anonymous user. If you want a block to display logout, the User Menu block displays user-specific menu links that also includes a logout link when a user is logged in.


As said in the documentation page for DrupalWebTestCase::drupalPost(), that method supposes to be called for a Drupal page containing a form; if that is not the case, you should use drupal_http_request().

The reason is that the method tries to emulate a click on a submit button, as said in the description for the $submit parameter.

  $submit: Value of the submit button whose click is to be emulated. For example, t('Save'). The processing of the request depends on this value. For example, a form may have one button with the value t('Save') and another button with the value t('Delete'), and execute different code depending on which one is clicked.


How to save webform submissions data in fields using rules module

Let's say that my webform contains the components: phone, address, city ..

I created a new content type that contains these fields: phone, address, city ..

Then, for each field I added

{ "variable_add" : {
      "USING" : { "type" : "text", "value" : "[data:address-value-raw]" },
      "PROVIDE" : { "variable_added" : { "var_address" : "Address label" } }
    }
  },

Where address is my MachineFieldName

and

  { "data_set" : {
      "data" : [ "article-created:field-address" ],
      "value" : [ "var_address" ]
    }
  },

To check your data as [ "article-created:field-address" ]

go to admin/config/workflow/rules/reaction/manage/rules_create_a_node_from_webform_data
go to add action and select set a data value
in the Data selector *: select article-created:...(Created article) Then you will see all your fields..

This answer to How to create a node from a Webform using rules? helped me..

I hope that can help someone..

Thank you


You would have to add them to a global token piece like [site] for them to be able to be used anywhere tokens are used.

But to use in a custom module you can use the following hooks:

Generate token info:

/**
 * Implements hook_token_info().
 */
function module_name_token_info() {
  $info = array();
  // Define a new token type.
  $info['types']['my_custom_tokens'] = array(
    'name' => t('My custom tokens'),
    'description' => t('A token type for my custom tokens.'),
  );
  // Define any new tokens.
  $info['tokens']['my_custom_tokens']['my_token'] = array(
    'name' => t('My token'),
    'description' => t('A token I use in my module.'),
  );
  return $info;
}

Give values to token:

/**
 * Implements hook_tokens().
 */
function module_name_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'my_custom_tokens') {
    // Loop through the available tokens.
    foreach ($tokens as $name => $original) {
      // Find our custom tokens by name.
      switch ($name) {
        case 'my_token':
          // Work out the value of our token.
          $value = 'Value of token';
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
      }
    }
  }

  return $replacements;
}

That should get you started with custom tokens. I've used this a few different times with different situations and it works very well.


I found that my /layouts/owr/owr.layout.inc file still said: template = simple-layout instead of template = owr-layout Changing it to the latter fixed my issue. Don't know why/where that parameter is used though.


Working on Drupal and Drush with teammates

Checkout configuration management in Drupal 8. Though there are many modules that can help you out but most of them are in active development and not stable for production use yet.

Two most promising modules are Configuration Update module and Features module.

Checkout What are the alternatives to Features module in Drupal 8 for further notes.


Specific field tag based naming conventions (overriding views-view-field.html.twig for specific fields)

I am able to use the tag to create template files for everything other
  than the specific field templates. – John Millnik

Your comment gave me the following thought: When you tag something, you tag the node and not the fields themselves. Fields do not have any tags, which makes me think that what you're trying to do is not possible.


You can use Rules module, force user to redirect to whatever page after login. It's very easy to get it done via the Rules UI, try it out. http://drupal.org/project/rules


Features will handle export and import of content types (a.k.a. products types, I think) but not nodes (which is what I think you mean by exporting "products".)  I have not used it myself, but I think that the Node export module is designed to do what you want.


How to specify a Rules event like "Content is 'going to be' viewed"?

You should react to the System > Drupal is initializing event and check for the URL there:

{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

Also, notice that in the rule above we test against the site:current-page:url token, which contains the (full) original URL (as seen in the browser address bar). Checking against site:current-page:path would not work in this case as all nodes, even the ones being accessed via URL alias, would match.


Can I just change Drupal's default timezone to test to see if some scheduled rules will fire?

I am 95% certain that drupal is using the server's system time so changing the timezone will have no effect as far as rules are concerned.

Alternatively, you could (temporarily) hack the contrib module to test whatever you need to test and when you're sure things are working, restore the original module when done.


drupal_goto() alters the header of the page, then calls exit(). So if it's placed before the drupal_add_js(), the function will never be called, and if it's placed after, the header says "Go some place else," and you will be redirected as soon as possible, not waiting for jQuery to execute.

Why do you need to close the shadowbox in the first place if you are going to redirect the user somewhere else? It sounds like there's a fundamental problem to what you want to do.


Cannot set menu link content field values in *links.menu.yml

Menu links discovered in *.links.menu.yml are not menu link content entities and therefore don't contain the field you have added to the entity. If you want to fill this field with data programmatically, create an instance of the entity:

$link = MenuLinkContent::create([
  'title' => 'Article',
  'menu_name' => 'main',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'entity:node/1']],
  'custom_field' => 'custom content',
]);
$link->save();

The content of *.links.menu.yml seems a bit odd. The title field is the only required value and you can see that the link is discovered and the title is displayed in the screenshot. The other values are optional. Check the documentation about which values you can use in this file https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-menu-links

The field seems to be for some kind of access control. You shouldn't do this in the menu link. Instead control the permissions of the target. Menu items are only displayed for users who can access the target.


Set value of file field using entity_metadata_wrapper non working

Fixed! Thanks to this post Save a new value with entity_metadata_wrapper to an entity field which is an array

$file = file_load(8172);
$node = entity_load('sys_ind', array(13718));
$wrapper = entity_metadata_wrapper('sys_ind', '13718');

$wrapper->field_allegati[NULL]->file->set( $file ); # This worked

$wrapper->save();

so the fix is using NULL (at least in multivalue field like mine is), not 0 or any other index nor [].


How do I import a csv-file into a table via Drupal?

I don't know if this quite what you're looking for, but the Feeds module can import CSV content into nodes. Perhaps it could help...

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from
import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files