moving *.tpl into "templates" folder, but Drupal does not recognize them. How?

I've also run into a situation where I had to create a page.tpl.php file before Drupal would recognize other page--foo.tpl.php files.


How to check if result from cache_get() is expired?

TL;DR Don't, unless you have to. Drupal has long history of optimization and even if it sometimes serves you outdated cache, it's not without a cause. It's to prevent overhead of constant cache wipes. If your application is time-critical for some reasons, read below.

As you can see in the code that does the actual work:

function getMultiple(&$cids) {
  try {
    // Garbage collection necessary when enforcing a minimum cache lifetime.
    $this->garbageCollection($this->bin);

    // When serving cached pages, the overhead of using db_select() was found
    // to add around 30% overhead to the request. Since $this->bin is a
    // variable, this means the call to db_query() here uses a concatenated
    // string. This is highly discouraged under any other circumstances, and
    // is used here only due to the performance overhead we would incur
    // otherwise. When serving an uncached page, the overhead of using
    // db_select() is a much smaller proportion of the request.
    $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
    $cache = array();
    foreach ($result as $item) {
      $item = $this->prepareItem($item);
      if ($item) {
        $cache[$item->cid] = $item;
      }
    }
    $cids = array_diff($cids, array_keys($cache));
    return $cache;
  }
  catch (Exception $e) {
    // If the database is never going to be available, cache requests should
    // return FALSE in order to allow exception handling to occur.
    return array();
  }
}

There is no test built in1, and no limit that makes Core return only unexpired nodes.

The way I prefer if I can, is to delete/hide table rows on database level, for example by creating a proxy view that never returns outdated records in the first place, but usually this is inconvenient. Don't try unless you know what you're doing.
The Drupal-only way would be to add comparison in PHP, like that:

