Rebuild Form Element with new property after Ajax

Finally I achieve it with following, Change autocomplete parameters prperty in form alter on rebuild event INSTEAD of changing property worked for me,

    use Drupal\Core\Form\FormStateInterface;
    use Symfony\Component\HttpFoundation\Request;

    function zeytondev_form_alter(&$form, FormStateInterface $form_state, $form_id) {

        if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {
            $form['langcode']['widget'][0]['value']['#ajax'] = array(
                'callback' => 'zeytondev_language_change',
                'wrapper' =>'mtrend-wrapper',
                'event' => 'change',

            );

            //kint( $form['field_trends']);
            $form['field_trends']['#prefix'] = '
';
            $form['field_trends']['#suffix'] = '
';
            $langcode = $form_state->getValue('langcode');
            if($langcode) {
                $langcode = $form_state->getValue('langcode');
                $langcode = $langcode[0]['value'];
            }
            else {
                $langcode = 'en';
            }
            //var_dump($langcode);
            $form['field_trends']['widget'][0]['value']['#autocomplete_route_parameters'] = array('lang'=>$langcode);
        }

    }

    function zeytondev_language_change(array &$form, FormStateInterface $form_state) {
        $form_state->setRebuild(TRUE);
        return ($form['field_trends']);
    }


This should echo the path to the theme logo, which you could wrap in an  tag:

<?php echo theme_get_setting('logo_path'); ?>

If you want to re-size, crop, or modify the image you should do that in an image style. Once you have made an image style in Configuration > Media > Image Styles, you can echo the logo with that style like so:

<?php echo image_style_url('my_style_name', theme_get_setting('logo_path')); ?>


how to set an absolute position to a view (or div class)?

If you have the div's parent element set to position: relative, you can then set the ad div to be position: relative and give it and offset from the bottom. eg. bottom: 20px;
You will need to be careful that your article list div doesn't expand over the space where your ads are as they will overlap.
Post a link if you need more help.
Hope this helps.


Multiple site with multiple databases and single login

This is not something that it easy to accomplish, your main problem will be to keep track on the users on the two instances, since users doesn't have a Global Unique ID (GUID) but instead uses the user id or uid which is a simple serial id.

You also have to figure out how to handle people editing the same profile at the same time on the two different sites, which easily can lead to some major headaches when site 1 wants to update site 2 and vice versa.

You can take a look at the bakery module which can be used for a single signup system. I'm not sure this will be useful out of the box for you, but you probably could find some inspiration to how you can handle signing in users on multiple sites.

In any regard - you will probably need some custom coding or a clever module I haven't heard off yet.


SEO friendly URL for drupal commerce products

the module Commerce product Url is for make unic urls based on product variations, it means when you have one product display showing different product variations.

Check this issue where they explain a little bit better what Im telling you

But there is a non-drupal solution to convert dinamic urls into SEO-friendly urls, that is using mod_rewrite:

EXAMPLE

Sad Original URL = site.com/node/1?id=54

Happy URL :) =  site.com/node/1/rueben-sandwich/

Use mod_rewrite in your .htaccess file to parse out the elements of the URL. Like this:

RewriteEngine On //check that in drupal's .htaccess the rewrite engine is on by default

RewriteRule /(.*)/$ node/.*$?id=$1

the (.*) pulls the element out and puts it in variable $1. and the .*$ is just a wildcard that accepts everything after node/

Try it and tell us if it worked because I have not tried it with Drupal websites.

by the way, try to use sku, or some other argument in the url through the module configs, so your url would look better because using "id" the final result of the above code would be /node/1/54


How to make views header sticky while scrolling?

Under the format in views select table.
Got to settings on table there will find the checkbox named Enable Drupal style "sticky" table headers (Javascript) . Enable it
In views preview u can see the sticky headers of the table.


drupalLogin in functional JavaScript tests passes locally but fails on Drupal.org?

After reading through the Jenkins results for the nth time, it finally occurred to me that during Drupal core (and other contrib) tests all JavaScript tests always run separately from the other tests. All my tests however were in the same list.

This happened because all test classes started originally as functional tests, but as I went ahead some of them were changed into functional javascript tests. Class extending was changed into JavascriptTestBase and the tests were working perfectly fine. At least, when running individually. Running multiple tests at the same time made them somehow interfere with one another.

The problem was that I had never changed the namespace from Functional into FunctionalJavascript. The Drupal testrunner makes sure that all FunctionalJavascript tests are ran one by one, but performs other tests in parallel.

After changing the namespace, the tests were listed separate from the rest, ran after each other and finally showed up green on Drupal.org


Messages in the inbox can be filtered by subject.  To do so, if you are on the default path (messages), just click the blue link for "Subject" at the top of the table.

Alternately, if you want to always filter by subject, you can change the messages link to this:
messages?sort=asc&order=Subject.


Author who is not a user - Does a module exist?

The solution was clearly provided by @Clive in his comment:

  users only make sense in the context of authorisation. Since you don't
  want/need that, you should just create an 'Author' content type and
  use that to store your authors and use EntityReference to relate them
  as Nikhil suggested

If a logged in user needs to be associated with a user in order to pre-fill this author display field you could have an entity reference on the user profile page.
If this needs to be a module, use features module to export:

Author content type
Author entity reference on users
Author field base with form field and display handling

I never actually created a module for this.


How to write a Drupal 7 query with "count" and "having" properties?

This is off the top of my head so use caution...

$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->condition('n.type', 'test')
  ->condition('tn.tid', array(23, 37))
  ->condition('n.title', '%' . db_like('name') . '%', 'LIKE')
  ->condition('n.status', 1)
  ->groupBy('n.nid');

// Add the COUNT expression
$query->addExpression('COUNT(n.title)', 'ncount');

// Add the HAVING condition
$query->havingCondition('ncount', 2);

// Add the JOIN
$query->join('taxonomy_index', 'tn', 'n.nid = tn.nid');

$results = $query->execute();


You can override the default views templates for summaries in your own theme. There are two of them, which are located at:

sites/all/modules/views/theme/views-view-summary.tpl.php
sites/all/modules/views/theme/views-view-summary-unformatted.tpl.php

Which one you have to override depends on the type of summary.


Check this out http://drupal.org/project/facebook_status.
Also if ur on D7 then https://drupal.org/project/statuses


Redirect to an external site when accessing the page of a node meeting a set of condition

I would use hook_node_view.

Remember to check the view mode along with the conditions, so you don't redirect on pages where only the teaser is shown.

It should look something like this:

module_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full' && "Conditions") {
    drupal_goto('http://example.com');
  }
}


ApacheSolr - No Documents or Data in Index

Fixed the problem by reinstalling Solr. I might have missed something along the way the first time.

As for the original issue, I have no idea, but I'm considering this solved.


Autosave module works fine with a multilingual Drupal site.

So I'm assuming that you are working on a single language Drupal site.

In order to make Autosave module work on single language Drupal site, you need to apply this patch file

Edit:

The patch file should be for Autosave 7.x-2.x-dev

Check the actual issue


Views block: select one item from each content type

That is easy. Simply create the most recent item for each content type on a different attachment display, and combine them all into the views block display. That is only way you will be able to achieve that


How to create dynamic contents with view

There are multiple ways to implement this. Either by creating a new content type landing pages and set a specific template file only for this content type (I think this is the most strait forward option), or you can create a view with multiple pages (if you want to work with views) and again create a specific template for the view. Also I think that you could use the panels module and create your landing page with custom layout.


custom display of taxonomy list in views

If I understand well your question, you'd like to add the image associated to a term in your view ?
If so, in the view go to advanced (right sidebar) => Relationships. choose "Content: Taxonomy terms on node", then in "add fiels" you should be able to add any field of your terms, like name, description or image...

To Avoid duplicate output, go to "advanced => Query settings" and check "Distinct".

In case you have duplicate output anyway, you can try this other solution :

Add a content-> Nid field (Exclude from display).

Add a global php field. In output code, write something inspired from that, with your own details.

<?php
$q = "SELECT tid, filename FROM `taxonomy_term_data` INNER JOIN `field_data_field_tags` ";
$q.= "ON `taxonomy_term_data`.tid = `field_data_field_tags`.field_tags_tid ";
$q.= "INNER JOIN `field_data_field_img` ON `taxonomy_term_data`.tid = `field_data_field_img`.entity_id";
$q.= "INNER JOIN `file_managed` ON `file_managed`.fid = `field_data_field_img`.field_img_fid ";
$q.= "WHERE `entity_id` = ".$row -> nid;
$m = db_query($q);
while ($s = $m -> fetchObject()) {
  $img = "path_to_img_folder". $s -> filename;
  $tid = $s -> tid;
  echo "".$img."";
}
?>

You'll have then all your taxonomy images displayed in the same row. You may use the style settings to wrap the output with some classes. You'll have also to go to "advanced => Query settings" and check "Distinct". Hope it helps.


Using taxonomy filter produces duplicate content in node view

Under advanced, click aggregation settings then check Aggregation.  Then click Query Settings and check Distinct.


Lingotek Translation showing interim status for every translation

That happens when the translation is not complete.
This could happen because you have a pending review phase in your workflow.
What happens if you use the "Check target status" operation?

PS: As @user73757 said, it's easier to get support in the Lingotek module issue queue.


Recently, Drush changed the default setting for recoverable errors to abort rather than continue when they are discovered. If this is causing problems, e.g. in an old module, then you can turn it off.

Create a file called drushrc.php, and place it in $HOME/.drush. Add the following contents:

<?php
$options['halt-on-error'] = FALSE;

You should then be able to continue without needing to fix the error in the non-compliant module.


