Custom block created with GUI stripping some  tags, not all of them

There was a similar question recently and the problem was CKEditor, could be the same here.

If you want to be sure that your markup is not altered in any way, create a text format without ckeditor and use that.


Content status, view different fields, different roles

If pictures should be part (field) of a case node type, use Field Permissions module to set separate permissions for different roles.

If pictures should be separate node type, use Entity reference module to reference parent case from picture node. On the case page you can add a Views block with pictures referencing this case with a button to add new picture.

In both cases you would need some custom code to support your particular workflow.


The problem was that the Body field was not added to the DrupalGap Display Mode for the content type:

  By default, there are no fields displayed using the DrupalGap Display
  Mode. We need to specifiy which fields, labels and formats will be
  used when our nodes are displayed in the mobile app. Do this for each
  content type.


Can I pass variables from more specific template/preprocess function up to less specific?

Nodes In Block or Node Block can help to place nodes in blocks.

The other part, to theme that particular node can achieved by different scope of templates from general to specific node templates. e.g.

node.tpl.php
node-[type].tpl.php
node-[nid].tpl.php


A quick grep of the views module points to the views_plugin_row_node_view class, whose render() function contains the following lines:

$node->view = $this->view;
$build = node_view($node, $this->options['view_mode']);

return drupal_render($build);

So when a node is rendered using the node row plugin, the view is attached to the node object immediately prior to it being passed through node_view(), which is why you see it in the theme preprocess functions.

To actually answer the question (which I missed before), hook_node_view() would get a valid view object, while the others you mentioned wouldn't (I don't think).


Render exposed filter without creating block

I found the solution. I created a custom block which uses the following code.
use Drupal\Core\Form\FormState;
use Drupal\views\Views;

$form = [];
$view_id = 'Your-view-id';
$display_id = 'your-display-id';
$view = Views::getView($view_id);
if ($view) {
  $view->setDisplay($display_id);
  $view->initHandlers();
  $form_state = (new FormState())->setStorage([
    'view' => $view,
    'display' => &$view->display_handler->display,
    'rerender' => TRUE,
  ])
    ->setMethod('get')
    ->setAlwaysProcess()
    ->disableRedirect();
  $form_state->set('rerender', NULL);
  $form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
  print render($form);
}

You can create your own exposed filter in a block without requiring any third-party module.


Best way to convert PHP block to improve site

Just make them a custom module!

The best start I can think of would be taking block_example.module from the Examples for Developers project as a start. Rename it, of course, and then just define your blocks in it, the way example blocks are defined. For blocks' content - move code from where it is now to appropriate functions.

That's pretty much all, if you will have more specific question during development, ask it, too.

Understanding the hook system for Drupal modules might be a useful read, too.


rewrite engine is required to use clean url and you need to intall on terminal by execute the below command.

sudo a2enmod rewrite


Use below code in else condition...

$user = user_load($comment->uid);
print theme('user_picture', array('account' => $user));

OR

$filepath = variable_get('user_picture_default', '');
$default_image = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => '', 'title' => ''));
print $default_image;


Publishing option is not available for one content type

I have managed it already.
I found a form_alter hook in one of my modules. and in this hook there was the line below (i just commented it)

$form['options']['#attributes'] = array('style' => 'display:none');


You can try hook_entity_view_alter() API function provided by Drupal Core to alter any entity.

If you want to alter how the entity will look, you can also try using Display Suite or Panels module which are used to override the display.


I can not believe that you will have one different JS for every group. So caching is cool, and I assume your problem is the triggering of a function in the JS.

You can use the Drupal.behaviors to call a function in your JS everytime a page is loaded, i.e.

(function ($, Drupal) {

  Drupal.behaviors.anyInit = {
      attach: function () {
        myInitFunction();
      }
  }
})(jQuery, Drupal);

function myInitFunction() { do something }

And you can pass variables to the JS (like your group name), by attaching them to your rendering array, like so:

$build['#attached']['library'][] = 'bootasde/asdejs';
$build['#attached']['drupalSettings']['bootasde']['proreos_server'] = SystemTools::getProreosServer();
$build['#attached']['drupalSettings']['bootasde']['checktyp'] = 'a';
$build['#attached']['drupalSettings']['bootasde']['id'] = $id;

Then you access that variables in your JS like:

  var server = drupalSettings.bootasde.proreos_server;
  var id = drupalSettings.bootasde.id;
  var tp = drupalSettings.bootasde.checktyp;

Hope that helps.

Another way could be to add the group names to the CSS classes in your twig template and have some special selectors for each groupname.


Your use of the functions cache_set() and cache_clear_all() does not look right.

First let us look at cache_set(). It stores some serialized data in some persistent cache bin.

Its arguments are:

$cid - a string that identifies the stored data.  The same string is stored in the $cid field in the database table named by the $bin argument.
$data - the data to cache.  This is stored in the data field identified by $bin and $cid, usually as a serialized object.
$bin - The name (a string)  of the cache bin to use.  This corresponds to a database table with that name.  It should either be 'cache' or start with the string 'cache_'.
$expire - when should the item expire. If set to CACHE_PERMANENT, the item can only be expired by calling cache_clear_all().

You want to cache some parameters attached to some node.  To do that, you may use:

$cid = 'mymodule:node_' . $nid;
$data = ...; // Set it to hold whatever object you want to cache.
$bin = 'cache';
cache_set($cid, $data, $bin, CACHE_PERMANENT);

Note that $bin need to be set to the name of one of the bins (i.e. cache database tables) that are already defined.

Now, to clear out this particular item, you need to call cache_clear_all() with the same $cid and $bin as was you to set the cache.  The final parameter to cache_clear_all() can indicate that $cid is a wildcard (in your case, it is not). I.e.:

cache_clear_all($cid, $bin, FALSE);


How to change the product type of selected Drupal Commerce products (without direct DB updates)?

For sure I'd not use the approach of changing things in the Database directly. Instead I would try to use the Rules module to create a clone (using the new product type) of the selected products. A solution that could possibly work is to (also) get the Views Rules module involved. Some details about this module (from its project page):

  Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (yet), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

Create a view (using Views) so that you have 1 Views result (row) for each product of old product type and for which you want to create a similar one with the new product type. This view should have fields (columns) for each of the fields from your old products that you want to use to create your new product (with your new product type). Important: use a Views display type of "Rules".
Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop". If you're not familiar with Rules Loops, then have a look at the tutorial titled "Lists and loops".
For each iteration step in your Rules Loop, perform a Rules Action to create an entity which corresponds to your product but with the new product type. At that point you'll have all data from each column of your Views results available as so called Rules Parameters (remember: they are the values used in your products with the old product type). So at that point it's a piece of cake to populate the various fields of your product with the new product type.
The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

Possibly, you also want to delete the product (of the old product type), e.g using a variation of this rule (to delete those products instead of creating new entities). I would definitely do that in a separate rule (not as an extra Rules Action in the same rule), to be able to verify that the new products are created (correctly) before deleting the products with the old product types (better safe then sorry ...).

Note: Refer to my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?" (the option 2-part of it) for an example (with screenprints) about how to use the Views Rules module.


How to save single value from a select field?

I would use jQuery to deactivate and uncheck the other two checkboxes when the third has been checked. If they uncheck the third, they will all become active.

Your Drupal form will look something like this:

    <input type="checkbox" class="form-checkbox" value="pr" name="field_terms[und][pr]" id="edit-field-terms-und-pr">  Print Required

    <input type="checkbox" class="form-checkbox" value="dp" name="field_terms[und][dp]" id="edit-field-terms-und-dp">  Digital Print Required

    <input type="checkbox" class="form-checkbox" value="tp" name="field_terms[und][tp]" id="edit-field-terms-und-tp">  Print has been taken

jQuery code would be something like this:

(function($) {
$(document).ready(function() {

    $("#edit-field-terms-und-tp").click(function() {
        if($(this).is(':checked')) {
            $('#edit-field-terms-und-pr, #edit-field-terms-und-dp').attr('disabled', true).prop('checked', false );
        } else {
            $('#edit-field-terms-und-pr, #edit-field-terms-und-dp').removeAttr('disabled');
        }
    });

});
})(jQuery);

Haven't tested it, but it should work.


Best answer on how to theme 3rd party modules is always to check their local documentation first, as most of the top-tier modules have very specific hooks, documentation, guidance for how you can theme their results. In the case of the Rate module, check the README.txt file for some guidance on what theme variables are able to be used in your node templates.

It looks like the best answer would then be to make a copy of the rate template into your theme folder and add your styling there:

* rate-widget.tpl.php
  This is the default template for all custom widgets.
* rate-widget--NAME.tpl.php
  This is a widget specific template. Use the machine name for NAME. Replace
  underscores by dashes in this name. This template is only available for custom
  widgets.

This does depend on exactly what it is your trying to theme in the emotion widget.


How to get users (entities) for a certain field value?

Simple example for the use case I asked about:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_birthday', 'value', $birthday);

$result = $query->execute();
$users_ids = array_keys($result['user']);


First of all, you should't use a Drupal default theme. As when you update Drupal core, you're going to overwrite all your theme files. So if you want to use a default Drupal theme you need to create a sub theme, if you haven't already. Follow this tutorial Creating A Drupal 7 Sub Theme.

Secondly, it looks small because you have items in your left column.

Thus, you need to remove the left column blocks. Go to /admin/structure/block and disable those blocks. OR Edit those blocks and in the Show block on specific pages you can control on which pages you want them to show up or be excluded from.

If that still doesn't do it, you need to edit your theme files. Go to /sites/all/themes/YOURTHEME/ folder and edit the page.tpl.php file and get rid off the left column.

Even after doing this, if you still want it bigger, then right mouse click on the page and select inspect element. Find the name of the div class or id that is controlling your output.

