How to add highlighting to exposed views_autocomplete_filter in Drupal 8

So it seems it is necessary to extend the ViewsAutocompleteFiltersController class to do this.  In order to override the routing so that a custom controller can be used instead, an entry must be added to /mymodule/mymodule.services.yml:

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

Then provide your /mymodule/src/Routing/RouteSubscriber.php file, which redirects to our local ViewsAutocompleteFiltersController

<?php

namespace Drupal\mymodule\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    // Replace "some.route.name" below with the actual route you want to override.
    if ($route = $collection->get('viewsfilters.autocomplete')) {
      $route->setDefaults(array(
        '_controller' => '\Drupal\mymodule\Controller\ViewsAutocompleteFiltersController::autocomplete',
      ));
    }
  }
}

Finally provide your local /mymodule/src/Controller/ViewsAutocompleteFiltersController.php which filters for the view of interest, then modifies the output of the base ViewsAutocompleteFiltersController.  The tricky part of that process is that the data member of the JsonResponse output is protected, so we use a customized JsonResponse wrapper to perform the highlighting:

<?php

namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Overrides default ViewsAutocompleteFiltersController to provide highlighting of autocomplete suggestions
 */
class ViewsAutocompleteFiltersController extends \Drupal\views_autocomplete_filters\Controller\ViewsAutocompleteFiltersController {

  /**
   * {@inheritdoc]
   */
  public function autocomplete(Request $request, $view_name, $view_display, $filter_name, $view_args) {

    $response = parent::autocomplete($request, $view_name, $view_display, $filter_name, $view_args);
    if($response instanceof JsonResponse && $view_name === 'my_view' && $view_display === 'my_view_display') {
      $response = new HighlightedJsonResponse($response, $request->query->get('q'));
    }
    return $response;
  }

}

/**
 * Overrides default JsonResponse to provide highlighting of autocomplete suggestions
 */
class HighlightedJsonResponse extends JsonResponse {

  function __construct($jsonResponse, $q) {

    $data = \json_decode($jsonResponse->data);
    if(isset($q)) {
      $qPattern = '/(' . preg_quote($q, '/') . ')/i';
      foreach($data as &$datum) {
        if(isset($datum->label)) {
          $datum->label = '' . \preg_replace($qPattern, '$0', $datum->label) . '';
          $datum->label = \str_replace("","",$datum->label);
        }
      }
    }

    parent::__construct($data, $jsonResponse->statusCode, $jsonResponse->headers->all());

  }
}


Consider what's at the top of the html.tpl.php file...a call to <?php print $scripts; ?>.

This would logically mean that all scripts added by drupal_add_js() in the current page call have already been rendered down into the $scripts variable, and printed to the page.

Thus, when you call drupal_add_js() inside html.tpl.php, it's too late to add new scripts with drupal_add_js().

This sort of code should never really be inside a template file anyway to be honest, it should be inside a preprocess function inside your theme's template.php file.

On another note, it looks like you're trying to insert jQuery 1.7 into the current page. This may cause you all sorts of problems as Drupal already loads its own version of jQuery into the page...you'll probably get conflicts.

The better way would be to install the development version of the [jQuery update][1] module, which has the option to use jQuery 1.7 throughout the site. I don't know the current state of this; the last time I checked (a couple of months ago) there were still some core JS elements that break using 1.7.

You can find a bit more info here: How do I update jQuery to the latest version I can download?


How to enable install from url in Drupal Commons?

Also you can try Drush

  Drush or drupal shell is a command-line utility to help the site
  building and maintenance workflows.

The following will download and enable the module:

drush en module_name -y

Example Commands

drush dl cck zen

Download current recommended versions of CCK module and Zen theme.

drush en content

Enable the content (cck) module.

 drush vset theme_default theme_name

make theme_name theme default theme


Creating custom cron jobs in the same module

Found a solution with a help from a colleague. Will post it here if someone would have need for it some day.

I'm missing a callback function here that triggers the actual feed import. And also I changed from Ultimate Cron to Elysia cron. (not sure if that actually makes a difference here though)

the actual function that triggers feed import is from feed_import_base.module

_feed_import_base_process_feed($feed);


It will be Solved by adding

--root=/full/path/to/your/webroot

to the drush command.


Display multiple values in entity reference view

Try to use Entity Reference Views Select module. For me it worked when I had the same issue.


how to import some content to a new site?

The deploy module can move nodes between Drupal sites.  For advanced uses there's also migrate.


You can try the Workbench Moderation module.

  Workbench Moderation adds arbitrary moderation states to Drupal core's
  "unpublished" and "published" node states, and affects the behavior of
  node revisions when nodes are published. Moderation states are tracked
  per-revision; rather than moderating nodes, Workbench Moderation
  moderates revisions.


Set active trail in hook_preprocess_node

The menu active trail is defined by the menu.active_trail service. Unfortunately it doesn't use a tag based extension like breadcrumbs.

You can replace that service and in case you detect that you're on a patch displaying a certain content type, return your desired structure.

You could also try out the https://www.drupal.org/project/menu_trail_by_path module, which defines the active trail based on the aliased path, like breadcrumbs do by default.


Using the Commerce Kickstart distribution to sell non-standard products

Not really an answer, but only my point of view.

I would create a dummy item without price and add the calculated price to the carrier fees.
You can trigger almost every action you need from Rules.

Add FOO item to cart.
Add the transport fee to the order.

This rules are already there in Kickstart, you will only have to tune the Carrier fee calculation rules to fit your use case.
Of course I don't think Kickstart is designed with selling services in mind but I don't think you are going to find any major problem in going this way. Think of a store with only one product that ships worlwide with different transport fees. The carrier can well be a variation type of your product.

My 2 cents.


Render node content in page.html.twig level or blocks at node.html.twig level

So one thing is directly accessing the node object that you have available. E.g. {{ node.some_field.value }} (which prints the raw value of e.g. a text field, not what you want in most cases) or {{ node.some_field.view() }} (which views it using the default formatter configuration, you can also provide a view mode or formatter configuration to it).

See also the two related questions that I already added as a comment:  Render a node field inside page.html.twig AND Render image field from node in page.html.twig.

As you found out yourself, you can also use blocks for this. However, using views for that is a bit backwards. Views executes a query. So what it does is get the node from the already loaded ID, then does a query to get the node ID and then gets the node again for that Node ID ;)

As an alternative, blocks in D8 support context. So they can get things from the site injected and use it directly. See https://drupal.stackexchange.com/a/188629/31 for some explanation on this. You can implement a custom block yourself and print out what you want, or you can use the block that ctools provides that allows you to view a node with a specific view mode.


Flagging users as spam and giving a reason for doing so

Why not use the Flag Note module.

  Extends the Flag Module to allow users to enter a note when they flag
  a piece of content and eventually build a flag history.

  Usage examples:

  flag nodes or comments for abuse providing a descriptive reason
  flag users as friends leaving a hint

  It's possible to opt to keep old notes even when the content gets
  unflagged


How to use "db_query" instead of "db_select"?

db_query can be used with an actual MySQL query - you just insert the MySQL query as you would in, say, PHPMyAdmin or some other UI for MySQL (or command line).

You can also substitute arguments into the query based on the second argument passed to the function, as such (found on Drupal.org as an example):

$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

Here the $uid variable is being passed as an argument to the query. Theoretically you could also write this as such:

$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = ' . $uid);

As Clive mentions in the comments though, this is just for illustrative purposes, as it does open you up to potential attack.


How to display form module in two coloms?

You can use the markup-type in your form array to group form items and then style the groups.
The code below will wrap the three items with a div which has the class column-left. Do the same for the right column.

To clear things up: The column_left-item is of the type markup, which is the default type.

$form['column_left'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
);
$form['column_left']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    '#maxlength' => 20,
    '#required' => TRUE,
);
$form['column_left']['last'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
    '#maxlength' => 20,
    '#required' => TRUE,
);
$form['column_left']['street'] = array(
    '#type' => 'textfield',
    '#title' => t('Street Address'),
    '#required' => TRUE,
);

For Drupal 7, you can use the container-type and use the attributes array to add the class. A div is generated automatically.

$form['column_left'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('column-left'),
  ),
);


Get submitted values of webform in hook_alter function

hook_alter_form() is only invoked during form array build time, not when the form is submitted, so it's not possible (as is trying to submit a form that isn't rendered to the browser yet). If you want to handle the submitted form values for your own custom processing, add a submit handler to the form array.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'webform_client_form_ID') {
    $form['#submit'][] = 'MYMODULE_webform_client_form_ID_submit';
  }
}

function MYMODULE_webform_client_form_ID_submit($form, &$form_state) {
  // @TODO: process $form_state['values'] as needed.
}


How to add file extensions to list of acceptable in IMCE

Go to admin/config/content/wysiwyg. Under the textformat table if CKEditor is choosen on full html for example under the operations column, select edit. And you should see buttons and plugins, and you should find the Imce checkbox listed as one of the last checkboxes


Eventually figured it out! (obvious in hindsight!)

I shouldn't have had the line:

'unix_socket' => '/opt/bitnami/mysql/tmp/mysql.sock',

in the database setting in settings.php

Removed it for the remote db's and it works perfectly.


No, hardcoded function calls can not be replaced.

The only thing you can do is add your own preprocess function for "forum_list "(yourmodule_preprocess_forum_list()), and then call another function to overwrite the value returned by the function.


The rewrite rule will not work because page is not a valid path on the server. By default Drupal rewrites all requests into index.php. When you rewrite to page apache will expect a path page on the server.

This is not quite the right way to accomplish what you are trying to do in Drupal. However you can achieve what you are trying to do with the following

RewriteRule category+/(.*)$ page?id=$1 [R=301,L]

That will redirect category/5 to page?id=5 and you will get 5 in $_GET['id']

Check these out as well

https://www.drupal.org/docs/user_guide/en/content-paths.html