Mark location on Gmap without Click on gmap

The location module already geolocates automatically. Go to admin/config/content/location/geocoding and make sure you have chosen a geolocation service for the counties you need.


How to report about how many users have registered in a given timeframe?

Here are some modules to consider, for anybody who is not able or willing to write some PHP coding to answer such typical reporting question (or anybody who does not want to enable the PHP filter in a site):

The Forena module can be used for such types of reporting. It comes with all sorts of Sample reports and solutions, such as the Site administration reports, which contain data about the actual Drupal site. Here are some details about those reports:

Active Users - A variation of D7's admin/people, including hyperlinks to the Logs for User report.
Active Users Email - A demo of the ability to send email to all active users of a drupal site.
Logs for User - Most recent watchdog log entries for a user (specified as a report parameter).
Role Details - A table displaying all users for a Drupal role (specified as a report parameter), and the Drupal permissions granted to them, with for each user hyperlinks to either view or edit the user's profile.

Cloning these sample reports into custom variations is straight forward. E.g. tune the active users report with some report parameters to only report about user registered this week.
For somebody looking for info related to visitors of a website (registered users is a subset of them, no?), the Visitors module might be a valid alternative to consider also (and/or addition to the above module). Obviously, to submit a registration request one has to "visit" an URL like user/register (or something similar).

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module. Refer to the Visitors community docu for some more details.

Extra reporting features can be enabled via these sub-modules:

The Visitors GeoIP module, to also report about countries and cities.
The Visitors Browscap module, providing statistics on visiting browsers.

Both modules also support charting of those data (a typical related requirement ...)

Disclosure: I'm a (co-)maintainer of Forena, and the maintainer of Visitors.


What is the origin of your CSV file? Are you sure that it is properly encoded using UTF-8? This error is coming from an issue with the database handler trying to process non-UTF8 characters (see: http://drupal.org/node/1140194).

The particular character it is having problems according to your error above is the "&nsbp;" character or 0xC2 and 0xA0, you'' want to convert your file to UTF-8 or alternatively if you have control over what ever is generating your export, strip it out using php following the advice here


Easiest way to expose existing data in secondary database as entities?

Some googling has revealed that the easiest solution is

Declare a new entity
Create a new Controller class for it that knows how/where to apply data operations.
Declare all your metadata as properties as opposed to fields.

I hope I'll be able to expand on this answer once I actually try it out. :)


It seems like all js variables are missing, that are in:

<script type="application/json" data-drupal-selector="drupal-settings-json">{...}</script>

This json array is on every page drupal delivers. You can check this on a fresh drupal install.

There can be a problem with your theme, probably with the html template.


How to log in to site after removing login form

Best bet is to reset the default theme to Bartik or one of the other core themes to log in, then you can fix your mistake there.

Using Drush:

drush vset theme_default bartik

Not using Drush:

Look in your variables table and switch out whatever is currently in theme_default for bartik (ensure that the number following from s: matches the number of letters in the theme name, so Bartik would be 6, Garland would be 7)

UPDATE variable SET value='s:6:"bartik"' WHERE name = 'theme_default';
TRUNCATE cache;

(Modified from Unusable theme - How To reset your theme)


Print the secondary links as expanded in a template file

In your themes template.php add the following:

function THEMENAME_preprocess_page(&$variables) {

  // Get the entire menu tree (you can replace this string with any menu you want)
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Generate structure for rendering the menu.
  $menu = menu_tree_output($tree);

  // Replace the $menu array with the #below array beloning to the first top
  // level menu item.
  $menu = $menu[key($menu)]['#below'];

  // Add $main_menu_no_top as a variable to use in our theme
  $variables['main_menu_no_top'] = $menu;
}

Then, in page.tpl.php, you can just use:

<?php print render($main_menu_no_top); ?>


Custom forms for custom post types in D7

You should use your content type's form, customized to suit the basic user.

You'll have to give the allowed users role the right permission (like `Create the content type').

Then you'll have to change the form to mask all irrelevant information. There are many ways to do this :