example <div id="hello" class="cool">

then on your css you put

#hello { width: 5000px; } if its and ID

.cool { width: 5000px; } if its class

If it has both, pick whichever you want

BTW: Your themes css file is located in the sites/all/themes/YOURTHEME/css folder.

Finally, after you make changes always remember to clear/empty your cache


Saving form data of forms modified with form_alter hook

Exactly like you alter a form to add custom fields, you alter it to add custom validation and submit handlers.

It should be:

$form['#validate][] = 'custom_validate';
$form['#submit'][] = 'custom_submit';

use those function to control the additional user input and store them later.


How to replace the button when the user is not authenticated?

You can use predefined logged_in variable.

{% if logged_in %}

    {{ content.flag_like_group }}

{% else %}

     J'aime

{% endif %}


How to create front page for every language?

You have to use the language detection method "URL" for this. When using other detection methods the language prefix is not used.

Even then a URL without a language prefix still works and uses the default "Selected Language" at the end of the detection methods list or another method you have enabled between those two.

If you want that the homepage is redirected to the language prefixed URL instead, use the module Redirect and set this option:

  GLOBAL REDIRECTS

  [x] Enforce clean and canonical URLs.

  Enabling this will automatically redirect to the canonical URL of any
  page. That includes redirecting to an alias if existing, removing
  trainling slashes, ensure the language prefix is set and similar
  clean-up.


If you have a naming pattern for the groups, you could use the Automatic Nodetitles module or the Automatic Entity Label module to give the groups a default name and use the Devel module to generate the groups.

Also since groups are nodes, you could use one of those node import modules to bulk upload the groups from an excel sheet.


How can I dynamically load options into a select list?

For just populating select list options, you don't need to go through an Ajax approach! Simply write a separate function and write your database query inside it and then just call that function in '#options' of your $form['select-user-group'].

For example for displaying all node types in a select list you can use the following function:

function get_node_type_info() {

  $wizard_plugins = node_type_get_types();

  $options = array();

  foreach ($wizard_plugins as $key => $wizard) {
    // Don't forget the $ before wizard
    $options[$key] = $wizard->name;
  }

  return $options;
}

And then use this function to populate the '#options' like so:

$form['display_options'] = array(
  '#type' => 'select',
  '#title' => t('Component Type'),
  '#options' => get_node_type_info(),
);


Module Webform won't send email to certain address

I was having this same issue. I contacted my host (Hostmonster) and found that there is a setting in your Zone Editor that can fix this issue.

Under MX (Mail Exchanger) I selected Remote Mail Exchanger and under the section that says "Points to" I put exchange.domain.com (replace domain with your domain name). I did this because we are running all of our email through an exchange server.

Try calling your host and explaining the problem.

I hope this helps!


How to show only the comment form, not the comments

Implement hook_node_view() and check for $node->type == 'article' and $view_mode=='full' then unset the comments as follows

unset($node->content['comments']['comments']);


Drupal 8 CKeditor behaves LTR in an RTL site

The default CKEditor text language direction is LTR.
To change it to RTL, you can try setting the JS config setting:

config.contentsLangDirection = 'rtl';

Reference: http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.contentsLangDirection

In D7, there was a config textarea that can be set:

In D8, you can set the CKEditor config settings in:

hook_editor_js_settings_alter

Something like:

/**
 * Implements hook_editor_js_settings_alter
 */
function MYMODULE_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats'][$name]['editorSettings']['contentsLangDirection'] = 'rtl';
  }
}

More info on creating Drupal 8 modules here: https://www.drupal.org/developing/modules/8

You can also set the config in JS, for example your theme

Something like:

(function ($, Drupal) {
  Drupal.behaviors.customCKEditorConfig = {
    attach: function (context, settings) {
      if (typeof CKEDITOR !== "undefined") {
        CKEDITOR.config.contentsLangDirection = 'rtl';
      }
    }
  }
})(jQuery, Drupal);

More info on adding theme assets here: https://www.drupal.org/theme-guide/8/assets

For your other question on the toolbar button ordering. That appears to work, just make sure you set the toolbar button order on all the "Text formats" that you want to use it with (e.g "Basic HTML", "Restricted HTML" and "Full HTML") in the CKEditor admin settings.


Multiple field, but each one as individule

Just use the single image field, add field description text for the user in regards to clicking to "add another" item when uploading the two images.

On updating, the user can adjust the weight of the images and drag/drop the front/back images into order.

Alternatively, you could look at using two fields, or a module like field_collection


You need to load the node to render it if the page you are viewing is other than node page... In node page page.tpl.php contains $node object.. See page.tpl.php documentation for more details...

  $node: The node object, if there is an automatically-loaded node
  associated with the page, and the node ID is the second argument in
  the page's path (e.g. node/12345 and node/12345/revisions, but not
  comment/reply/12345).

If other than node page you need to load the specific node from which you want to render the field in your login/registration/profile pages.. You can override page.tpl.php for specific pages.. For more details see Template suggestions..

To load the node specifically you can use node_load API function...

$node = node_load($nid); // Where $nid is node id


How do I rewrite the way my view rows are displayed

Did you override view ?? If your not override view Please follow below views view suggestion -

views-view-fields--(yourviewmachinename).html.twig
views-view-unformatted--(yourviewmachinename).html.twig

Note - In views-view-fields--(yourviewmachinename).html.twig,file render your fields which are present in that view Eg. If will have field - title follow below render

{{ fields.title.content }}

Note - If your rendering page title then render {{ label }}

In these file - views-view-unformatted--(yourviewmachinename).html.twig - You will get loop here,don't change here any think.

Hope, this will help you.thanks!


Unable to send e-mail. Contact the site administrator if the problem persists

Try using:

SMTP Authentication Support

with
PHPMailer

If You use Gmail to set up STMP follow this steps:

SMTP server: smtp.gmail.com
SMTP port: 465
Use encrypted protocol:Use SSL
SMTP Authentication -- Your User Name and password
Leave the other options by Default


You might be able to use custom variables within Google Analytics. That way you can get all your sexy graphs in one easy place.

You would have to use existing tokens or create some new ones and attach them to your users report to Google.

You can then install : https://chrome.google.com/webstore/detail/jnkmfdileelhofjcijamephohjechhna?hl=en

This shows you what variables are being tracked. For example I track my users on what content type they are viewing, what taxonomy, tags, roles etc.

What you are asking for is very specific, so I think you would end up creating custom tokens.

As an example you could show all first time users by attaching the token [user-created-date] then filter in GA to only show today's date for that custom variable.


Debugging is the art of removing all possible reasons why some unexpected/undesired issue arises ... so make sure your site is NOT in maintenance mode ...

To do so, navigate to admin/config/development/maintenance and ensure that "Put site into maintenance mode" is NOT (repeat: NOT) checked.


I can't help with the PHP filter and I don't think it is safe to use it in D8 by looking at the project's page.

There are better solutions. You could for example add a Views Reference Field to the block type or use Twig Tweak in a template. You can also try to embed the View in the WYSIWYG text area, which is a bit more work to set up, but then should give you all options you have now in D7. See Views entity embed.


How can I add player parameters to a core oembed field for a youtube video?

I had the same problem before with a local provider. So I share the solution I used and hope it works for you too.
The Drupal core, fetch providers form https://oembed.com/providers.json automatically. So you need to change the provider to what you want.
Oembed Providers module helps to add custom providers too.

Add custom oEmbed providers via an admin user interface (providers are
stored in configuration)
Global enable/disable of providers
Modify the provider list URL (which is > defaulted to
https://oembed.com/providers.json)
Disable the fetching of the
provider list (useful in an instance where only custom providers are
used)
Provides hook_oembed_providers_alter() to alter provider
definitions

So, all you need is to add a new provider for your custom provider "youtu.be" with your parameters too.
try it and let me know if you need more details.;)
Screenshots that shows it's working without any validation error:

what I did, was just add "oembed_providers" module and enabled it


Programatically trigger a click on an AJAX enabled form field (button, select, etc)

In order to select radio buttons using jQuery I came up with the following solution:

base = 'edit-my-radio-button';
id = '#'+base;
$(id).click();
Drupal.ajax[base].eventResponse($(id), 'click');

After some digging around in misc/ajax.js, I found that Drupal AJAX stores the result of new Drupal.ajax(base, element, element_settings) in the Drupal.ajax[] JavaScript Array. This led me to realize that I did not need to create a fake element or an element_settings object as the Use Drupal7 AJAX goodness programmatically answer suggested. While that simplified my code, and eventResponse() created a successful AJAX request, the AJAX commands being returned still did not execute.

On a hunch, I decided to use .click() followed by .eventResponse() because I noticed that false was being printed on the console.

After looking at the .eventResponse() code, I am not 100% sure where it is looking for the element to be currently selected. After stepping through the function calls, I believe jquery.form.js is checking to see if the item is selected, but since this file is minified by default, I have not gone through it yet. If anyone else can shed light on this or be willing to step through the function calls, that would be great!

FYI: If I run these commands manually in the console, .eventResponse() still returns false, so don't be alarmed when you see that.


Navigate to Hosting » Settings » Task Logs to Display and you can check/uncheck the boxes for the different types of log messages.

As Add proper UX to the selector for choosing logs types to show is fairly new (see that issue for background), it hasn't made it into a release yet so you'll probably still see the text area.


Change content of views_field_view field using hook_views_pre_render

Try using template_preprocess_views_view_fields

If you still can't access that field there then:

Ditch views_view_field
Add a "custom text field" (their field_name will be nothing).
In template_preprocess_views_view_fields programmatically add view to this "custom text field".

/sites/all/themes/THEMENAME/template.php