How do I retrieve the query parameters from a path?


If you are talking about the $context variable (and I think you do), then the official description is: an associative array containing extra information about what triggered the action call, with $context['hook'] giving the name of the hook that resulted in this call to actions_do() (from here:  http://api.drupal.org/api/drupal/includes!actions.inc/function/actions_do/7)

But if you want to understand it better, this page is very useful: http://www.sysarchitects.com/node/47


Make blog available to authenticated users only

Would the 'Content Access' module be what you are looking for?

http://drupal.org/project/content_access

Using this you would be able to set your Blog content type to be viewable only by registered users.


Is it possible to theme node add form in drupal 7

The $variables['theme_hook_suggestions'][] only suggests theme for the node itself not the form to add content!

You have to let us know how exactly do you want to display your form. Some times a few CSS codes may be enough.

Anyway to theme the node add content you can use hook_form_alter to add some attributes to the form elements, add CSS classes or ... . You can also use Firebug to get the fields ID or class names then use CSS to theme them.

The following code

function THEME_form_alter(&$form, $form_state, $form_id) {
      print $form_id;
}

gives you the ID of the form. Find the ID of the node add form and do the changes. like

function THEME_form_alter(&$form, $form_state, $form_id) {
      if($form_id == "NODE_ADD_FORM")
            ////
}


Why can't I save a Send HTML Email action?

Thanks Pierre for your suggestion. I didn't need to try it, but it makes a lot of sense. Wish I'd have thought of it!

In the end (before I saw your suggestion), I rebuilt the email using a different generator tool, which seemed to produce much smaller and cleaner HTML.
This works OK. It looks like there was either a problem with the HTML or there is some kind of limit on length.


You should disable the view by going to
Structure -> views
Inside views on the right side there will be a tab and when u click on it you can disable the view so that you can enable it for future use.


Features versus Configuration Management

I would advise using Features. This would allow not only exporting functionality and compartmentalizing it a lot easier, but you could also have the ability to bring in features later from an external source, and/or, use certain features here on a different site that didnt start with your installation profile.

Currently there is an issue to support custom path generation for Features:  https://www.drupal.org/node/2693123

When that is addressed, you can generate the features to the path of your choice. For now, you can generate the result, grab it out of modules/custom and place the generated feature module into your profile.


Rewrite results output creates 2 links for one for one rewritten custom text field

When rewriting a field into a custom link you have to make sure that the tokens used for the link text aren't formatted as links, because links can't be nested one into the other.

Edit the field settings for the fields corresponding to {{ field_tool_manufacturer }} and {{ title }} and make sure their Formatter option is set to Plain text, or that the option to "link this field to content" is not checked.

Most field settings will be applied to the token in the Rewrite field option, so you have to control the output yourself.

You can test what the field output is by simply viewing the field without any Rewrite options, and if you see the field output as plain text, and not a link, you can proceed to set up the Rewrite options.


How to check if a scheduled Rules action set has already been scheduled?

The answer to this is simple.

In the action of the rule that calls the schedule component evaluation, in the Identifier section, set a unique value, such as:
reminder-[node:title]-[node:nid]

This value will be a unique identifier of the scheduled task. Scheduled tasks with the same ID will simply be replaced. Problem solved.


How to loop through a dynamic taxonomy vocabulary and if term is chosen, do an action?

If a new node of node type 1 is saved,

= Rules Event: After saving content, of type "type 1".

  then check which taxonomy terms are selected.

= Rules Action: Create a Rules loop, which iterates over each of the selected taxonomy terms, assume you use a name for each list item like "selected_term".

  for each selected term:

= Rules Action (which is part of the loop), in which you perform a "Rules Component", and which uses as parameter the "selected_term".

  create a new node of type 2

= 1st Rules Action performed as part of the Rules Component, which is to "Create an entity" (a node of "type 2").

  and prepopulate the entity reference field of node type 2 with the value of node type 1.

= 2nd Rules Action performed as part of the Rules Component, which is to "set a data value", for the entity reference field, as part of the entity (node) that got created in the previous Rules Action, and followed by a Rules Action to "save the entity".

Refer to the List and loops video for more details about processing lists and loops via Rules.

Note: no need for the Conditional Rules module ...


Facet blocks are not shown with Facet API Pretty Paths activate

Ok... I got the 'error'

The Facet blocks are visible for the URL: products
When you install Face Pretty Paths, the URL is modified including the segment of the search result.
I just added the "products/*" to the visibility of the block.

Show block on specific pages -> Only the listed pages: products/*


'Text format field is required' error when saving Better Exposed filters (BEF)

I found the problem.

Navigate to the BEF settings under the view in question (like the screenshot above).

Scroll down to  Require input before results are shown, select the checkbox, there should be a "Text on demand" field.

Set the Text format field to one a valid text format.

Then apply the changes.

I created a video tutorial for you to follow: http://recordit.co/V75Zl4gAAl


How to implement expiring roles in Drupal 7 today?

There is the Commerce License module that has a stable release and some support. I highly recommend it.


Best practice for moving content from production server to dev server

Modifying an existing project without loosing data is a common need.

Use Features

One of the best practice I know, is to use the Features module to deliver all the modifications you have made on the production server. Features allow you to make custom modules containing content type structures, views definitions, and a lot more.

You'll probably also need to use the Strongarm module to be able to retrieve the settings variables of some part (modules configuration for instance).

Those modules really help to deploy modifications on a production site, even using git. You'll find easily some good tutorials about using Features.

The only important part to know is when you start using Features, it's difficult to stop using it. Because it will create and implement custom module containing all the specifications of your website (content types, fields, views, pages, ...). If you disable it / them, everything disappear.

Export modifications

If the modifications on your project are not to complicate (mainly content types structures and views), you can use the export / import possibilities offer by some modules (views for instance).

You can also use Bundle Copy module for the node content types export and import part.

Hard way

After, there is a hard way I use sometimes. It is working only if you did not change the fields settings of your existing content types, and if you just add some (fields and content types).

You can copy in your development server database the content tables of your production server. You have to well know all your content types, and specifically the fields used in them (specially the machine names of the fields).

=> You will lose all the new and modified nodes of your dev server. Then do not hesitate to make a backup of your database first.

If you are in the case, you can copy from the production server all the content tables :

node : the base node table with all the content informations
node_revision : if you want to get back the revisions informations
for each one of your content type fields :

the data table : field_data_[field_name] (ie : field_data_body)
the revision table : field_revision_[field_name] (ie : field_revision_body)

url_alias : The custom path of your content (if needed)
taxonomy tables : if you need to, but it can be tricky
user tables : users and users_roles (if needed)


Show certain content to roles based on taxonomy terms

Have you taken a look at Taxonomy Access? It allows you to set access control for roles based on taxonomy terms.

EDIT: Ignore the above dumb reply and feel free to downvote.

I think you could do this by creating a custom contextual filter in Views. Your contextual filter would look at the current user and decide which taxonomy terms ids to return.

If you are using Drupal 7 you could tag the users themselves with the same terms as a way to store which terms are associated with which users. Otherwise you might need to create a separate table to store the user to taxonomy association.


page not found after restoring from the backup except home page (Tried all solutions, which I got through googling)?

Looks like you have lost your .htaccess in the process. Download newest Drupal core from Drupal.org, extract it and put .htaccess in the root directoy of your Drupal. If this still does not work, and your .htaccess is ignored, go to official Clean URLs documentation, and find a section Server configuration for Clean URLs on a dedicated server, with httpd.conf - this should show you how to configure it properly.


Where to translate SHOW DETAILS from a display view?

This string seems to be a part of the interface, so you can translate it through Configuration » Regional and language » Translate interface (/admin/config/regional/translate/translate).
You have to enter the exact capitalisation into the search as is written in code (it's case sensitive), not necessarily what you see on the screen (CSS can affect what capitalisation is used in display).
The string won't appear on this list unless you have visited a page with that string in another language (other than English) so Drupal picks it up and makes it available for translation.


How to restrict access to some nodes based on roles or users?

The Group module is what you should be looking at.

It creates groups as entities, making them fully fieldable, extensible and exportable. For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types.

For the private sector (as in your question), it seems that you would want to grant access to what, in Group, is called "Members". But you wouldn't allow access to that part of the website for:

"Outsiders" (=  logged in users who are not a member of a group).
"Anonymous" (site visitors that are not logged it).

More info

Refer to "What are the various roles supported by the Group module?" for more details about the supported roles.
Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


How to send comma separated taxonomy term (as link to taxonomy term url ) from preprocess to twig file as single variable?

I have solved this like below :

It was always considered as string so I have to send topics in from of array like below:

$topics = array();
foreach($value['#row']->_entity->field_topic2 as $val){
  $topics[$val->entity->tid->value]= $val->entity->name->value;
}

And then in Twig I made links from them and it worked.

    {% for key,item in value.topics %}
        {{item}}
        {% if not loop.last %},{% endif %} # for adding commas after each term
    {% endfor %}


noddejs module is hard to configure and make it work as it is under development and not stable yet (I tried personally)

take a look at tha sandbox project it may help nodejs-chat-d7


%1 doesn't get converted to taxonomy name when overriding title

It works for me with Drupal 7.

What I did was enabling the validation criteria, set the validator to Taxonomy term, and the type of the filter value to Term ID.

When I visit http://example.com/programming-languages I get the list of all the taxonomy terms terms for the "Programming languages" vocabulary.

When I visit http://example.com/programming-languages/20, I get a page using the overridden title.


Fullcalendar is putting my events into the "all-day" category

Fixed; my bad.  I hadn't (properly) set the granularity of the node's time field.  Duh.


Implement the redirect in a module. Either in a kernel request subscriber, see this change record https://www.drupal.org/node/2013014 or in a kernel response subscriber, see https://git.drupalcode.org/project/age_verification/blob/8.x/src/EventSubscriber/pathGate.php.

The second example is from a contrib module you can try as it is. I don't have first-hand experience with this module, so I can't recommend or not recommend it, but this would be off-topic here anyway.


I want to enable a disabled input format

This is a known issue, though you are warned before you disable the textformat that this cannot be undone. See the issue Disabled text formats can't be seen in the GUI and the comment #60:

  It is possible to reenable disabled text formats with the
  configuration manager:

  go to /admin/config/development/configuration/single/export
  choose Text format as the Configuration type
  choose the disabled text format as Configuration Name
  copy the configuration
  go to /admin/config/development/configuration/single/import
  again choose Text format as the Configuration type
  paste the configuration
  change "status" from false to true
  click on import

  Voilá, the text format is available again. This is working but not
  user friendly :(


How can I find all the listeners or subscribers to the KernelEvents:REQUEST event?

Instead of ddebug use the Symfony Webprofiler, that is included in the D8 version of the module Devel:

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

WebProfiler (D8+)

Add a powerful footer to all pages of your site. There, admins can review resource utilization, cache effectiveness, database queries, Views, and so much more.


How to hide taxonomy terms with no content

If you  create a view to show terms, you can create a relationship for "Taxonomy term: Content with term". This will allow you to access all the nodes referencing each term.

In the configuration screen for the relationship, you can check the "Require this relationship" checkbox (see screenshot below). Like that, terms that are not referenced by any node will not be displayed.


Remove link from title of custom content type in Drupal 7

In the view configuration, click "Field: Title" and un-check "Link this field to the original piece of content".

If you can't find it, you can also add some css to that title. For example:

.view-id-case_studies h1 a{
   pointer-events: none;
   cursor: default;
}


A change in the production site affects test and staging sites and vice versa

What you're describing can happen when you link several sites up to the same cache system, but give the same prefix for each of them in settings.php (or don't provide a prefix at all, which is essentially the same thing).

I'm not 100% sure, but disabling the memcache module might not stop it being used if you're declaring its use in settings.php, which you most likely will be.

It might not be the cause, but it definitely could result in exactly the situation you find yourself in. Check settings.php in each of the sites, and see what the state of those prefixes are. If this is the problem, providing different prefixes for each site will fix it straight away.


New link added in user page but not visible to non admin user in Drupal 7

You need to declare your permission with hook_permission().

function newtab_permission() {
  return array(
    'access new tab' = > array(
      'title' => t('Access new tab'),
    ),
  );
}


Your logic is fine, so check these:

Your module is named 'Opti_Search". If not, Opti_Search_theme() needs to be changed to MODULENAME_theme(), and the caches cleared. This one seems most likely given the error message you received.
You've cleared the caches since implementing hook_theme().
The module is installed and enabled.


Yes you can do $term->id() which should return the term id if $term is a Term object. See id().


You want hook_field_formatter_prepare_view() instead. Note this hook operate on a group of entities, not on a single one.

Here's a working snippet. Some array-fu is needed to not end up writing an ugly loop of ten lines, since deltas must be preserved linear.

<?php

function MODULE_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  foreach ($entities as $id => $entity) {
    $array = array(0 => $items[$id][0], 1 => $items[$id][0]);
    if (count($items[$id]) > 1) {
      array_splice($array, 2, 0, array_slice($items[$id], 1));
    }
    $items[$id] = $array;
  }
}


Drupal Commerce: Calculating a shipping rate: Custom Shipping Price

It's probably easier to have multiple flat rates, and a conditional rule that the product for that price is in the cart.

Notes:

There's a commerce shipping rules module that has a "cart contains item" condition.
If you could get at the logic behind the prices you could deal with this more easily, like weight based or size based shipping. For hundreds of products it's unreasonable that there's no logic behind it outside of what they want to charge for shipping. What I could think of is a custom module using hook_commerce shipping method alter where the shipping method matched the shipping price in the field. I've written a small module that alters the shipping weight, but that again assumes logic the weight based shipping.


After doing a quick test, turns out that hook_preprocess_node will always override hook_preprocess_field's attributes.

Therefore, instead of adding the class in hook_preprocess_field, and if you don't want to use '#markup', you could add it in hook_preprocess_node like this:

function THEMENAME_preprocess_node(&$variables) {
    $variables['content']['field_test'] = array(
    '#type' => 'processed_text',
    '#text' => 'Test 123',
    '#prefix' => '
',
    '#suffix' => '
',
  );
}


Use a distinct resource name, or simply enable the same resource on the other services endpoint to use it there.

To debug issues with the controller, you can check in RESTServer.inc in particular the functions getController and resolveController. Adding some debug/logging code there may help to resolve the issue.


Configure visibility of block based on URL parameters

You can use condition_query it will give you an extra box where you can put query parameters like q=term


I would recommend you to use a Viewfield or the EVA Module. With both of them you can attach a view to an entity and add arguments. I personally prefer EVA to do stuff like this. Very handy and allows you to use the same in different contexts without exposing it to the site admin directly.


view to work for particular set of taxonomy terms

You can give Taxonomy Views Integrator module a try.

  The TVI (Taxonomy Views Integrator) module allows selective overriding
  of taxonomy terms and/or vocabulary with the view of your choice.
  Using TVI you can easily create custom views to output all terms in X
  vocabuarly.

  TVI will try not to interfere with views or taxonomy/term page
  displays if no TVI views exist for the current page request.


You said you downloaded Drupal, then downloaded Open Atrium?

Open Atrium is a specialized version of Drupal, you install it standalone.


How can I insert a variable into query condition?

Outside of extreme circumstances, never, ever concatenate variables into an SQL string. You'll leave yourself open to SQL injection.

It feels like you should be using an entity query for this, but for the sake of the exercise, use a placeholder and pass the arguments in:

$args = [
  ':fields[]' => ['id_1', 'id_2', 'id_3'],
];
$query->innerJoin('node__field_field', 'nfc', 'nfc.entity_id=node.nid AND nfc.field_field_target_id IN (:fields[])', $args);


How do I let users unpublish and publish their own content?

A UI approach which I have used on some sites is the Override Node Options module, adds permissions similar to those that my other answer provides, plus a bunch extra.


If you want to display a list of content a user has flagged - You want build your view as you would any other. Then you add a relationship to the view for the flag you wish to display.

If you wish to allow your user to simply add a flag directly from the view results, you would add a field to the view of the type "Flags: Flag Link". This will add the add/remove flag link to each result in your view.


Custom language that displays content from two languages

The whole idea of linking language with country falls apart when you consider countries like Canada. You could separate language and applicable country since they're not really the same thing. In your example:

Australian Website

Home (Lang: English - Country: UK, US, Canada, Australia)
About (Lang: English - Country: UK, US, Canada, Australia)
Products (Lang: English - Country: UK, US, Canada, Australia)

Product One (Lang: English - Country: UK, US, Canada, Australia)
Product Two (Lang: English - Country: UK, US, Canada, Australia)
Product Three (Lang: English - Country: Australia)
Product Four (Lang: English - Country: Australia)

Resources (Lang: English - Country: UK, US, Canada, Australia)
Contact (Lang: English - Country: UK, US, Canada, Australia)


You need rewrite 'form' like this:

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  $form_registry = &$theme_registry['form'];
  $form_registry['function'] = 'mymodule_form_theme';
}
function mymodule_form_theme($element) {
  // I'm not sure that $element has 'from_id' but you could pass it if you need.
  if ($element['form_id'] == 'yours_form_id') {
    return theme_form($element);
  }
  // Else return what you need I guess that better to use hook_theme()
  // and then call theme() function.
}

Look at theme_form() to understand what variables need to pass in form tag.
I don't understand why do you need this. What is the reason to use template file?


The easiest solution is to make use of twig tweaks module, Install twig tweak

drush -y en twig_tweak,
drush cr,

now you can place navigation anywhere. In your case inside header.twig file place

{{ drupal_block('crmnavigation') }}

You can also render entities, views and many other things. well explained here http://www.wdtutorials.com/drupal/theming/drupal-8-tutorial-43-twig-tweak-module-article-video#.WCPOxeErIyk


How to serve 404s for non existent views paths with facets

The solution here was to alter the Views404 module.

The module works by running a single hook_views_pre_view. This function runs a series of tests and if none of them pass returns a 404.

I added in an extra set of tests which would pass on my facets and so avoid the 404.

This problem doesn't exist with all facets. The problem comes because I'm using Facet API Pretty Paths. It turns:

https://mysite/view?f[0]=host_entity_node%253Afacet_label%3Afacet_value

Into:

https://mysite/view/facet_label/facet_value

And while views404 will allow para-metered search, it won't allow folders unless they pass one of the tests.

I altered my facet pretty paths in the UI, so one of the labels was country and all the rest began with 'filter':

e.g.

Country Facet: Pretty path alias = country
Every other facet: Pretty path alias = filter_x

I then added the following code to views 404

$args_passed = 0;
foreach($args as $arg) {
  if($arg == 'country') {
    $args_passed++;
  } elseif(is_int(strpos($arg, 'filter'))) {
    $args_passed++;
  }
}

if($args_passed == (count($args)-1)/2) {
  return;
}

Facets always come in pairs, so it goes through every arg and looks for either country or filter. If if finds half of the url arguments are facet_labels then that's a pretty strong indicator this is a genuine path and shouldn't throw a 404.


It was my bad, the person who originally made the view did not make the relationship properly. But the weird thing is, it worked properly on a Drupal 7.30 installation and broke on 7.34.


How to add link internal or external to an image in a view for a slideshow?

I solved using theming in the view. I use the template in the image field. I ended up with a template like views-view-field--field-slideshow-image.tpl.php.

  <?php
//dpm($row); only work if devel module enabled

$url='';

if (!empty($row->field_field_link_in_picture_)){

    $url=($row->field_field_link_in_picture_[0]['raw']['url']);

}

if (!empty($url)) {
     echo "" .$output .""; //print image with link
}
else {
    print $output; //print image
}

?>

If someone knows a better way to do this please feel post it here. If I am not doing something in the Drupal way please let me know or you have another way to accomplish this. I would love to hear it :)

If you know little  about theming views you can check this video to understand better
Theming Views


How can I make the summary field required?

It might be easier to create a new field for the summary and just manage it that way, you will then have to remove the summary option from the body field. Otherwise I think you will have to write some code and use hook_form_alter.


Uninstalling a created custom module in drupal 8

See How to delete a content type, programmatically?

You can add enforced dependencies on any config entity, if you do so, drupal will automatically remove them.

That's much better then using hook_uninstall(), as the user is informed about what will be removed on the uninstall confirm page.


Is it possible to hide a menu item using menu blocks in context based on user roles?

you could hide it programatically

function YOURTEMPLATE_menu_alter(&$items) {

 global $user;

  if (in_array('anonymous user', $user->roles)) {
  unset($items['user/%user/profile']);   // example link
  }

 }

This will hide that menu item for anonymous users.


How to show Numeric keyboard while entering in textfield?

First, create a module named html5_form_element. Then you need to set up the following

Implement hook_element_info() to tell Drupal about your element type:

/**
 * Implementation of hook_element_info()
 */
function html5_form_element_element_info()
{
  $types['number_input'] = array
  (
    '#input' => TRUE,
    '#theme' => 'number_input',
    '#theme_wrappers' => array('form_element'),
  );

  return $types;
}

Next implement hook_theme() to define the theme for your input type:

/**
 * Implementation of hook_theme()
 */
function html5_form_elements_theme()
{
  $theme = array
  (
    'number_input' => array
    (
      'render element' => 'element',
    ),
  );

  return $theme;
}

And finally, create the theme function that will theme your element:

function theme_number_input($variables)
{
  $element = $variables['element'];
  $element['#attributes']['type'] = 'number';
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-number'));

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input']))
  {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#autocomplete_input']['#id'];
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';

  return $output . $extra;
}

Clear your caches, and you can now use '#type' => 'number_input' in the Form API.


This should get you on the road:
https://www.drupal.org/node/1216132


How to get a list of all javascript files in a directory

libraries_get_libraries should return an array of library directories, with the library name as the key and the directory as the value.

libraries_get_path will get you the path to a specific library (js).

Follwing your approach, this works fine for me:

  $dir = "sites/all/libraries";
  $files = file_scan_directory($dir, '/.*\.js$/');

I think it might be base_path that is breaking it in your example, as it adds a / in front of the (relative) path from the site root.

Combining libraries_get_libraries with file_scan_directory will also get you libraries from profile and site specific directories:

$libraries_array = libraries_get_libraries();
foreach($libraries_array as $library => $directory) {
  $files = file_scan_directory($directory, '/.*\.js$/');
  $js_paths[$library] = $files;
}
dpm($js_paths);

It may be worth noting that these libraries may contain many javascript files that are not actually used by modules.


You need to build a render array
$build = \Drupal::entityTypeManager()->getViewBuilder('media')->view($media, $view_mode);

and then place it unrendered in a template, Twig renders this automatically.


Solution is

 $form_state['uid'] = $user->uid;
 user_login_submit(array(), $form_state);

and final code :

$user_info = array(
  'name' => 'temp-payment-'.rand(1,999),
  'pass' => user_password(),
  'mail' => 'no@no.com',
  'init' => 'temp-user-'.rand(1,999),
  'status' => 1,
  'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),
                    'access' => time(),
                    );
  $user = user_save('',$user_info);
//drupal_save_session(FALSE);
//$loggedin = user_authenticate($user->name, $user->pass);
//ym($loggedin);
$form_state['uid'] = $user->uid;
 user_login_submit(array(), $form_state);
//drupal_save_session(FALSE);
$GLOBALS['user'] = $user;
drupal_save_session(TRUE);
//drupal_goto('/user');

hope be useful for another users,.

This code generate and login to it programmatically


Drupal sites extremely slow due to cache SELECT-queries

Sounds like MySQL needs to be tuned. I would start with the InnoDB Buffer Pool Size. This answer has info on innodb_buffer_pool_size: Do Drupal websites have bad performance or are heavy?

If the innodb buffer pool is a reasonable size and If MySQL is in ball park of doing 3k+ queries per second and your running MySQL version 5.1 or lower you might be affected by the query cache bug. At work I ended up disabling the MySQL query cache after reading this bug and verifying that the version of MySQL we are running (5.1) does not have this fix http://bugs.mysql.com/bug.php?id=43758 (available in 5.5). The bug is that a lot of queries get stuck in the “freeing items” state http://dev.mysql.com/doc/refman/5.1/en/general-thread-states.html#id770305 (The thread has executed a command. Some freeing of items done during this state involves the query cache. This state is usually followed by cleaning up). I issued this command SET GLOBAL query_cache_size = 0; and saw an instant improvement in query times.


Broken/missing handler error for my custom views filter?

Specify the data table instead of the base table, just replace node with node_field_data in your hook and run drush cr.

/**
 * Implements hook_views_data_alter().
 */
function alias_views_filter_views_data_alter(array &$data) {
  $data['node_field_data']['alias'] = [
    'title' => t('alias filter'),
    'filter' => [
      'title' => t('alias filter'),
      'help' => t('Provides a custom filter nodes by their alias.'),
      'field' => 'nid',
      'id' => 'entity_alias',
    ],
  ];
}


Yes, this is the function you are looking for:

function mythemename_preprocess_page(&$vars, $hook) {
  if(request_path() == 'your_path') {
    drupal_add_js(path_to_theme().'/js/yourjs.js');
  }

  $vars['scripts'] = drupal_get_js();
}

Request path is an easier way to do this than the < Drupal 6.x method of reading the arg() string (ex. if arg(0) === 'node' && arg(1) === 'some node id')


Change a block programatically, accesing to the Views results

Reading from some sources and experimenting a little, I have been able to reply to my question. In your template, you must put the views-view-unformatted.tpl.php file (from themes folder), and there you can modify each of the rows based in some logic (though logic should be constrained to template.php y from there populate a variable in this tpl).
The output of the view must be unformatted text, and the "auxiliary" data must be added, but hidden from view.

<?php

/**
* @file
* Default simple view template to display a list of rows.
*
* @ingroup views_templates
*/
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; $i = 0;?>
<?php foreach ($rows as $id => $row): ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php

if($view->result[$id]->taxonomy_term_data_description != ""){
 // Here I use a logic to show only the item name surrounded by dots.
  print ".." . $row . "..";
}else{
 // Here I use opposite logic to show the link
     print "result[$id]->taxonomy_term_data_description . "'>" . $row . "";
} // if
$i++;
 ?>


Replacement Pattern to get current node url

I think what you want to do is add "Content: Path" as a field. This is the path to the node.

Make sure the "Exclude from display" box is checked.
After you have added the field, make sure it is above your custom text field (click the arrow next to "Add" and select "Rearrange").
Once, you've done that, [path] will become a replacement token.


How to add a line item to show total cost in Ubercart 2?

There is uc_order_pane_line_items_add

  Order pane submit callback: Add a line item to an order.

function uc_order_line_item_add($order_id, $type, $title, $amount, $weight = NULL, $data = NULL) {
  if (is_null($weight)) {
    $weight = _uc_line_item_data($type, 'weight');
  }

  $line_item = array(
    'order_id' => $order_id,
    'type' => $type,
    'title' => $title,
    'amount' => $amount,
    'weight' => $weight,
    'data' => $data,
  );
  drupal_write_record('uc_order_line_items', $line_item);

  return $line_item;
}


You can change the page header title in template.php by adding the below code in template_preprocess_html().

 function my_theme_preprocess_html(&$vars) {
   if (current_path() == 'you_path') {
     $vars['head_title'] = t('header title');
   }
 }


Drush policy restriction doesn't restrict sql_sync

I added this to my sync_enable commandfile, and it definitely worked:

function drush_sync_enable_sql_sync_validate($source = NULL, $destination = NULL) {
  if (strpos($destination, 'live')) {
    return drush_set_error('DRUSH_BAD_DEVOPS_NO_BISCUIT', dt("Don't sync to live."));
  }
}

That looks the same as what you've got, so the next thing I'd recommend that you try is drush cc drush, to clear the Drush commandfile cache.  That will insure that Drush can see your policy file.

UPDATE:

Sorry, the problem was that Drush looks for site-wide commandfiles in '/usr/share/drush/commands', not '/etc/drush'.  Move your policy file there, and then drush cc drush, and it should work.


You have to set the option alias:

$link = Link::createFromRoute(
  $this->t('my business'),
  'entity.commerce_store.canonical',
  ['commerce_store' => $store_id],
  ['alias' => TRUE, 'attributes' => ['target' => '_blank']]
)->toString();


How do I add class "caption" into image?

There is an option in the Insert section of the field to add classes. See the screenshot below.


Commerce Kickstart 2 Need Rule To Apply Sales Tax To Shipping

don't know if you solved this yet (hope so). The trick is to set your tax rate and THEN apply is a calculation rule to shipping. Not the most intuitive way to do it, but it works.


Unable to get CKEditor to work using Drupal 7

Here are the steps that worked for me on Drupal 7.7

Instal the WYSIWYG module and enable
Download the latest CKEditor and unzip it in sites/all/libraries
Go to configuration => wysiwyg and choose the editor for the input format (use it on the full HTML or PHP)
Now you can edit and there you can choose under buttons and plugins what buttons appear
When you create a content type don't forget to set the correct text format

btw a while back I had a problem where the WYSIWYG used the background from my site. I had to change the CSS settings, below buttons and plugins, and set it to use editor default.


Drupal in subfolder, clean urls and images (htaccess not quite right)

The ultimate goal here is to get any request to the base domain (http://www.example.com) redirected the drupal subdir (http://www.example.com/drupal), correct? Why not just remap everything to the subdir and let Drupal handle the www. prefix and clean-url mapping?

RewriteCond %{REQUEST_URI} !^/drupal
RewriteRule ^(.*)$ /drupal/$1 [L,R=301]


Rest Export View multilingual content taxonomy filter fails

Pretty sure that's "just" yet another variant of the bug that this issue is trying to fix: Views should not condition joins on the langcode of fields that are not translatable


How to access "add a card" page in Commerce Card on File?

commerce_cardonfile looks for a 'create callback' from the payment method modules. commerce_authnet does not come with the callback, but this patch adds one:

add_card_on_file-2051357-21.patch

Here is the discussion: https://www.drupal.org/node/2051357

After I applied the patch, commerce_authnet_cim_cardonfile_create() was defined on both lines 760 and 1021. I renamed the latter so that Drupal was happy. Then "+ Add a card" became available on each user's "Stored cards" tab. And... it works!

Can I get my +250 points back? ;)


Content display errors - Missing styling and content

Seems to be related to a PHP error, see which are the the resources (images, css, js, ...) that are returning 500 HTTP error.

Check if the issue only happens with a specific content type.

Check the Drupal log (admin/reports/dblog) and the Apache log to find more info about this issue.


Can I show an image in place of a Drupal 6 message?

There is a way to do this.

One problem here is that the confirmation message is just that, a confirmation which is unrelated to any context.

What you could do is to use jQuery to react to the string of the message is being put out ... so if it's something along the lines of: "Success, your message was sent" - which you "could" assign a string-match on and create a reaction to it. Most likely you would append/prepend a container with a custom confirmation message or image at this point. This would involve a bit of a work-around however (Assign a .js script to handle it -  which in Drupal means editing your template.php file).

I usually opt for the confirmation page either way. Users also often don't see the little confirmation message on the same page and a dedicated confirmation page can go a long way in keeping a user on your site - you could for instance use this to display a range of your latest blog entires/products etc. as a block on that page or even have an ad block to collect a few clicks, depending on the kind of site you're working on atm.


With REQUEST_URI i get id node or alias path?

The right way to check on which page are you, is to use the current_path() function. Below is an example:

if (current_path() == 'your/system/path') {
  // Do whatever.
}

This is the best way because aliases can change, while system paths stay the same.

However, if you really need the aliased path, use the drupal_get_path_alias() function instead.


How to remove default divs on views result?

Go to the Settings of your Fields and uncheck the Option: Provide default field wrapper elements


Are Drush vbo-execute actions supported?

After much searching to no avail, I decided to dig into the VBO codebase. It turns out that I was using the wrong action id (the 2nd argument to the drush command after the view id). Whatever action id was being used in the post I referenced is not the right one (either it was custom or VBO has since changed the convention for action id's). I discovered this by finding the file that implemented the action (delete) that I wanted, which happened to be in /drupal_root/modules/contrib/views_bulk_operations/src/Plugin/Action/EntityDeleteAction.php. This file has an annotation block that specifies the action id to use:
namespace Drupal\views_bulk_operations\Plugin\Action;

use Drupal\views_bulk_operations\Action\ViewsBulkOperationsActionBase;
use Drupal\Core\Entity\TranslatableInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Delete entity action with default confirmation form.
 *
 * @Action(
 *   id = "views_bulk_operations_delete_entity",
 *   label = @Translation("Delete selected entities / translations"),
 *   type = "",
 *   confirm = TRUE,
 * )
 */
class EntityDeleteAction extends ViewsBulkOperationsActionBase {
...
}

running drush vbo-execute my_delete_view views_bulk_operations_delete_entity did the trick! No idea why there doesn't appear to be any documentation about this (at least that I can find), but I'm glad I finally figured it out and hopefully this helps someone else having the same trouble.


Import issue in other languages using csv file to drupal node creations

I found a way to overcome this issue. What I exactly did is that, in the imported view, I just added another charset=ISO-8859-1 which retrieves back the symbols or characters from db and displayed them properly.

<?php
drupal_add_http_header('Content-Type', 'text/html; charset=ISO-8859-1,utf-8');
$new_output = utf8_decode($output);
echo $new_output;
?>

That put back all special characters or symbols which was missing.


Why I've got Fatal error of undefined validation function in my form?

Change page callback form drupal_get_form to function, because if you use drupal_get_form in call back it return form and in your function you create another form, it means form in form and make conflict.

$items['share/%'] = array(
    'page callback' => 'ym_alter_sharing_content',
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);


Why isn't my integer value processed correctly with PHP in Rules?

I was able to solve this problem after finding the answer on my question 'How to use variables in a PHP evaluation in a rule?'.

Instead of activating the Rule when an event "After saving a new field collection item" occured, rather use "After updating existing content" and grant the Userpoints for the first Field Collection item in a different Rule. Afterwards, follow the instructions in the referenced answer and use the code underneath.

<?php
if ($old_total > 5) {return 0;}
elseif ($new_total > 5) {return 5 - $old_total;}
elseif ($new_total == $old_total) {return 0;}
else {return $new_total;}
?>


How to remove "All Products" item in main menu of Commerce Kickstart 2?

I don't know why I couldn't find it, But I got it in admin/structure/menu/manage/main-menu eventually. This question is a pseudo-question.


Is there a reason you want to use the theme_preprocess_views_view_fields hook?

Why not add the attribute Content: type to your View fields (see image), and then check the content type within a View template:

Then your code in views-view-fields--[my_view]--[my_display].tpl.php could look something like this:

<?php
  //check content type
  if($fields['content_type']->content == 'My content type') {
    //trim description by 200 chars (respecting full words)
    $pos = strpos($fields['field_my_description]->content, ' ', 200);
    substr($fields['field_my_description]->content, 0, $pos);
  }
?>

<?php print $fields['title']->content; ?>

  <?php print $fields['field_my_description']->content; ?>

I haven't tested or tried the above code, but the proof of concept should be enough to help you along.

Using a Views template instead of a hook is also easier for site builders / themers to debug or change.


Apache Solr Indexing data of custom Table

I believe this issue has the information your looking for you have to modify the ApacheSolr schema file to include your custom fields. And tell Solr with an update hook where your data is .... importing that much data could be difficult.

An even better resource may be this blog post from Acquia: Using Apache Solr to Index Custom Data.

Sorry, I wont be able to code up any examples. I dont have Solr installed now, and dont have that much free time.

Both these example links are for D6.


How to sort a view on a Drupal Commerce product image field?

One way to solve this is to store a sortable value in an extra field.

Computed field can be a good choice. There is a quite lengthy article here. See "Additional Values for Sorting".

I also want to quote the "Downsides" mentioned in this article:

  Since the stored value computed field is only computed when the node
  is saved, your nodes need to be re-saved to allow for code changes. If
  you change the content type’s field, you may need to re-save all nodes
  of that type. If you have thousands of nodes, this can be troublesome.
  However, several modules (which are outside the scope of this post)
  can help, as can simple one-off scripts.


See Messaging and Notifications framework.


Enable the Metatag Views module (part of Metatag)
Visit a View edit page
Configure your meta tags


Is there any hook to multiple total price only in payment method

Personally I would rather use hook_commerce_price_field_formatter_prepare_view.

  This hook is used by modules like the Product Pricing module that implement ways to alter prices prior to display.

That way you could keep your prices as regular dollars internally, and only display them as kilodollars for your customers. Regular storage will make it easier to interact with gateways.

Other way, although I'm not sure about it's specific implementation, would be to define second currency. You can have a shop that sells in Euro and USD, and internally re-calculates prices to meet client's payment method, right? Maybe you could define kilodollars just he same way, with exchange ratio 1000:1 to regular dollars?


So it seems like the JavaScript file you are trying to remove is actually coming from a theme. You were also trying to unset array item in non existing variable $js. You could try if this works for you:

function bootstrap_ncr_js_alter(&$javascript) {
  $path = drupal_get_path('theme', 'bootstrap');
  unset($javascript[$path . '/js/bootstrap.js']);
}


How to delete a content type, programmatically?

Just make sure that the node type depends on your your module, then Drupal will delete it automatically for you.

See node.type.book.yml in the book module for an example, this is the relevant part:

dependencies:
  enforced:
    module:
      - book

Note that users will have to delete all content of that type before they can uninstall the module then.


Custom Date Format Not Available to my Date Field

They seem to be build differently, you really can't do that I guess. But do this:

Add a new format at admin/config/regional/date-time/formats. Then add a new Date type at
admin/config/regional/date-time and here select your new format. Then you can select this in the view.


URL redirect module working fine with nodes not with alias url's

You can use Path Redirect module in your scenario. Module page says :

  This module allows you to specify a redirect from one path to another
  path or an external URL, using any HTTP redirect status.


Taxonomy Term Reference Tree Widget with Other field

You might do this with the alternative module Hierarchical select.

Hierarchical select:

  Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!


Add a new rule with some name, e.g - Award Userpoint for Product A.
In event select "Completing the checkout process".
If you want to award userpoint only if payment has been done in full, then after going forward delete the "Completing the checkout process" & add another action "When an order is first paid in full".
Add condition "Order contains a particular product", put the SKU of the product A. User operator & quantity as per your requirement.
Add a action named "Grant points to a user", in data selector choose "commerce-order:owner" & set the points which you want to award.

Done...this is how I am doing.


How to alter the default font displayed INSIDE CKeditor

The font is set in ckeditor/ckeditor/contents.css, although it is generally inadvisable to alter a module, it can be done safely so long as you document the changes (in the event that updates are required and would overwrite your work).


Is it possible to join dynamic tables (subqueries) using db_select()?

Both db_select and addJoin documentation says clearly that the table

  May be a string or another SelectQuery object. If a query object is passed, it will be used as a subselect.

So,

$sub_select = db_select('comment');
// Convert.
$select = db_select('comment')->addJoin($sub_select...


When you run a batch the URL automatically changes to /batch...at that path, Drupal doesn't know to include your module_definition.inc file. It'll only process the menu hook when the path is 'some-pretty-url', so module_definition.inc will only be included then.

If you move your batch definition into the module file it'll start working, and the file you've told the batch system to find the processing function in will be included as you'd expect, because now Drupal knows it needs to be included.


How do I rewrite a facet item label using facetAPI bonus?

This snippet forces the output to be uppercase by using drupal_strtoupper($item["#markup"]);. And then sets $build[$key]["#markup"] to this new uppercased value.

If you need to check for a specific item, you could use:

function HOOK_facet_items_alter(&$build, &$settings) {
  if ($settings->facet == "YOUR_FACET_NAME") {
    foreach($build as $key => $item) {
      if ($item["#markup"] == 'my value') { // Check if this is the right item
        $build[$key]["#markup"] = 'my overridden value';
      }
    }
  }
}


Is there any documentation for the UUID module?

UUID is an "API" module. It wont do anything out of the box. It is for other modules to use the functionality provided by UUID.

See the module's README.txt file:

  This module provides an API for adding universally unique identifiers (UUID) to Drupal objects, most notably entities.

  FEATURES

  Automatic UUID generation:    UUIDs will be generated for all core entities. An API is provided for other    modules to enable support for custom entities.    See https://www.drupal.org/node/2387671
  UUID API for entities, properties and fields:    With this unified API you can load entities with entity_uuid_load() so that    all supported properties and fields are made with UUID references. You can    also save entities formatted this way with entity_uuid_save() (depends on Entity API).
  Export entities to use as default/demo content:    The integration with Features module provides the ability to export UUID enabled entities with intact dependencies and references to other entities.  This functionality depends on Deploy module 7.x-2.0-alpha1 (soon to be    released) and is probably the most robust way for installation profiles and    distributions to provide demo content!
  Services integration:    The integration with Services module alters all UUID enabled entity resources    (nodes, users, taxonomies etc) to be based on UUIDs instead. This way it   becomes easier to share and integrate content between sites. This   functionality is used by Deploy module.
  More integrations:    UUID module integrates with Views, Token, Rules and provides some CTools  plugins.


admin/commerce/orders/{orderId}/payments/add "You are not authorized to access this page."

To solve this issue, I needed to add one payment method that is not "Offsite"

the error message is just very misleading.


How to configure role to edit only specific nodes by field?

This looks like an ideal case for one of the Taxonomy access modules.

There are several to choose from, though I favour
Taxonomy Access Control Lite as it also allows you to grant access to individuals (should the need arise) as well as giving access rights based on roles.

The basic setup would be:-

Create a Taxonomy of the different kinds of event that you wish to use.
Give each "Event" node a Taxonomy reference field, that references the values from the Taxonomy that you setup in step 1.
Install and activate Taxonomy Access Control Lite via your preferred method.
Configure the access for each role to the Taxonomy from step 1. via the TAC lite configuration screen.  There are options to control the viewing, updating, and deletion of nodes, as well as the visibility of the Taxonomy terms in selection lists - which prevents users creating nodes tagged with event types that they don't have access to.

I hope that helps.


Migrating Contacts from Joomla to Drupal

Used phpmyadmin to dump the data from the table containing the content I needed, and put it into a CSV file. Then I used Drupal's Feeds module to import the CSV into the content type that I created.

Worked beautifully.


How can I override or alter a module's help text?

I don't recall doing exactly this, but I think you can use a hook_module_implements_alter() for this:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook === 'help') {
    unset($implementations['layout_builder']);
  }
}

This should disable layout_builder_help(), and then just yours will run.  A hook_help_alter() would be nice, but I don't recall ever seeing an issue for it.


Drupal 7: Custom content types become un-editable and do not output correctly

Dylan - have you looked here?  http://drupal.org/node/1029230


Adding custom button to Add Article form?

In template.php the form is already build.

You have to create a simple module and a hook_form_alter to edit your form or add buttons, fields etc.


Is it possible to display a content type (availability calendars) inside a Forms API form?

To add a form inside already existing form you can try out the following:

$form['another_form'] = array(
'#markup' => drupal_get_form($form_id);
);


Rabbit hole: what's the recommended setting for content that should not be directly accessible?

It's really up to you what you want to do but the way I see it, if a user goes to a random non-existing path on your site they will get a 404 error, so if the rabbit hole page is a page the user should never be able to get to then it should also be a 404 error because as far as that user is concerned it is not a valid page.

Now if you redirect all 404 errors to your home page or search page or something then these pages should have the same behavior.

If the page is something that anonymous users cannot see but a paying member can (or some similar scenario), then it may make more sense to set rabbit hole to a 403 error, because it is a page that they can't currently see but could see if they log in.


Correct way of formatting dates for output in node theming

Instead of date(), try using format_date()

It has an otional last parameter $langcode that tells it what language code to use for the date.


New users not created when migrate source is nodes instead of users

Since you know SQL, It would be simpler and definitely quicker to use SQL and SELECT the users from the source nodes and INSERT it into the user table rather than attempting to write a PHP script.


It's not working because you're not using a reference to $form.

Change your function declaration to:

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

Note the & in front of $form.  This means you're actually working on the variable as passed to the function, not a copy, or at least that's my understanding of it.

A useful thing to do to avoid this kind of error with hooks is to check out the API for the hook you are trying to use and copy the parameters verbatim.


how to access node variables in region preprocess function?

The template files for nodes and pages don't share any variable; that is true also for their preprocess and process functions.

Assuming we are talking of a node field implemented with the field API, then what follows applies:

The page preprocess and process functions have access to $variables['node'] which contains the node object, in the case the page is a node page

function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    // …
  }
}

The function to access the content of a entity field is field_get_items(), which returns its raw content
The function to render a entity field is field_view_value()

The following code should work.

  function mytheme_preprocess_page(&$variables) {
    if (!empty($variables['node'])) {
      $output = '';
      $node = $variables['node'];
      $items = field_get_items('node', $node, 'field name');
      foreach ($items as $item) {
        $field_output = field_view_value('node', $node, 'field name', $item);
        $output .= render($field_output);
      }
      // Set $variables with the value you need.
    }
  }

Unfortunately, $variables['view_mode'] is passed only to the node preprocess/process functions; that value would be helpful to field_view_value(), as its last parameter is the view mode.


You can pass it in via the --root argument

drush status --root=/Users/nicklas/Documents/SourceTree/Drupal/docroot


How to prevent result from being displayed when user selects search/apply

If you go to advanced settings of the view, you can set the exposed form settings to input required.

Another option if you are making use of the Better Exposed Filters, there's a patch for it which adds 'input required' option/functionality,


There is a recipe for How to implement client-side calculations.


After migration the login form no longer submits, why?

Please have check with your php.ini file as per old system & your new server by calling php phpinfo(); and look in the "Loaded Modules" for mod_rewrite.

Please refer this link it may helps you.


I'm pretty sure this is quite doable with the #ajax key in a renderable array. From http://drupal.org/node/752056:

<?php
/**
 * AJAX-enabled select element causes replacement of a set of checkboxes
 * based on the selection.
 */
function ajax_example_autocheckboxes($form, &$form_state) {

  $default = !empty($form_state['values']['howmany']) ? $form_state['values']['howmany'] : 1;

  $form['howmany_select'] = array(
    '#title' => t('How many checkboxes do you want?'),
    '#type' => 'select',
    '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
    '#default_value' => $default,
    '#ajax' => array(
      'callback' => 'ajax_example_autocheckboxes_callback',
      'wrapper' => 'checkboxes-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),

  );

  $form['checkboxes_fieldset'] = array(
    '#title' => t("Generated Checkboxes"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('This is where we get automatically generated checkboxes'),
  );

  // Complete example below!

Basically, define what function is going to be triggered by what action (in this case, a checkbox toggle). With the above code, define a function such that its signature is ajax_example_autocheckboxes_callback. Voila.


How to use group audience in drupal 7 views filters

Please check the screenshot.Basically you need to add a relationship as in screenshot.


How to hide a DIV if ther's no value in that Content in a node--customtpl.tpl.php file

Your if statement needs a condition, ex: 'greater than' > 'less than' < 'equal to' == or 'not equal to' !=

The special NULL value represents a variable with no value.

So try:

<?php if ($content['this_is_a_drupal_field'] != NULL): ?>
  <div class='special-offer'>
    <?php print render($content['this_is_a_drupal_field']); ?>
  </div>
<?php endif; ?>

So basically we're saying if $content['this_is_a_drupal_field'] is not equal to empty print...


How do I alter/change the "field is required" message?

Try this, it might work.

$name = $form_state->getValue('name');
if (empty($name)) {
   $form_state->setErrorByName('name', $this->t('Email is required.'));
}


After saving a new comment How to fetch all comments for a given node?

If your rule reacts on event "After saving a new comment",
add a Loop in actions section and select comment:node:comments as a selector.

The loop will go through an array of comments from commented node. There you can specify additional actions/conditions that you wish to perform on each comment.

PS: You will run in the issue of not being able to modify comment fields via Rules

  "Unable to modify data "field-taxonomy-term": Entity property
  comments doesn't support writing."

Here is more information about the issue:

"The selected data property doesn't support writing." when Action: Set a data value is applied to a taxonomy field:tid
How to fix entity property X doesn't support writing, when setting content type field values?


Entity Reference - Not required to be in database

Entity Reference can reference entities only. It would be a really big hack to the module to allow non-entities to be referenced. But there is no need to.

There are dedicated modules for exactly what you are trying to do. Instead of Entity Reference, create User Relationships. Use User Relationship Invites submodule, it

  allows users to specify a relationship to a user that they invite to join the site.

Invitation is done by using e-mail, so it seems this will fully satisfy your use case.


Copy template file
sites/all/modules/calendar/theme/calendar-month-row.tpl.php
to
sites/all/themes/YOUR_THEME_NAME/templates directory and edit it in this manner:

<?php
/**
 * @file
 * Template to display a row
 *
 * - $inner: The rendered string of the row's contents.
 */
$attrs = ($week > 0) ? 'week="' . $week . '"' : '';
$attrs .= ($iehint > 0) ? ' iehint="' . $iehint . '"' : '';
if ($week == date('W')) $class .= ' calendar-current-week';
$attrs .= ($class) ? ' class="' . $class . '"': '';
?>
<?php if ($attrs != ''):?>
<tr <?php print $attrs?>>
<?php else:?>
<tr>
<?php endif;?>
  <?php print $inner ?>
</tr>

Don't forget to clear page cache after this.


What's the correct way to redirect the user when a Batch API job finishes?

You can set 'redirect' in hook_batch_alter().
For example:

$batch['form_state']['redirect']['path'] = 'cart';


What is the easiest way to upload video and audio content?

Get a media management suite that integrates with as many third party hosting providers as possible. It means less work for you, less complexity, and less bandwidth on your server for which you have to pay.

Good suite's include, but are not limited to:

Scald

  Scald is a popular and flexible way to handle media in Drupal.

  Scald can handle images, video, audio, tweets and even Flash files.
  Scald works with YouTube, Vimeo, Soundcloud and other many other
  providers.

and Media

  The Media module provides an extensible framework for managing files
  and multimedia assets, regardless of whether they are hosted on your
  own site or a 3rd party site - it is commonly referred to as a 'file
  browser to the internet'.

For a front end media solution you can look at MediaFront

  The MediaFront module is a front end media solution for Drupal. It
  employs an innovative and intuitive administration interface that
  allows the website administrator to completely customize the front end
  media experience for their users without writing any code.


hook_menu doesn't exist anymore in D8.
Instead use a example.links.menu.yml file.

example.my_page:
  title: 'First page'
  description: 'yout description'
  route_name: example.my_page


Services user update function internally calls Drupal's user_account_form function (via user_profile_form).  In user_account_form, it's specifically looking for pass-reset-token as a $_GET parameter, so to update password via Service, unfortunately you have to pass it as a GET parameter on a PUT call.

Example:

PUT https://drupal/:api-endpoint:/user/:uid:?pass-reset-token=:pass_reset_token:
and the body is {"pass":":new-password"}.

If you wanted to be able to pass "pass_reset_token" as a parameter in the body, you could override _user_resource_update so that it checks if the pass_reset_token parameter is present and puts it into $_GET['pass-reset-token'] prior to calling user_profile_form.


Rotate Specified # of Views Results on a Time Based Schedule

Not many answers so I'll add my two cents.. A week long cache for the view sounds like it could do the trick.


How can I theme a single value from a multi-value theme?

It seems like there are properties in $content['field_hero_slideshow_header_text'] which determine how it's themed. Perhaps a '#theme'.

Can you try making a copy of the entire field with just the value you want?

$content['field_hero_slideshow_header_text_copy'] = $content['field_hero_slideshow_header_text'];

// Unset all multi values, they have integer keys.
foreach($content['field_hero_slideshow_header_text_copy'] as $k => $v) {
  if (is_int($k)) { unset($content['field_hero_slideshow_header_text_copy'][$k]; }
}

// Add just the one we want back in.
$content['field_hero_slideshow_header_text_copy'][0] = $content['field_hero_slideshow_header_text'][0];

// Output single field.
render($content['field_hero_slideshow_header_text_copy']);

// Do you need to remove the field from the original array?
unset(render($content['field_hero_slideshow_header_text'][0]);

Not the nicest way I know. You could try copying properties from the parent to the child and it might output correctly, though I don't think so because the theme function probably expects data in a parent > child format.


How to add multiple terms to a taxonomy reference field via feeds?

Use the Feeds Tamper module to "explode" the comma-delimited list of taxonomy terms into individual references.

  Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below.
  Additional plugins can be added in separate modules or through the issue queue.


You need to specify the entity type (node, taxonomy_term, ...) in the template name suggestion as you specified, i.e. field--node--field-test.html.twig.

node is the entity type, and field-test is the field name.

If you want to know which template is generating a particular markup element, you can use Twig's debug option. You enable Twig debugging in sites/default/services.yml; set the value of debug in twig.config to true.

I have added the field_test field to the Article nodes, and I got the template suggestions in the HTML source.

<!-- FILE NAME SUGGESTIONS:
   * field--node--field-test--article.html.twig
   * field--node--field-test.html.twig
   * field--node--article.html.twig
   * field--field-test.html.twig
   * field--string.html.twig
   x field.html.twig
-->

After getting the suggestion, I created a template file and kept this in the templates directory of the theme.

Remember to clear the cache.

See Working With Twig Templates for more information.


Is Content: ID really the Drupal 8 equivalent of Content: Nid?

Yes

  Additionally, the Content:ID dialog has options not seen in the
  Content: Nid dialog, such as the options for Formatter, Thousand
  marker, and Display prefix and suffix.

Thousand marker makes sense. The other two not so much, bug maybe?

  In Drupal 7, many views are using Content: Nid (for the node ID),
  which doesn't exist in Drupal 8. I've read here and elsewhere it has
  been replaced by Content: ID, in Drupal 8.

I could see them thinking when developing the D8 version, who links to a Node/Entity using the ID? Using something descriptive like a Title, or "view/edit/delete" text makes a ton more sense, don't really need this feature for ID. Plus having to hover over single digits is not user friendly.

But, if you still want to link using the ID

Add the ID field and checkmark hide from display.

Then either add field:

Link to content OR Link to edit content

Under rewrite results:

Checkmark override the output of this field with custom text

Example:


Embedding Javascript in Content or Block Causes Misalignment of Regions / Overflow

Yes, CSS is the way to go with this. I had a similar problem with a twitter feed in a block. Using Chrome developer tools, I just targeted the twitter content without making adjustments to the block.

You definitely don't want to mess with the JavaScript if there isn't an option in your script tag.


Multiple instances of same form in views do not work properly

After looking for a while on the Internet, I found a solution.

Firstly, you can add a '#name' to your submit buttons to distinguish them, and then do a switch case in the submit handler... I was trying this for a while before realising that it was not my problem.

My problem consists in the fact that I am calling the same form multiple times on the same page. I found a previous post which highlighted the fact that each form should get a unique form_id in order for it to work. Using hook_forms was the best method for this. I followed the instructions from here. It worked despite it being for Drupal 6.

Amended code...
I added this hook:

function mymodule_forms($form_id,$args){
  //Check if the form_id passed to drupal_get_form() contains the string 'mymodule_form'
  if (strpos($form_id, 'mymodule_form') !== FALSE) {
     //Lets attach mymodule_form to $forms[$form_id].  This effectively allows you to use the same form builder function to build a form with any form_id of your choice.
     $forms[$form_id] = array(
       'callback' => 'mymodule_form',
     );
     return $forms;
  }
 }

And then, the code that calls the form was amended to this:

function mymodule_answers($nodeid) {
   $theform3 = drupal_get_form('mymodule_form_'.$nodeid,$nodeid);;
   $output .= '
'.drupal_render($theform3).'
';

   return $output;
}

Voila!


LDAP lets you query an LDAP service, create a View of an ldap query, process an ldap result using Feeds, or import/update Users to your site.

An RSS view, provided by Views RSS, is simply a contributed View type from a community module. You must tell Views what fields should show up in the RSS feed you're creating. Typically there is a Settings option next to the Row Style to set what fields to display.

See the attached settings options (which is using an LDAP Query View). You need to make your LDAP Query first using the LDAP module, then add a new Display Type of type Feed in Views and then configure the Fields settings for the RSS feed.


if I suppose cst.admin_menu_menu_tabA: is your sub-menu A then also add

  cst_core.links.task.yml for tabs or sub menu tabs in an admin page

then add the following code below

cst.admin_menu_menu_tabA:
  route_name: cst.admin_menu_menu_tabA
  title: 'sub-menu A'
  base_route: cst.admin_menu_menu

proceed so on for the rest of the tabs..

and also add a route for cst.admin_menu_menu_tabA in cst_core.routing.yml


How to determine what image style an image field of a node has?

You can use the field_info_instance() function to get that information:

$entity_type = 'node';
$field_name = 'field_image';
$bundle = 'article'; // Or whatever content type you need.
$view_mode = 'default'; // Or whatever view mode you want to get settings for, e.g. teaser.

$info = field_info_instance($entity_type, $field_name, $bundle);

$settings = $info['display'][$view_mode]['settings'];

$image_style = $settings['image_style'];


How to limit form submission per user per day and week?

Make a custom module to implement hook_node_access, i will post some code based on a user date field that compares 'today' with this user-date-field and return access deny if dates comparison goes beyond 'today', and another with today+7 days, you will have to adapt this code to your needs; please add in user profile a date field, this field it has to be updated by rules every time a user adds content of your 'special content-type', maybe you will need 2 user-date-fiels, one for each 'special-contentype' if you need help with this last comment please ask.

// replace HOOK with yourmodulename and field machine names
function HOOK_node_access($node, $op, $account) {

  $type = is_string($node) ? $node : $node->type;

  global $user;

  // check if not anonymous
  if($user->uid!=0){

    //check if not administrator role, admin will have allways access
    $user_role = '';
    if (in_array('administrator', $user->roles)) {
      // do fancy stuff
      $user_role = 'administrator';
    }

    if (!$user_role == 'administrator') {

      $user_logged = user_load($user->uid);
      $user_date_field = $user_logged->YOUR_USER_DATE_FIELD[LANGUAGE_NONE][0]['value'];

      // today date in UNIX date stamp
      $today_int = date('U');

      // your user_date_field in UNIX time stamp
      $date_int = (int)strtotime($user_date_field);

      // check if 'today' is > than user_date_field
      $diff = $date_int - $today_int;
      $diff = round($diff/86400); // diff in days betwen 2 dates

      // today comparison
      if ($diff >= 0 ) {
        // code... user do have access to add/edit content

      } else {
        // code... retunr access deny 'today' add/edit
        if ($type == 'YOUR_CONTENT_TYPE_MACHINE_NAME') {
          // if options are update ore cerate content, return access deny
          if ($op == 'update' OR $op == 'create') {
            return NODE_ACCESS_DENY;

          }
        }
      }

      //  1 week comparison
      $diff7 = $diff + 7;

      if ($diff7 >= 0 ) {
        // code... user do have access to add/edit content

      } else {
        // code... retunr access deny 'today +7 days' add/edit
        if ($type == 'YOUR_CONTENT_TYPE_MACHINE_NAME_7') {
          // if options are update ore cerate content, return access deny
          if ($op == 'update' OR $op == 'create') {
            return NODE_ACCESS_DENY;

          }
        }
      }
    }
 }
}

NOTE, if you do not want to add fields to user profile form, it could be done by adding variables to logged-user by HOOK_entity_property_info_alter(&$info), if this is needed please ask.

EDIT:

please specyfy in your question that is about webforms, so, above code do not apply, i'll leave it, could be usefull for someone else.

what you can do is still keep 'user_date_field', install the following mudules: flags, rules and panels.

I will explain only ‘today’ settings, same thing for ‘1 week settings’, only in this last case you will need another field (or user-variable) to store how many webforms has submitted this user in current week.

Steps:

• enable rules, rules scheduler, flag & panels modules.

• make a user flag ‘user-posted-a-webform’

• in rules:

• make a component, unflag current user (it will be invoked later).

• make a rule, flag user when submit a webform, update 'user_date_field' with site-current-date

• in panels make a page and add your webform, add a rule (inside panles content section) make it visible only if user is NOT flagged.

• Return to your rule, add an action “schedule component evaluation”, choose your component, inside action setting, on ‘scheduled evaluation date’ enter ‘+1 day’.

• Done

COMPONENT unflag-user


You need some way to assign UUIDs to menu links. Just like how the uuid_features module assigns UUIDs to nodes.

For Drupal 6, there's a patch to the uuid_features module that has worked well for me. (See comment #2 on the issue for instructions.)

Haven't tried for Drupal 7.


Correct image path to use in template files of custom themes

I think these functions could be useful in your templates:

print base_path() . path_to_theme();

path_to_theme() Return the path to the current themed element.
base_path() The base path of the Drupal installation.

for example, I have an image called bg-bar.png inside images directory in my template directory called garland. then I can use base_path() and path_to_theme() to get the path to the image, for example inside node.tpl.php:

print '';

Update: if you want to use the current domain, you can use global $base_root:

  $address = ''.base_path() . path_to_theme() .'/images/bg-bar.png';
  global $base_root;
  echo '';

I hope information be useful.


Pass parameters for node access on RESTful call

The entity index resources unfortunately cannot be used to filter by field values, they can only filter by entity property values (e.g. node nid, title, type, etc). I think you have two options:

create a custom service resource that uses parameters and a database query (or entity field query) to filter and return what you want
use views_json (a sub module of views_datasource) to create a View with a contextual filter for your field


Where to add custom theme function that generates HTML?

Your nearly there...

If your going to do this on the theme layer then create the custom function and call it in a process function assigning to a variable that can be passed to the template.

Thats typically the "Drupal way".

template.php

function THEME_customFunction() {
   // blah blah...
}

template.php

function THEME_preprocess_page(&$vars) {
   // blah blah...

   $vars['animation'] = THEME_customFunction();

}

page.tpl.php

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


Converting JavaScript from Drupal 7 to Drupal 8 standards

As you already linked from the docs https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview I just repeat the most important parts here:

MYMODULE.libraries.yml

foobar:
  js:
    js/foobar.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

js/foobar.js

(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      $('.MYSELECTOR', context).once('myCustomBehavior').each(function () {
        // Apply the myCustomBehaviour effect to the elements only once.

        // I guess you have to pass something to `settings` first.
        // $("#mapplic").mapplic(settings.mapplic);

        console.log('Hello world!');
      });
    }
  };
})(jQuery, Drupal);

MYMODULE.module

function MYMODULE_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] =  'MYMODULE/foobar';
}

Update: removed some flaws.


Is it a security issue to put CSRF token in drupal settings?

Drupal.settings, and other global variables, will be available to cross-origin scripts that happen to be injected (possibly maliciously) into the site. The same applies to any other part of the document body, like meta tags or JSON script tags.

Sensitive tokens should ideally be stored in a place that is restricted to same-origin scripts, which includes cookies and localstorage: https://stackoverflow.com/questions/34782493/difference-between-csrf-and-x-csrf-token

(This shouldn't normally be critical, because script injection shouldn't be possible in the first place, and is a severe vulnerability by itself. But it's probably still a good idea to rely on multiple layers of security.)


Can tokens be used to set values of other fields and in modules which use tokens?

You try use hook_tokens()

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'key_token' && !empty($data['node'])) {
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      $replacements[$original]='Some_value';
      }
    }
  }
  return $replacements;
}

See more document hook_tokens()


Image Upload Issues Same Image Different File Name Always Receive This Error

You may have the File Hash module installed, and the Optional duplicate file protection feature enabled. That configuration would result in exactly the error message you're seeing, but obviously you may have custom code that does this instead.

If you are using File Hash, and don't want that functionality, you can either disable it at /admin/config/media/filehash, or uninstall the module entirely.


Got it! Used the below code and everything works fine.

filter_var($snippet, FILTER_SANITIZE_STRING);


It is better to use construction

{% if page.region|render|striptags|trim|length > 0 %} ... {% endif %}

So you can check if there is some content or not.


How to get the count on the select list in views?

Assuming Drupal 7 and Views 3:

Create a view based on your content type with a page or block display
Add a contextual filter, based on your select field
Under "When the filter value is NOT available" select "Display a summary"
Configure the summary as you like, with "Display record count with link" enabled


Form modes and form operations are a bit strange. You also need to define a form operation through hook_entity_type_alter() to be able to use a custom form mode.

Which makes the UI to create form modes pretty useless, but ssshh, don't tell anyone :)

For an example, see views_ui_entity_type_build(): $entity_type->setFormClass($operation, $class_name)


If you want a title for each type of view, I would click the add button for a "header" then click on Global text and enter in the Title you want for that view.

UPDATE:

Also, if you are looking to put in a title for each entry you could look into making that a content type that the view pulls from. It can pull the Title of each entity.


Straightforward method to get related items view from Solr

The feature is actually built in to apachesolr.module. It is called 'mlt' (short for More Like This).

You can add differently configured MLT blocks via ?q=admin/settings/apachesolr/mlt/add_block and then configure their visibility in ?q=admin/build/block or whatever block visibility mechanism you are using (context etc).


After setting $base_url, I can only access the front page

It sounds like the answer from Oleg Ivanov would work. However, if you want to tackle this with a .htaccess approach, the following works for me. Find and replace SUBDIRECTORY with your subdirectory.

Amend your Drupal's .htaccess with the following:

RewriteBase /

# homepage redirect
RewriteRule ^$ /SUBDIRECTORY/index.php?q= [L]

# if directory or regular file...
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_URI} =/favicon.ico
# stop here
RewriteRule ^ - [L]