if (isset($cache->data) and time() < $cache->expire) {

If your cache is relatively long, you can, and for performance reasons probably should omit testing their expire date on each call and leave it to Drupal's core. It will allow minimum cache lifetime to work with your data, for example. That's how core is doing it.1

1 There are some tests in prepareItem method, but for performance reasons they do not guarantee that outdated cache items will not be returned - see actual code for details.


rest POST via Postman always ends in 403 access denied

Your request need ?_format=json on the end of request.
Clear cache.
Delete all sessions, delete from sessions.
Call login service, /user/login?_format=json,
method POST
choose raw in Body and there put username and password in JSON format:

{
   "username": "value",
   "password": "value",
}

and choose JSON (application/json).

This service will return X-CSFR-TOKEN, use it for your request.


What is Content Construction Kit (CCK) in Drupal

It used to be called CCK in Drupal prior to Drupal 7, and came in the shape of a contributed module.  In Drupal 7, most of the functionality of the CCK module was moved into the core and it is now usually referred to as "fields" (or "fields in core").

The purpose of the CCK was to provide a simple UI for adding new "fields" to entities so that new, specific content types could be created by site designers.

In Drupal 7, you do exactly the same thing by adding "fields" (which may be typed) to entities.  A full tutorial about CCK/fields is beyond the scope of this Q+A site, but GIYF (Google Is Your Friend).

Edit: As noted in a comment by jimajamma, the CCK project page has more information and links to tutorials.


Passing an argument to a node causes 404

There are modules to accept subpath aliases.

If you're on Drupal 6 then look into the subpath_alias module.

Drupal 7 has subpathauto which does the same thing.

What they do is expand Drupal's path matching to work with subpaths, so no extra aliases are added. I've used it in the past when embedding views within nodes and it worked a treat.

So if you have node/4 aliased to path/test then it will recognise path/test/argument as node/4/argument


Custom form which on submit click inserts into the database

drupal_get_form doesn't return a markup as such. it returns an array of the form structure. to get the html out put you should run the drupal_render function.

something like drupal_render(drupal_get_form('formtest');


Cannot get JQuery plugin working on Drupal 7

From the Drupal 7 upgrade guide:

  Javascript should be made compatible with other libraries than jQuery
  by adding a small wrapper around your existing code:

(function ($) {
      // Original JavaScript code.
})(jQuery);

  The $ global will no longer refer to the jquery object. However, with
  this construction, the local variable $ will refer to jquery, allowing
  your code to access jQuery through $ anyway, while the code will not
  conflict with other libraries that use the $ global.

(function ($) {
  // Create the tooltips only on document load
  $(document).ready(function() {
    // By suppling no content attribute, the library uses each elements title attribute by default
    $('#content a[href]').qtip({
      // Simply use an HTML img tag within the HTML string
      content: 'dfdfdfdfdf'
    });
  });
})(jQuery);


Views AJAX pager not working, though AJAX is enabled

I can't (yet) answer your question, but I can see where I think it's going wrong.

The Views JS is loading for your site, but the Views classes aren't being applied the same on your site and the test I'm using. I expect if you swap to another theme, you'll see the View start working. (That doesn't mean you need to abandon your theme, but it may help you track the problem down.)

In your JS console, you can inspect variables - and the relevant variable for you looks like Drupal.views.instances.GENERATEDNAMEHERE.element_settings.selector.

On a working test site, I see this (zoom in to see the JS). Note that the value in selector can then be used to obtain the wrapper div for the view HTML.

(To test: Copy the value from selector, and use it as a jQuery() selector. You can do this in your JS console.)

On your site, I see a value set in the same (similar, due to the generated ID) location, but that same value doesn't match an element in your HTML - jQuery returns an empty array, instead of an array populated with (one) matching HTML element.

So ... you need to work out what about your theme is preventing that DIV being applied. If your theme is from Drupal Contrib, you might check the issue queue. If you're using a module which strips extraneous DIV elements, that might be a place to look. And so forth.

Hope this helps ... it's not really an answer, but I hope it moves you closer to one!


Auto populate a node add with values of another node

Did you mean node clone module?

  The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original content.


What license can I apply for a theme I sell?

One technique you might consider is committing your basic theme to a project on drupal.org, distributed under the GPL.  Then, develop premium css and graphics that can be installed over your basic theme using instructions that you provide. The later package could be distributed under a license of your choice.

It is okay to use a separate license for the css and graphics files because they can be considered separate works that stand on their own. To make it more clear that the css and graphics are separate works, you could distribute them with a static html file that shows what the final theme should look like. Your customer has the right under the GPL to combine the css and graphics with his GPL theme; tt would be a violation of the GPL to distribute the combined works, but they can be used by the licensee of the separate works (your theme).

Finally, regarding the "basic theme", note that there is nothing special about css and graphics vis-a-vis the GPL; it is still necessary to deliver the "source" of your works along with the "binaries" when they are included in a GPL-licensed distribution. If you built the css using some tool, then you must deliver the source files that were used to produce that css. If you created the graphics in photoshop with layered psd files, then you must also distribute those files with your theme, and so on.

Edit Edit Edit: Reworked my prior answer(s) for clarity, and to remove a mistake.

Postscript: I believe that the FAQ referenced below is partially incorrect; graphics and css are not excluded from the GPL because they are "data"; if they are an integral part of the work being distributed, then they are covered by the GPL as much as the code is.


Drush 8 not working correctly on (LAMP) Ubuntu 16.04

Recently run into a similar problem on my local environment after an ubuntu update and php 7.2 became my default version.

make 7.1 or lower your default php version

I believe you should make php 7.1 the default or perhaps even a lower php version for Drupal 7 installation as not all modules are ready for php 7.2 (even some of Drupal 8 modules are not ready for php 7.2)

type this in your shell

$ sudo update-alternatives --config php

and this is what you will get

There are 4 choices for the alternative php (providing /usr/bin/php).

  Selection    Path             Priority   Status
------------------------------------------------------------
* 0            /usr/bin/php7.2   72        auto mode
  1            /usr/bin/php5.6   56        manual mode
  2            /usr/bin/php7.0   70        manual mode
  3            /usr/bin/php7.1   71        manual mode
  4            /usr/bin/php7.2   72        manual mode
Press <enter> to keep the current choice[*], or type selection number:

Choose the appropriate version

might need to update drush to a later version.

8.1.16 is out at this moment and might already have solved the problem you describe. Update using composer

alternatively you can try to setup drush without composer

# get drush latest 8 version from
# https://github.com/drush-ops/drush/releases
wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# make it executable
chmod +x drush.phar;

# move it to home directory or any other directory
mv drush.phar ~/drush;

# go to that directory
cd ~

# find out the path to the directory
pwd
# the output would look similar to this
# /home/your_user

# edit the following file
nano .bashrc
# or
# nano .bash_profile

# add this the end of the file
alias drush='/home/your_user/drush';

# use the alias you just setup
source ~/.bashrc;

might want to specify site directory when you invoke drush

as you drush might have a messed up setup/aliases

drush status -r /path/to/site/rootdir

doublecheck your settings.php

Does it include the correct database connections? Does the site actually run with those connection settings ?

Look in your logs for any problems

in my system I can see apache errors like this

tail -50 /var/log/apache2/error.log

You might discover that some apache packages are missing or disabled just an example lets say mod_rewrite is not enabled

sudo a2enmod rewrite
sudo service apache2 restart

or you might find that some package is missing like mysql-client

sudo apt-get install mysql-client


Deleting all Webform Submissions and Content from specific IP

You could use Views Bulk Operations.

Add Bulk operations: Content as a field and check mark Delete item under Selected Bulk Operations. Make your view format as Table.

You could try using IP Address manager or User IP Log and hopefully one of these modules will allow you to add IP address as a field to your view.

In your View, under Advanced, you may possibly need to add a relationship of author to your view so you can access user fields (IP Field).


How to get "Add another item" option for fields based on taxonomy terms

Problem solved by installation of the Taxonomy Single Tag module and the patch from #6 of this thread. Answer provided by "Poieo" on drupal.org. I have applied this and it is working as desired. However I noticed that without the patch, I was getting errors not only with the new field where the "Single tag autocomplete text field" widget was applied, but also with other fields allowing multiple-item adding – even though they were neither autocomplete nor based on taxonomy terms.


If you are using Drupal6 Have a look at Mobile Tools module.

  The Mobile Tools module provides Drupal developers with some tools to
  assist in making adjustments to your site based on the visitor's
  device.

Once you install the module you can define different paths for desktop and mobile, then browser will detect the device and redirect to corresponding path.
For Drupal 7 Mobile Switch module is the alternative


Is it possible to create a hierarchical exposed filter in views using the Data module?

First Install Hierarchical Select Module for display taxonomy of parent/child relations then add that taxonomy as a field to your content type then add this field to your exposed filter. it's working..


How to get the field collection field value in twig file?

Say you have a field collection field_test and the field collection has fields say field_name and field_age, you can access them using the below snippet.

{% for details in node.field_test %}
    Name: {{ details.getFieldCollectionItem().field_name.value }}
    Age: {{ details.getFieldCollectionItem().field_age.value }}
{% endfor %}

See reference and
another reference

I assume getFieldCollectionItem().field_name.value is what you are looking for.


Images not displaying after transfer to temporary site ~username

Sorry, I just re-read the question and realised I misread it before.

Try setting your base path in the .htaccess file and also the base path in the settings.php file. (actually I think I'm confusing myself. I'll leave this here anyway.)

Previous answer

Are you talking just image style images or all images?
Can you look in the source of your page and give an example of one of the file paths that is not loading properly?

I know you have stated you have already done some of these, but this is what I would try.

Check a few images by looking at their path in the source and checking on the server that they exist in that place.
Try going in your browser, directly to one of the files, for example yoursite.com/sites/default/files/yourfile.png or whatever it is.
Check permissions of files directory and also the temporary files directory, which must exist and be writable (the status page should alert you to these anyway).
Try saving your image styles to force them to regenerate your images, and clearing your caches again.
Check files .htaccess
Check your watchdog logs for any errors that might be related (any unrelated errors should be investigated too.


How to add a title attribute from a different field to a link produced by a view

You can achieve this by using   views Rewrite results feature, Rewrite your Link with checking Override the output of this field with custom text and put your markup there and with Replacement patterns put your title as  your link attribute title.

More details Provided by @Raf

Thanks to zhilevan for pointing me in the right direction. After much trial and error this is the only thing I got to work other than completely rewriting the input with custom html.

I needed to add a "path to content" field. Note my fields are called 'field_heading' and 'title' respectively.

Note: the field that will actually host the link has to be at the bottom of the list. I wasted ages trying to figure out why I couldn't target my title text before realising this...

You need to uncheck "Link to content" in the setting for the host field - in my case 'Heading'

In the 'Rewrite output' section you need to actually provide a link or it will not work - or at least I could not get it to work without it. So the 'path' field I added earlier was used here as the path for the link. I could then add title field to the title attribute. You can see the available replacement patterns in the drop down with that name.

and the title attribute override...

Anyhoo, that was what i had to do to get it to work. Hopefully it is useful to someone else. I would love to see a simpler way to do this.


How can I programmatically create a node?

The following code will help you to save an image in a new node.
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

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

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


Superfish is pretty configurable. You can use classic drop downs or try a mega menu


Trigger submission via Javascript when exposed filters are changed on a block display in Views

Was there a while ago, still don't understand why they'd scrap-off such an essential feature. Thanks to this thread @ drupal , found a solution.

Download the module at #5


In your field in your view, if you uncheck the option "Display all values in the same row" in the "Multiple field settings", each new image in any photo piece of content will be considered as a row. You then will be able to show only the last 5 images instead of the last 5 photo albums.


Trigger an event when file is upload on managed_file field

Finally I found a solution. I decide to use the '#upload_validators' parameter on my form and to declare my own function:

'#upload_validators' => array(
  'myOwnFunction' => array(parameters)
),
.
.
.

function myOwnFunction(parameters){
do stuff();
}


How to load current user cart in Commerce 2?

It depends what you need, really. If you just need all carts for all stores, the cart provider service can give you that:

$all_carts = \Drupal::service('commerce_cart.cart_provider')
  ->getCarts();

If you need a cart for a particular store based on context, it gets trickier. A reference to the "current" store can be found via the current store service:

$store = \Drupal::service('commerce_store.current_store')->getStore();

And the cart related to that store via the cart provider:

$cart = \Drupal::service('commerce_cart.cart_provider')
  ->getCart('default', $store);

(incidentally in all the above snippets, if you can inject those services into your current context instead of using the static methods, all the better).

The problem is in Commerce's definition of a "current" store. Out of the box that either comes from the order entity when viewing an order, or it's the default store. From your description neither of those will do the job, so you'll need to write a custom store resolver.

I don't know what context you have available when needing the cart entity, so here's a naive example based on a product page. Since a product can be in more than one store, it just returns the first in the array.

namespace Drupal\MODULE\Resolver;

use Drupal\commerce_product\Entity\ProductInterface;
use Drupal\commerce_store\Resolver\StoreResolverInterface;
use Drupal\Core\Routing\RouteMatchInterface;

class ProductPageStoreResolver implements StoreResolverInterface {

  protected $routeMatch;

  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  public function resolve() {
    $product = $this->routeMatch->getParameter('commerce_product');
    if ($product instanceof ProductInterface) {
      $stores = $product->getStores();
      return reset($stores);
    }
    return NULL;
  }
}

And the entry for MODULE.services.yml:

MODULE.product_page_store_resolver:
  class: Drupal\MODULE\Resolver\ProductPageStoreResolver
  arguments: ['@current_route_match']
  tags:
    - { name: commerce_store.store_resolver, priority: 100 }

Once you clear the cache, the first code snippet above will return the first store a product is assigned (when viewing it).


Image upload: Failed to open output stream

In /admin/config/media/file-system look at the value of "Temporary directory" (/var/tmp or /tmp or ...) and check if that path is writable by the webserver user.


How to create and display user content submission form and display it in a block?

You can make use of the form block module.

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Since the drupal 7 version is still in development, make sure to test it on a development site before moving it to a live site.


Where to put a script to provide AJAX/JSON response?

The easiest is to use Views datasources if it can solve your problem, in essence this means that if you can use views to display the data you need, you can use this module to return it as JSON.

Another option is to write a custom module and use hook_menu to define a 'menu' item which you can use from the calling code. To return your data as JSON you can use the standard php functions.

If you need multiple scripts and advanced configuration you can always have a look at Services or


create a datetime field with data module

To get date and time data types in the Drupal that can be used in fields, etc., install the Date module in addition to the Data module.


User defined field not updating with PHP code

Change this:

<?php
      $node->field_productid['0']['value'] = $order->order_id;
?>

To this:

<?php
      $node->field_productid[LANGUAGE_NONE][0]['value'] = $order->order_id;
?>

See if that helps.


you can create a module. inside the module you can use the function form_alter to modify the form, and specifically use the function drupal_set_title() to add the title, for example:

create a module with the name "change_title".
add a form_alter function (note that the name of the module is added to the _form_alter name function)

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

 //dsm($form_id) this function is to know the $form_id

   if ($form_id == 'content_type_node_form') {
       drupal_set_title('this is my new title');
   }

}

note: about how to get the $form_id value, you can use Devel module to use the function dsm($form_id), then the return of this function will show you the $form_id value.


Views Row style Node heading between different dates

I think you need fields to group by date. You can use Views node field to have a field that shows as a node (with a choice of build mode). I think that should work.


Adding Comments to Custom Node Template File

You may want to take the sample node template file and update as per your requirement. Here is the code which renders the comments section of the node template file.

<?php print render($content['comments']); ?>


Check “Archive” view from standard Views install for start.
In your case you need to use contextual filter “Content: Created year” instead of “Content: Created year + month”.


Is it possible to have a specific page.tpl.php for mobile devices?

If these advertisements are in a block, you can put some intelligence in that block, eg:

if USER_AGENT == MOBILE DEVICE
   return // eg, nothing
else
   return the AD

This way, the ad is never delivered on the mobile device.  The USER AGENT can be gleaned from $_SERVER['HTTP_USER_AGENT'], eg:

if (strpos($_SERVER['HTTP_USER_AGENT'],'iPhone')!==FALSE) {
   // I'm an iPhone
}


How to add indexed:has taxonomy term id(with depth) in the contexual filter of view?

In custom module

you can use hook__views_pre_view to change contextual filter,
add children terms till depth to the contextual filter,
function taxonomy_get_children_all() defined below, will fetch all child terms till depth:
In view, don't forget to allow multiple value contextual filter for contextual filter.

function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
  $c = taxonomy_get_children($tid, $vid, $key);
  $result = array();
  foreach ($c as $t => $d){
    $result[$t] = $d;
    $below = taxonomy_get_children_all($t, $vid, $key);
    if (!empty($below)) {
       foreach ($below as $nt => $nd){
         $result[$nt] = $nd;
       }
    }
 }
 return $result;
 }

 function formalter_views_pre_view(&$view, &$display_id, &$args){
 if($view->name == "category_view") { // && $display_id == "page") {
   $vid = <Your vocabulary id>;

   $t = $args[0];

   $tt = taxonomy_get_children_all($t,$vid);
   foreach($tt as $k => $v) {
     $a = (string)$k;
     $args[0] = $args[0] . "+" . $a;
   }
 }
}


your problem is $new_node->status = 0;
This is setting the node to 'unpublished'.
either change the permissions to allow the users to see it or set $new_node->status = 1;
To create a link use the l() function eg. l('link text', 'node/'.$node->id);. http://api.drupal.org/api/drupal/includes!common.inc/function/l/7