function THEMENAME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  foreach ($view->field as $id => $field) {
    if ($something == 'some condition') {
      $vars['fields']['nothing']->content = 'some string' . '

' .
        views_embed_view('view_name', 'view_machine_name', $contextual_filter_value);
    }
    else {
      $vars['fields']['nothing']->content = views_embed_view('view_name', 'view_machine_name', $contextual_filter_value);
    }
  }
}

If your view does not need a contextual filter, then it's:

views_embed_view('view_name', 'view_machine_name');


Trouble with maximum registrants for RNG

The current minimum and maximum registrant fields as found in RNG 1.5 are per registration.

Perhaps you are looking for maximum registrants per event?


Put the classes in an array:

{%
  set itemclasses = [
    'project-label',
    'project-term' ~ loop.index,
  ]
%}

And add the array to attributes:

{% set item = item|merge({'#attributes': { 'class': itemclasses } }) %}


View sorting becomes arbitrary with grouping field?

It seems that disabling "Reduce duplicates" on the exposed filter of the grouping field will bring the sort back in order. So, in this case, unchecking "Reduce duplicates" on the exposed filter, Country (which is also the grouping field) did the trick.


drush cc segmentation error when clearing theme-list

This turned out to be a problem with the Drush installation on my Vagrant box.


How can I add some style to title of side bar block?

First add position: relative as a style to the containing element (most likely the nav element.
Add a pseudo element after the h2 element, which you probably want to have your specificity include the class of the nav element.
Style the pseudo element with position: absolute; right: 0;
Tweak the styles of the h2 and h2:after blocks to suit your needs.


Since people may not check the comments for the answer:

Yaazkal suggested in comments try using webform_client_form_25

Hyphens(-) are generally translated into underscores(_) for machine names in drupal.


Views group different number of divs of a view by wrapping them

Here is what worked for me. Mind that I only got it to work in an unformatted list format in views.

<?php
  $currIx = 1; // This will be our incremental index variable. Let's make it 1-based to maintin consistency with your example.
  $currWrapperIx = 1; // Wrapper counter
  $wasOpen = FALSE; // This variable will be used later as a flag to watch for properly closing wrapper divs.
?>

<?php if (!empty($title)): ?>
  <p class="<?php print $title ?>"><?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php switch ($currIx){
    // List the row indices that are supposed to begin a new wrapper.
    case 1:
    case 27:
      if($wasOpen == TRUE){ // Close current wrapper div before opening a new one.
        print "
\n";
        $wasOpen = FALSE;
        $currWrapperIx ++; // Increment the index for next wrapper's class.
      }
      // Open a new wrapper div
      print "
\n";
      $wasOpen = TRUE;
      break;

    default:
      // For other row indices do nothing.
    }
  ?>

  <div class="<?php print $id ?>"><?php print $row; ?>

  <?php $currIx ++; ?>
<?php endforeach; ?>

<?php
    // Close the last wrapper.
    if($wasOpen == TRUE){
      print "
\n";
      $wasOpen = FALSE;
    }
?>

Kudos go out to @Artur. Great support. Many thanks.


Here is the format I found working:

field_teaser_image/target_id:
  plugin: migration
  migration: attachment_image
  source: file_id
field_teaser_image/alt: file_alt


How can I programmatically distinguish if a block is enabled or disabled from block layout?

Use BlockContent::getInstances to get all blocks placed for this custom block, then check for each block instance if it is enabled with $block->status().

See Get block programmatically and How can we check whether block is enabled or disabled in .theme file?


Add a .mouseleave() event to the popup div

Taking the example code from the SO question you mentioned, see the working version at http://jsfiddle.net/Laxman13/Mw8VD/6/


User Profile Picture Cached After Change

use a random tail after the filename like
http://www.domain.com/filename?122492834932
it will detect your file as a new file and browser cache will not read it as the same as the old one


How to disable CKeditor for a particular node?

You can configure text formats to have different editors with WYSIWYG API, all you need to do is create a new format (like Full HTML) and set it for no editor, then on any node you don't wish to have an editor, simply set the text format to your new custom one.


Download file field dependent on user role vs role field values

After some digging... I found that I am able to get field information like...

$variables["#object"]->field_roles_allowed["und"]; //array containing id's of roles allowed
$variables["#object"]->field_download["und"]; //array containing information about the file

and that I can get the current user's roles like...

global $user;
$user->roles; //array containing current user's roles

Then I can compare the field roles allowed with the current user's roles and determine what to output from there.

Still not very happy with this, I would prefer something where I don't have to write PHP logic in a field.


How can I include a simple php in a Drupal 8 twig file?

One way to do it would be to add the variable in a preprocess function, and print that out in the chosen twig template as {{ your_variable }}.

function yourtheme_preprocess_page(&$variables) {
  $variables['your_variable'] = \Drupal::get('date.formatter')->format(args);
}

I'm not sure where you are doing this, so your use case could be _page, _node, _html, _block for the preprocessor.

Since you are not passing a timestamp to date, it will assume current time and print that. If that is your intent, you should consider that when caching mechanisms are enabled, it won't show the current time anymore, and you should consider a Javascript based solution to keep that accurate (something like momentjs?). Again, don't know your full use case here.

edit: see https://api.drupal.org/api/drupal/core%21includes%21common.inc/function/format_date/8

and https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Datetime%21DateFormatter.php/class/DateFormatter/8


Import a custom field type record and relate it to a node

Just to double check: You have a content type with fields for your images from cloudinary, and you have nodes that already exist in your site that you need to get the data from Cloudinary into your node?

It looks like your looking up nodes through a query by the entity id (nid). Instead of doing that I would simply just load the node object by the node_load function (like node_load($entity_id). You should be able to then assign the value of cloudinary fields in the node (it's gonna be something like $node->FIELD_NAME['und'][0]['value']). Once you have all your custom fields inputed, just use node_save($node).


How to programmatically add a link to an image field in a view

As per your question, I assume that you want the image link to open the image in existing/new tab. For this you can add a relationship of 'File Usage : File'.Post that you get the file path field in the fields section of the view.
Add that file path field and in the rewrite result section or in template file you can create  tag with the required image.
PS: In field image setting select noting in link image to setting.


Best way to migrate inline images in content fields to drupal 7

First off, there really can't be a best way without describing any requirements that can be objectively measured (e.g. speed, loc, number of steps, etc.). However, you can do a few things to do use those inline files in Drupal.

First thing is to sync (e.g. rsync) your content file dir under Drupal's publically managed file system. Depending on your organizational preference, this can be:

The default path (sites/default/files from your Drupal root).
A subdir in the default path (e.g. sites/default/files/assets)
Or a completely arbitrary dir; you can use any directory in Drupal root to be the public file system by configuring it in the admin/config/media/file-system admin page. In fact, you could make it the same directory as your previous CMS (assets/default).

If you decide to use a new directory (i.e. not assets/default) you'll need to either:

Create web server redirect rules (e.g. Apache .htaccess RewriteRule) from the old URLs to the new URLs.
Find old URL references in your imported content and replace them with the new URL references.

The first option is the better of the 2 since it accommodates other caches of your documents (e.g. cached web crawler versions of your content) that you can't update and it's less error prone (e.g. no breaking content because regex mismatches).

The last thing to mention is programmatically inserting records into Drupal's managed files system (its file_managed DB table). This isn't required for your imported articles to display, but if you ever want to manage the imported files through various Drupal file-management tools, it will be needed.

Since you're already using a PHP script to programmatically, you can add to the script a function to iterate over all sync'd files in the public directory and save them to Drupal.

//Assume $files is an array of file paths relative to the new public directory
//(e.g. 85/858dee4200c7f440cd6d4dba8814d56a8e81ab1f/original.jpg)
foreach ($files as $filepath) {
  $uri = "public://$filepath";
  $file = file_save((object) array(
    'filename' => basename($uri),
    'uri' => $uri,
    'status' => FILE_STATUS_PERMANENT,
    'filemime' => file_get_mimetype($uri))
  );
}


db_select with mysql reserved word in the statement

You can use where() instead:

$query = db_select('my_table', 'd')
  ->fields('d', array('sort_id', '`when`', 'user'))
  ->condition('user', '123')
  ->where('`when` = :timestamp', array(':timestamp' => 1448160590))
  ->execute();

Produces:

SELECT d.sort_id AS sort_id, d.when AS when, d.user AS user
FROM
{my_table} d
WHERE  (user = :db_condition_placeholder_0) AND (`when` = :timestamp)


Cause for Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: error

Looks like the namespace defined in your class file does not match the one you put into the resource, there's a "Form" sub-namespace missing.

Also make sure that the class is placed in the right folder.

The reason for that error is apparently that for some reason, the specified class can't be found, so apparently the router then falls back to the service. So the _ thing is just one possible reason.

Also, there are some errors in your hook_menu(), route_name is a string, access callback can be removed and you still need the first entry for now so that you have a menu link to it.


Is there a setting to add a suffix and prefix to a list(integer) field like there was in Drupal 6?

You can do it with Simple Field Formatter module, see the below screenshot

Which allows site administrators to easily control the display of
field values with following features

  Prepend the field value with specified text/HTML
  Append the field value with specified text/HTML
  Reverse the Field Value
  Trim the Field Value
  Convert the field value to lowercase letters
  Convert the field value to uppercase letters
  Convert the first character of the field value to uppercase
  Convert the first character of each word in the field value to uppercase (7.x-1.x-dev)
  Replace some characters with some other characters in the field value (7.x-1.x-dev)
  Link the field value to node(7.x-2.x-dev)


This wasn't quite exactly what I was looking for, but it suits my case and is simple to use, so just in case anyone stumbles upon this looking for a solution:
The Menu Manipulator module hides menu links that are pointing to contents without the current translation. You can specify which menus will be managed by this, so this is at least a little bit customizable.


Translating taxonomy list name for a custom link in rewrite result field

How can I achieve this? There's no translatable field for this view that I can add and use as variable.

Really?!? If you have a representative node of the category content (with the proper language set) you should be able to have a relationship to that nodes language settings, and also the url path to nodes' url path for say, French, in this case.

There's no token support to Rewrite the link in Views to the path with X language setting for the node? .... eg, under Replacement Tokens for the field there's no configurable token for like, node:path:lang:YOUR-LANG or something similar -- I typically dont do internation sites, but i'm 99% sure this type of flexability comes out of the box.


You could use something like auto_login_url and generate a url then redirect the user to that URL before you go to the node. This is mainly an API module that allows you to generate URL login links so you will have to code the solution. There are a couple of other URL login modules out there but this one has a pretty easy API to handle with no large learning curve.
From the module page:

Creates auto login URLs on demand and through tokens.
This is mostly a developer's module. The better use for me is to convert all links of a specific text to auto login links.

Similar module urllogin


How to properly add a Commerce Shipping Service option via AJAX during checkout

Since Stackexchange does not allow me to comment, did you find a solution? I am experiencing exactly the same issue. Thanks.


How to access webform elements in webform.html.twig

I have figured out a solutions for this situation.

create a tempalte file for your form (ex. webform--newsletter.html.twig)
there is a variable (element) where you can access each field of the form like this:

  {{ element.elements.YOUR_FIELD_NAME }}

you need to output the form action (submit) at the end of the form link this:

  {{ element.actions }}

the trick with this solution is that you need to output a couple of hidden form elements that is required for the form to be submitted properly:

  {{ element.form_token }}

  {{ element.form_build_id }}

  {{ element.form_id }}

My final form template looks like this:

      {{ element.elements.form_description }}

      <form{{ attributes }}>
        {{ title_prefix }}

            {{ element.elements.name }}
            {{ element.elements.email }}
            {{ element.elements.phone }}

            {{ element.elements.message }}
            {{ element.form_token }}
            {{ element.form_build_id }}
            {{ element.form_id }}
            {{ element.actions }}

        {{ title_suffix }}
      </form>

Hope that helps anyone else

Update:
I forgot to mention that you also need to print out the following element:

  {{ element.form_token }}

Credit goes to maestrojed Webform twig template causes “the form has become outdated” error


site redirecting to core/install.php after migration

I encountered the same issue today (my site kept redirecting to install.php after migration to new host) and spent half-a-day troubleshooting.
The db connection was OK. I double-checked that the db-name, db-user, and db-user-pass are correct in the site/defaults/setting.php
In the end, it turned out that when I exported the database from my previous hosting, the names of the tables were prepended with a prefix. After importing the tables in the new database, I didn't specify the prefix in the settings.php file. Therefore, drupal was not able to locate the correct tables, because it looked for the users table but in the db, that table was actually named prefix_users and so on.
$databases['default']['default'] = array (
'database' => '',
'username' => '',
'password' => '',
'prefix' => '!!!',
'host' => 'localhost',
'port' => '',
'namespace' => 'Drupal\Core\Database\Driver\mysql',
'driver' => 'mysql',
);
Hope it helps!


Views content pane - return half the results

When editing your view, click on (+Add) button at the top and select block. So now you should have 2 blocks.

In block 1, for pager, select Display a specified number of items, then for items to display, put 10 and leave offset 0.

In block 2, do the same, except you need to put an offset 10, so it starts displaying at row 11.

Then add block 1 and block 2 to your panel.

EDIT: Possible solution when you don't know the number of items

In summary: We are going to move row x and everything below that using jquery.

You would have to use php in the template file and divide the view
total count by 2 and round up the answer (cause you might have 21 in
total).
Add a Global view result counter field, to your view.
So now we are able to target each row.

So for example if total is 21 then /2 = 10.5, roundup to 11. The 11 will be saved as a variable.

Then just do an if statement if

( $fields["counter"]->raw = $variable) { print "<div class"move"> ... all the other stuff }

Then use the total to close the div at the last row.

Then just do an if statement

if ( $fields["counter"]->raw = $total) { print all the other stuff ... "</div>" }

You would also have to print the calculated number (11) inside a div, so then we can grab the total using jquery.

If your middle pane varies in height, you would have target the div and calculate the height with jquery so then we can add this number to the jquery $('.move').css()

Also, you would need to caculate the height of the "move" div and and assign that to the last panel div.

Lastly, you move the "move" div using jquery .css() by the height of the middle pane + 5 or so more px.


/**
 *Implements hook_form_FORM_ID_alter().
 */

function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  unset($form['account']['pass']);
}

Hope it works.


How can I get the saved value in the variable table to show on a form?

You'll have to refer to the Form API docs for radios for tips.

Second, it might make things easier to reason about if you do:

$one = variable_get('one', array('visibility' => 0));
$is_visible = $one['visibility'];

$form['one']['visibility'] = array(
 '#type' => 'radios',
 '#title' => t('The title'),
 '#options' => array(0 => t('Yes'), 1 => t('No')),
 '#default_value' => $is_visible,
);


How do I fix this Configuration Directory sync error?

Create the directory specified in the error. This is fixed in an upcoming release.


Store the values of a views exposed filter Form

This seems like the perfect scenario for a custom module in my opinion. I know it's possible to get this working based on some light research I did (specifically this web page).

Your solution is using a custom module anyway, best to create the form and hooks and sql in the custom module and remove your dependency on views.

Create your hook_menu:

function MODULE_menu()
{
    $items['PATH'] = array(
        'title'            => t('TITLE'),
        'description'      => t('DESCRIPTION'),
        'page callback'    => 'drupal_get_form',
        'page arguments'   => array('MODULE_form_function'),
        'access arguments' => array('access content'),
        'type'             => MENU_NORMAL_ITEM,
    );

    return $items;
}

Create your form function (using the Form API and Database Abstraction Layer):

function MODULE_form_function($form, &$form_state)
{
    // handle creation of your form, including sql to replace views.

    return $form;
}

Create your validate and submit handlers:

function MODULE_form_function_validate(&$form_state)
{
    // handle the validation of your form
}

function MODULE_form_function_submit(&$form_state)
{
    // handle the submission of your form
}

This is a much simpler and proven way to accomplish what you are trying to do.


Custom personal contact form with webforms

You can use hidden fields in your webform which are associated with user's details, such us email, id etc.


Field with type 'Term Reference' (only if I use View as data source) display N/A as first value

A very late answer, but hopefully it will still help you.
I think if you change the term reference field, you have an option if it is optional or mandatory the field. When you choose mandatory, it should be removed that option.


How to change upload destination from private to public?

You could accomplish this by moving the files out of the private directory and into the public directory (make sure the paths stay the same!). Then you would need to update the 'file_managed' table. The 'uri' table will list the files as either private or public. The mySQL would be similar to:

UPDATE file_managed SET uri = REPLACE(uri, 'private://', 'public://') where instr(uri, 'private') > 0;

NOTE Please make sure to test this on a dev site before doing in production.


Check Skinr module.

If you are only looking for a straightforward way to add classes to nodes, you could do that even without any additional module.

Create a field called "css_class"
Hide that field from output
Edit the node.tpl.php file and print the value in the wrapper element

That should do the trick.


Sort by one criteria and have another to fall back on

Managed to find the issue. The resources that didn't have a weight set were treated as having a lower weight than ones that did. I changed the weighting to sort by descending, which is the opposite of how weight should work, but seems to be the only solution.


1) You just need to add a contextual filter of "Content: Nid".

2) Then select Provide Default Value, type: Content ID from URL.

3) Add a field of Nid and check mark the box that says "exclude it from display".