# if a regular file in SUBDIRECTORY directory
RewriteCond %{DOCUMENT_ROOT}/SUBDIRECTORY/%{REQUEST_URI} -f
RewriteRule .* SUBDIRECTORY/$0 [L]

# Redirect everything to /SUBDIRECTORY
RewriteRule .* /SUBDIRECTORY/index.php?q=$0 [QSA]


Allow view access to current user and admin

Create another view or a page within same view with path /mystat or path can be different without using contextual filters. And in page seetting option in view choose access from none to role and select admin role.


Redirecting Drupal multisite non-www to www with varnish / nginx

I was able to do it with the following nginx config:

if ($host !~* ^www\.) {
   rewrite ^(.*)$ http://www.$host$1 permanent;
}


Drupal 7 CKEditor and KCFinder, how to upload to private files directory

I found a solution that works at least in my case. I was on the right path... If you simply want to hardcode an upload path, you just need to configure two things in the uploader.php, the uploadDir where the files will be stored, and the Drupal URL where Drupal can find the private files, in my case:

// UPLOAD FOLDER INIT

    // hardcode private file upload path outside of web root, can't be configured through the UI that I could find
    $this->config['uploadDir'] = '/var/www/private_files';
    // hardcode the private file url that Drupal needs to be able to access private files internally
    $this->config['uploadURL'] = '/system/files';

I know uploadDir already because that's where I've already configured private files to be stored. To find uploadDir, I linked to a private file already located in /var/www/private_files, then double clicked to see the first part of the URL on the dialog that points to where the root of /var/www/private_files is located.

The next thing I had to do was disable htaccess checking in the KCEditor config file (/sites/all/libraries/kceditor/conf/config.php) by setting '_check4htaccess' => false


What is the accepted way to display certain content on different pages

That is definitely one way to do it.  I don't think there is a "Drupal way" to accomplish this per se, but you can also accomplish this through taxonomy and panels.  It really just depends on if having an extra Content Type bothers you or not.

I think the way you currently have it is the most efficient way.  To me you should only use taxonomy if it fits the mold of Drupal's definition of taxonomy.

    Taxonomy, a powerful core module, gives your sites use of the organizational keywords known in other systems as categories, tags, or metadata. In Drupal, these terms are gathered within "vocabularies." The Taxonomy module allows you to create, manage and apply those vocabularies.