How to get the URL for the re sized image

I wouldn't use your approach because as you can see by yourself now you have no reference to the resized image, what I would do is use image_style_path :

function adddeals_submit($form, &$form_state){
    global $user;

    $file = $form_state['storage']['file'];
    unset($form_state['storage']['file']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    $url = file_create_url($file->uri);
    // this
    $derivative_uri = image_style_path($your_style, $file->uri);
    $url = image_style_create_derivative(image_style_load('your_style'), $file->uri, $derivative_uri);
}

This creates a folder in your files folder with your style name and stores the image there, then wherever in your code you want to get that image you just reutilize this code:

$derivative_uri = image_style_path($your_style, $file->uri);
$url = image_style_create_derivative(image_style_load('your_style'), $file->uri, $derivative_uri);

Drupal checks if an image is there and gives you back the $url, if it's not there it creates the image applying your style.

P.S. you need to register your style in configuration and once the style folder is created check it's permission settings.


Using the API to add a column is the right thing to do, but it can't/won't update the code in your hook_schema() definition for you.

Drupal relies on that definition to map values to columns, so if you haven't explicitly declared the 'test' column, entity API doesn't know it exists, and so discards the value.

To solve, you should declare the new column in hook_schema():

$schema['my_subscription'] = array(
  'description' => t('The base table for subscriptions'),
  'fields' => array(
    'sid' => array(
      'description' => t('Primary key identifier for an subscription log.'),
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'email' => array(
      'description' => t('Email of a users subscription.'),
      'type' => 'varchar',
      'length' => '250',
      'not null' => TRUE,
    ),
    'name' => array(
      'description' => t('Full name of a user subscribing.'),
      'type' => 'varchar',
      'length' => '250',
      'not null' => FALSE,
    ),
    'test' => array(
      'description' => t('Test field.'),
      'type' => 'varchar',
      'length' => 255,
    ),
  ),
  'primary key' => array('sid'),
);

After you clear caches things should start working.


Treat this as an upgrade. You won't have a problem with missing columns, because those are in your database. You'll have a problem with missing plugins to access those columns.

First, of course, back everything up.
Then install Drupal. It makes
sense to follow @Schnippy's hint and look in the database for the
version number, and install that version of Drupal. Otherwise,
install the current version; it will tell you if it needs to update the database.
Look in your database (hopefully you have phpMyAdmin available) for tables created by plugins. Use that and your memory to reinstall any modules. You might also look at admin/reports/updates and see if it'll list your missing plugins.

Later, I recommend installing the Schema plugin, which will report any mismatches between your modules and database tables. This gets reported on the Status Report page and is wonderful when developing a custom module.

If you lost your images and file uploads from your theme or site/default/files directory, you may be out of luck for that content. Good luck!


Implementing hidden content parts (as in old "Hidden Content" module)

You could use Block Class module to set blocks with some useful classes like "only-role_name", etc. and hide/display it on your theme stylesheet.

Maybe even you could set a new block type and, if this type has its own css class (I'm not sure about it), use it to hide/display using, again, your theme stylesheet.

You could, too, use a new content type to create the block contents and Views to render this as blocks where you need. Views is able to restrict his view depending on roles or permissions.


How to change the language of a node and all its fields and all related data?

If this is just a one-time conversion, you should be able to do it with Views Bulk Operations (VBO).

Here's one way to do this that doesn't involve writing any code.

Install the VBO module.
Create a new view showing Content of whatever content types you need to convert.  Use the Fields display method.
Add a field Bulk operations: content.
Check Modify entity values and select Language.
Choose Apply.
Save the view (add any other filters if necessary to limit the selection) and go to the created view page.
From the view page, choose the option to select all items on all pages and execute the Modify entity values action.
Choose the language and click next.

If you have an extremely large number of nodes, you may need to play around with the queuing settings so that not everything is executed at once, but I would try doing it in one pass first because hey, if it works, you're done (note: always test on a backup first!)

Source: How can I set the language of nodes in bulk to existing content when making a site multilingual? - please upvote that one if you liked the solution above.

To force the default language to be undefined, in the setting.php file used by your site, add the following lines:

$conf['language_default'] = (object) array(
  'language' => 'und', 'name' => '', 'native' => '',
  'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
  'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''
);

This will force Drupal to use 'und' as the default language for all new content.


For the creation of a prepopulate link, how can i strip out slashes if they occur in the title?

echo 'field_eventform['und'][0]['nid'].'/'.str_replace('/','',$node->title).'/'.$node->nid.'">'.str_replace('/','',$node->field_eventform['und'][0]['node']->title).'';

You have to check, if the link works, when you strip the '/', if not, replace the '' in str_replace with the correct replacement, that your path alias use.


How do I store my client's passwords securely and make them retrievable?

Try either the Field Encrypt module:

  Adds options to encrypt field values.

  The goal of this module is to create a method for encrypting field
  values when stored in the database.

  This module depends on the Encrypt module
  (http://drupal.org/project/encrypt) for encrypting and decrypting
  strings.

Or which sounds better for your use-case of "settings" the Encrypted Settings Field module:

  This module adds the "encrypted settings" field through Field API,
  which has the following two features:

  The field can be encrypted before saving to the database
  The field can be validated to follow INI format

  This module is ideal to save
  credential settings information, such as a "Credit Card" field to add
  to users' profile.

A more developer friendly form which stores the final encrypted value into the drupal database and plays nicely with Drupal 7 core Form API elements is the Encrypt Form API module:

  After installing and enabling this module, you will be able to add an
  '#encrypt' property to any of the following supported Form API element
  types:

  textfield
  textarea
  checkboxes
  checkbox
  radios
  radio
  select
  password
  password_confirm

To use this module I would recommend assuring your site is served only in SSL, then the contents of the field is encrypted on save, after normal form validation occurs.


Organic Group OG membership relationships

You just need to add OG membership: Group ID as a contextual filter,
click Provide Default: The OG groups of the logged in user
and under More at the bottom of the filter's settings,
click Allow multiple values.


I would recommend you to use Wysiwyg API template plugin module

  In TinyMCE, CK Editor and FCK Editor, there is a template function, which allows a user to select a HTML template from a drop-down and insert it into the WYSIWYG text-area. This module supports those features for use with the WYSIWYG API.


What is the naming convention for theme region template files?

Yes, the naming scheme is region--[region].tpl.php where [region] is the region machine name defined in the theme info file. See Drupal 7 Template (Theme Hook) Suggestions for more information. You will need to flush your theme registry cache for the template to take effect.


Custom button for CKEditor not showing up in node creation page

See the documentation at https://www.drupal.org/developing/api/8/ckeditor.

You can find examples in Drupal 8 core, at:

\Drupal\ckeditor_test\Plugin\CKEditorPlugin\Llama
\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaButton
\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaContextual
\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaContextualAndButton

(This is the exact same answer as I gave at https://drupal.stackexchange.com/a/191869/7632.)

To answer specifically why the button is not showing: CKEditor's Advanced Content Filter (ACF).

Please add your button to CKEditor in the "Full HTML" text format. Check if it shows up then. Chances are it does.

Your plugin does not specify ACF metadata. ACF is what ensures CKEditor produces clean markup. In "Full HTML", there are no restrictions, and no guarantees of clean markup.


How can I customize a menu to be intuitive for my users: show user name, have dropdown items

This can be easily done with the available following contributed modules.

Create menus from Admin UI, and restrict the visibility by Menu Per Role module. Here, you might like to to show the menus Create Account and Sign In only to anonymous (not logged in) users.
You can use the Menu Token module, if you wish to show username as menu. You'll need to install the Token module and the Ctools module in order to do this. This can be done in following way:

Create a menu link in your User menu using Admin UI by visiting http://yoursite.url/admin/structure/menu/manage/user-menu.

In the link title you input the user name. The following will replace the [current-user:name] with the username of the logged in user. You can even use other fields, under the "Menu Token Options" > "Replacement Patterns".

The output of the above:

As admin:

As an authenticated user:

For the dropdown feature of the menu, you can use the DHTML Menu or the Superfish menu.

Hope that helps. Please feel free to ask questions.


If you want more control on this, you can choose the option "Pages on which this PHP code returns TRUE (experts only)" and you can write the following similar code snippet the the box.

<?php
if( arg(0) == 'user' /* && you may add more conditions here by checking arg(1), arg(2) */) {
    return TRUE; // will display the block
}
return FALSE; // will not display the block
?>

The alternative way is to check the path with regular expression:

<?php
if( preg_match('/^user\/[[:digit:]]$/', current_path()) ) {
    return TRUE; // will display the block
}
return FALSE; // will not display the block
?>

This will show your block only at the path user/*.


Given your definition of studiga_theme_theme(), Drupal will never call custom_add_property_form() because there isn't any relation between the theme template you define, and that function. Eventually, you could implement the preprocess function for that theme template, and set there a variable that is passed to the template.

function studiga_theme_preprocess_add_property_form(&$variables) {
  $variables['form'] = /* define here the form */;
}

Now your theme template will get a $form variable.

Keep in mind that, except in a case, themes don't define forms; that is the task for a module. Eventually, themes can alter a form provided by a module, but (generally speaking) you will never see a theme that defines a form that is not for its own settings.


Programmatically render a custom form in a view template while passing view argument to form

Print form before the views:

function mymodule_preprocess_views_view(&$variables) {
  $form = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\DefaultForm');
  $variables['attachment_before'][] = $form;
}

===

Another way is to add your custom form and the views in own controller (and route),

In views add filters and expose them, set exposed in block = yes (this will detach the form from the views),

in exposed filters settings set the names as they are in your form - for each one,

make your form to redirect on submit to the route passing the values as query params (?param_name=value&param_name2=value2), for multiple select or checkboxes params are in format: param_name[6]=6&param_name[17]=17

the rest will be done by views - it will get params automatically

Controller:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\views\Views;

/**
 * Class DefaultController.
 */
class DefaultController extends ControllerBase {

  /**
   * Content.
   *
   * @return string
   *   Return Content string.
   */
  public function content() {

    $elements = [];

    $elements['form_search'] = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\DefaultForm');
    $elements['form_search']['#weight'] = 0;

    $views_name = 'machine_views_name';
    $display_id = 'page_1';
    $view = Views::getView($views_name);
    $view->setDisplay($display_id);

    $elements['view'] = $view->render($display_id);
    $elements['view']['#weight'] = 1;

    return $elements;
  }

}

example module with controller, form and exported views "Content list": https://github.com/svetlio/mymodule


How do I programmatically set the view title?

If someone else is looking for an answer, Here is how I achieved this.
I implemented hook_views_pre_render and in this hook, I implemented a method of views class setTitle. This allowed me to set the page title. Here is the complete code.

function MYMODULE_views_pre_render(ViewExecutable $view) {
 if ($view->id() == 'ABC') {
  $view->setTitle('MY CUSTOM TITLE');
 }
}

Hope this helps.


How to convert text area data into select list in forms?

As requested in the comments, in answer format:

Use the explode() function on your string
Loop through the results and split each entry
Add the result to the options array you feed to the select box

Eg.

$options = array();
$lines = explode(PHP_EOL, $entityoptions);
foreach($lines as $line) {
  $line = explode('|', $line);
  $options[$line[0]] = $line[1];
}


How do I duplicate a menu item properly?

The code that works in any case, whatever corporate/contact-us is a view, a menu item defined from another module in its hook_menu(), or a path alias for a node, is similar to the following one.

function mymodule_menu() {
  $items['the menu path you prefer'] = array(
    'page callback' => 'mymodule_page_callback',
     // …
  );

  return $items;
}

function mymodule_page_callback() {
  drupal_goto('corporate/about-us');
}

The only problem with this code is that it could redirect users to a page to which they could not have access, and for which they would get an access denied error. If the users don't have access to a menu item, the menu item should be hidden to them, and that can be done by adding the right access callback to the menu item.

function mymodule_menu() {
  $items['the menu path you prefer'] = array(
    'page callback' => 'mymodule_page_callback',
    'access callback' => 'mymodule_access_callback',
     // …
  );

  return $items;
}

function mymodule_page_callback() {
  drupal_goto('corporate/about-us');
}

function mymodule_access_callback() {
  if ($router_item = menu_get_item('corporate/about-us') && !empty($router_item['access'])) {
    return $router_item['access']);
  }

  return FALSE;
}

In this case, the access callback just checks the users have access to the menu item to which they are going to be redirected.


Show / Hide login menu item not connected to node

For login add a menu item into main menu named as Login and path should be user/login.

For logout add a menu item into main menu named as logout and path should be user/logout

Now when user will be login then login menu will replaced by logout automatically. And when he/she will be logout then a login menu will appear again.


How to get field structure for a custom content type?

I have to say sorry, I made a mistake in my other part of code.

$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'mytest');

is correct, it returns all fields belongs to "mytest"


Would love to be proven wrong, but I don't think that's easily possible using hook_menu().

Core only considers / as a separator, and matches on string, so urn:, urn:myscheme and urn:myscheme:foo:bar:12345 can only be represented as completely different paths.

The guts of it happens in menu_get_item():

$original_map = arg(NULL, $path);

$parts = array_slice($original_map, 0, MENU_MAX_PARTS);
$ancestors = menu_get_ancestors($parts);
$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

The call to arg() splits the path by /, which is hardcoded:

$arguments[$path] = explode('/', $path);

When menu_get_ancestors() returns for a path like urn/myscheme, it has two elements in the array: 'urn' and 'myscheme'. The same call for urn:myscheme returns an array with a single element, 'urn:myscheme'.

Those ancestors are used directly in the query to match the path in menu_router, so for the path urn:myscheme, you'll get this query:

SELECT * FROM {menu_router} WHERE path IN ('urn:myscheme') ORDER BY fit DESC

Try the same thing with urn:myscheme:foo:bar:12345, and as far as Drupal's concerned, it's a separate path that has to be handled by a different router item, as the query will be:

SELECT * FROM {menu_router} WHERE path IN ('urn:myscheme:foo:bar:12345') ORDER BY fit DESC

Without resorting to replacing menu.inc (which I think is pluggable if I remember rightly), hook_url_inbound_alter() will probably be the best best.


Form API select list remove blank entry (default select an entry)

The blank option was added by yourself:

$companyArray['empty'] = "";

If you remove that line you wont have a blank line, or alternatively your could change it to

$companyArray['empty'] = t("Please select");

To make the phrase Please select appear as default in the select option.


I'm afraid you need a long answer for this..
But using a data*base* to store different values like this is not the best way I guess.

You can use multiple databases with Drupal and switch them without a problem. But real question would be, why.

However, you can store categories in different table,and refer the category ID from the main sms message table. It's much easier to JOIN queries and get the data you want,rather than having a table for each category.
Also, I'd suggest using core functionality  when you can. With new entity system in Drupal 7,you can make a new entity, an SMS, and attach fields like category it to.

If you are storing settings of the module, consider using system_settings_form to store settings. You can set/get them using variable_set and variable_get. But make sure that you don't store big text using this.

Good luck!


How to construct a db_query() with complex criteria?

The answer provided in the comment above did get the code to work, but according to Jaypan in the Drupal forums, using that solution is a security risk. The error was caused by not using placeholders and the associated array argument, and the purpose of those devices is to prevent SQL injection attacks. The solution of reversing the quotation marks was able to stop the error messages, but at the cost of leaving open a security hole in the code. Jaypan gave me the code to implement the complex criteria with placeholders:

<?php
db_query('SELECT * FROM {table} WHERE concat(if(field1 = :empty, field2, field1), :value1) = :value2',
array(':empty' => '', ':value1' => 'value1', ':value2' => 'value2');
?>

I've implemented that and it works. The pattern seems clear enough to be able to adapt it to other complex criteria in the future, although it would be nice if we had some documentation of placeholders and their syntax.

===============

Edit: It turns out there is some documentation of placeholders, although it's not comprehensive and the discussion with Jaypan (linked above) helped to clarify things.


Create fields programmatically via content type settings

Thanks Clive, I ended up using the following code to set and get the config settings.

function module_name_form_node_type_form_alter(&$form)
{
    //get node type
    $bundle = $form['type']['#default_value'];
    $node_type = NodeType::load($bundle);

    //create vertical tab
    $form['new_option'] = array(
        '#type' => 'details',
        '#title' => t('New option'),
        '#group' => 'additional_settings',
    );

    //add checkbox to vertical tab
    $form['new_option']['new_option_options'] = array(
        '#type' => 'checkbox',
        '#title' => t('New option checkbox'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#weight' => 10,
        '#default_value' => $node_type->getThirdPartySetting('new_option','new_option_options'),
    );

    //create submit handler
    $form['actions']['submit']['#submit'][] = 'module_name_form_submit';
}

function module_name_form_submit(&$form)
{
    //get node type
    $bundle = $form['type']['#default_value'];
    $node_type = NodeType::load($bundle);

    //set checkbox value to config and save
    $node_type->setThirdPartySetting('new_option','new_option_options',$form['new_option']['new_option_options']['#value']);
    $node_type->save();

   //enable/disable fields
}


Entity Query Condition for the referenced entity's type

since the reference field is using DER, you can use $fieldName.target_type for finding the referenced entity's type.


How to prevent Devel module to be installed on production environments

Method: Drush

Drush can ignore the enabled states of extensions when synchronizing configuration.

drush cex --skip-modules=devel

drush cim --skip-modules=devel
With Drush CMI tools you can operate with a list of configuration to ignore.

drush cexy --ignore-list=/path/to/config-ignore.yml

drush cimy --delete-list=/path/to/config-ignore.yml

Method: Modules

You can use the Configuration Split module that allows you to:

Split off some configuration to dedicated folder
Blacklist configuration
Ignore a set of configuration
Configured by configuration entities

Configuration Read-only mode module

  This module allows to lock any configuration changes done via the
  Drupal admin UI. This can be useful in scenarios where for example
  configuration changes should not be done on the production
  environment, but only on staging or local environments.

$settings['config_readonly'] = TRUE;
And another module is the Environment Config that allows you to override configuration on a per-environment basis.


How to pass node ID argument to Drupal 7 div auto update ajax script

I probably would have done this differently but than again I'm not a hundred percent sure what you are doing.

In response how can you pass the node id to javascript. Perhaps in hook_page_alter():

$node = menu_get_object();
if ($node) {
  drupal_add_js(array('your_module_name' => array('nid' => $node->nid), 'setting');
}

Then in your ajax code get the nid via:

Drupal.settings.your_module_name.nid


Webform isn't the right choice here because Webforms are designed for multiple submissions against a template. You seem to want to extend/create user profiles and include these fields in registration. I recommend you use the Profile 2 module instead.


Bulk update pages that use old URL alias by content type

you can disable patterns that you dont want to update. In this way update will only update the patterns belong to content types


Drupal Commerce - Out of Stock, customer clicks to notify store owner to order more

There are two similar kind of sandbox module for this particular functionality.

One was started by me - Commerce Stock Notify

Another by itamar - Commerce Stocklist.

Both can be starting point for further development. As I left doing anything else for this as he started it before me, but my module do what you want except mail template which I was supposed to do later.

But now I think, I will spend some time on it & try to release stable soon :)


Yes you need one more command to set the data back to nothing before you can overide it from trial and error the "merge" FALSE does nothing.
so ...

// $response = new AjaxResponse();
// If want to replace you need to empty the array first.
$response->addCommand(new SettingsCommand([
  'MyData' => [],
], TRUE));
// then add new ones.
$response->addCommand(new SettingsCommand([
  'MyData' => [
    'New' => 'New values'
  ],
], TRUE));

See my New full example:  https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21SettingsCommand.php/class/SettingsCommand/8.6.x#comment-64379


Trouble passing PHP variables to JS using "attach"

Have a look on this page

For getting the value of a variable that has been set in the module you have to use like this Drupal.settings.<modulename>.<variablename>

In your module file

function mymodule_page_build() {
  $status = variable_get('mymodule_status', 0);
  drupal_add_js(array('MODULENAME' => array('mymodule_status' => $status)), 'setting');

  $page['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('module', 'mymodule') . '/mymodule.js',
      'options' => array(
        'preprocess' => TRUE,
        'every_page' => TRUE,
      ),
    ),
  );
}

So in your case it should be

Drupal.settings.mymodule.mymodule_status


Inserting images and preventing the layout from breaking

Image styles are built into Drupal 7. You can define image styles to have a particular size, by either cropping, scaling, or some combination of the two. Drupal 7 also supports scaling only down but not up.

If you want to do this in Drupal 6, you do it by installing the Imagecache module and configuring your styles with that.


For Drupal 6, I normally add the following to a custom module:

function mymodule_form_alter (&$form, &$form_state, $form_id)
{
  if ($form['#id'] == 'comment-form') {
    $form['comment_filter']['format'] = array(); // nuke wysiwyg from comments
  }
}

To be honest, I can't recall why I am using $form['#id'] instead of $form_id for the conditional.


How do I do an if conditional based on a view in template.php

You can call menu_get_item() and it will return an array containing a lot of information about the path you are on.

Inside that, you can look for

[page_callback] => views_page
[page_arguments] => Array (
  [0] => arg0
  [1] => arg1
)

or similar, and then based upon that, figure out what View you are looking at.

FYI:  It might not be obvious from the documentation, but if you call it without arguments, it returns the information about the path/page you are currently on.


Access to image uploaded in article content type is denied

If you have uploaded an image as a private file it is not accessible by other users even if any user has access to the node. Please check "Upload destination" in image field settings.


Uploaded images classified as files rather than under the media tab

Files tab is a view you can add filter by editing this view and based on your filter they can be removed from files tab. Then you can again work on filter of Media tab so that they can display under media tab.

It is up to you what filter criteria you have to move them from one tab to another tab.


Securing folder in Custom Module for Drupal 6

The real problem here is that the files shouldn't be written into the module directory. There are actually two reasons for this (one of which you've run into):

it becomes harder to upgrade the module codebase (i.e. because you have to worry about accidentally overwriting the log files)
anybody can access the files (i.e. this question!)

You mention that you'd like certain users to be able to access the log files. You have a few options:

Move the logfile directory outside of the webroot

In other words, if your Drupal site resides at e.g. /home/foo/public_html, create a new directory at /home/foo/module_logs and write the files there instead.

This prevents Apache (or whatever webserver) from delivering the file, but lets it remain accessible to PHP which access it directly from the file system.
Deny access to the files in their current location

Assuming you're using Apache, you can use a .htaccess file in the directory where the files are written to deny access to them. Some variant on this should work:

<FilesMatch "\.txt$">
Deny from all
</FilesMatch>

As in #1, your module will still be able to read the files (this is what also happens in Drupal's default .htaccess file--you can see that it denies access to e.g. .info files, but Drupal can obviously still read them...)
Turn on private file downloads

I don't really suggest this to solve your problem, as it's kind of the 'nuclear option' and would affect every file controlled by Drupal. You can find this under the file system settings in the administration area.

In options 1 and 2, you will have to alter your module. In this one you probably wouldn't need to, but you might need to modify everything else in your site :-)
Use file system permissions

Again assuming this is running on an Apache webserver, you could also have your module set the o ('other users') bit of the log files' permissions to zero using PHP's chmod() function.

In other words, your files are probably being created with permissions 644, so you might try creating them with permissions set to 640 instead. Your PHP scripts (i.e. Drupal) should be unaffected unless you change the first or second digit.

In addition to being Apache-specific, this item also might work differently than expected if your Apache-PHP setup is different than I'm expecting.


Rewriting Views results with tokens on multi field

yes using field_fieldnamename:delta

"Our camera case works with model [field_fieldnamename:0], [field_fieldnamename:1], and [field_fieldnamename:2]"


Filter condition like "from now to now+1 year" on a date field in Views

I believe I can help, if I understand your question correctly.
First you should make sure that when you set the filter up, it's in Select form.

Then you can select the operator as "is between"
Then you select "Enter a relative date" in the dropdown, and you can put now and now+1 year. Not sure if your date fields have a start and end date...


Having issues saving altered value in a view pre render

You should set the format of body to full_html try with:

function mytheme_views_pre_render(Drupal\views\ViewExecutable $view) {
  if ($view->id() == "news" && $view->current_display == 'block_1') {
    foreach ($view->result as $key => $row) {
      $body = $row->_entity->body->value;
      $stripped_img = preg_replace('/<img[^>]+\>/i', '', $body);
      if ($stripped_img != $body) {
        $row->_entity->body->setValue($stripped_img);
        // Here set the format of body to full_html
        $row->_entity->body->format='full_html';
      }
    }
  }
}


Programmatically adding argument to view that already uses a context filter

I now have a better understanding and found a solution. hook_views_pre_view() is indeed too early to see arguments that are NOT passed to the view via URL. That explains why $view->args was empty in my case. In hook_views_post_build() you do see ALL arguments (URL+nonURL) passed to the view. However, the way I solved my issue is still using   $args[0] = $value; in hook_views_pre_view. That means the first argument passed to all views will always be $value. For views that are using additional arguments, Drupal will add them to $args later on. In my special case I have views that might not necessarily need the first argument that I pass, so I had to add a contextual filter Global: Null (at the first position) that allows a contextual filter value to be ignored (and as a default I set 0). This way each view does have the correct number of contextual filters and the order is correct, whether the view needs to use the very first argument or not. It might not seem intuituve to pass an argument to every view, even though not all views really need it, but adding a Global: Null dummy filter is easier than excluding views in an if() statement and always having to modify the module code when a new view has to be added later on.


Different content in same blocks through different contexts

Solved this through using delta.  What's not mentioned above is that I was using Omega 3 when I had this problem.  I've not used it yet, but I believe Omega 4 handles this differently.


Commerce price fields have a different data structure from standard fields.

i.e not:

$product->commerce_price[LANGUAGE_NONE][0]['value'] = 500;

but instead

$product->commerce_price[LANGUAGE_NONE][0]['amount'] = 500;
$product->commerce_price[LANGUAGE_NONE][0]['currency_code'] = 'USD';

or just:

$product->commerce_price[LANGUAGE_NONE][0] = array('amount' => 500, 'currency_code' => 'USD');

They also have a 'data' property for additional price component information.

More info: commerce_price_field_data_property_info


You have many ways to apply what you are looking for.

The easy way is to use Context module with Empty Front Page module

Another way is to write your own module, something like the following code:

function myfront_menu() {
  $items = array();

  $items['frontpage'] = array(
    'title' => 'My homepage',
    'page callback' => 'myfront_front_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function myfront_front_page() {
  global $user;

  if (in_array('administrator', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  if (in_array('authenticated user', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  if (in_array('role2', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  if (in_array('role3', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  return '';
}


What's The Security Implications for "Send arbitrary files" in Permissions

It means that MimeMail (because that's a MimeMail permission) would be able to attach a file that's it not in the public files directory, like private files, settings.php or any other file in your filesystem.
However, using this permission is mandatory to attach private files, for example, because they are outside the public files directory.
What are the security issues? Well, it depends on what you attach to your email and how. For example, if the path of the attached file depends on some user input, the user can potentially craft a special input that may lead to attaching certain files like the settings.php file or any private file (if the malicious user knows the file path, or can guess it). If your code doesn't allow this you are probably safe.
For example, you may have private files in your nodes and your code just emails the private file of a certain node given its nid, and you get the nid form a button in the full node view page. On this scenario, it seems a malicious user can't craft any submission that attaches an arbitrary file as a result.
In MimeMail words:

The 'send arbitrary files' permission allows you to attach or embed
files located outside Drupal's public files directory. Note that this
has security implications: arbitrary includes even your settings.php!
Give to trusted roles only!

Also, check how MimeMail uses the 'send arbitrary files' permission


Programmatically append values to entity reference field of node with a dynamic field name

Yes, the class Node is a good starting point to look for an OOP way:

Click on get(), which returns a field object FieldItemList, where you can use the method appendItem():

$node->get($field)->appendItem([
  'target_id' => $id,
]);

Replace ->get() with {} and ->appendItem() with [] and you get the shorter version which @Clive mentioned in the comment:

$node->{$field}[] = $id;

This is possible because of the  magic method ContentEntityBase::__get and the ArrayAccess interface the field implements. I've also dropped target_id, because you don't need this for the main property of a field.


I get "/tmp is not writeable by the webserver" on migration

If you search Google for "drupal iis tmp not writeable by the webserver", the first result is a post on drupal.org, telling you to:

  Try going to admin/settings/file-system and set /tmp to just tmp

and a comment saying:

  Confirming this fix. It might have something to do with going from linux system to windows.

I guess that will work in your case too.


Adding print friendly link on specific nodes

Well If I understood your question properly, you want to show the print link only on specific nodes right? This is straightforward, by default if you enable print links for a content type, then the print links will be displayed on all the nodes of the content type.

For those nodes which you don't want the print links to be displayed, you can disable the print links option in the node-edit page itself.


Summary/Trimmed field in view doesn't include Read More link

did you check " Add a read-more link if output is trimmed. "?

If yes, maybe the problem is, that the text is not trimmed. If you want to have a "read more" link in any case, then you sould add the field "Link" to the view. You can then also enter your custom text, e.g. "details..." instead of "read more" etc.


How to speed up Drupal 8 when pages are not cached yet (1st time visit after clearing cache)?

You'll want a crawler (e.g. a cron script running wget) to trigger a local cache rebuilding or some proxy caching solution (e.g. Varnish, CloudFlare) to prevent your server from being hammered on every request upon Drupal page cache flush. Use a crawler if you have a relatively small/fixed amount content and a proxy cache for large/dynamic amount of content.

There really isn't a Drupal-centric solution here. The closest thing might would be the Boost project which has a proxy (local file)/crawler solution, but that's for D7.


Remove entire column from the table programmatically in twig file

User hook_views_pre_view()checkout this code snippet.

/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view($view, $display_id, array &$args) {

  if ($view->id() == 'view_name' && $display_id == 'page_1') {
    $view->removeHandler($display_id, 'field', 'name_of_your_column');
  }
}

Bingo!


How do I enable a menu link only when the user has created a node?

Here are the steps

For example If you want give permissions for authenticated users to create 'Basic page'

Go to Home » Administration » People (admin/people/permissions) and check the checkbox

Basic page: Create new content and Administer menus and menu items for AUTHENTICATED USER

That's it now authenticated  user can create basic page (node/add/page) with menu item.

If you want to generate URL/path aliases automatically, use the Pathauto module

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


How to create something like a textual "add other term" for taxonomy terms?

When you go to your Taxonomy Vocabulary ([your_domain]/admin/structure/taxonomy/your_vocabulary) you can click on Manage Fields tab and add any field you want. Or go to [your_domain]/admin/structure/taxonomy/your_vocabulary/fields.


Viewing Referenced Field Images in node template

Thanks to the slack channel #drupaltwig, I found a solution!
I leave it here, in case somebody else needs it

{% for curr_poi in node.field_poi %}

{% if curr_poi.entity.field_image.entity.uri.value is not empty %}

<img class="product-image" src="{{curr_poi.entity.field_image.entity.uri.value | image_style('app_list')}}" />

{{curr_poi.entity.title.value}}

{% endif %}

{% endfor %}

Main hints:

use node instead of content
iterator is curr_poi do not use a index
I used twig_tweak drupal module in order to user the filter | image_style('app_list')

Thanks to @kekkis @markconroy


How to use managed_file to upload many files

You may want to use plupload form element instead. Install Plupload integration module and then use something like:

$form['my_element'] = array(
  '#type' => 'plupload',
  '#title' => t('Upload files'),
  '#description' => t('This multi-upload widget uses Plupload library.'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('jpg jpeg gif png txt doc xls pdf ppt pps odt  ods odp'),
    'my_custom_file_validator' => array('some validation criteria'),
  ),
  '#plupload_settings' => array(
    'runtimes' => 'html5',
    'chunk_size' => '1mb',
  ),
);


Quick edit many SKU fields in Drupal Commerce

An alternative way of doing this is as follows:

Create a view for the products including SKU & Product Id (assigned by drupal commerce)
Export the view into a csv using the views_data_export module.
Amend your SKUs in the csv file using any text editor. This should make it easier to amend.
Create a feeds importer, with settings "Update existing commerce products", and using the "Product Id" as unique key (instead of SKU).
Load the amended csv to update the SKUs in the database.


How to add an image field to a programmatically created form?

You cannot use fields from the Field API in forms of the Form API directly, as Fields can be used directly in entities, and entities can be used directly with forms.

Instead, you can use the approach described here, as Clive kindly pointed out. Alternatively, you can use ctools_field_invoke_field() function of CTools module too.

The two fields 'file' and 'managed_file' of the Form API are similar, with the difference that the latter provides a progress upload widget. Also, managed_file will add the file entry to a table with the same name. Beyond that, there is some work involved in order to render the file on a page, and that is not the imagefield of the Field API.


Moving content from dev directory to production server

Frankly, I have never suffered from any path reference issue that you are describing, speaking of managed files.
As per unmanaged files, which laying around on the ftp server, that you may happen to refer to in raw code or WYSIWYG editors, make sure you don't use absolute paths starting with domain name. Check your WYSIWYG editor settings. Instead, you'd want to:

use links starting with slash - I call them root links
edit the settings.php file and provide an explicit URL of your current site root in the $base_url variable. This is what the root links will refer to as base. Thus, when you move your site to another domain, it should require just changing of that one value.

I'm not sure there is a tool to do global replacements of absolute path you might already have. You could however dig into database and do a global search on it.


Getting a blank screen after copying project in my server

Few things to check
1- Check what PHP version on your server, you will need PHP 5 not PHP 7.

2- Make sure you update the $base_url in you settings.php file, assuming you copied that from your local


This is why when viewing data out of a Drupal database you should always use the provided wrapper functions. Because the timezone is applied at runtime and not stored in the database, which makes sense because Drupal allows for users to be "part of a timezone" and format their dates based on such.

So for you to get the field rendered just:

render(field_view_field('node', $node, 'field_date_name'));

More on this function can be found here.


How to render a view programmatically and set as node field?

Because your variable reference is incorrect. It should be:

{{ embedded_view }}

Since you added it to the $variables array as $variables['embedded_view'].

As an alternative you can get the Twig Tweak module. Example on the docs page:

{# You can pass arguments to the view if needed. #}

View:

{{ drupal_view('view_name', 'page_1') }}


"This entity (node: id) cannot be referenced" error

The view_unpublished "module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard."

composer require drupal/view_unpublished
drush en -y view_unpublished

At /admin/people/permissions set permissions as required:

Finally, at /en/admin/reports/status/rebuild rebuild the permissions, which may take some time:


What is it called when a Drupal Module installs with several modules?

what is each piece called?

I don't have an official reference, but "submodules" or "sub-modules" is by far the most common phrase I've seen used for modules included in a main module to complement/extend its functionality. Prominent members of the Drupal community seem comfortable with referring to them as such.

  If they show up in one group, does that mean they are all written by the same entity?

It can in some cases, but there's nothing to guarantee it. Any module can list itself under any of those groups by setting the package key in its .info file. A lot of modules that provide field types list themselves under the generic "Fields" group, for example.


Views - List of content that user (ID from URL) voted on

Contextual filters by definition should already filter your result set on the field for an entity you choose based on the value of the URL.

Set up the contextual filter to filter on Votes: User and make sure you have no other filters or relationships that restrict your result for the logged in user.


How do I display a history of messages between two users using the Privatemsg module?

The OP succeeded in doing this by creating a helper function in a custom module.

The function accepts two arguments, the sender uid and the recipient uid.  It returns the list of messages.

Then one can call this function from anywhere to get the required list of messages.

Here is the function the OP created:

function get_message_history($sender_uid, $recipient_uid) {
  $query = db_query("SELECT * FROM pm_index, pm_message
    WHERE ((pm_index.recipient = $sender_uid AND pm_message.author = $recipient_uid)
      OR (pm_index.recipient = $recipient_uid AND pm_message.author = $sender_uid))
      AND pm_index.mid = pm_message.mid
    ORDER BY pm_message.timestamp DESC");
  $messages = $query->fetchAll();
  return $messages;
}


How do I access the Drupal class from a standalone PHP file?

You can make use of drush php-script command.

drush scr /path/to/file.php


How to group two fields while creating content type?

If you want to group fields together to be accessible as a single field on your form, the easiest way is using the Field Collection module. It:

  Provides a field-collection field, to which any number of fields can be attached.

Using that you can group your Title and Links fields into one, and you'll have an 'Add more' button for the group, rather than for each individual field widget.


Can I get the absolute path to the frontpage in theme_preprocess_html?

I used \Drupal::urlGenerator()->generateFromRoute('<front>', [], ['absolute' => TRUE]); from one of the comments in:

How to get the base URL of a site

Here is the entire working snippet:

/**
 * Implements hook_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {

  // Modify if we're on nodes
  if ($node = \Drupal::request()->attributes->get('node')) {
    // Get the node-type
    $nodetype = $node->getType();
    // Switch class for node-type
    switch ($nodetype) {
      case "landing":
        // prefetch frontpage from landing pages
        $frontpage_path = \Drupal::urlGenerator()->generateFromRoute('<front>', [], ['absolute' => TRUE]);
        $prefetchfront = [
          '#tag' => 'link',
          '#attributes' => [
            'rel' => 'prefetch prerender',
            'href' => $frontpage_path,
          ],
        ];
        $variables['page']['#attached']['html_head'][] = [$prefetchfront, 'prefetch'];
      break;
    }
  }
}


cache_token table doesn't exist after Drupal 6 to Drupal 7 upgrade

After enabling back your module have you run update.php to ensure all needed queries are executed ?
It seems its the first update the token module runs.

/**
 * Add the cache_token table.
 */
function token_update_7000() {
  $schema['cache_token'] = drupal_get_schema_unprocessed('system', 'cache');
  $schema['cache_token']['description'] = 'Cache table for token information.';
  db_create_table('cache_token', $schema['cache_token']);
}


You can use CAPTCHA module. To add captcha in in drupal registration form there is no need to edit any single line of code. First you download and install the module then go to module settings page (/admin/user/captcha/captcha/settings) and enable the captcha for user registration form.


It's using context to make the combination of blocks.

Admin>Structure>Context

Under Reactions, choose block and make combination.


How to translate strings available in JS library?

See the plugin's translation documentation for a list of strings and their option names.
Pass these strings through Drupal.t() when attaching your popup.


if current_node is in menu, do something in theme.inc

To set if the node has menu link you can use menu_ui_get_menu_link_defaults function from menu_ui.module something like:

/**
 * Implements hook_preprocess_HOOK().
 */
function YOUMODULE_preprocess_page(&$vars) {
  /** @var \Drupal\node\Entity\Node $node */
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    // Get the default menu link.
    $defaults = menu_ui_get_menu_link_defaults($node);
    if ($defaults['id']) {
      // It has a menu
     // set your variable here.
    }
    else {
      // It has no menu link
      // It mean Provide a menu link not checked
    }
  }
  }


How to use User Points to buy/sell a custom content type?

Use the integration between the User Points module and the Rules module to create some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

If you simply adapt the amount of points (-2 and -1) to something like (eg) +25 and -25, you've a prototype to transfer (25) user points from one user to another.

If you replace the Rules event by an event like "something is flagged" (created with the Flag module), a simple click could be used to indicate "I want to transfer 25 user points of mine to this user). You could take this even a step further: since flags are fieldable, you could add a field to indicate the amount of points to be "moved".

The above Rules example may need further refinements, e.g. if you want to ensure that after moving points van User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.

PS: I'm assuming this question is about D7.


what about multiple files and their archives in sites/default/files/[css] and /[js]?

The files are created when you enable 'Aggregate and compress CSS files.' and 'Aggregate JavaScript files.' The do have a positive effect on the performance since the browser has to do fewer http requests.

The overrides are normal as well, and they also happen when aggregation is turned off. Avoiding those means you probably have to re-write most of the css from core.


Drupal isn't an MVC framework.

Content types and entities give you a way to insert records into a database, and edit them as well.

Making a "view" of one kind of record is possible with the Views module, and also the VBO module.

Deleting "related things" is trickier and requires the use of built-in hooks to remove related items from the database typically. Or if using Entities you could wire removing relationships into the Entity Controller.

Simply put, Drupal isn't a Ruby on Rails-like framework where you get CRUD capability for free; it currently acts more like the Linux kernel (in my opinion) where you register or "hook-into" the lifecycle of a thing and alter it to your needs.

You may find these 2 modules useful:

Model Entities uses Entities to kind of create a CRUD like interfaces for custom objects built with D7 Entity(s).
SBDO an ORM for custom object tables in drupal


Should we use Drupal Commerce for a real estate site?

I think you should definitely consider Drupal Commerce or Commerce Kickstart for this, because it seems to have everything you're looking for.

About the facilities you don't need, like "Checkout, Payment, Discount, Shipping, Taxing, etc": that's a matter of NOT enabling the corresponding modules you get with it.


Send an email notification to admin prior to poll close date

You will need to create a Rule that will schedule component evaluation (send email).

CREATE COMPONENT

Create component plugin of type Rule (admin/config/workflow/rules/components/add) - name it "Notify admin about poll closure".
Provide a variable for the component to act on. Variable Data type = Content, Label - Poll Node, Machine name = poll_node, Usage = Parameter.

Add Conditions if you need any
Add Actions -> Send HTML e-mail. Set you email parameters
below is the export of the component

{ "rules_notify_admin_about_poll_closure" : {
    "LABEL" : "Notify admin about poll closure",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_i18n", "rules", "mimemail" ],
    "USES VARIABLES" : { "poll_node" : { "label" : "Poll Node", "type" : "node" } },
    "DO" : [
      { "mimemail" : {
          "key" : "poll_closure_notify_admin",
          "to" : "adminemail@email.com",
          "subject" : "Poll will close tomorrow",
          "body" : "Poll [poll-node:title] will close tomorrow",
          "plaintext" : [ "" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

CREATE RULE

React on Events: "After saving new content of type Advanced Poll", "After updating existing content of type Advanced Poll"
Add Conditions "Entity has field": Entity: node, Field: advpoll_dates
Add action "Schedule component evaluation" - select the component that you created "Notify admin about poll closure".

Scheduled Evaluation date -> node:advpoll-dates:value2. Add offset "-1 days". This will schedule the email 1 day before poll closing.

Set an identifier to something like "Poll closure notification: [node:nid] - [node:title]". It should have unique values everytime new scheduled task is added in queue, that is why you should use node:title and node:nid.

Set Poll Node field to node.

Save your rule and test.

{ "rules_schedule_notification_about_poll_closure" : {
"LABEL" : "Schedule notification about poll closure",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_scheduler" ],
"ON" : {
  "node_insert--advpoll" : { "bundle" : "advpoll" },
  "node_update--advpoll" : { "bundle" : "advpoll" }
},
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "advpoll_dates" } }
],
"DO" : [
  { "schedule" : {
      "component" : "rules_notify_admin_about_poll_closure",
      "date" : {
        "select" : "node:advpoll-dates:value2",
        "date_offset" : { "value" : -86400 }
      },
      "identifier" : "Poll closure notification: [node:nid]",
      "param_poll_node" : [ "node" ]
    }
  }
]}}

I provided an export of the component and the rule that you can use and modify to your preference. Hope this helps.

P.S. Cron should be enabled and configured on your website in order for scheduled events to work properly.


custom template for entity as referenced entity

What you can do is to add a custom view mode for your node type, and then use the new view mode for your entity reference field. You have a couple of options, depending on whether you want to code a custom module, or stick with available contrib modules.

The entity view modes module will allow you to add your new view mode, or you can use hook_entity_info to programatically add a new view mode in a module you write yourself. This article provides an example of adding a view mode with hook_entity_info:

function acme_view_modes_entity_info_alter(&$entity_info) {
  // Define the view modes
  $entity_info['node']['view modes'] += array(
    'featured_story' => array(
      'label' => t('Featured Story'),
      'custom settings' => TRUE,
    ),
    'secondary_story' => array(
      'label' => t('Secondary Story'),
      'custom settings' => TRUE,
    ),
    // Define more in this array as needed, e.g. tertiary_story
  );
}

That same article also provides an overview of adding theme hook suggestions so you can supply the name you want to use for your template (the entity view modes module will handle this step for you).

For selecting the new view mode to use for the display of your entity reference, which you do on the "manage display" tab of your content type that includes the entity reference field, choose "Rendered Entity" as the Format for the field's display, then a settings-gear button will appear to the right of it. Click that button and among the available settings will be a select element to choose the view mode.


How do I make form_set_error() affect the submitted form only?

There is definitely a limitation in Drupal core that is causing form fields with with the same name to be styled as "error" even through the validation error happened on a different form that was submitted on the same page.  Looking at the code for Drupal version 6,7,8 (as of now) - they all have this limitation.  The good news is that the patch I put together (for Drupal 6) to fix this problem is fairly minimal and it involves using the form_id to properly scope the form element with the validation error.  I've haven't done much testing with it, so use it at your own risk.  The changes required for Drupal 7 should be similar.

diff --git a/includes/form.inc b/includes/form.inc
index 1529c19..4052133 100644
--- a/includes/form.inc
+++ b/includes/form.inc
@@ -798,29 +798,41 @@ function form_execute_handlers($type, &$form, &$form_state) {
  *   The error message to present to the user.
  * @param $reset
  *   Reset the form errors static cache.
+ * @param $scoped
+ *   Returns the errors scoped with the form_id
  * @return
  *   Never use the return value of this function, use form_get_errors and
  *   form_get_error instead.
  */
-function form_set_error($name = NULL, $message = '', $reset = FALSE) {
+function form_set_error($name = NULL, $message = '', $reset = FALSE,$scoped = FALSE) {
   static $form = array();
+  static $form_scoped = array();
   if ($reset) {
     $form = array();
+    $form_scoped = array();
   }
   if (isset($name) && !isset($form[$name])) {
     $form[$name] = $message;
+    if(isset($_POST['form_id'])) {
+      $name = $_POST['form_id'] . "::" . $name; // Scope it based on form_id
+    }
+    $form_scoped[$name] = $message;
     if ($message) {
       drupal_set_message($message, 'error');
     }
   }
-  return $form;
+  if($scoped) return $form_scoped;
+  else return $form;
 }

 /**
  * Return an associative array of all errors.
+ *
+ * * @param $scoped
+ *   Returns the errors scoped with the form_id
  */
-function form_get_errors() {
-  $form = form_set_error();
+function form_get_errors($scoped = FALSE) {
+  $form = form_set_error(NULL,'',FALSE,$scoped);
   if (!empty($form)) {
     return $form;
   }
@@ -828,16 +840,29 @@ function form_get_errors() {

 /**
  * Return the error message filed against the form with the specified name.
- */
-function form_get_error($element) {
-  $form = form_set_error();
-  $key = $element['#parents'][0];
-  if (isset($form[$key])) {
-    return $form[$key];
-  }
-  $key = implode('][', $element['#parents']);
-  if (isset($form[$key])) {
-    return $form[$key];
+ *
+ * * @param $scoped
+ *   Returns the error scoped with the form_id
+ */
+function form_get_error($element,$scoped = FALSE) {
+  if($scoped && isset($element['#form_id'])) {
+    $form_id = $element['#form_id']; // Try to make the error form specific
+  }
+  $form = form_set_error(NULL,'',FALSE,$scoped);
+
+  for($i=0;$i<2;$i++) {
+    if($i==0) $key = $element['#parents'][0];
+    else $key = implode('][', $element['#parents']);
+
+    if(isset($form_id)) {
+      $key0 = "$form_id::$key"; // Provide the scope based on form_id
+      if(isset($form[$key0])) {
+        return $form[$key0];
+      }
+    }
+    if (isset($form[$key])) {
+      return $form[$key]; // If form_id not found then try without it
+    }
   }
 }

@@ -896,6 +921,7 @@ function form_builder($form_id, $form, &$form_state) {
   $count = 0;
   foreach (element_children($form) as $key) {
     $form[$key]['#post'] = $form['#post'];
+    $form[$key]['#form_id'] = $form_id;
     $form[$key]['#programmed'] = $form['#programmed'];
     // Don't squash an existing tree value.
     if (!isset($form[$key]['#tree'])) {
@@ -2246,7 +2272,7 @@ function _form_set_class(&$element, $class = array()) {
   if ($element['#required']) {
     $class[] = 'required';
   }
-  if (form_get_error($element)) {
+  if (form_get_error($element,TRUE)) {
     $class[] = 'error';
   }
   if (isset($element['#attributes']['class'])) {


How to Rebuild Registry On Admin Form Submit

In order to fire a submit callback you have to add it to #submit array within your form. Here is an example.

/**
 * Form builder.
 */
function my_admin_interface($form, $form_state) {
  $form['#submit'][] = 'my_admin_interface_submit';
  return system_settings_form($form);
}

/**
 * Submit handler.
 */
function my_admin_interface_submit($form, $form_state) {
  drupal_set_message(t('Hey there!'));
}

Here is a link to the manual.


Ajax webform do submit without ajax when it is loaded via ajax

Short answer: you need to attach the Drupal behaviors after inserting your new content into the DOM:

$.ajax({
  url: '/path/to/my/node/with/webform'
  success: function (data) {
    // Add html to existing container.
    $(data).appendTo('body');
    // Attach the new behaviors to the DOM
    Drupal.attachBehaviors();
  }
});

Long answer: Although Drupal has jQuery included with core, it does not use jQuery functions like $.on() or $.delegate() or $.live(), which attach behaviors to elements when they are inserted into the DOM. Instead Drupal uses behaviors, which is a Drupal specific method of attaching behaviors to elements.

Behaviors have three parts:

1) Scripts add new behaviors to the Drupal.behaviors object. Example:

Drupal.behaviors.someArbitraryKey = {
  attach: function (context, settings) {
    attachHandlerToElement(context, settings);
  }
};

Generally people consider this to be an onload function, as it is called when the document has loaded and is ready to have JavaScript executed on it. However, it can also be called using Drupal.attachBehaviors(), which will be addressed in #3 below. When the DOM is loaded, or Drupal.attachBehaviors() is called, the .attach() function of the behavior is executed, in this case calling attachHandlerToElement(context, settings); whenever this is executed.

2) $.once() is used to ensure that handlers are not attached multiple times to an element. Because behaviors can be executed multiple times, event handlers can be attached to elements multiple times, if steps aren't taken to prevent that. The jQuery $.once() function, provided by core, ensures that the code it contains is only attached to the element a single time:

function attachHandlerToElement(context) {
  $(context).find(".some_selector").once("some-arbitrary-key").each(function () {
    // Note that $(this) is the current iteration
    // of .some_selector
    $(this).click(function () {
      // Do something.
    });
  });
}

By calling $.once() on elements, the contained code in the $.each() loop is only ever attached a single time. This means that the $.click() handler above is only attached a single time to elements with the class .some_selector.

3) When new content is inserted into the DOM, whether that be from an AJAX call, or even just new elements inserted using JavaScript, Drupal.attachBehaviors() is called. This in turn loops through all behaviors, and executes their attach() handler.

A final note on context. On initial page load, context is the full DOM. Drupal.attachBehaviors(context) takes an argument, context, which should be an element of the DOM (not a jQuery object containing it). In your case, you are appending your content to the body, so there is no need to pass an argument, as you will need to parse the full DOM. If you were appending your content to some element though, you could do something like this:

$(data).appendTo('#some_element');
Drupal.attachBehaviors($(#some_element").eq(0));

This would pass it the element of the DOM to which the new content was attached. This element becomes context in the attach() handler, and is more efficient than passing in the full DOM.


How to repeat events with the calendar module?

Check that Date repeat API is checked on your module listing page


Drupal user profile image alt text is showing special characters

Assuming Drupal 7, in the template.php of your theme, add this function:

function themename_preprocess_user_picture(&$variables) {
  $variables['user_picture'] = htmlspecialchars_decode($variables['user_picture'], ENT_QUOTES);
}

The problem arises from the template_preprocess_user_picture() function in user.module. It passes the alt text through the t function, which in turn calls htmlspecialchars() and it is here the apostrophe is encoded as &#039;

In your theme function, the HTML code of the user picture tag will be available in $variables['user_picture']. Passing the HTML code through htmlspecialchars_decode() will convert &#039; back to an apostrophe.


A few things to try if composer update drupal/core --with-dependencies doesn't work

If you're composer.json contains these lines, remove them (where XX equals anything)

"replace": {
    "drupal/core": "~8.XX"
},

Then run composer require drupal/core:~8.5.1 (even if your composer.json did not contain the above lines)

If that fails, try my last ditch method:

Remove the core & vendor folder (we will then re-add)

sudo rm -rf core vendor

Clear Composer cache

composer clearcache

Then again

composer require drupal/core:~8.5.1

Don't forget to make a backup first if you haven't already!


how to reorganize with twig a form builded in a custom module and keep working ajax callback?

The solution for this case was just to add {{ form|without('global') }} at the end of the .twig file, like this :

<div>
  {{ form.global.info }}
  {{ form.global.controls }}
  {{ form.global.description }}
</div>
{{ form|without('global') }}


When should I add a new tpl.php file, and when should I implement a theme function?

There are two types of theming something (theme('function', $args);)
Functions
The call to theme will result in a theme function being called: theme_foo with the arguments which will return the HTML string to be outputted. These can be overwritten by creating THEME_NAME_foo function in template.php
Templates
For template theme functions two things happens, preprocess_foo functions are called which will populate variables for the template. These can not be overwritten, but new ones can be added, as the alter an array which will contain all the variables used in the template by reference. The template file itself can be overwritten, by create a file withe the proper name. With use of suggestions, some can take precedence over others in certain cases. (node-forum.tpl.php used for forum type nodes vs node.tpl.php used for all nodes if no better match exists.)
Answer
So in short, it depends on the definition of the theme function if you should use

a template and/or preprocess function
a theme function

But there is never a case where you can use a mix of these.
So

No, no template file can be implemented as a theme function.
No, you can never use both a theme function and a template, but you can use a preprocess function and a template.


That will be caused by an overload on resources. kint() is very resource intensive. If you are calling kint in a views-view-files.html.twig template for example then it could get called multiple times and overload the system.

If you check your logs you'll find an error like this:

General error: 2006 MySQL server has gone away

The DB has been overloaded and Drupal thinks there's no install, hence ending up on the install page.

Here are three ways of limiting the kint maxLevels variable which can help avoid this. Set maxLevels to 3 or 4.

1) In settings.php:

require_once DRUPAL_ROOT . '/modules/contrib/devel/kint/kint/Kint.class.php';
Kint::$maxLevels = 3;

2) In /modules/contrib/devel/kint/kint/ duplicate the config.default.php file to config.php and modify this line:

$_kintSettings['maxLevels'] = 3;

3) In a preprocess function, add the following:

kint_require();
Kint::$maxLevels = 3;

You can also filter the kint output so it only shows the KEYS, e.g.

{{ kint(_context|keys) }}

Alternatively, use Symfony var-dumper which is a bit more lightweight:

composer require symfony/var-dumper

Visit the devel settings page and set Symfony var-dumper as the Variables Dumper.

Example usage:

{{ devel_dump() }}
{{ kpr() }}
{{ dpm() }}


This message occurs with a working site if the site settings.php file is not in the sites/default directory but a sites/example.com directory. In that case to specify the uri of the site you wish to address you use the syntax

drush --uri=example.com [command]


I have not tried Boxes myself, but looking at its code, it looks like they use a theme function to produce the markup for the boxes.

If you implement theme_boxes_box (found in boxes.admin.inc) in your own theme/module you can just copy the code from it and remove the markup you don't want.

/**
 * Overrides theme_boxes_box().
 */
function MYMODULE_boxes_box($variables) {
  $block = $variables['block'];

  $empty = '';

  // Box is empty
  if ((empty($block['title']) || ($block['title'] == '<none>') ) && empty($block['content'])) {

    // add a class to mark the box as empty
    $empty = ' box-empty';

    // show something if the block is empty but the user has the permission to edit it
    if (boxes_access_edit()) {
      $block['content'] = t('This box appears empty when displayed on this page. This is simply placeholder text.');
    }
    else {
      return;
    }
  }

  $output = "
";
  $output .= '
' . $block['content'] . '
';
  if (!empty($block['controls'])) {
    $output .= '
';
    $output .= $block['controls'];
    $output .= '
';
  }
  if (!empty($block['editing'])) {
    $output .= '
' . drupal_render($block['editing']) . '
';
  }
  $output .= '
';
  return $output;
}


Database problem after moving the site: unknown server error

In the above database configuration the problem seems to be with the host, you need to enter the "database hostname", or try entering the static ip "xxx.xxx.xxx.xxx" of the database host.

Aslo check the credentials of your database if they are correct or not. Discussion about the same issue faced be other people is available at: https://drupal.org/node/1315592 .


Creating Nodes Programmatically but cannot edit fields using Drupal once created

In your code you have:
$node->field_event_type_intro = $vals->field_event_type_intro;

But if you want to add values to your fields you can use this:

if is a text
$node->field_event_type_intro[LANGUAGE_NONE][0]['value'] = field_event_type_intro;

if is a taxonomy
$node->field_event_type_intro[LANGUAGE_NONE][0]['tid'] = field_event_type_intro;

if is a field reference
$node->field_event_type_intro[LANGUAGE_NONE][0]['target_id'] = field_event_type_intro;


How to declare a custom theming function for block content?

It's an obvious answer, so sorry if you've tried it, but have you cleared your cache, specifically the theme registry?