4) Add a custom field, Deliberables

PS: Make sure the nid field is above the custom field so the custom filed can use the nid token.


How can I log in as admin to my Commerce-kickstart demo site?

Check if anything in this list of typical things might help:

Check if you get the same problem using another browser. If with another browser it works, then it might be a cookie problem. To solve that, delete the cookie in the browser where you have the problem.
Make sure "clean urls" is enabled. Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.
Make sure the value of "base_url" is set correctly (in your settings.php).


Why are MailMime images not embedded when sending an eMail via Rules?

Double check your setting on the mime mail configuration page.

In recent versions of the mime mail module there has been options added in relation to embedded images.

The option is called "Link images only". Generally I would turn that on as I don't see the need for embedding images in emails. You will generally have less issues with remote images.

There is also a permission for the mime mail module that relates to attached images, so check out the mime mail permissions too. Edit That permission is only a drupal 6 thing.

Update

In regards to your plus - space issue, what happens if you comment out the line

  $url = str_replace('+', '%2B', $url);

in the  _mimemail_url function in the mimemail.inc file?


#default_value not being displayed in form

Assuming Drupal 7...

The signature for form functions needs to follow a strict pattern; Drupal will pass along $form and $form_state as the first two args, and anything else as subsequent args.

So assuming $str should be the first custom arg to the form, the signature should look like this:

function myfunc($form, &$form_state, $str) {


I do not know what a free tagging cloud is, but I can help you with setting up a free tagging field.

On your entity (content type), add an entity reference field that references taxonomy terms. Optionally you can limit to a specific vocabulary. Also select the checkbox to create new items if they do not yet exist.

Then on the manage form display tab of the content type, make sure that you select the Autocomplete (Tags style) as the Widget for your created field. This should give you a free tagging text field.

(You can use the Article content type of a clean Drupal site as example)


I applied this patch
https://www.drupal.org/files/issues/2019-07-31/facets-3070461-3-Facet-links-break-in-modal_0.patch and issue resolved. Hope this will be helpful for others.


Calendar view: Making year+month exposed filter go to the right URL

I dunno but I ended up just doing it all manually with markup and JS, probably is an easier way but yeh:

<select id="month" name="month">
  <option id="01" value="January">January</option>
  <option id="02" value="February">February</option>
  <option id="03" value="March">March</option>
  <option id="04" value="April">April</option>
  <option id="05" value="May">May</option>
  <option id="06" value="June">June</option>
  <option id="07" value="July">July</option>
  <option id="08" value="August">August</option>
  <option id="09" value="September">September</option>
  <option id="10" value="October">October</option>
  <option id="11" value="November">November</option>
  <option id="12" value="December">December</option>
</select>

<select id="year" name="year">
</select>

<button id="gotomonth">Go</button>

$('#gotomonth').click(function() {
  var month = $("#month option:selected").attr('id');
  var year = $("#year option:selected").attr('id');
  location.href = year + '-' + month;
});

var currentMonth = ("0" + (new Date().getMonth() + 1)).slice(-2);
var currentYear = new Date().getFullYear();
for (i = (currentYear - 3); i < (currentYear + 3); i++) {
  $('#year').append('<option id="' + i + '" value="' + i + '">' + i + '</option>');
}
$('#month #' + currentMonth).attr("selected", "selected");
$('#year #' + currentYear).attr("selected", "selected");


How can I automatically rotate images based on EXIF data prior to image styles being applied?

Another option is to process the images before they are uploaded. I wrote a windows script to do this 5+ years ago. It still works, but I won't be offering any support for it.
http://www.autoitscript.com/forum/topic/85891-imagemagick-batch-jpg-processor/


How to limit users to posting 1 node per a day?

Check the answer here:
Denying access to node form edit.
Deny access to user by checking whether he has created a node the specific day.

function MYMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($type == 'my_type' && ($op == 'create' || $op == 'update')) {
    my_module_check_if_user_has_published_content_today($account);
    if ($account->something == 'something') { // allow access
      return NODE_ACCESS_ALLOW;
    }
    else {
      return NODE_ACCESS_DENY;
    }
  }
// Return the default ignore value if your module doesn't need to get involved in this decision
  return NODE_ACCESS_IGNORE;
}

You should implement the select query that loads all nodes for the specific user on the specific day. You need to join node and user tables. Every node has a UTC value of the creation date. You can check if there is a node that was created after 00:00:01 and 23:59:59 in the specific day.


How do I get Views PDF to Download a file?

The headers are returned from TCPDF. The argument 'D' for download needs to be passed from views to TCPDF.

To do this I created a menu entry.

function yhivepasses_menu() {
  $items['yhivepasses/download/yogahive_passes_user_balance/pdf_1/user/%'] = array(
      'title' => 'YogaHive Passes',
      'page callback' => '_yhivepasses_views_pdf_download',
      'page arguments' => array(2,5,5),
      'access arguments' => array('access checkout'),
  );

Called the view manually.

function _yhivepasses_views_pdf_download($view_id, $views_display, $arguments) {
  if (!empty($view_id)) {
    $view = views_get_view($view_id);
    if (!is_object($view)) {
       drupal_set_message("Sorry, couldn't load your YogaHive Passes.", 'error');
       return FALSE;
     }

    $view->set_arguments(preg_split("/\r\n|\n|\r/", $arguments));

  if (!$view->set_display($views_display)) {
    $views_display = 'pdf_1';
    if (!$view->set_display('pdf_1')) {
      return FALSE;
    }
  }

  $view->pre_execute();

  $display = $view->display[$views_display];
  if ($display->display_plugin == 'pdf' && isset($display->handler)) {
    // arguments '' and I
    // Setup rules to take you to the 'completed' page and then do a redirect.
    //header('refresh:0;url=' . $base_url . '/user/14');
     $display->handler->execute('', 'D');
     $display->handler->post_execute();
    }
  }
}

The way that views-pdf calls views, I don't see a way to set the argument 'D'. There are no hooks, just a conditional call.


Issue with content access and multilingual system

I see 2 possible explanations for your issue, as further detailed below. Consider checking both of them to see if either one of them apply in this case.

Cookie problem

It is possibly an issue with a cookie. So try the same scenario usiing another browser. If with that browser the problem does not occur, then it is probably a cookie problem. In that case, just delete the session cookie in the browser where the problem occurs. Then check if the issue is resolved.

Site may be hacked

Since the version of this Drupal site is 7.32, it might simply be that your site was hacked. Refer to SA-CORE-2014-005 (posted a week before this question was asked ...) for some more details.

For way more details about that, and possible approaches to do more research on that, refer to Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?, which also suggests to use the Drupalgeddon module.


How to stop animation and turn off the delay time in superfish menu?

Adding custom js did the trick.

jQuery(document).ready(function() {
    jQuery('ul.sf-menu').superfish({
       delay: 0,
       autoArrows: false,
       speed: 'fast',
       disableHI: true
    });
});


ubercart checkout review button position

your better off targeting the checkout button via CSS than mess with ubercarts tables on checkout as the $form contains all of the other code which you would need to parse to extract the button and apply it somewhere else.

Just do a position: absolute on the button.

If your CSS isn't up to par, then I would parse the $form variable and preg_replace() it out. You'll need to have good regex skills to grab it.


Is it possible to have an external script run index.php that bootstraps Drupal?

To answer your question - Yes, it is possible to have an external script to bootstrap Drupal.

If Drupal is installed in the folder [root], and the index.php file that you want to get working is in [root/myscript], you'd first get the working directory and then call bootstrap.inc and bootstrap Drupal.

<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// do your thing
?>


In a "Global: Custom Text" you will see a number of tokens listed under "Replacement patterns", such as [title], [php] (referring to a "Global: PHP" field), [nothing] (referring to another "Global: Custom Text" field), ...

These tokens (or replacement patterns), are not listed when working with a "Global: PHP" field, you can only see a list of "Available variables", and if you put a token in the "Output code" textarea, it does not get replaced.

However, there is a way to access these tokens in "Global: PHP" fields. For example, if you are trying to access the [nothing] token, put the following code in the "Output code" textarea (not in the "Value code" textarea):

<?php
$static = $view->display_handler->get_handlers('field');
echo $static['nothing']->last_render;
?>

Solution found here: https://www.drupal.org/node/507012#comment-3410296

Except it was for Drupal 6, so they used $this->view. In Drupal 7, you have to use $view.


How to use form_set_error if no form field is involved in the error?

There is a plain solution

form_set_error('form',$error_messages);

Does not highlight any field, and the validation fails as expected. It doesn't allow multiple message, but this can be solved using a little hack

$error_messages = "";
if (type_error_1)
   $error_messages .= "Error Message on First Line
";
}
if (type_error_2){
   $error_messages .= "Error Message on Another Line
";
}
if(strlen($error_messages) > 0){
  form_set_error('form',$error_messages);
}


If you want to remove the link from the admin menu altogether, you just need to change the type to something other than MENU_NORMAL_ITEM. MENU_CALLBACK is the standard for this type of thing:

$items['admin/configuration/content/brd_contact'] = array (
  'title' => t('BRD Contact Form'),
  'description' => t('Configuration options for the BRD Contact Form module.'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array ('brd_contact_admin'),
  'access arguments' => array('administer brd_contact'),
  'type' => MENU_CALLBACK
);

After you clear Drupal's caches the link should be gone from the admin menu.

If instead you want to move the link from the top level of the menu into the sub-menu under 'Configuration', then you just need to change the string 'configuration' to 'config' in your path, to match the other system menu paths:

$items['admin/config/content/brd_contact'] = array (...

You'll need to clear the caches before that'll take effect too.


User specific permission to add links to a menu

Check this Menu Per User and let me know if you face any issues.


If you have one tid by node use:

$tid = 0;
$newNode->taxonomy[0]->tid = $tid;

if the node can have more than one term use:

$tids = [0, 3, 4, 5];
$i = 0;
foreach ($tids as $tid) {
  $newNode->taxonomy[$i]->tid = $tid;
  $i++;
}


Way to allow instantiating derived classes

You can do it however you like, really; however PHP will let you.

Basically you need to make a decision at some point in custom_get_my_service() about which class you're going to use. Drupal's paradigm is hooks, so a contrived example might be:

function custom_get_my_service() {
  $service = &drupal_static(__FUNCTION__, NULL);
  if (is_null($service)) {
    $service_class = custom_get_service_class();
    $service = new $service_class();
  }
  return $service;
}

function custom_get_service_class() {
  // Default
  $class = 'MyService';

  $modules = module_implements('custom_service_class');
  foreach ($modules as $module) {
    $function = "{$module}_custom_service_class";
    $class = $function();
  }

  return $class;
}

Then another module would implement the hook:

function another_module_custom_service_class() {
  return 'AnotherClass';
}

Obviously that's a very limited example, which will only let one module override the class, has race conditions, no error checking, etc. But that's the basic idea, I'm sure you can extrapolate from there based on what your module is providing.

You could also look at a DI approach, and have modules pass in their implementations of an interface you define into your functions, which then make the necessary use of them. It kind of depends on your level of experience with OO, and your opinions on 'best practice'.


To suggest specific templates you probably need to do it in your theme's template file, use the hook_preprocess_HOOK where the first hook is the name of your theme and seconde HOOK is either page to suggest a page template or node to suggest a node page.

Here's an example

/**
 * Implementation of hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$variables){
  // change the condition to whatever you like
  if(isset($variables['node']) && arg(2) != 'edit')
    $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
}


Variable default_bundle in migration? Field collection to varying paragraph types

Don't use the default_bundle at all, instead set the bundle type like other field values in the process section:

process:
  temp_bundle_type:
    plugin: static_map
    source: field_list_item_type
    map:
      card: card
      header: header
    default_value: card
  type: '@temp_bundle_type'


How can I bulk add existing commerce products to a display node?

entity reference view widget module solved my problem. it basically allows you to replace the add existing product button with a view. just customize the view to select any range of existing products you want and add them to the display node. saved my a boatload of time.


How do I set the node path with a contextual filter?

First of all you don't need Contextual filter in your first case where you are generating link as "node/[nid]" , what you need is replacement pattern. Todo this you can simply add nid to fields list and place above read more link and use the pattern.
Change read more link to "jobs/current/posting/[nid]"

Regarding what you are trying to solve

You cannot have a view with path "node/%" since it's already taken by node module to render node pages. It will conflict with node module and as you said "bombs out ALL of my other content"
In your view set path as 'jobs/current/posting/%'
Add a contextual filter nid and set provide default value to content id from URL as shown below.


The password recovery page is at "/user/password", not "/user/pass".

I also get an Access Denied when visiting "/user/pass" on one of my sites, whether I'm logged in or not, so I think you can assume this is the expected behaviour for that particular path.


How to create a node programmatically in Drupal 7?

You're trying to do a lot there.

You can do most of what you want without having a node in the database. I think node reference is a sticking point.

Views can be used with a number of back ends, you can get it to point to a different database or index your data with solr and use solr views to search and access your content, there is an issue with using completely external content but you can get round that. Sparql views can allow you to get data from a triple store.

You can populate a node object with fields and use theme node to display it without using node save.

A common pattern is to create stub nodes, which contain only a reference to an external resource and use nodeapi hooks to load the data when the node is viewed. This is often less work and would allow you to use the standard search and node reference functionality.

Without knowing quite why you don't want to save the nodes, it is difficult to make a concrete suggestion.


Login user programatically (Create user session)

User::load() loads information about an account, it does not inject or alter the current session in any way. user_login_finalize() is one of the key functions when doing programatic user logins because it will create and set a session for the current user.

See more:
https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user_login_finalize/8.7.x


How to validate a file upload field added to a form using hook_form_alter?

What you describe is what the Upload module does: In upload_form_alter() (an implementation of hook_form_alter()), it adds the form element to the node edit forms, and in the form submission handler it adds to the form (upload_node_form_submit()), it handles the uploaded files. With _upload_file_limits(), it checks the user didn't reach the assigned quota; with file_save_upload(), it checks the file passes the validators, and saves the file.

The Upload module, once enabled, allows you to enable the file upload for the content types. For example, for the Page content type, you can enable it at admin/content/node-type/page.

In the node edit form, the form element the Upload module adds appears as in the following screenshot.

If the Upload module is already enabled, and you need a upload form element more, than you should use the CCK module.


How to make a table sortable by CCK field

Try out Tablesorter moulde and add js function to your js file

$("Table").tablesorter();


How to set multiple domains for one language

Once you've set up Drupal to serve different languages in different domains, you need to instruct your web server to send requests from multiple domains to the same Drupal site.

In Apache, you'll need to edit the .conf (httpd.conf) file and add aliases to all the different domains. For example:

ServerName en.example.com
ServerAlias en.m.example.com

In addition to this, you'll also need to point the domain name server (DNS) to your server for all the domain names in different languages.


500 Internal Error Drupal 7.26 - Can't access forums

The "500 internal server" error message just means: "Your web server just crashed". There are many different things that can have gone wrong.

To determine the cause, you need examine your web server logs (your hosting provider can tell you where these are if you don't know where to find them).

Below is a list of some of the most frequent causes of a "500" error on a Drupal web site (I am trying to make this generic - for future reference - I know you've covered the PHP memory limit already):

The setting for PHP memory_limit is too low.  Note that if you're on shared hosting, you can't change this yourself.  You need to get it increased by your hosting provider.
Your hosting provider has set restrictions on what php_values or php_flags you can put in .htaccess that is violated by one of the .htaccess-files created by Drupal or by directives added to these by you.
Your have syntax errors in one of the .htaccess-files in your configuration. (In particular if you've edited the default .htaccess.)
There exists permissions on files or folders that is outlawed by a security measure your hosting provider uses.

As the message says: "The server encountered an internal error or misconfiguration". To gather information about what type of error this was, you need to examine the server (error) logs. There is no way we can help you with this without seeing the relevant error messages from your logs. We don't have access to your server or your logs.

You may also increase the level of error reporting from PHP to get better diagnostics. You'll get full runtime error reporting by adding this to the start of settings.php on your site (just below <?php):

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

In addition, navigate to: Administration → Configuration → Development → Logging and errors and select the radio button "All messages". This sets $conf['error_level'] = 2;.

When you examine the logs and diagnostics from PHP error reporting, you may find out more about what made your server crash.  If you do not fully understand what those messages means, you can update the question with the specific error messages, and hope that someone here shall be able to shed more light on the cause of the problem.

If everything else fails, make a backup of your database (you may use the Backup and Migrate module or some DB tool that works independent of Drupal (e.g. phpMyAdmin).  Then disable and uninstall the module that you thinks is the cause of your problems (sound like it is the Advanced Forum in your case.  Make sure you not only disable, but also uninstall (these are two separate steps).

Verify that your site is now stable.

If it is stable, re-install the module (e.g. Advanced Forum) that caused the problem from scratch.

Re-assess the status of your site. Is it still stable?  Is any content missing?

If it is not stable, then the problem is not solved, and you need to reconsider the use of module that causes grief (i.e. ditch it and find a better module).

However, if content is missing, you should be able to restore that back from the back-up yiu made (perhaps after looking through your backup files for anything problematic, and deleting it from the backup before restoring).


How to solve the apostrophe problem in node title? (' -> ')

Your issue seems similar to what's written in issues such as this or this.

The solution appears to be to use decode_entities, e.g. something like this:

$node->title = decode_entities($node->title);


How to start views at %nid position (from path)?

In jQuery Cycle there is an option called startingSlide. By default this is set to 0, like this: startingSlide: 0

If I remember correctly there is a tab/textarea for advanced settings where you can add options to jQuery Cycle from within the Views UI. I think you can add "startingSlide: 5" for example there.

You will need to find out which is the starting slide (convert the %nid to which row in the view it is) and add it as a HTML element. When that is in place we can fetch it with jQuery and add it as a jQuery Cycle option. I'm not sure which is the best way but I think you could do something like:

    function MYMODULE_views_pre_render(&$view) {
      if($view->name == "MYVIEW") {
        $view->attachment_after = $startingslide;
      }
    }

You will have to add more code to find out $startingslide there of course. Look inside $view->result and find out which of the rows that is the argument, that will be your $startingslide. Use dpm() on the view to search through the object.

Hope this will help you. Let me know what you ended up doing :)


How to validate a value against an existing field

install entity_validator module .

  Unlike Drupal 8, Drupal 7 has not validation for entity objects what
  so ever. One of your modules can create a node object without any
  title or a language and you don't want that.

for drupal 8 Use Entity Validation before save your fields.

as a example

 $violations = $typed_data->validate();
    $definition = DataDefinition::create('integer')
      ->addConstraint('Range', ['min' => 5]);
    $typed_data = \Drupal::typedDataManager()->create($definition, 10);
  if ($violations->count() == 0) { // this means there is not any validation error
     // save Entity
  }


For readability, and simplicity, I like to use the core API:

Check if current user is authenticated

user_is_logged_in()

i.e:

if (user_is_logged_in()) {
  // User is authenticated
  print $content;
}

You can also use

if (!user_is_logged_in()) {
  // User is anonymous
  print $content;
}

though there's even a user_is_anonymous() function

if (user_is_anonymous()) {
  // User is anonymous
  print $content;
}

Check if particular user is logged in

If you want to check if a particular user is online

You can use Rules, or hook_user_login to respond to login event

EXAMPLE_user_login(&$edit, $account){
  /* do stuff */
}

or query the session table for that user session uid

// Check if user $uid is online in the last 10 minutes
$online = db_query("SELECT uid FROM {sessions} WHERE uid = :uid AND timestamp >= :time", array(':uid' => $uid, ':time' => (REQUEST_TIME - 600)))->fetchField();


How to get notified when a user is locked?

You can use Login Security module for D7. It has notifications.

Form the project page :

  A set of notifications by email or Nagios may help the site
  administrator to know when something is happening with the login form
  of their site:


Implement hook_node_access based on field value

You don't need the node form to access its fields to check for conditional access. Use the field data in your node object.

if($node->my_field_name[LANGUAGE_NONE][0]['value'] == 'TESTED_VALUE') {
  return NODE_ACCESS_ALLOW;
}


Create a list of taxonomy terms which filter specific nodes

There is no need to install module. create a field of taxonomy terms, in the view create a contextual filter of that field and it will work.

To create a navigation you need to loop through the taxonomy terms. it is something like this code. I am not able to execute the code right now to give you the exact code but using Devel module and looping (foreach)throught the objects you can get the terms and use them to build the navigation.

$name = 'YOUR_VOCAB_NAME';
$myvoc = taxonomy_vocabulary_machine_name_load($name);
print kpr($myvoc);

This code will print out the list of terms and their properties.


How to change the place of a block or region based on url path?

Hope this will help you.

In Drupal 7 you can achieve it using Context module as suggested by the Jack.

Steps

Fist of all disable the menu block using admin/structure/block.

As you specified you need to show menu block in two regions, then those 2 regions(main content and above the content) must exist. If not then create it.
Create a new context and add menu block based on your requirement and path.
Showing menu block block in region Content

Showing menu block block in another region user bar second

Reference :

create custom regions


Creating mobile-applications (like Android applications) with Drupal?

I would recommend to take a look at DrupalGap

Also especially regarding Drupal 8 I would recommend reading this article:


How do I debug connection problems while testing Deploy module while using local host?

There are few issues with your examples.

You're missing routing-script for the built-in PHP web server. It's recommended to use since you're using PHP built-in web server and by default it may have some problems handling certain clean URLs (for example URI containing dots are treated as direct files). So you should apply this patch from #1543858 and re-run you server as below (same file you can use for both Drupal 7 & 8):

php -S localhost:8000 .ht.router.php

You should use -l in order to specify URI of the Drupal site to use, so your code knows what's your proper hostname (since the fail is related to the connectivity issue).

drush -v -l http://localhost:8000/ cron

If you still have Connection refused, you should check where the code is trying to connect and check the connection (e.g. wrong configuration or firewall in place). To debug the connectivity issue, on OS X you can use dtruss, on Linux this can be debugged by strace, e.g.

strace -e trace=network -fp $(pgrep -fn php)


There is no direct way to do it nor any programmatic way. This is because the template structures differ so much. But here are the steps you should take for the fastest conversions...

Load theme in Wordpress then view site in a browser. (the purpose of this is to extract the basic HTML structure of the template).
View source on the page, copy all the HTML and drop into a text editor. Save into a new project folder.
Copy over CSS and JS files to this new project folder. I recommend using a "css" folder and a "js" folder for organization.
Copy over all images to this project folder. I recommend using "images" folder.
Now you have the base template you need to turn it into a theme for Drupal. Time to get busy!
I recommend copying the "garland" theme to a new project folder and renaming it to your new theme name. This will speed things up.
Copy over the css, js, and images folders to the new theme project.
Edit the .info file to load css and js files.
Modify the css and js files to load any images and other file paths to be relative to them.
Using a side-by-side comparison between the page.tpl.php and your template html file you will need to transform the structure of the tpl file to be close to that of the html file. Be careful not to remove dynamic references.
Test, troubleshoot as needed.

Its a lot of steps, but it works. You can also use a theme framework that provides a skeleton theme to build upon. The only problem with this is that sometimes these frameworks are very heavy handed and do far more than is needed. Zen is a common one, but it is very heavy handed. You can find more on the Drupal website at drupal.org (search for themes). Below are some links to a few base themes.

Zen Framework
NineSixty (960 Grid System, very flexible concept, I have never used it though)
Fluid Grid (another great concept, I have seen this in action and its pretty nice)

Finally, here is a link to Drupal's theming guide.


Peer-to-peer recognition system using User Points and Rules modules

To solve problem #2:

  How to automatically add +1 point to UserA who add point to UserB

In the rule Do section:

First, add action "Load current user account" and set User Id: [:global:user-id]. Name it as "Current user".
Then, in the "Grant points to a user", refer to "Current User" as User argument


Yes this can be achieved by using views module. And the structure should go something like:
a. Content Type Book.
b. Content Type Chapter.

Now chapter CT will have node references field of CT Book.

Create a view of books content type which will show all books then create a page within same view with some changed filters to show /books/book-name.

Now create another view  with link /books/book-name/chapter-number where book-name will match the node reference field or /books/book-name/ from previous view to get book name.


if you wont find any other solution without coding to deselect that checkbox you can try to do it via your custom module (if you don't have any you will have to make one - that's different story).

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id){
  $form['field_order_details']['und']['0']['value']['#resizable'] = FALSE;
}