Implement a module with a `hook_form_alter'. Flexible but involves coding.
Use a module or a combination to achieve the same goal. This one for example seems to be interesting.


Add Checkboxes to a views listing of titles

It can be done. You have to build a view -> Entity view and pull in your fields.
Then in the form create a field -> Entity Reference -> Check boxes/radio buttons -- under Entity selection -> Views: Filter by an entity reference view -- then pull in the view you created.

Easy Peesy when you figure it out.


I'd just disable the core search module for performance reasons and create a view with Search API views unless you're already using panels and you can integrate a much richer solution, for example the one described in: http://ygerasimov.com/ajaxified-solr-search-drupal-search-api-views-panels


How to structure a "many-to-many" relationship between nodes

You can achieve by these two modules:
Field Collection and Entity Reference,

You can create Field Collection field (unlimited instances) to Product, the collection field (act like a wrapper) contains an Entity Reference field references to Seller, and a price field for that seller.

Some screenshot for you:


How to include js file in a module which depend on jquery?

I actually think it is pretty unlikely that you have a weight problem, unless you redefined your module to have a extremely low weight.  Make sure you have JS optimization turned off, and then do a view source and make sure jQuery is the first script loaded (nearly always is).

My two guesses are

You have a JS error somewhere else, and this is a weird side effect.
You have a JS error in your catalog_menu.js (or another file) that is nuking the $ object by accident.

Also, you should you use an anonymous closure or JS module pattern for code, because Drupa 7 defaults jQuery no-conflict mode.

(function ($, Drupal) {
  function init () {
    $("body").addClass("catalog-menu");
  }

  Drupal.behaviors.catalog_menu = {
    attach: init
  };
}(jQuery, Drupal));


How do I render a form from a controller?

First of all why use a _controller if all you need to do is print a form? Instead it should have _form something like this: Drupal\example\Form\DefaultForm in the routing definition.

Here is a simple guide on how to create a form in drupal 8 https://www.valuebound.com/resources/blog/step-by-step-method-to-create-a-custom-form-in-drupal-8

And if you really want to embed a form in a controller response check this out How do I embed a form in a controller response?


Something like:

$query = db_select('tablename');
$query->fields('tablename', array('field1', 'field2'));
$query->condition('field3', $var1);
$query->condition('field4', $var2);
$query->orderBy('field1', 'DESC');

$result = $query->execute();

foreach($result as $row){
  // Debug
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}

More info:

https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7
https://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3AorderBy/7


You will have to do this in code. Use hook_node_insert() in a custom module and filter by content type. You can then invoke the tumblr API and send the node data across. See tumblr.lib.php for API usage.


Is it possible to change all node assigned on TermA to TermB?

The Views Bulk Operations module can achieve this in one fell swoop.

Build a page view that lists the titles of your nodes and is filtered to nodes of Term A. Add a field "bulk operations" (if on D7) and set it to modify entity values then select your term field that you want to bulk update. You'll then be able to mass update your nodes, and can replace Term A with Term B


Install and enable colorbox module. And add place colorbox library in sites/all/library and rename folder to colorbox

Goto to admin/structure/views
Click edit on your views, here my view name is "Colorbox"

Click on your image field, eg., content:Image

select Formatter as colorbox and click "apply"

Save the view and clear the cache.

Hope it works


Better late than never...

Well the problem is in the Drupal server response, which is not valid json. You need to patch drupal_js function in commons.inc.

diff --git a/includes/common.inc b/includes/common.inc
index 80fc911..084b5fc 100644
--- a/includes/common.inc
+++ b/includes/common.inc
@@ -2551,8 +2551,8 @@ function drupal_to_js($var) {
     case 'resource':
     case 'string':
       return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
-                              array('\r', '\n', '\x3c', '\x3e', '\x26'),
-                              addslashes($var)) .'"';
+                              array('\r', '\n', '\u003c', '\u003e', '\u0026'),
+                              str_replace("\'","'", addslashes($var))) .'"';
     case 'array':
       // Arrays in JSON can't be associative. If the array is empty or if it
       // has sequential whole number keys starting with 0, it's not associative


The $node argument to hook_webform_submission_insert() contains the info you're looking for. For a Webform node, you'll find an array $node->webform->components where, for example, $node->webform->components[2] would correspond to the item whose value is "Chandler Mann" in your data.


How can I render [webform_submission:values] in a table?

You can use the Webform tokens from submitted data as following guide:
[webform_submission:values:?]

Omit the '?' to output all values. Output all values as HTML using [webform_submission:values:html].
To output individual elements, replace the '?' with…

element_key
element_key:format
element_key:raw
element_key:format:items
element_key:delta
element_key:sub_element_key
element_key:delta:sub_element_key
element_key:sub_element_key:format
element_key:delta:sub_element_key:format
element_key:delta:format
element_key:delta:format:html
element_key:entity:*
element_key:delta:entity:*
element_key:delta:entity:field_name:*
element_key:sub_element_key:entity:*
element_key:sub_element_key:entity:field_name:*
element_key:delta:sub_element_key:entity:*
element_key:checked:option_value
element_key:selected:option_value

All items after the 'element_key' are optional.
The 'delta' is the numeric index for specific value
The 'sub_element_key' is a composite element's sub element key.
The 'checked' or 'selected' looks to see if an 'option_value' is checked or selected for an options element (select, checkboxes, or radios)
The 'option_value' is options value for an options element (select, checkboxes, or radios).
The 'format' can be 'value', 'raw', or custom format specifically associated with the element
The 'items' can be 'comma', 'semicolon', 'and', 'ol', 'ul', or custom delimiter
The 'entity:*' applies to the referenced entity
Add 'html' at the end of the token to return HTML markup instead of plain text.

For example, to display the Contact webform's 'Subject' element's value you would use the [webform_submission:values:subject] token.

Then you can use your custom style by adding them into table or list


How can i use DB Connection of another site of my multisite?

You can initialize multiple database connections like this in your settings.php file:

<?php
$databases['default']['default'] = array(
    'database' => 'sitedb1',
    'username' => 'admin',
    'password' => 'admin',
    'prefix' => '',
    'host' => 'localhost',
    'port' => '3306',
    'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
    'driver' => 'mysql',
);

$databases['yellow-site']['default'] = array(
    'database' => 'sitedb2',
    'username' => 'admin',
    'password' => 'admin',
    'prefix' => '',
    'host' => 'localhost',
    'port' => '3306',
    'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
    'driver' => 'mysql',
);

$databases['green-site']['default'] = array(
    'database' => 'sitedb3',
    'username' => 'admin',
    'password' => 'admin',
    'prefix' => '',
    'host' => 'localhost',
    'port' => '3306',
    'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
    'driver' => 'mysql',
);

Then you can get the connections with your module etc.:

<?php
$greenSiteDatabase = Database::getConnection('default', 'green-site');
$yellowSiteDatabase = Database::getConnection('default', 'yellow-site');
$defaultDatabase = Database::getConnection('default', 'default');

You can query a database like so:

$banana = $yellowSiteDatabase->select('SomeTable', 'st')
  ->fields('st', ['fruit'])
  ->condition('fruit', $someCode)
  ->execute()
  ->fetchObject();


It's literally /libraries in your web root, not in a subfolder. This is from the Base-Level Directories section of the Directory Structure docs (which began life here):

  /libraries - All third party external libraries leveraged by Drupal, such as a WYSIWYG editor. This folder is not included by core, but used with many contributed modules.


I think https://www.drupal.org/project/taxonomy_display has the option to render the term in a certain view mode and then render a view below it. You should check it out.


No, you have to turn those features on if you'd like to use them.

Create a group and then in that group go to Settings -> Customize Features, here you can enable the features you need.


ddblock-processed class is added to your div when the Javascript event is attached to it by Drupal. This is normal behavior, but it shouldn't be too hard to override the style with CSS.

To show you a simple example of CSS overrides (even though this is considered an inefficient selector, it doesn't matter too much in cases such as yours):

If on the original style, the CSS is declared as follows:

.ddblock-processed {
  width: 100px;
}

You can easily override it in your own stylesheet by including the "parent" element in the CSS selector. So if ddblock-processed div's parent is a div with an ID of myregion then doing this will override it:

div.ddblock-processed {
  width: 200px;
}

/* OR */

#myregion .ddblock-processed {
  width: 200px;
}

/* OR */

body .ddblock-processed {
  width: 200px;
}

/* OR */

div .ddblock-processed {
  width: 200px;
}

This is called CSS specificity if you want to read up about it.


Using Views to filter the content based on the current month

In the latest versions of Views, you can use a date argument to do this.  For example, you could select the node post date as a date to use with the argument, and then if you passed 2011-12 as the argument, it would limit the display to only nodes posted in December 2011.  You can use any ISO date for this, too, so P1M, which means a period of 1 month, would create an argument for the current month.  Check out http://en.wikipedia.org/wiki/ISO_8601 for an indepth explanation of a lot of different ISO date formats.  All should work here, the only one you have to be careful of is the interval format; with drupal you need to use -- instead of / to separate them for hopefully obvious reasons.

If, however, you are wanting to group or aggregate your content by month, check out http://drupal.org/node/388140.


how to filter blog posts by taxonomy and by year

You're on the right track. Views is good way to solve this with Contextual Filters. You need to create a page view with the path blog. That will create a page example.com/blog that shows all blog posts.

Adding a Content: Created year contextual filter will set up a filter rule so that example.com/blog/XXXX filter the view by posts created on year XXXX.

For your last need, tag filtering, you're going to need to add another page view since a page view can't do a mixed contextual filtering; views doesn't know how to treat XXXX in example.com/blog/XXXX as both a year or tag.

See this post on how to set up a filter Content: Has taxonomy term ID filter that will you create something like example.com/tags/YYYY where YYYY is the name of your tag.


Is there a way to execte jquery event after ajax callback has been completed?

You can use custom ajax commands for this. Ajax commands are php classes that correspond to a JS function on the server, which the Drupal JS API calls after Ajax responses.

At a quick lookover, this tutorial looks like it gives a good overview on how to create a custom Ajax command in Drupal 8.


Unable to perform update when adding new menu field

Just update entities it will work: run the command drush entity-updates.
No need for hook_update_N.
You can add hook_install to update entities automatically when you install your module don't need to do it by command each time or get the error on every installation .

/**
 * Implements hook_install().
 */
function my_module_install() {
  \Drupal::service('entity.definition_update_manager')->applyUpdates();
}


Multiple webforms: Show list of those user has submitted?

If you are using Drupal 6.Try this view export code

$view = new view;
$view->name = 'test_webform';
$view->description = '';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'webform_submissions';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('relationships', array(
  'nid' => array(
    'id' => 'nid',
    'table' => 'webform_submissions',
    'field' => 'nid',
  ),
  'uid' => array(
    'id' => 'uid',
    'table' => 'webform_submissions',
    'field' => 'uid',
  ),
));
$handler->override_option('fields', array(
  'title' => array(
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'relationship' => 'nid',
  ),
));
$handler->override_option('filters', array(
  'uid_current' => array(
    'id' => 'uid_current',
    'table' => 'users',
    'field' => 'uid_current',
    'relationship' => 'nid',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->override_option('relationships', array(
  'nid' => array(
    'label' => 'Node',
    'required' => 0,
    'id' => 'nid',
    'table' => 'webform_submissions',
    'field' => 'nid',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
  'uid' => array(
    'label' => 'User',
    'required' => 1,
    'id' => 'uid',
    'table' => 'webform_submissions',
    'field' => 'uid',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('fields', array(
  'title' => array(
    'label' => 'Title',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'exclude' => 0,
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'relationship' => 'nid',
    'override' => array(
      'button' => 'Use default',
    ),
  ),
  'submitted' => array(
    'label' => 'Submitted',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'submitted',
    'table' => 'webform_submissions',
    'field' => 'submitted',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
  'sid' => array(
    'label' => 'Sid',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'set_precision' => FALSE,
    'precision' => 0,
    'decimal' => '.',
    'separator' => ',',
    'prefix' => '',
    'suffix' => '',
    'exclude' => 0,
    'id' => 'sid',
    'table' => 'webform_submissions',
    'field' => 'sid',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('filters', array(
  'uid_current' => array(
    'operator' => '=',
    'value' => '1',
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'uid_current',
    'table' => 'users',
    'field' => 'uid_current',
    'relationship' => 'uid',
    'override' => array(
      'button' => 'Use default',
    ),
  ),
));
$handler->override_option('block_description', '');
$handler->override_option('block_caching', -1);


What is right way to modify a node field in a multilanguage system (LANGUAGE_NONE or $node->language or ...)

field_language() returns the field's display language. You should use code similar to the following one:

$language = field_language('node', $node, 'body');
do_something_with($node->body[$language][0]);

Of course, note that field_language() will determine the right display language ('en' or LANGUAGE_NONE or whatever); if you're modifying fields you might want to modify more than one language.


How to use Rules to send an email after a user submits a first node and grant a new role after 5 nodes?

This can be implemented perfectly by using the Goals module (disclosure: I'm its maintainer), as further detailed below.

Part 1 - Configure 2 goals

You'd start by configuring the appropriate set of Goals and related Tasks. For a basic introduction about Goals, have a look at:

How to implement gamification in a Drupal site and award incentives?
Its video tutorial.

Here is what it would take:

Goal1 = "New user", with only 1 Task = "Save 1 node" (say with machine name = save_a_node).
Goal2 = "Mature user", with Task = "Save 5 nodes".

Part 2 - Create a rule to record progress on the tasks

Create a rule using Rules Event "After saving new content". The purpose of this rule is to make Goals automatically track the progress on completing the tasks (which you can do via an appropriate Rules Action to record that progress).

The interesting part of this is that you can reuse the same rule (related to that machine name = save_a_node) to keep track of the progress of any user to become a New/Mature customer (check the video for a similar sample).

Part 3 - Trigger your rules after a goal is achieved

Together with what is above, you should write these 2 rules to implement what your question is actually about:

a rule with these specs:

Rules Event: "After a user completed Goal1"
Rules Action: "Send an eMail"

a rule with these specs:

Rules Event: "After a user completed Goal2".
Rules Action: "Assign role to user".


Unnecessary showing admin content in main theme

If you use customError module, make sure you your theme dropdown setting is set to "Default theme" in yoursite.com/admin/config/system/customerror.


How to override core taxonomy/term/% with a view?

The Taxonomy views integrator module can help you; it allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice.


How to create authentication token in the HTTP header request for Json view

views_datasource uses the standard drupal session to authenticate.

First set the permissions on the view to what you want. And test this in the browser.

then you can go onto your user authentication.
Im assuming that you're using ajax to call the view, in a headless mode ?

then you've got 2 options

1) Make the users log into the Drupal site somehow first - that will then give them a session , and when they call that ajax request, the session will be sent.

2) Authenticate the user from your code - you can do this with the services module. you can follow this post https://www.drupal.org/node/910598 for more information


While I still don't know where the problem is (it should work this way) I've found a solution.

Instead returning the whole $page_array in callback function and hoping that Drupal will understand it and replace the div specified in '#ajax' => array('wrapper' => 'TSTDiv',... property of the link with it you can simply use ajax commands and 'return' something like this:

$commands[] = ajax_command_replace('#TSTDiv', render($page_array));
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

And vuala it works just fine (and looks more professional at the same time!).

Would still appreciate and answer why the original approach didn't work, though.

BTW: I didn't know the AJAX commands before.


What are the URLs for devel generated images in CCK fields?

Drupal uses the file_create_url() function for this:

  Creates a web-accessible URL for a stream to an external or local file.

Code example:

$url = file_create_url($field_name['und'][0]['uri']);


Making fields, condition and join dynamic in db_select query

Don't chain your query, just put in some ifs and add to the query.  Like so

$query = db_select('node', 'n');
if(isset($field)) {
  // Add each field separate
  $query->addField('n', 'title', 'title');
}

if(isset($article)) {
  $query->condition('n.node-type', 'article', '=');
}

if(isset($join)) {
  $query->join()....
}

$query->execute();

I think this will get you to where you want.  Please also see this thread: http://drupal.org/node/310075


How can we achieve multiple forms in a single page?

You can do it!
With the drupal fapi. You can overload every HTML attributes by using the element #attributes.
Exemple:

  $form['form_element'] = array(
    '#type' => 'textfield',
    '#title' => t('If you Have a Code, Redeem it here:'),
    '#attributes' => array(
      'id' => 'your_id',
    ),
  );

If you add a counter or something to your id, you will have a different id for each fields.
Cheers


Schedule a rule to repeat every week at specific time not working

Make sure you're running cron on demand to force your process to run every those 2 minutes, the way rules scheduler works is to create a hook_cron process that checks the dates:

function rules_scheduler_cron() {
  // Limit adding tasks to 1000 per cron run.
  $result = db_select('rules_scheduler', 'r', array('fetch' => PDO::FETCH_ASSOC))
    ->fields('r')
    ->condition('date', time(), '<=')
    ->range(0, 1000)
    ->execute();

  $queue = DrupalQueue::get('rules_scheduler_tasks');
  foreach ($result as $task) {
    // Add the task to the queue and remove the entry afterwards.
    if ($queue->createItem($task)) {
      db_delete('rules_scheduler')
        ->condition('tid', $task['tid'])
        ->execute();
      $task_created = TRUE;
    }
  }

  if (!empty($task_created)) {
    // hook_exit() is not invoked for cron runs, so register it as shutdown
    // callback for logging the rules log to the watchdog.
    drupal_register_shutdown_function('rules_exit');
    // Clear the log before running tasks via the queue to avoid logging
    // unrelated logs from previous cron-operations.
    RulesLog::logger()->clear();
  }
}


Are there any module options or techniques to authenticate through OpenAM on Drupal 8?

Yes. Port OpenAM to Drupal 8 yourself.

Alternatively, create a new issue and wait until maybe someone else ported it.


hook_views_query_alter if date field empty sort with another field postdate

The solution that comes to my mind now (after your question's comments) is make two queries, one query with the records that have publish_on field empty and the other with the field non empty and then use a UNION between them.

Why this? AFAIK You can't sort some records in a query based in a condition and other records based in another condition, so to achieve this you must split the records and apply the sort method separately. This is records of a condition first and records of another condition before, but you can't merge the records and the order condition.

Maybe this posts can help you:

https://stackoverflow.com/q/2258376/3653989

https://stackoverflow.com/q/19296047/3653989

https://stackoverflow.com/q/3730093/3653989

Maybe you also want to read http://www.w3schools.com/sql/sql_union.asp


How to add an existing field to an user account?

You have to use "Add new field" until you haven't used your term reference field for the Departements at least once before.

If have created this field once, you can reuse it for other content types.


How can I check to see if the current user has an an order in checkout?

Preload $user variable.
Remove those / at the end of each url.
Add a semicolon at the end of each PHP line.

global $user;
if ($order = commerce_cart_order_load($user->uid)) {
  drupal_goto('checkout');
}
else {
  drupal_goto('someotherpage');
}


Ctools content types- What do I need to do to get my content to render in the right place?

From the top of my head you should simply be able to do:

$pane = new stdClass();
$pane->title = 'Check this out!'; // Optional
$pane->content = '
My content
';
return $pane;

It's also worthwhile to review What are Ctools plugin (content type, access, etc), and how does one create them? which contains an example content type.

The question
Correct way to render a modules output through a template? shows an example of rendering through a template, so you can strip the markup out from your pane and have it contain only the relevant content.


Add conditional where condition to hook_views_query_alter()

You can achieve this using switch-case or if-else in mymodule_views_query_alter.

function mymodule_views_query_alter(&$view, &$query) {
  //Get your variable $scope here
  switch($scope) {
    case 'G':
      $query->add_where_expression(0, "$variable = :placeholder", array(':placeholder' => 'value');
      break;
    case 'L':
      $query->add_where_expression(0, "$another_variable = :another_placeholder", array(':another_placeholder' => 'another_value');
      break;
  }
}

Hope this helps.


You could do the following.

Add the title node with link.
Filter it with Content Type A B and C (Which all content types you want to display.
Add the reference field in Content Type A B and C
Group by the Reference Field.


Profile image goes over the text on advance forum in drupal 7

It might not be exactly the answer you're looking for, but using CSS only, you can add this rule to your theme's main css file:

img{
max-width: 100%;
}


cache keys $cid naming practices (cache_set and cache_get)

is ':' the recommended delimiter? I haven't heard that : is recommended over anything else, but since it's definitely used all over core, it would make a lot of sense. All cache backends that work with Drupal will be handling : well.
should the module name go first? (seems sensible)?
Yes, this is general practice, not just cache keys.
are there characters to avoid?
None that I've heard of. In general, in 2013, if any system doesn't properly handle any character in a string properly, I would find really bad to be honest. With that said, we'll always be dealing with one form or another of legacy software. So stick to a-z, numbers and : if you're feeling risk averse.
are there other considerations?
Can't immediately think of any.


Change the way "add content" and "node's" are displayed

page--node--[content-type].tpl.php = node template for a specific content type (no square brackets)

page--node--add--[content-type].tpl.php = node/add template for specific content type.

Copy/paste the code you have in node.tpl.php and clear your server cache. Now you can add custom classes everywhere or even create a custom HTML structure to render your fields. See the node.tpl.php documentation and Drupal 7 template suggestions.

Hope this helps!


I would use jQuery to detect the button click on the submit button and then force the action of closing the lightbox with parent.Lightbox.end();.

The reason I would use jQuery to attach to the event is that you don't have to alter the webform in any way, and can do this passively.


Send custom data to endpoint based on checkbox value via webforms POST handler

You could use a Computed Twig element to execute the ternary operator and set the value in the remote post data.

@see https://www.youtube.com/watch?v=rRlTTkwdP_o


The values for comment_body is not stored in $form_state but in something like:

$form_state['values']['comment_body']['und'][0]['value']

function banana($form, &$form_state) {
  if ($form_state['values']['comment_body']['und'][0]['value'] == "example") {
    form_set_error('comment_body', 'Your comment can not contain example!');
  }
}


How to add/remove a permission from a user role to a particular user without modifiying the user role?

You can't do that, at least with standard Drupal setup. Probably you can code a hack that allows it, but is not how Drupal is designed.
Besides this, you can use current role system to achieve what you want. You only need to add more roles. You want edit own articles, view own articles and delete own articles to be independent. You can define 3 roles, and assign to users as you need.
If your problem is you'd have lots of roles (because you want lot of different permissions to be independent) you may use Content Access along with ACL:

This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.
[...]
It tries to reuse existing functionality instead of reimplementing it. So one can install the ACL module and set per user access control settings per content node.

Alternatively, you can code your own access system implementing a combination of hook_entity_access, hook_node_access and hook_query_TAG_alter.
You can have a full explanation of how node access rights works on this documentation page: https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/group/node_access/8.8.x

Next, all implementations of hook_node_access() will be called. Each implementation may explicitly allow, explicitly forbid, or ignore the access request. If at least one module says to forbid the request, it will be rejected. If no modules deny the request and at least one says to allow it, the request will be permitted.


How do I override the taxonomy default content?

This information is added in taxonomy_term_page(). As you can see there, the page callback returns a renderable array, which means that you can easily replace it in a custom module by implementing hook_page_alter().

In that hook, check that you are on a taxonomy term page, look if the 'no_content' block exists, and if yes, override the #markup.

I suggest to use dpm() from devel.module to print $page so that you can more easily figure out  where exactly the page content is in that huge render array. Somewhere in system_main, if I remember correctly.


How to set ajax event to onkeypress event?

See this link.

You can specify any valid jQuery event.

So, you need to change 'onkeypress' to 'keypress'.


How to proceed after update.php fails due to memory limit?

Short Answer
You can't. Though comment F0ns's comment is a good start, depending on your PHP skills you may find this frustrating to impossible.
Long Answer
I am not sure that the easiest resolution is to deal with the (possible) problem after the event.
I would not normally suggest this as an answer except that you begin your question with 'Sometimes', implying that this a is a workflow consideration rather than a specific bugfix.
You should consider your upgrade process in general. Ideally you would put the site into maintenance mode if you absolutely must perform the upgrades on a live site, so there would be no changes to the site during the process. You should always take a database backup before performing core or contrib updates, and this is made easy using backup_migrate module. If you are updating core backup the files as well (if it is contrib simpler to just download previous version)
As long as you know which updates you are applying (I do not recommend applying many at the same time), and what version of core/module you are upgrading from, then you can now easily return to your pre-upgrade state by overwriting the db and files, rather than trying to pick apart potential problems caused by a failed upgrade.
Depending on the usage of your site, it might be preferable preferable to limit administrative access to the site temporarily (or put it into maintenance mode), perform updates on a local clone of the site, and overwrite the live version with the tested, working local version, restoring administrative access.


How do I separate custom template from the administration theme?

You can sniff the user's role and/or permissions and then conditionally change the template.

You can test permissions with user_access('view the administration theme') and depending on the result, assign your custom template.


you can try views distinct module
from module page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

I hope it helps, be carefull in features, the module settings are not exported in features. If you use features, once you push your code, on production site, set your view UI settings again, it's easy and simple.


Performance is very subjective and varies widely from site to site, depending on how much custom code you have, how many logins you have, and what your expected usage patterns are.

The first thing you should do is figure out what your expected usage patterns are going to be, put them in a spreadsheet and estimate how many concurrent visitors you'll have on various pages, etc (for example, how many logins will happen at one time, which pages have the highest traffic, are your users authenticated or not).

The second thing you should do is prepare some kind of load test using something like LoadStorm, or even something very basic like JMeter. Set up some scenarios that mimic or exceed your expected traffic patterns. Then run the tests.

When you start load testing you will very quickly see where the bottlenecks in your site are. You can take cachegrind dumps of your site while you are load testing to see where the performance bottlenecks are using the XDebug profiler. You can also watch your database performance (CPU/memory and disk I/O are easy things to keep an eye on).

Once you've done all that, you can look into the following:

PHP opcode caching to speed up your web server
A reverse proxy like Varnish to take some of the load off
Setting up memcached to take load off of the database
Tuning the database
Setting up load balancing with multiple instances

Drupal has a decent listing of caching modules/options and how they perform for authenticated and unauthenticated users here.


Passing the actual path in File Save Data

The issue was that the script was running from a subdirectory. Calling chdir(DRUPAL_ROOT) before file_save_data() fixed it.


How to re position the breadcrumb on the product detail page?

I figured this issue out, I had to look into the Block configuration and adjust the region.


Unable to get through to the custom form using hook_menu page callback?

Sanity checks first:

Make sure you're returning $items from hook_menu()
Make sure you've cleared the caches since making changes to code in hook_menu()
You probably don't mean to have two spaces between the first two words in your permission string.
Make sure there's a node with an ID of 18 in the system; if not the %node load argument will fail and you'll get a 404.

The only other problem (but not one that would causes a 404) is the signature for your form function; it should be

function heart_form($form, &$form_state, $node) {


In D7 how do I get JUST the value of a field in a view field template?

If you have devel installed then add dpm($field); to the template and see if the field array contains the value itself (if I remember right - it isn't). The second step (if the field array doesn't contain the value) will be to use dpm($view); ,and in the view array you have the value for sure (I think it is something like $view->$row['field_name'][0]['value'] )


SCORM (v 1.2) integration for Quiz module

Have a look at the Opigno LMS distribution, which is fully compliant with SCORM 2004 v3. Here is a quote from its project page:

Opigno LMS is a full-fledged Learning Management System based on Drupal.
It allows to:

Manage training paths organized in courses and lessons.
Assess students thanks to varied quizzes.
Award certificates to successful students.
Sell your trainings online.
Facilitate interactions thanks to live meetings, forums and chats.
...

Maybe not to start "using" this distribution, but by reviewing it to get an idea about it's SCORM compliance, and then copy-an-paste whatever fits / makes sense to also include in your own site.
Contributed module SCO Node somehow relates to SCORM and might potentially be of some help to get you going (quote is from its project page):

The SCO Node module allows nodes to be created that contain SCORM content. The SCO content can then be played and scored on a Drupal 7 site.
The module currently supports SCORM 1.2 and some of SCORM 2004


That's exactly what drupal-project does. Your index.php should be at projectfolder/web/index.php.

Personally, I like this approach because it provides one directory level above your site root. This makes a good, secure place for files (settings, private file system) that should never be served directly by your web server.

The drupal-project composer template uses this level above your  site root to install composer dependencies and tools like Drush and DrupalConsole. That's nice because when you bundle these tools with the project (instead of using a globally installed Drush for instance), you can always be sure that your colleagues are using the exact same version.


Get text_long field value with EntityMetadataWrapper

Since the long text field is an array in the entity Metadata wrapper (due to fact that long text fields can have an input format applied to them),  you should decode the text.

See the Drupal.org entity Metadata documentation and search for the example
$wrapper->body->value->value(array('decode' => TRUE));
Also, check out this similar post about handling the formatting of long text fields when extracting with entity Metadata wrappers


Use dropdown in views exposed filter on text fields with entity not node?

Think I found a solution at last. It works in my local test environment for the exposed filters in views:

function dd_city_form_views_exposed_form_alter(&$form, &$form_state) {
  $field_id = 'field_selected_field';

  // Only alter forms with the necessary field
  if (isset($form[$field_id .'_value'])) {
    // Build a query to get all node ids having the specified field
    $query = new EntityFieldQuery();
    $results = $query->entityCondition('entity_type', 'model')
                      ->fieldCondition($field_id, 'value', 'NULL', '!=')
                      ->fieldOrderBy($field_id, 'value', 'ASC')
                      ->execute();

    // Attach the field values to the nodes
    $entities = $results['model'];
    field_attach_load('model', $entities, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

    // Add a default so the filter is optional
    $options = array('' => '<select>');

    // Buld the options array based on the query results, overwriting duplicate entries
    foreach($entities as $id => $entity) {
      $value = $entity->{$field_id}['und'][0]['value'];
      $options[$value] = $value;
   }

    // Alter the field
    $form[$field_id .'_value']['#type'] = 'select';
    $form[$field_id .'_value']['#options'] = $options;
    $form[$field_id .'_value']['#size'] = 1;
  }
}

I only had to change a tiny bit more, than I posted before.
Summary for the above code:

Rename 'field_selected_field' to your field. Example: If it is called 'city',
then rename it to 'field_city'.
Change 'model' to the name of your entity. In your case 'site_object'
These are the places:

$results = $query->entityCondition('entity_type', 'model')
$entities = $results['model'];
field_attach_load('model', $entities, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

Save the file to your module, upload it and enable it in Drupal.

A few screenshots of my test environment:

Here my example configuration for a view with an entity named 'model' with the field 'selected_field'.

If you go to the respective view (in my case /modeltestview), you get the following (the screenshot is only part of the screen). The left part is the starting part,you get the right part if you click on the dropdown list. To show there actually is something in the dropdown list.


How do I remove variables from the variable table when my module uninstalls?

Keep track of your variables and add appropriate variable_del() calls within an implementation of hook_uninstall():

function foo_uninstall() {
  variable_del('foo_variable1');
  variable_del('foo_variable2');
}

As hook_uninstall() is an installation hook, it needs to reside in your module's .install file (e.g. foo.install).

You ought not to delete all variables prefixed with your module's name as namespace collisions will come back to bite you. For example, if your module's name is foo, you might think you should just poll the variables table for all variables prefixed foo_. But what if I write a module named foo_awesome? You'd delete my variables, too. That wouldn't be nice.


How to show text fields from a User object to anonymous users without "View User Profile" permission?

Conversely, how I can prevent anyone from getting to user/* pages?

Getting technical here, you wouldn't want to block all /user/*; otherwise, you wouldn't be able to /user/login or /user/logout and also you would still want admins to access those /user/{uid} pages.

If  you inspect core/modules/user/user.routing.yml you can see most of the user routes. But what you expect, the /user/{uid} is not defined here.

It's actually defined in UserRouteProvider.php as /user/{user}

You can easily find the route name by enabling WebProfiler module that comes with Devel and  going to /user/1

Now all you gotta do is override the route's access by giving it a role of administrator.

mymodule/src/Routing/RouteSubscriber.php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Allow only admins to access '/user/{user}'.
    if ($route = $collection->get('entity.user.canonical')) {
        $route->setRequirement('_role', 'administrator');
    }
  }

}

Alternatively, in your custom module, you could create a new permission and use that for the Route's setRequirement instead and then assign the new permission to the roles that you want to have access.

mymodule/example.services.yml

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

For more in depth information about altering routes, see: Altering existing routes and adding new routes based on dynamic ones.


How do I add an external JavaScript file using a custom module?

Firstly drupal_add_js() removed in Drupal 8, check here.

So create library in your module folder as MODULE_NAME.libraries.yml and in this file if you want to add external js add code like below.

external:
  version: 1.0
  header: true
  js:
      https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js: {type: external, minified: true}

and in any of your module/Form/Controller you can call above library using "#attached"

  $build['#attached']['library'][] = 'MODULE_NAME/external';


The question how to put a custom field in the user tab is already answered, btw you don't need '#type', when using '#markup' in drupal 8.

As you said at the end, this is a caching issue. In general it is not a good idea to put the time in the html of every page, you better do this in javascript. If you don't care about performance, then you can disable the cache:

$build['#cache']['max-age'] = 0;

This does not work for anonymous users, because in drupal 8 there is also the page cache enabled by default. If you deliver a different page on every request, you don't need this module and you can uninstall it.

If you want to disable it only for the user default tab, then use this command:

\Drupal::service('page_cache_kill_switch')->trigger();


Where do I find the settings for adding a vocabulary to a content type in Drupal 7?

Head over to the Manage fields tab of your content type. For example, for "article" that would be admin/structure/types/manage/article/fields. Then add a Term Reference field.

This question is about Drupal 7, but be aware that Term Reference appears to be deprecated and potentially be removed from Drupal 8 (in favor of the entity reference field). For more details on that, refer to the question about "Are there any benefits/caveats with using Entity Reference over Term Reference?", in which there is a comment also like "Term reference isn't going anywhere and there will be an upgrade path from 7 to 8".


Modify apachesolr's 'did you mean?' suggestions to provide better alternatives

I found setting:
<str name="spellcheck.onlyMorePopular">false</str>

(instead of true) in solrconfig.xml dramatically improved the quality of the spelling suggestions.


webform telephone field validation fails

The international phone number element is only a client-side enhancement which is using the International Telephone Input library.

To validate the phone number via server-side validation you would need write custom code and to use a PHP library like https://github.com/giggsey/libphonenumber-for-php


It turns out that if you use the IP of your host machine, if you're hosting Solr and the Site on the same box, you can't use the IP of the box to connect.  In my case, I was trying xx.xx.xx.xx:8983/solr/my_core which was failing.

After changing the address to http://127.0.0.1:8983/solr/my_core I am finally connected.


How to programmatically trigger a click on an AJAX enabled form submit button?

jQuery('#edit-submit').mousedown() - apparently there's a big difference.


Adding items to another Modules Admin form

For the sake of clarity, let's say that your custom module is named CUSTOMMODULE, and the one you want to alter is ALTERTHIS.

You can use hook_form_FORM_ID_alter() like this:

/**
 * Implements hook_form_FORM_ID_alter() for ALTERTHIS_admin_form().
 */
function CUSTOMMODULE_form_ALTERTHIS_admin_form_alter(&$form, &$form_state, $form_id) {
  // Alter the $form here.
}


Drupal 6 - emfield is blank when logged out

I'd check that permissions are actually set to view this field.  If you go to admin/user/permissions you can see these as well as all permissions set on your site.


That data selection interface often has jQuery Update-related issues; for the most part those should be solved by using the dev version (at the time of this answer) of jQuery Update and the current stable of Rules (7.x-2.7) as recommended by https://www.drupal.org/node/1810656#comment-9298435. That issue also has a good history of these problems.

Another issue appears to describe your exact issue and has a patch. It sounds like that resolved the problem, so future visitors might try that as well after seeing if updating jQuery Update doesn't work.


The best way to list persons information

Stick with 1: In your view at the top where it says Access: Permissions. Click on permission and change that to Role; in FILTER, add a filter of Role.


How do I chose recipient email address depending on textfield value?

The first solution that comes to my mind will be using hook_form_alter.
and take the value of the field.
Based on the value, send the mail to appropriate address.

But most likely there will be a module for that.
Meanwhile..

http://agileadam.com/webform-mail-alter
can be of service

Regards

Oleg


need to replace default drupal user picture with an image field from user profile

how to render the image???

Sounds like you're probably looking for image_style_url(). Assuming you have an image preset called thumbnail, try something like this:

$picture_style = 'thumbnail';
$picture_uri = $account->field_profile_picture['und'][0]['uri'];
$variables['user_picture'] = image_style_url($picture_style, $picture_uri);


Drupal Apache Solr How to process all the results and not only 10?

You can both preprocess, https://api.drupal.org/api/drupal/modules!search!search.pages.inc/function/template_preprocess_search_results/7 and https://api.drupal.org/api/drupal/modules%21search%21search.pages.inc/function/template_preprocess_search_result/7, and theme search results (even with solr), with search-results.tpl.php and search-result.tpl.php


How can I assign values to radio buttons with the forms api?

The keys of the array set as #options determine the values and the values determine the labels.

In other words: The example in my question uses a regular array array(t('M'), t('F')) which, behind the scenes, is an associative array using non-negative integers as keys (same as array(0=>t('M'), 1=>t('F')). Since the radio buttons use these keys to know what to store in the database, the solution is simply to change them: array('M'=>t('M'), 'F'=>t('F')).


How to efficiently divide entities into groups based on field values

As it turns out implementing the Search API Saved Searches modules is pretty much as easy as turning it on and it works great... No great insights here, just an excellent module.

It allows you to save searches with full facet information (i.e. filter search with 4 different facets and then save that.)


Conditional checkbox fields if checked show a related textfield

If you need to show a field when something gets checkked, you could just use JS to display a hidden field.

My approach would be to make custom table form that has the required input field as hidden. Then add javascript event listener to checkboxes that show the input at that row.

Then just do the normal validation and submit callbacks to update entities based on rows which are checked.


all internal links won't work in a local-wamp site even after .HTaccess and mod_rewrite setup

For the 404 errors on any internal links, have you edited the /rewritebase in htaccess? If the site now resides in a file, or in the root, this may need commenting out, or enabling.

As for the error. Are you certain you copied all files correctly?

Also, are you certain your mySql was dumped correctly?

Steps to try and fix can be...

Move files again.
Try dropping and reimporting the database.
Running registry rebuild. Note: this is not a module, this is something you can run with drush, or by placing the php in your directory and accessing it.
Try following this guys comment https://www.drupal.org/node/1323786#comment-5305922


How to override output (query) for views exposed filter?

It depends on what exactly you want to accomplish, some commonly used hooks are:

hook_views_query_alter
hook_views_pre_render
hook_views_pre_view
There plenty of hooks to programmatically affect the results in the Views API

Also there are plenty of Views Plugins like the Row Plugins


How to fire a Rule when an image is removed from Image field with unlimited values?

To my knowledge there is no Rules Event like the one you are looking for. However, as illustrated in my answer to the question you linked to, you can use an approach like so:

iterate over all field values of your field of the unchanged node.
within each iteration step, check if the list of items in the changed node does NOT contain the field value being processed in the current iteration step ... If it is NOT contained in it anymore, it means  the values is removed.

Note: processing image fields in Rules is a bit special. You may have to use a token like [node:field-pictures:file:url] and [list-item:file:url]. And if they appear to be empty, then retry by adding a Rules Condition like "content is of type = article"


Change drupal admin password for 100 sites using drush

Recover password with Drush

Drush offers several ways of recovering the administrator's password.
Generate login-link

Drush can generate a one-time login link.

drush uli

Reset password

drush upwd --password="givememypasswordback" admin

(where "admin" is the user name)

For more info visit here


Altering Views Exposed Form Elements and their Associated Labels

Should add #attributes to your element form so the form alter should be like:

function HOOK_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $form['name_of_element']['#attributes']['twig-suggestion'] = $form['#id'];
}

HOOK_theme_suggestions_input_alter will works only with input elements textfield.


Drush installed globally via composer as root user, but how to access Drush with ordinary user?

To install for all users on the server:

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
ln -s /usr/local/bin/composer /usr/bin/composer

git clone https://github.com/drush-ops/drush.git /usr/local/src/drush
cd /usr/local/src/drush
git checkout 7.0.0-alpha5  #or whatever version you want.
ln -s /usr/local/src/drush/drush /usr/bin/drush
composer install
drush --version

Personally I don't bother making the composer symlink from /usr/local/bin to /usr/bin and made the drush symlink to /usr/local/bin (rather than /usr/bin) as I have /usr/local/bin in my $PATH but YMMV...

Source: http://docs.drush.org/en/master/install/


HTML Form that Passes Information to Hidden Fields Through URL

You need to write a multistep form with the Form API and CTools.

The Form API allows you to write forms: See Creating a builder function to generate a form.

Because your form is multistep you need CTools to implement it, and handles issues like carry those values over the different steps.

This two subjects are too broad to explian in an answer, but there's lot of documentation about them.


Create a view page and add a menu item entry: "Default menu tab" to "Menu tab" and select "User Menu" in dropdown in your view.


ajax form, send data from js modal to form

I have worked on a similar case in D7.
Take a look at these tutorials.
https://www.deeson.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7
http://internetdevels.com/blog/big-manual-for-creating-ctools-popups-in-drupal-7


Search engines tries to access node editing links

One possibility is that one or more logged-in users have Google Toolbar or something similar installed. I don't have it installed any more because I noticed when developing locally that every time I fetched a page in my browser the request was repeated by the toolbar, presumably sending it to Google.

In my experience there is no such thing as a non-public URL as far as Google is concerned. Any URL can be listed for indexing and so crawlers may attempt to fetch it from time to time. I suspect other tools may record URLs in a similar manner.


What is the value returned by theme_get_registry, and why is it not NULL?

The value returned from theme_get_registry() is initialized by _theme_set_registry(), which is called by _theme_load_registry(), which is called by _init_theme(), called by init_theme().

function _theme_set_registry($registry) {
  // Pass through for setting of static variable.
  return theme_get_registry($registry);
}

init_theme() is called from theme(), right before calling theme_get_registry().

  $args = func_get_args();
  $hook = array_shift($args);

  static $hooks = NULL;
  if (!isset($hooks)) {
    init_theme();
    $hooks = theme_get_registry();
  }

The value used by theme_get_registry() ($theme_registry) is a static value; this means that the value theme_get_registry() gets from _theme_set_registry() is then returned all the times theme_get_registry() is called. NULL is the default value for $theme_registry, until $theme_registry = $registry is executed, and the calling function uses a value different from the default one.

To notice that the declaration of a static variable is different from the declaration of other local variables used by a function.

If I declare a variable as static $registry = NULL it doesn't mean the variable is always set to NULL. The constant value used in the declaration is the value assigned to the variable when it is initialized; the second time the function is called, its static variables are not initialized anymore, but they retain the value they had in the previous call of the function.
As reported in Variable scope:

function test() {
  $a = 0;
  echo $a;
  $a++;
}

  This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

function test() {
  static $a = 0;
  echo $a;
  $a++;
}

  Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.


Request body to post a new comment using REST API

I've solved it by these below

{
    "entity_id": [{
        "target_id": 612
    }],
    "entity_type": [{
        "value": "node"
    }],
    "comment_type": [{
        "target_id": "discussion"
    }],
    "field_name": [{
        "value": "discussion_comments"
    }],
    "subject": [{
        "value": "Goodbye World"
    }],
    "comment_body": [{
        "value": "comment which you want write"
    }]
}


Views contextually filtered by terms in paragraphs

Although there are multiple ways of doing this, here is probably one of the better ways if editor/front-end control is what you are after. These days, paragraphs are pretty commonly used to give easier control to editors.

It will be setup a little differently however.

First, install and enable the block_field module. This will
create a new type of reference field. We will use this later on.
Create a new View, choose Block display. Choose the Article bundle
for your content. Add some fields from Article that you want to see.
Add a new basic filter criteria for the category term reference
field. Set its default value to Sports.
You should now have a view showing all articles where the category
contains sports. Now duplicate this sports block, make another block
for politics, and so on. Changing the filter criteria to match each
term.

Your view should have a few blocks in it now. One for each term. Now
go edit your Multi Article Paragraph type.
Delete your term reference field from the paragraph, and add a new
field. Under references you will see a Block (plugin) now. Choose
that. Name it whatever, set to unlimited.

On your new field, at the very bottom, drop down the Blocks
fieldset. By default every block will be checked, uncheck them.
Scroll down until you see your 3 view blocks you made. Check each of
them. Then save the field.

Now go create a new landing page as if you are an editor. Your Multi
Article paragraph will have a block reference. Choose add block, and
pick one of the view blocks. Add a paragraph item for each view
block    you want to display.

You can then make many landing pages, allowing the editor to choose which types of articles to display. Here is my landing page A.


else condition does not work in my code in twig template

You need to check if variable is defined (defined in twig) and additionally also check the length of variable in twig.

{% if content.field_image_link[0]['#url'] is defined and content.field_image_link[0]['#url'] | length > 0 %}
    //do stuff
{% else %}
    //do another stuff
{% endif %}


This is how I have gotten this working:

First thing you need to do is install the References module
Update your Place content type:

Rather than add a Destination term reference field, you should create a Destination node reference field.

Configure your view.

Under Format > Settings, select Grouping Field Nr. 1 as Content: Places (or whatever you called your places term reference field).
Assuming you have no relationships added, create a Relationship on Content: destination (field_destination) (or whatever you called your node reference field).
Save your relationship.
Assuming you have no contextual filters added, create a Contextual Filter on Content: Nid.
Select the relationship on field_destination (or whatever you called your node reference field).
Select Provide default value with a Type of Content ID from URL.
Save your filter.
Save your view.

Configure View Block

Go to Structure > Blocks
Configure your View Block
Add to region and set Content-Type to Destination.
Save the block.

Now if you go to one of your destination pages, you will see a list of places grouped by place type.


Getting 443 Forbidden Error on my custom module

_permission: 'TRUE' is not a thing unless you've defined a custom permission TRUE (and if you did, I'd advise you to change that). What you have is looking to see if a user has the permission TRUE - which I doubt any user has, and correctly denying access. If you want to grant access to the route for everyone, in all contexts, use _access: 'TRUE'. See Structure of Routes on d.o for more info.


Just because there hasn't been a commit for ages doesn't mean it's totally not worth investigating further - as you say the tags are not complicated so probably that hasn't changed.

I had a quick look and the first issue on the issue queue is for the 8 version and it's to do with how libraries are loaded, which I believe did change as 8 moved along. Someone's posted a patch in Dec 16 so not that long ago and it's marked as 'needs review', so best would be to try it out and report back there as to whether that works or not, if so and something else doesn't work then create another issue if you can't fix it yourself, or post another patch if you can.

If you use composer to install Drupal 8, for example using:
https://github.com/drupal-composer/drupal-project

then you can also apply the patch in the patches section of your composer.json by adding the link to the patch so it can find it:
https://www.drupal.org/files/issues/views_rss_itunes-fatal_error_call_to_undefined_function_libraries_load-2839012-3.patch

This is kinda how it works - if you wait it may never arrive, and if you can't do the above it's all googleable skills.


Just edit the rule and add another event to it. Reaction rules can have multiple associated events.


How to override ID's in Drupal and comply to CSS Lint|?

Using a subtheme you can override whatever templates contain IDs and change them to use classes instead, updating the CSS along the way.

For example you can override the node template by creating a node.tpl.php file in your subtheme, and the markup can be changed to whatever you need.

You'll have to identify which templates need to be overridden yourself, as there isn't a list available; it will depend on what modules you have installed, and what base theme you're using.

It's also worth bearing in mind that contributed modules (and possibly core modules) may use IDs to target elements in javascript. So test thoroughly, as you might need to make some changes there as well.

However

Don't forget that you're just trying to comply with CSS standards here. You don't need to actually remove the IDs to do that, just any CSS that uses them in selectors.

Drupal 8 core conforms to the rule anyway (see .csslintrc in the root), so you should be covered there, but contributed modules may not. That's when you'll need to check manually and maybe override templates/CSS files that they provide.

Earlier versions of Drupal don't conform to the same standards as far as I know so YMMV.


Imagefield submit breaks when I move it in the DOM

I think you need a clone() in there to move the event handlers along with it.  Check out http://api.jquery.com/clone/ and see if that helps.


Commerce view of node checkout hides unpublished content, therefore can't relist

Fixed:

In the view, go to: Advanced > Other > Query Settings.
Switch on Disable SQL rewriting.

Unpublished nodes should now be visible in the view.


Published-Draft articles are not searchable

is this a known issue with the search or it is the expected behaviour?

It’s very much the expected behaviour

  If yes, any specific reason for implementing like this?

Yes. Only published content should be visible, unpublished content should not. That’s the whole point of the distinction between the two states.

If unpublished content appeared in search results (without manual intervention if there was an edge-case requirement  to do so), that would be a major bug.


This worked for me:

Clear the site's cache (drush cc all)
Re-index the search api index that powers the view
Refresh the view edit page

After that you should see the "Rendered entity" option appear with your view modes as options.


How can I set values in the $conf array using the admin interface?

Sure, you can do this at devel/php if Devel module is enabled and you have access to Devel module's Execute PHP code.

The PHP to do what you want is

variable_set('journal_form_ids', array(
    'fivestar_custom_widget' => 0,
    'guestbook_form_entry_form' => 0,
    'imagefield_js' => 0,
    'img_assist_header_form' => 0,
    'img_assist_properties_form' => 0,
    'link_widget_js' => 0,
    // ...
  ));


How can I get the file id if I use the file_save_data function?

Try

$filesaved = file_save_data($file, 'public://'.$file_directory_name."/".$file_info['file_name']), 'FILE_EXISTS_REPLACE');
$fid = $filesaved->id;

file->id is the id if file that you can use it as entity reference target_id (I mean file field).

and a good example how save and attach file to Node

use \Drupal\node\Entity\Node;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
  ],
]);
$node->save();

What if the file is already present in your local file system and you want to attach it to an existing node? Here's an example for that too:

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

// Create file object from a locally copied file.
$uri  = file_unmanaged_copy('public://source.jpg', 'public://destination.jpg', FILE_EXISTS_REPLACE);
$file = File::Create([
  'uri' => $uri,
]);
$file->save();

// Load existing node and attach file.
$node = Node::load(1);
$node->field_image->setValue([
  'target_id' => $file->id(),
]);
$node->save();

And lastly, what if you want to stick a placeholder file to a node? Thanks to Drupal 8, this is too easy:

use \Drupal\node\Entity\Node;

$node = Node::create([
  'type'  => 'article',
  'title' => 'Generated image test',
]);
$node->field_image->generateSampleItems();
$node->save();


I don't think this is the best way to go about it as you are messing directly with Drupal's Ajax object.

The best way to do this, is to basically write your own click handler and handle the confirmation yourself, then trigger a Drupal AJAX call yourself.

Here is an example:

l(t('Click here'), 'mypath', array('attributes' => array('id' => 'my-id', 'class' => array('toms-ajax'))));

In your js file:

(function($) {

Drupal.behaviors.tomsAjaxLinks = {
  attach: function(context, settings) {
    $('.toms-ajax',context).once('toms-ajax').on('click', this.handleAjax);
  },
  handleAjax: function(e) {
    // Cache the anchor link
    var $element = $(this);

    // We need some unique id, either ID of link or create our own
    var nowStamp = new Date().getTime() + Math.floor(Math.random() * (1000 - 0) + 0);
    var base = $element.attr('id') || 'toms-ajax-'+ nowStamp;

    // Change the event type to load, so we can trigger it ourselves
    var drupal_ajax_settings = {
      url : $element.attr('href'),
      event : 'load',
      progress : {
        type: 'throbber',
        message : '',
      }
    };

    // Create the ajax object
    Drupal.ajax[base] = new Drupal.ajax(base, this, drupal_ajax_settings);

    // Your confirmation code e.g. Jquery UI Dialog or something
    // Open dialog
    if(yes) {
      $element.trigger('load');
    } else {
      // Dont trigger ajax
    }
  }
};

})(jQuery);

Essentially what this does is:

Attaches the handleAjax function to your ".toms-ajax" links once to ensure we do not attach multiple event handlers
On click, the handleAjax function is called
A corresponding Drupal Ajax object is created with it's own unique ID.
It is attached to the link and triggered on the event 'load'. You then
handle the confirmation box.
If the confirmation box confirms the ajaxcall, we simply trigger the 'load' event on the link object and therefore make the Drupal AJAX object do it's thing.


How to attach token in a custom form field

token.module has various examples, for example this:

// Add the token tree UI.
$form['email']['token_tree'] = array(
  '#theme' => 'token_tree_link',
  '#token_types' => array('user'),
  '#show_restricted' => TRUE,
  '#weight' => 90,
);

This displays a link for tokens for the type user (and global tokens).

You can also use the #element_validate callback token_element_validate together with also adding #token_types to have it validated.


How to Hide Specific Pages to Anonymous Users

The first can be done by not giving the permission to view user profiles to anonymous users. The latter is not the same page as for anonymous users that's where they login. Blocking it would prevent anyone from logging in.


How to integrate an exported Rules component in a custom module?

Here is what's needed to integrate your exported Rules component in a custom module:

<?php
function MY_MODULE_NAME_default_rules_configuration() {
  $configs = array();
  $rule = '{ "my_exported_rule" : {
    "LABEL" : "My Exported Rule",
    ...,
  }
}';
  $configs['my_exported_rule'] = rules_import($rule);
  return $configs;
}
?>

So to use such exported Rule, you need to run it through the function rules_import(). This will change the exported Rule in a format that is  usable for the Rules module.

To reuse this example:

Replace MY_MODULE_NAME with the machine name of your module.
Replace the value used for $rule by the content of your exported rule.
Make sure to use the machine name of your rule (= my_exported_rule in my sample) as the key in $configs.

In the sample contained in the question, the machine name of the rule is rules_faircent_rules, though that is NOT what is used in the $configs ... Therefor I think you should correct your code like so:

$configs['rules_faircent_rules'] = rules_import($rule);
echo '<pre>';
print_r($configs['rules_faircent_rules'] );

Refer to the articled "Drupal 7 - Defining rules within a module using PHP" for some more details.


What events, conditions and actions I should use for this case?

I found the answer:

For Event I used:

 1. After updating an existing commerce product

For Conditions I used:

1. Entity has field - Parameter: Entity: [commerce-product], Field: field_stock1

2. Entity has field - Parameter: Entity: [commerce-product], Field: field_stock2

3. Entity has field - Parameter: Entity: [commerce-product], Field: field_stock3

4. Entity has field - Parameter: Entity: [commerce-product], Field: field_totalstock

For Actions I used:

1. Calculate a value - Parameter: Input value 1: [commerce-product:field-stock1], Input value 2: [commerce-product:field-stock2]; Provides variables: Calculation result for Stock1  and Stock2 (stock1_plus_stock2_result)

2. Calculate a value - Parameter: Input value 1: [stock1-plus-stock2-result], Input value 2: [commerce-product:field-stock3]; Provides variables: Calculation result for stock1-plus-stock2-result and Stock3 (stock1_plus_stock2_result_plus_stock3)

3. Set a data value - Parameter: Data: [commerce-product:field-totalstock], Value: [stock1_plus_stock2_result_plus_stock3]

You can see what I wrote here -> http://ucreateawebsite.com/DRUPAL/dalexgrup/pt


Theme UberCart catalog page to use custom html

Your theme's files will override the module's files.

You should install the "Devel" and "Theme Developer" modules.

https://drupal.org/project/devel_themer

WHen you have these installed and configured, it will show you the template names to use for specific pages/blocks/views/etc.


I coded two imports; one for the files and one for the nodes.  The nodes import then references the files using the oncomplete callback that the migration api provides.
Thank you to the Drupal irc channel for pointing out the oncomplete function.

Special thanks to stack exchange for the most depressing achievement ever, the tumbleweed.


After adding data to nodes using hook_node_load(), will this data be saved in the cache?

First of all, you generally don't want to implement hook_load() and hook_node_load() for the same node type. So just FYI.

Secondly: There's a bunch of different caching you could mean... The caching you implement depends on why you need it.

If you trace back the functions that call hook_node_load(), you end up at NodeController::attachLoad(). It just invokes the hooks and then bails to its superclass, DrupalDefaultEntityController. Basically this means that node itself doesn't do any caching.

This gives you a few options:

1) Come up with your own caching system for your own subset of the node's data, which means that you have to mark all nodes using it as uncacheable, since you're caching a little bit of it.

2) Install EntityCache. :-) EntityCache does what you'd do anyway but does it for the whole node entity at the entity layer.

BUT... If the real problem we're solving here is to have a next and previous reference per node, then you want EntityReference, which lets you set that up as fields, and which can then be used with Views and whatnot, for free, without coding anything. :-)


You need to set a dependancy on your library definition. e.g. if you want your custom.js after geofield then in the library you define custom.js you need to set a dependancy e.g.:

mylibrary:
version: VERSION
js:
  js/custom.js: {weight: 0}
dependencies:
  - geofield_gmap/geofield_gmap


Is it safe removing block-inner clearfix classes from block templates?

You can remove them, but they are there so that you can properly float elements within your content. That will depend on the modules you use (whether they include clearfix), and your own CSS.

Not sure about whether Admin requires it. In my case, I use an admin theme for all editing, precisely to avoid such complications.


You can use login destination module, it is easy to use, you just need to create a rule where you can define after login specific role user can redirect to a specific page or you can use write php code too.

  The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.


Filter nodes by date ( excluding year ) show upcoming/previous based on today

I am not sure how you are displaying your date, but if it is 'post date' then in Views on the lower left column choose 'Sort Criteria' and search for date. I will have multiple granularity and you can choose to filter by month.

If you have a text field where you manually type the date associated with the content, then you can use the 'Sort Criteria' and sort by that specific field in 'ascending' or 'descending' order.

If you want to keep the 5 newest and the older separate, you might need to create two different blocks and display them next to each other.

Finally you can do a 'Filter Criteria' by date and select a range of' 'Is greater than or equal to' a specific time period. For example from today to 5 months ago will only display content created within that month period, and anything beyond 5 months will not be displayed.


How to customize home page layout according to the user?

It would be quite hard to provide an exact answer as I don't know how you can affect the view results in your setup. In terms of the rearranging the content and even to save the settings I would suggest that you create a new 'textarea' user field which will be hidden in the front end and use a jquery plugin like this: https://github.com/troolee/gridstack.js to update the value of the field using AXAX when the onchange event fires. That way when you load the homepage you can request that user field and arrange your blocks in the order they wanted. You could use a similar approach for which content is shown and then read it back on page load and pass it to the view as an argument.


If this is a formal drupal node you can use node update event , then check if the node->status is changed or not (you have 2 versions of node in this event one referring to unchanged and second refers to changed noge)


You can pass variables to the batch process by doing the following...

     $year = "2018";
     $batch = array(
          'title' => t('Bulk Add happening within the Bulk Add Form file...'),
          'operations' => array(
            array(
              '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAdd',
              array($uids, $year)
            ),
          ),
          'finished' => '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAddFinishedCallback',
        );

Year in this case can obviously be anything... a piece of $form_state for instance also works.

You could then change

public static function bulkAdd($uids, $year, &$context){
    $message = 'Bulk add happening in functional file...';
    foreach ($uids as $uid) {
        $user = \Drupal\user\Entity\User::load($uid);
        \Drupal\node\Entity\Node::create([
            'type' => 'perf_plan',
            'title' => 'Perf-plan-' . $year . '-' . $user->get('field_user_employeeid')->value,
            'uid' => $user->id(),
            'field_employee_uid' => $user->id(),
            //'field_supervisor_uid' => $user->get('field_supervisor')->first()->getValue()['target_id'], //Brilliant means of getting entity reference UID from User. SM
            //'field_director_uid' => $user->get('field_director')->first()->getValue()['target_id'],
          ])->save();
    }
    $context['message'] = $message;
  }

Hope this helps. It took me a while to figure out where in the batch array structure this needed to be placed. I didn't find the docs particularly helpful.


How to setup Page Cache to work with the Flag Module and Views?

Similar to the first answer but not assuming your cache is in the database. (memcache, redis, apc, etc)

function hook_flag_flag($flag, $entity_id, $account, $flagging) {
  $view_name = '<view_name>';
  $display_id = '<display_id>';
  $cid = $view_name . ':' . $display_id . ':*';
  cache_clear_all($cid, $bin = 'cache_views_data', $wildcard = TRUE);
}


Create Alias URL to taxonomy term page with TID

If what you are asking is, "How can I create a link to a taxonomy term path alias if all I have is the TID," you can use drupal's built in l() function in any php function or template.  For example, if taxonomy/term/34 exists and location/texas exists as its alias and $tid equals 34...

<?php print l('Texas Taxes', 'taxonomy/term/' . $tid); ?>

...will create Texas Taxes because l() will by default look up and use the alias for any system path.


Database Connection error by giving specific IP address

Definitely MySQL remote access would be blocked.

You can edit MySQL conf to enable it.
Loginto your remote db server and edit main configuration file.

vim /etc/my.cnf (in case of Linux)

Comment out skip-networking by adding # before it, should be located under [mysqld] and update bind-address for the desired IP you are using as connection host.

[mysqld]
...
...
bind-address = 192.168.85.10
#skip-networking


How to add site Validation for all pages

One way to do that is using the "site_verify" module and you can add another hook to add it to all page that will look like this:
 /**
 * Implements hook_init().
 *
 */
function YOUR_MODULE_init() {
  $meta_tags = db_query("SELECT svid, meta FROM {site_verify} WHERE meta <> ''")->fetchAllKeyed();
  foreach ($meta_tags as $svid => $meta_tag) {
    $data = array(
      '#type' => 'markup',
      '#markup' => $meta_tag . "\n",
    );
    drupal_add_html_head($data, 'site_verify:' . $svid);
  }
}

you need to change "YOUR_MODULE" with your custom module name. Also clear drupal cach after adding it