Something similar should work for your checkbox.

See hook_form_alter().


Does cache-tag / cache context bubbling up mean core doesn't actually individually cache separate page components?

The bubbling is for the cache_tags and contexts, so it's related to when the cache on the parent item clears.  The parent item will clear based on the children, as the parent has all the child cache tags.  It doesn't mean that the children don't cache.  They do, but they won't refresh at the same rate as the parent.  The parent will potentially clear more often and then rebuild from the cached components.


Additional fields for my entity from another table in views

Technically it's possible, using hook_views_query_alter(), you can adapt the view query to add or change conditions. So you could add a join with something like this:

function modulename_views_query_alter(&$view, &$query) {
  $join = new views_join();
  $join->table = 'mytable';
  $join->field = 'eid';
  $join->left_table = 'entity_table';
  $join->left_field = 'eid';
  $join->type = 'left';
  $query->add_relationship('relationship_name', $join, 'entity_table');
}

But a better approach would be to use hook_views_data() to expose your table to views, and then add the relevant fields when needed (with a relationship though), but in practical terms is no different than altering the query.


node_delete() does not trigger the "deleting content" Rule?

Short inspection of rules code showed that it should be triggered after node delete:

function rules_entity_delete($entity, $type) {
  switch ($type) {
  ...
    case 'node':
      rules_invoke_event('node_delete--' . $entity->type, $entity);
      rules_invoke_event('node_delete', $entity);
      break;
  ...

(from events.inc)

Have you tried turning on rules debug to see what is happening? Go to admin/config/workflow/rules/settings and turn on Show debug information to Always.

Maybe the event is being invoked, but some of your condition is incorrect and it appears that nothing is happening.


How to use a terminate kernel event to log page access statistics?

The comments you got are golden, my answer is along the lines of what @IvanJaros suggested, but follows a simpler approach. And take care to check the case of external caching (if any is in play).

The following should make your current approach work.

public function logAccess(PostResponseEvent $event) {

  $request_format = $event->getRequest()->getRequestFormat();

  if ($request_format === 'html') {
    // \Drupal::database()->
  }
  else {
    // Do other stuff.
  }
  ...

This snippet tries to detect requests with the html format (i.e. page requests) and will ignore other ones, like e.g. application/json.

Good luck!


Entity create access based on a custom field

Use the rules module instead? https://www.drupal.org/project/rules

Before saving entity of type X
Entity has field Y
Entity field Y is Z
Allow, else deny


You can put almost anything you want in a Views Header or Footer, so if you added a Global Text Area field there, you could put in a link to a page display of a view that shows your content types, and that should do what you want.


Entity Wrapper : how to delete multiple values field?

Well, I solved it. The answer is kind of tricky.

You can't delete a value in a multiple values field. However, you can set it to "empty". When it's empty, it's removed.

Here is the code to use:

// Also, note the ->count() method
for ($i = 0; $i < $user->field_data->count(); $i++) {
  $user->field_data[$i]->set();
}

This way, values are now empty and the multiple fields have no value left. It's well shown in the UI too and the deltas are correctly handled in the database.


What's the latest in the page lifecycle a module can send an HTTP header?

Headers can be sent anytime up until the content is sent to the page which happens in drupal_page_footer(). The whole page is output buffered: _drupal_bootstrap_page_header has the ob_start and drupal_page_footer has the ob_flush.

Headers are also overwritten by default so there is no reason why you can't re-send the Last-Modified header at any point.

So, how about hook_exit() (called from drupal_page_footer just before the ob_flush).


what is the hook when a commerce order is updated?

The documentation for commerce_order_status_update() says:

  While there is no explicit Rules event or hook devoted to an order
  status being updated...

It is possible to use hook_commerce_order_presave():

/**
 * Implements hook_commerce_order_presave().
 */
function my_module_commerce_order_presave($order) {
  if ($order->status != $order->original->status) {
    drupal_set_message("The order status changed from {$order->original->status} to {$order->status}");
  }
}

Here's an optional helper function for use elsewhere if you have an $order object, and are curious if its status has changed from what is stored in the database:

/**
 * Given an order object, this returns FALSE if the order status has not
 * changed. If it has changed, it returns an associative array with the
 * following keys: new_order_status, old_order_status
 */
function my_module_order_status_changed($order) {
  $result['new_order_status'] = $order->status;
  $result['old_order_status'] = db_select('commerce_order', 'co')
    ->fields('co', array('status'))
    ->condition('co.order_id', $order->order_id)
    ->execute()
    ->fetchField();
  if ($result['new_order_status'] == $result['old_order_status']) {
    return FALSE;
  }
  return $result;
}


WYSIWYG do not make url when pasted in a hyperlink

This is the solution--
On drupal administration:

Administration » Configuration » Content authoring » Text formats

you must remove "Converts URL into links" and then all it's Right!!


To get the users filtered based on profile2 field, field_ngouniqueid is created through profile2

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'profile2')
->fieldCondition('field_ngouniqueid', 'value', (int)$company_id, '=');
$results = $query->execute();

$users = user_load_multiple(array_keys($results['user']));


How to use Subtitles/Captions with MediaElement.js module

The MediaElement module doesn't support it. In order for ME.js to display subtitles, you need to add a <track> element (e.g. <track kind="subtitles" src="subtitles.srt" srclang="en" />). The module's theme function, theme_mediaelement_video(), doesn't render that element.

In lieu of this, you can override the theme function to add the required <track> element. For example placing this in your theme's template.php:

//Here we're assuming an .srt with the same name of the video exists alongside
//(e.g. "sites/default/files/video.mp4 & sites/default/files/video.mp4.srt)
//Given you might want to upload srt files along with content
// you'll want a better solution

function MYTHEME_mediaelement_video($variables) {
  $output = '
';
  $output .= '<video ' . drupal_attributes($variables['attributes']) . ' >';
  $output .= '<track kind="subtitles" src="' . $variables['attributes']['src'] . '.srt" />';
  $output .= '</video>';
  if ($variables['settings']['download_link']) {
    $output .= '
' . filter_xss_admin($variables['settings']['download_text']) . '
';
  }
  $output .= '
';
  return $output;
}


how should I hide the menu and url setting in from alter?

As explained in hook_form_alter

  The call order is as follows: all existing form alter functions are
  called for module A, then all for module B, etc., followed by all for
  any base theme(s), and finally for the theme itself. The module order
  is determined by system weight, then by module name.

  Within each module, form alter hooks are called in the following
  order: first, hook_form_alter(); second,
  hook_form_BASE_FORM_ID_alter(); third, hook_form_FORM_ID_alter(). So,
  for each module, the more general hooks are called first followed by
  the more specific.

So, your module hook_form_alter is called before path module or menu module which adds those elements. That's the reason you can able to see those elements when you print form in your custom module.

Try using same form alter hook in your theme template.php it should work. It worked for me ! I can able to see path settings and menu setting. See for Seven Administration theme below.

function seven_form_alter(&$form, &$from_state, $form_id) {
  drupal_set_message("<pre>" . print_r($form, 1) . "</pre>");
}

Else, you need to alter your module weights !!


The Hierarchical Select module does exactly what you describe. Here is a demo that even uses car brands as the example.


I'd try this link. So install that then apply some classes to the menu items that you can use in JQuery to target the links and have the dropdown links trigger them to show/hide. I'm willing to provide further explanation if there's something you're unclear of. Sadly there is no current module or plugin to provide this functionality that I know of.


Get media image url in views-view-unformatted template

I did with this code row.content['#row']._entity.YOUR_FIELD_NAME.entity.fileuri


"Notice: unserialize() [function.unserialize]: Error at offset 10301 of 11637 bytes on views_db_object->load_row()"

I have encountered the same issue and thus far to resolve but I found this article.

http://www.zyxware.com/articles/3337/drupal-errors-drupal-views-notice-unserialize-function-unserialize-error-at-offset-1009-of-1036-bytes-in-views-db-

so...i researched some more and found this solution. I added this line to bootstrap.inc

$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $variable->value);
$variables[$variable->name] = unserialize($data);

in the variable_init function


You're probably wanting the basic solution explained in this video: https://commerceguys.com/blog/using-calculation-rules-add-item-shipping-commerce-shipping-screencast

With a little modification, it looks like this:

Add a new "Calculation rule" for your shipping service.
Add an action loop that loops through the line items in the order.
Add an action "Calculate a value" and multiply the quantity times a field which holds the shipping price you want to charge for that item and store it in a named variable.
Add an action "Add an amount to the unit price" that adds the named variable to the unit price of the shipping line item.


Why do taxonomy_get_tree() & entity_load('taxonomy_term', etc..) give different counts?

After running some mysql queries on the taxonomy_term_data table it appears that the difference in counts is caused by differences in the terms language property.

When I count the terms in the taxonomy_term_data with the language set as 'und' it matches the total given by taxonomy_get_tree($vid)

When I count all terms in the taxonomy_term_data table regardless of language the total matches the the count given by entity_load('taxonomy_term', FALSE, array('vid' => $vid))

So if you only need terms in your current language go with taxonomy_get_tree($vid) otherwise you'll need entity_load().


How to write a rule for 'After sending email'?

There is no Rules Event like "*after sending eMail". However, you can create a Rules Component for sending an eMail. For a sample of such Rules Component, refer to the answer to "Rule to store user's last post date and scheduled rule based 30 day reminder".

If you then "invoke this Rules component" any time a rule has to send an eMail, you basically created the equivalent of the Rules Event you're asking for. All that's left to do is to expand that Rules Component with additional Rules logic that you want to happen "after sending eMail" (... as in your question).


It is much more easier to implement this using views module. In this tutorial, you can ask user an input, and search on any field in the content type.


Restrict editing of content based on form value in content type

(I think it'd be fine to have either 1) the rooms originally created
  by an admin and just have the building field hidden/disabled/limited
  when non-admins edit, or 2) even let them create new rooms with the
  building field limited based on their role/permissions.)

You could do this via a custom module or in your theme's mytheme.theme

function mytheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // check form id for edit
  if($form_id == 'node_room_edit_form') {
    // Load the current loggedin user.
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    // Check if user does not have administrator role
    if(!$user->hasRole('administrator')) {
      // get current node id
      $nid = \Drupal::routeMatch()->getParameter('node');
      // load the node
      \Drupal\node\Entity\Node::load($nid);
      // check if building field is not set to something
      if($node->field_building->value != 'something') {
        // remove access to field, make field not required so when
        // they save they don't get an error.
        $form['field_name']['widget']['#access'] = FALSE;
        $form['field_name']['widget']['#required'] = FALSE;
      }
    }
  }
  // check id for create
  if($form_id == 'node_room_form') {
    // logic goes here.
  }
}


Display plugin entityreference is not available

So - after getting another pair of eyes on this the issue is resolved. Somehow, the entityreference module was only partially installed and was missing the views directory (along with a couple other things) but was otherwise fully functional outside of the issue as described above.

Not sure how the module would be working for other purposes, not throw any errors at all without those directories but that was the case.

Thanks to Matt Glaman for the help tracking down the problem.


Cannot use feeds to import into data tables where the primary key is multiple

The simplest thing to do would be to use Feeds Tamper's Rewrite plugin to combine the unique fields in your source into one field and then map that to the GUID.

https://drupal.org/node/1539224 could use some help as well for supporting this properly.


Related Content View with multiple Entity Reference Fields

Basically you need to do the following.

Create a view based on content of type parts (as a block I'm guessing)
Add a relationship "Content: Country (field_country)" using the defaults
Add a relationship "Content: Type (field_type)" using the defaults
Add a contextual filter for "Taxonomy term: Term ID" with the following settings.

Relationship: country
Provide default value: Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Limit terms to vocabulary: Vocabularies country.
Multiple-value handling: Filter to items that share all terms

Add another contextual filter for "Taxonomy term: Term ID" with the following settings.

Relationship: type
Provide default value: Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Limit terms to vocabulary: Vocabularies type.
Multiple-value handling: Filter to items that share all terms.

Now just place your block on all car pages.


Is there way for create custom "add userpoints transaction" form

Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to Grant user points, to the user specified as a parameter for this Rules Component.

For an example of a Rules Action to grant user points, refer to the rule included in the answer to "How to grant User Points to viewing user when user has viewed content?".

Step 2

Create a view of the group of users for which those fields should be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.

Tutorial

To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

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


Hide fields on the user profile page with preprocess function

You do not need to use any preprocess functions tbh :> its pretty simple
Go to Home » Administration » Configuration » People » Account settings » Manage Display , History -> Format  chose hidden.


Have a look at this article, I've used the method in the past.

http://timonweb.com/working-with-drupal-fields-getting-single-field-values-for-display-and-manipulaton


additional Social icons in ShareThis module

You can do this by using Social Media Links Block module.

  The modules provides a configurable block that display links (icons)
  to your profiles on various popular networking sites.

For Flicker, use Flicker module.


how to start fresh and add custom backgrounds

Create a folder called "myTheme" in sites/all/themes
Create a file in that new folder called "myTheme.info"
Copy the sample .info from below into the info file
Now create a folder in your theme called "css"
Now copy style.css from Bartik's css folder into your css folder
Now change the background using CSS
Any other changes you want to make? Copy from bartik into your theme folder, make the change

Sample info file:

name = My Theme
description = My theme is amazing
core = 7.x
engine = phptemplate
base theme = bartik


How i can add a new line in my code here?

There are two options (simplified code example):

$description = t('Foo.
Bar.'); (recommended)
$description = t('Foo.') . '
' . t('Bar.');

The
 tag causes a line break in HTML. Both options give the same result technically. The difference is in what translators can do with it.

Option 1 treats the sentence as a unity and gives translators more flexibility. For instance, if the French translation needs to change the word order ('Barre.
Fou.'), that's possible. However the French translator would also have the possibility to leave out the line break completely.

Option 2 is more rigid. A translator could never control which part comes before the line break and which part comes after. The translator may not even know that the sentences "Foo." and "Bar." will be combined into a single page element, because they show up as separate strings in the translation interface.


Webform file upload not working after hook_from_alter

I fixed this by forcing the the 'op' value to

 $form['actions']['op'] = array( '#type' => 'value', '#value' => 'Submit', );


How to deal with this kind of node references, when creating a new instance of a content type?

I would create a taxonomy hierarchy that has nested State -> Cities. You can then provide a way for them to choose a state, and filter a drop-down by the parent taxonomy.

Hierarchical Select will do this for you.

If you need to create a content type for city, just apply the same taxonomy term to link the two together.

Kim


How do I increase the number of shortcuts allowed in admin menu?

The maximum number of shortcuts is defined in shortcut_max_slots(), which just returns a variable:

return variable_get('shortcut_max_slots', 7);

So all you need to do is change that variable to something larger than 7. You can use the devel variable editor to do it, or just run the following code from somewhere:

variable_set('shortcut_max_slots', 10);


How can I set product price per taxonomy term on Ubercart?

If you want to automate this, use Rules module. another option is ubercart core options.


Json-Import of nodes with taxonomy terms

Not knowing how the rest of your dependencies are set up, one thing I notice off the bat is that your keywords source field is a comma-separated single string, but you're treating it as an array of values in your processor. Maybe something like this:

protected function createBlog(string $json)
{
    $jsonout = json_decode($json, TRUE);

    foreach ($jsonout as $blog) {
        $newTags = explode(', ', $blog['keywords']);
        $newTagIDs = [];
        foreach ($newTags as $tag) {
            $newTagIDs[] = Term::create(array(
                'name' => $tag,
                'vid' => 'tags'
            ))->save();
        }

        $node = Node::create(array(
            'type' => 'blog',
            'langcode' => 'de',
            'uid' => '1',
            'status' => 1,
            'title' => $blog['title'],
            'field_tags' => $newTagIDs,
            'body' => ['value' => $blog['bodytext'], 'format' => 'full_html']
        ));

        $node->save();
    }
}

You're right that your approach would create multiple copies of the same term, though. The Entity Lookup plugin from the migrate_plus module might provide some help:

// $this->entityManager is a dependency-injected instance of Drupal\Core\Entity\EntityManagerInterface
$query = $this->entityManager->getStorage('taxonomy_term')
    ->getQuery()
    ->condition('name', $termNameToLookup)
    ->condition('vid', $vocabularyToLookup);
$results = $query->execute();
if (empty($results)) {
    // term doesn't exist in that vocabulary; should add it
} else {
    // the term already exists in that vocabulary; do something with it
}


How do I list my profile in the profile list after downloading the Drupal distribution with drush make?

You need a custom sh file that does the drush make, and moves the profile files for you.