How do I enable dynamic favicons in a custom theme? So, I'm working on a site that I didn't build and I'm trying to figure out how to get the favicons working. The site has favicons enabled in the theme settings folder as well as through the themes settings UI, however no favicons are showing up. From what I read, this should just be a question of putting the favicon in the theme root folder. The issue is that I have a bunch of favicons that are meant to be served dynamically (e.g. different devices/sizes, etc) from a subfolder of my theme e.g. themes/custom/mytheme/assets/images/favicon. I haven't dug too far into this yet, but I assume that there's a script somewhere that deals with this. So, how or what do I do to enable my favicons?

Unless your theme allows for functionality to add further icons you'll need to add head link tags yourself with something like this using template_preprocess_html:

function YOURTHEME_preprocess_html(&$variables) {
  $icon = [
        '#tag' => 'link',
        '#attributes' => [
            'href' => '<url to your icon-52x52.png>',
            'rel' => 'shortcut icon',
            'sizes' => '52x52'
        ],
    ];
    $variables['#attached']['html_head'][] = [
        $icon,
        'icon52x52
    ];
}

Or if you want to avoid adding code the metatag module as a sub module of "Metatag: favicons" to allow you to add them from the CMS
https://www.drupal.org/project/metatag


How should I structure my products I have a computer product that fits many types of computers.  The product has a brand, and more than one computer model can use the same product.  I want to let users search by product, or click through by brand, or click through by product.

I'm having trouble figuring out how to set this up with Drupal Commerce.  I read up and down on the site, but can't seem to get it.

One brand to many products.
One product to many computer types.
One computer type to many products.

Thanks for any help.

Brands are clearly taxonomies.
The other two are two product types.
With the help of Commerce Search API you can easily have facets on brands, as well as powerful search.


Getting a 403 error in REST So I'm giving REST a try. Installed drupal-8.0.0-beta12 in a VM. cURL works fine using curl http://testing.dev/drupal8/node/1?_format=json but I'm not sure why I'm getting a 403 error message using dev HTTP client:

Any ideas?

Have you got correct permissions for anonymous users to access the resource ?

testing.dev/drupal8/admin/people/permissions
under the RESTFul Web Services ensure that Access GET on Content resource is ticked for Anonymous User. Clear cache and try your request again.

Also you might not have the format type exposed for that resource in your rest.settings.yml file. This file sets the supported_formats and auth. Here is what is should look like in your case:

resources:
  'entity:node':
    GET:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - cookie


Multiple taxonomy/term/% views I am using Views 3. is it possible to have multiple taxonomy/term/% view? That's because i need different theme for every vocabulary

Sounds like a job for the Taxonomy Views Integrator module. It allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice.


Using hook_form_alter to change from text filter to checkboxes I'm using a custom module and hook_form_alter to change a Views Exposed Filter from a text field to checkboxes. When altering to a select list, the module works fine. However, when I change the form type to "checkbox", the filter renders as a single checked checkbox without a label. I thought I had solved it earlier by simply removing the #size line, but after reverting the code and trying to fix it that way again, it's no longer fixing it. Any idea what I need to change?

Working select list code:

function dropdown_bartab_form_views_exposed_form_alter(&$form, &$form_state) {
  $field_id = 'field_venue_bar_tab';

  // Only alter forms with the necessary field
  if (isset($form[$field_id .'_value'])) {

// Build a query to get all node ids having the specified field
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
                  ->fieldCondition($field_id, 'value', 'NULL', '!=')
                  ->fieldOrderBy($field_id, 'value', 'ASC')
                  ->execute();

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

// Add a default so the filter is optional
$options = array(
    '' => 'Any',
    '0' => 'Drinks',
    '1' => 'Food',
    );

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

You probably want to use #type checkboxES (uppercase only for emphasis ;)), which is a list of checkboxes. checkbox is just a single checkbox that can either be checked or not, it can't have multiple options, so that property is ignored.


Is drupal safe against brute force login attacks? A brute-force attack is an attempt to gain unauthorized access to a website by continually generating and inputting various combinations of a password. This task is usually done by automation software (a "bot") which looks for success or failure messages and keeps trying new passwords until it gets a success message.

Is Drupal 7 safe against it  by default?
what is more secure configuration for it ?
Which module can help me for more secure sign in?

As you can see in the code, the function user_login_final_validate register a flood event. That means if a same IP try to connect a user/login password many times we will be "banned" for a while.

This is one of the protections that Drupal offers. Another one, and I think if its happens to your web site you will notice it very fast, it's the CSRF token that Drupal generate for each form.

This means that the attacker bot should generate the form, then get the token and associate it with the submit form. That is very time consuming and will likely discourage the attacker. But first, you will see your server starting get hotter.


alter image field from views I have a content type called Image, it has 2 fields: a image field and a copyright field (with value yes or no).

I've created a view to display them a list. I have a requirement that if a user isn't logged in to our site (anonymous) and the value of copyright field is yes, the images in the view should have a mask added to them by default.

If user is logged in (authenticated), the images should be displayed normally.

Please tell me how can I do this?

You can create a template file for that image  field and there you can edit the image display as per your condition . You can get the name of the template file from your views (Theme: Information)


Add fields to user from a custom module I'm building a small custom module and I should somehow extend default user entity by adding about 20 more fields to it.

I located User class definitions from Drupal folder (\drupal-8.1.8\core\modules\user\src\Entity\User.php). There I can see field definitions but that's not right place to do modification for sure :)

Also, I suppose I should add User module as a dependency to my custom module, even though user module is part of the core?

I've done some research and I think I should implement a plugin, but I don't know how exactly and what plugin interface to implement etc.

Base fields

You can add base fields to the user entity in a hook:

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
/**
 * Implements hook_entity_base_field_info().
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'user') {
    $fields['field1'] = BaseFieldDefinition::create('text')
      ->setLabel(t('New field 1'))
      ->setTranslatable(TRUE);
    return $fields;
  }
}

Bundle fields

But most times you probably want to use bundle fields, which can be added and modified in UI and can be easily deployed through configuration. In D8 the user entity is fieldable like nodes.

See this tutorial:

Programming custom fields into your content type

You can apply the same procedure to users. Replace node with user, also the content type with user, because the user entity has no bundles and then you use the entity name as replacement.

In a standard install user_picture is the only user field configured out-of-the-box, which you can use as an example:

field.field.user.user.user_picture.yml

You can see that user is twice in the config name, for the entity type and the bundle name.

How to add the fields

The easiest way to implement this in a custom module is to add the fields in UI

/admin/config/people/accounts/fields

and then export the configured fields:

/admin/config/development/configuration

If you export the complete configuration before and after you've added the fields you can make a diff to catch all new yaml files.

Put the new configuration files in /config/install of your module. Remove the uuid line from the exported yaml files.


Panels Node template with additional arguments The basic crux of what I'm trying to achieve is this:

When viewing a node - Content Type A (which is currently overridden with a panels node template) I want to be able to show a views block that will display the fields from one node of content type B.

To control which node from Content Type B would display on Content Type A pages, the idea was to set up a views pane with a contextual filter, so that any two nodes from hte two content types could be displayed together. This works fine by itself and in the preview.

But, I am having trouble getting panels to comply with my wishes!

I can set up a node template panel, but can't work out how to pass the second argument to the view pane. And I have tried to create a new panel to override the node so that I can pass the argument to the pane but it isn't overriding the node.

Any ideas how I can do this please?!

You need a few components to make this work properly.

You View must have a display of type "Content pane".
A contextual filter.
In the Pane settings you should set your argument input to be "From context", and then picking an argument source that matches what your contextual filter wants. Most likely that will be a node id. (The argument setting could be a specific argument, first, second or so, as well, but that's generally not a very good idea)
Add the View pane to your panel page, not the View itself. If the Pane doesn't show up in the listing, your Pane settings are wrong.
Done.


CCK Field Not Appearing in Row Array In Drupal 6, I added a custom field and attached it to a custom post type. I added sample articles and sample data in that custom post type. I added that custom field to a view. On individual articles, the custom field data shows up. But on a template that shows the five latest articles does not show the custom field.

I put this on that template:

<?php
 print '<pre>' . htmlentities(print_r($rows)) . '</pre>';
?>

And the custom field does not show in the array as it should.

This is the field I'm trying to show:

So is there somewhere else I need to activate this field? Thanks in advance.

If you use (display: node) you can check:

admin/content/node-type/{Your-Content-Type}/display

else if you use (display: fields) check you add it to fields.


How to properly add inline Javascript? Now that drupal_add_js(...., 'inline') is no longer possible, how can I inject dynamic Javascript from a custom module's Controller? (I'm trying to upgrade a D6 module with as little refactorings as possible)

If you want inline javascript in order to pass some computed variables, then it seems that the only way to do it in D8 is to use a combination of drupalSettings and an attached library.  The following snippets are copied from Attaching configurable JavaScript in the official docs.
In mymodule.libraries.yml, declare a library containing your javascript file, with a dependency on drupalSettings (and on jQuery):
cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

Then, when building (or altering) your render array, attach the library and save something to the settings:
$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

Presumably, you have something more interesting than 'bar'.  Finally, access the setting in your javascript file as drupalSettings.fluffiness.cuddlySlider.foo.


How to go from View to Webform, submit Return to View User is working a list of names with Views... select a link on the view to open webform, submit the webform.  Then I would like to return the user to the view.. Where he can continue working the list of names.

Hopefully save url to a hidden token in the view (which token is current url?) then send token in the link to webform pre-populating hidden object in webform?
Back button is a bad idea because I don't want to go back to the webform.  I want to return to the View.

Does your views page had a direct url? E.g. www.mysite.com/my-views-url? If so you can just redirect the webform on submit

Edit the webform, select settings tab
Select confirmation tab
Chose either

URL (redirects to a custom path or URL)
URL with message (redirects to a custom path or URL and displays the confirmation message at the top of the page)

Set the url in Confirmation URL to redirect back to your view


How do I add the "cancel" button to a managed file I made a new component for webform that adds a file upload component. It has a "choose file" button, and an "upload" button. You can also choose to use a progress bar during the upload.

Now I want to include a "cancel" button to interrupt the upload process. How can I do this?

if you redirect your browser I'm 99.9% sure it will cancel the upload.

how you handle that redirection is up to you.  I'd probably just show a hidden div when the upload starts with a Cancel upload

hopefully what I wrote above helps, but I'd like to mention the other alternative:

don't put a cancel button in.  I would say that this is a useless "feature" and really why add things to your UI when you don't have to?

the user has to step through quite a few things, it'd be pretty odd if they selected the wrong file.


AJAX forms will break when used in subform When using the following AJAX element in a BlockBase extended class everything seems to work just jolly good in the Block-layout page.

$form['foobar_row']['add_more'] = [
  '#type' => 'submit',
  '#value' => $this->t('Add more'),
  '#submit' => [[$this, 'addOne']],
  '#ajax' => [
    'callback' => [$this, 'addmoreCallback'],
    'wrapper' => 'foobar-wrapper',
    'method' => 'replaceWith',
    'event' => 'click'
  ],
  '#id' => 'foobar__add_more'
];

Though, the block form will fail when used as a subform, in my case it's being used in a paragraph, which contains a block_field. And I can completely see why it's failing, since the $form in the callback method contains the entire node form. I even experimented with the following alteration to my callback method, which works, but is absolutely no solution since the entire path to the element should always be the same.

  public function addmoreCallback(array &$form, FormStateInterface $form_state) {
    $referral_field = $form_state->get('num_foobar_rows');

    // Note every parenting element being addressed in following, but I would ideally only have to define ['settings']['foobar_row'];
    return $form['field_paragraphs']['widget'][0]['subform']['field_paragraph_block_blocks']['widget'][0]['settings']['foobar_row'];
  }

How would I make my addmoreCallback more dynamic and make sure it returns the right element?

Use $form_state->getTriggeringElement()!

Example for the callback:

public function addmoreCallback(array &$form, FormStateInterface $form_state) {
    $items_field = $form_state->get('num_foobar_rows');

    // Gets the button that triggers the ajax call
    $triggering_element = $form_state->getTriggeringElement();

    // Retrieve the parents, so we can climb back up the tree and do not have to hard code the unknown position of our subform
    $parents = array_slice($triggering_element['#array_parents'], 0, -1);

    // Use NestedArray to get the element in `$form` at the path that `$parents` describes.
    return NestedArray::getValue($form, $parents);
}

Note that I'm using #array_parents, this will contain all the parents including simple array parents or elements without #tree. This will prevent problems you are most likely to encounter when your form gets embedded in a field and ofcourse other forms.

Also note that the array_slice part, this will just slice off some parents to make sure we have the path to our first (-1) parent. If the element that you want to return is one or more parents up the tree, you'll need to adjust the -1 accordingly. Also, if your to be returned element is not actually the parent of the triggering element you'll want to alter the $parents array accordingly.


Set default value radio button in template I'm trying to set a default value in a template file for a radio button on my register form.

Female has value 0 and male has value 1. This is the code I use to set a default value:

    $form['field_personal_details']['und'][0]['field_gender']['und']['#default_value'] = '1';

I also tried

    $form['field_personal_details']['und'][0]['field_gender']['und']['#value'] = '1';

This should check the radio button as male, but it doesn't work.
Whenever I set the default value to male through the UI it does work and I get the same outputs when I do a dpm.

What am I doing wrong?

Add direct user registration form alter and try to change "1" to 1.

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

  $form['field_gender']['und']['#default_value'] = 1;
    <---or --->
  $form['field_personal_details']['und'][0]['field_gender']['und']['#default_value'] = 1;

}


How to apply spam filter into signatures? The spam module, does not seem to examine forum signatures against custom spam filters. Spammers have figured this out and just pour their junk links into their signatures. I am wondering how can I fix this loophole.

Presumably the content that passes the spam module filter is posted by bots. In that case, using one of the following modules (maybe in addition to the Spam module) may help (by letting the bots fill in hidden forms):

Honeypot
Botcha


Custom title for facet display block I am new to Search API and Facet API, any clue how to change the default Facet filter block title?

To change the title of the block provided by the Facet API, go to admin/structure/block and choose the block of which you want to chage the title. Click on the Configure link and then change the title of block from Block Title textfield.


*.module file not included, even after cache clear I added a *.module file to a custom module, to implement some hooks.

I found that the *.module was never included, even after cache clear (via devel menu "Cache clear". Even putting a "die()" statement at the top of the file did not crash anything.

Only after drush pmu + drush en, was the *.module file included in every request.

What am I missing? Is this a bug?

Here are my own observations. It contains some details that were not mentioned in @kiamlaluno's answer.

Things that need rebuilding

There are two "caches" that need to be rebuilt, if a *.module file with hook implementations was just created, in a module that previously did not have such a file.

The "container.modules" container parameter, which we can inspect with dpm(\Drupal::getContainer()->getParameter('container.modules'));.
Each entry has a ['filename' => *] key, which can be either null or 'MODULENAME.module'.
If it is null, then Drupal has not found the *.module file yet, and will not include it when looking for hook implementations.
The hook implementations, which we can inspect with dpm(\Drupal::moduleHandler()->getImplementations($hook_name));.

Operations that rebuild those things - or not

The first part, the container parameter, is not rebuilt on devel cache clear, or on drush cr. This has been the real problem.

The second part, the module_implements cache, is not rebuilt on devel cache clear, but it is rebuilt on drush cr.

To rebuild the first part, the container parameters, one can, as suggested by @kiamlaluno, uninstall and re-enable the module with the new hooks. But this can be quite impractical, because uninstalling can cause data loss.

Solution:

Luckily there is an easier solution: Enable any other module that was previously not installed, and then uninstall it again.

E.g. for me it was "statistics" module. But can be any other.

drush pm-list | grep "Not installed"
drush en statistics
drush pmu statistics

EDIT: NOT SO FAST!

I have to correct myself, for now:

The above method of enabling and uninstalling any other module does fix the container parameter 'filename' setting, at first.
However, flushing the cache again afterwards removes the 'filename' setting again.

This means that this setting is stored in a more persistent place somewhere.

The reason: APCu file cache: cli vs web

ExtensionDiscovery uses a cache to store discovered extension files.
In my case, this is Drupal\Component\FileCache\FileCache, with a Drupal\Component\FileCache\ApcuFileCacheBackend apcu backend.

The problem: The APCu cache has isolated realms for cli and for web.
This means, if the file cache is cleared on cli, e.g. via drush, the entries in web are still there.

This problem seems to apply only to the file cache in ExtensionDiscovery. Other caches are not affected. Probably this is because this file cache sits on a lower level within Drupal bootstrap.

Another part of the problem, possibly, is that the file cache is never cleared completely. At least, I cannot find such a place. Instead, individual entries are deleted by key.


User referencing another user causes unexpected error I have a Drupal 7 site with a bunch of users. Some are clients and others are sellers (role). I put an entity reference field field_seller on the user account form which filters users with the seller role.

Now, when applying a seller to a client and the client logs in, he gets an error

  "The website encountered an unexpected error. Please try again later."

The following error is shown in the log:

  Recoverable fatal error: Object of class stdClass could not be
  converted to string in _theme_table_cell() (row 2418 of
  /mysite.com/includes/theme.inc).

Any idea why this happens?

I think, that the user entity will be rendered at the profile page. So you should check the settings here: admin/config/people/accounts/display

Also you check if the role client is able to access user profiles, if the seller will be rendered on the clients profile page


having a backup of 'sites' folder and database backup is all I need? I'd to be sure that having a backup of 'sites' folder and database backup is all I need to restore a site?

So long as you know which version of core you have and it is un-patched then yes.

If you are backing up sites, make sure you back up any other databases. You may have multiple sites under there.

One good way to test is to do a restore on another server and check things work, after all unless you know your restore works a backup is worthless.

I have found Drush make scripts a handy way to make sure that the core and modules that you use are correct. That way you only need to back up the make script, the site directory itself sites/yoursite.com and the database.


How to get the value of a taxonomy term from entity reference using a token? We have an Entity reference field on Basic Page content type that is set to Articles. The Articles content type has a field, field_category that is a taxonomy term.

What is the correct token to get the value of the field_category?

Basic Page:

field_articles -> entity reference to Article content type.

Article page:

field_category -> taxonomy term field.

Goal:

Return the field_category label from the Article node that is set on the Basic Page

Example:

Basic Page -> page1(nid=0)

field_articles = articlePage1 (target_id = 1)

Article page -> ArticlePage1 (nid = 1)

field_category = Cloud (tid = 10)

Token should return Cloud for page1.

We tried the following but it didn't work.

[node:field_articles:entity:field_category]

You try use hook_tokens

    /**
     * Implements hook_tokens().
     */
    function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
$replacements = array();
// $type is token type
      if ($type == 'node' && !empty($data['node'])) {
        foreach ($tokens as $name => $original) {
      // to do
        $replacements[$original] ='xxx';
       }
      }
      return $replacements;
    }

See more api hook_tokens()


Display a Menu and Submenu as tabs I have a simple 2 level menu like this:

Category1
   Link1a
   Link1b
   Link1c
Category2
   Link2a
   Link2b
   Link2c

I'd like to create a tabbed Menu/Submenu for this: When Category1 or any of it's sublinks are selected (clicked) Category1 is "active" and its links are shown. Category2 is visible but its links are not:

tabbed menu http://xooplate.com/assets/template/9845/p16qeq63ber8n2agm6hf8p2kb9-details.jpg
(random example from the web)

Can anybody point me in the right direction?

Simply use the quick tab module. It exactly do same thing.


How to import multiple values in a text field with Feeds module? In my content type, I have a text field that allow an illimited number of values.

How do I configure Feeds to import multiple datas in this kind of field?

Feeds Tamper will do this for you.

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

One of the default plugins is explode.  Just set up a feed tamper to take your multivalued field from your CSV and explode it based on whatever delimiter you fancy.  This will import it as multiple field values.


Adding price field on Drupal Commerce that affect Order Price The case is

When user place an order, shipping price must be manually calculated before the final invoice is sent to user.

What I do

I create Price custom field on Order named shippingfee.

Problem is

How to make shippingfee field affect the Order price?

Another thing that I tried is creating custom line item type. I'm thinking that by creating this custom line item type would update the value.But following this tutorial, the custom line item type did not appear when I check on admin/commerce/config/line-items.

Code added to custom module:

/**
 * Implements hook_commerce_line_item_type_info().
 */
function owemji_commerce_line_item_type_info() {
  return array(
    'owemji' => array(
        'name' => t('Shipping Fee'),
        'product' => false,
        'description' => t('Price of shipping.'),
        'base' => 'owemji',
    ),
  );
}

/**
 * Implements hook_enable().
 */
function owemji_enable() {
  commerce_line_item_configure_line_item_fields(array('owemji'));
}

I did try clear cache and disable -> enable the owemji module, but it's still not there.

There is a contrib module developed espacially for shipping - Commerce Flat Rate

  This module allows you to define any number of flat rate shipping
  services via the user interface in conjunction with Commerce Shipping
  2.x. When you define a new flat rate service, you specify the base rate for it in the add / edit form. You can further modify the base
  rate (enabling things like weight or quantity based shipping) using
  rate calculation rules.

  This is functionally equivalent to using product pricing rules to add
  discounts or fees to base product prices before adding them to the
  cart.

There are few old but still actual video casts from rfay about Commerce Shipping. Watch it for a basic understanding:

Introduction to Commerce Shipping
Free Shipping Based on Order
Value or User Role
Shipping Discount for Item in Cart using
Calculation Rules


Why isn't the default template used? I set Mime Mail as the sitewide default mailing system and overrode mimemail-message.tpl.php. My custom template is used correctly for e-mails like account activation, but when I send an HTML e-mail with Rules, the template isn't loaded: I simply get an unstyled HTML text.

Did I forget something (e.g. a configuration for Rules)?

Is your administration theme the active theme when the Rule fires? This documentation page about using a custom mail template with Mime Mail might be referencing the issue:

  If you use sub-themes or multiple themes, especially if you use a different administration theme than your default theme, you might end up with a different theme to what you expect.

In the Mail System module configuration settings (admin/config/system/mailsystem), try changing the Theme to render the emails from Current to the Default theme or to the theme where your overridden mimemail-message.tpl.php lives.


How can I move a node type's configuration into a custom module? I still a bit new to D8 and loving the new configuration management system that has replaced Features.

I am looking for the best technique for containing particular configurations in my custom modules.

I have a node type called quiz and a module called quiz_module. By default, when I execute drush cex -y the output yaml files are deposited into ../config/sync.

Is it the correct thing to do to move all the yaml files relating to the quiz node type in to my quiz_module? When do that, the same files are recreated whenever I execute drush cex -y.

To counter that duplication, I created a softlink of the files from quiz_module to '../config/sync' but that didn't seem to update the yaml files as I expected.

Any help, please?

Configuration Management did not replace Features completely, Features still has its place.

My understanding is that:

Configuration Management should be used to manage your configuration for a specific site/project.
Features should be used to export configuration to custom modules as you develop them if they're going to be re-used on another site.

The configuration in your custom module goes into 2 directories (install or optional).

Configuration in the install directory is considered required and only gets imported when your module is installed.
Configuration in the optional directory is optional and will import during your module install if all the dependencies are present. (I think it also gets imported if all dependencies are later installed.) E.g. If you define a View in your module's optional directory, that configuration would be installed only in two instances: 1. when you install your module, if Views is installed, or 2. when Views is installed later, sometime after your module is installed.

The Features module page lists several additional resources to help understand the differences between Configuration Management and Features.


Fetch discount start date and end date I have a discount 'women's day'. I have set start and end date as 8March 8AM to 8 March 8PM for this discount. In my coupon validation function, I want to check if the current time is in between 'women's day' discount start and end time or not. So I basically need a start and end time of discount.

I don't understand why do you need that..

From your question I can assume you have both the discount module and coupons module..

If using discount in general, you don't need to apply a coupon, and the discount will be applied with rules only on the dates that you put in on the default discount creation form.

The same goes for coupon creation, when creating a coupon, you can set coupon criteria as date range and that will also be applied by default in coupon validation.


How does one set up aliases per domain on a multi-domain site? I have a site where there are several domains each with different content:

www.domaina.com
www.domainb.com
www.domainc.com

I want to make the alias foobar to different paths on each domain

www.domaina.com/foobar => page/100/14
www.domainb.com/foobar => page/136/12
www.domainc.com/foobar => page/96/14

I would like to be able to create the aliases using tokens and pathauto in my own module.  I've considered Domain Access, but I'm not sure this allows you to create different aliases per domain.

Can someone please confirm what the best approach would be?

UPDATE:

It looks like I can use Domain Path and Domain Access, but looking at the source code of Domain Path, I'd have to add entries for each alias:

$domain = domain_get_domain();
$domain_id = $domain['domain_id'];
$record = array(
    'domain_id' => $domain_id,
    'source' => "node/$node->nid",
    'alias' => $path,
    'language' => isset($node->language) ? $node->language : LANGUAGE_NONE,
    'entity_type' => 'node',
    'entity_id' => $node->nid,
);
drupal_write_record('domain_path', $record);

This is drupal 6 code, so I don't understand why there is an entity_type and an entity_id.  I'm going to be creating aliases to sources that are views with arguments.  Does anyone know how I'd create that record?

Domain Access does allow you to have per-domain auto alias settings (but I have never tried this), but I am only seeing one alias on an edit page.

A less than idea option if you are using Panels is to have a panel page for each path, and then create a selection rule for each domain, and then assign the node that way.  This would be a lot more work, though.


How can I add an operation to the node and user lists? I am looking for a way to add entries in the "Operations" Column at:

/admin/people

and or

/admin/content

I considered hook_node_operations and hook_user_operations

But those are for adding commands to bulk operations.

If you look at the User module in DRUPAL_ROOT/modules/user you'll see the user_menu() function:
http://api.drupal.org/api/drupal/modules!user!user.module/function/user_menu/7

You can add your own operation by making your own hook_menu() that mimics what Core does for the "Permissions" Operation. Its also important to note that these tabs or drop down operations (depending on your theme) are essentially defined as MENU_LOCAL_TASK items in the drupal menu system. See below:

// What Core does in user_menu() ...
 // Permissions and role forms.
  $items['admin/people/permissions'] = array(
    'title' => 'Permissions',
    'description' => 'Determine access to features by selecting permissions for roles.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_admin_permissions'),
    'access arguments' => array('administer permissions'),
    'file' => 'user.admin.inc',
    'type' => MENU_LOCAL_TASK,
  );

// You do something similar in your own module ...
  function mymodule_menu() {
    $items['admin/people/foobar_operation'] = array(
      'title' => 'Foo Bar Operation',
      'description' => 'A form with my custom settings',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('yourmodule_foobar_permission'),
      'access arguments' => array('administer yourmodule permissions'),
      'file' => 'yourmodule.admin.inc',
      'type' => MENU_LOCAL_TASK,
    );

    // Do the same for stuff under admin/content.

    return $items;
  }

Hopefully this tidbit helps...


When are '$form_state['values'] copied to '$form' on rebuild? as far as I understand it whenever you submit and rebuild a form (e.g. 'Add another item' on fields with infinite cardinality) something like this happens:

User submits a form with filled values
User input is copied to $form_state
Element validation happens
Form validation happens
drupal_get_form is called (form is being rebuild)
??? old user input from $form_state is copied to every $element[#value]
Individual elements of the form are created in $element[#process] callbacks
Rebuild form is shown to a user

My question is, when and how is user input from the old form transferred into the new one?

From what I've been able to understand by reading the documentation it must happen somewhere in drupal_build_form before the element #process callback is called. But when exactly that I haven't been able to find.

//I know about this FAPI flowchart if anyone could point me in the right direction on it I'd appreciate it.

Nothing like "??? old user input from $form_state is copied to every $element[#value]" happens. Simply $form_state['input'] is kept so that when the form is built the values are filled in based on that.


Possible to group views by date field larger than current date? I want to group my nodes into active and expired based on a date field. Currently I have the view set to group by this field but I don't want the active and expired groups to be broken down into specific dates such as 2 weeks, 3 days etc. I just want two groups, active and expired. How can I do this? An example of what I currently have http://www.glumbo.com/deals/footlocker.com-deals

I used this module to accomplish this http://drupal.org/project/views_customfield. It allows you to define a new views field using custom php code


would like to replace node contents with pdf under some conditions I have been using hook_node_view to set the node contents depending on a bunch of things - this works well except when I need to replace the entire page with a pdf.
The hook function looks something like

function gcc_event_node_view($node, $build_mode = 'full') {
if ($node->type !== 'eventlist') {
    return;
}
if (have replacement html) {
    $node->content['body'][0]['#markup'] = "new stuff";
} else if (use pdf) {
    header('Content-type: application/pdf');
    header('Content-length: ' . filesize($fullPath));
    header('Content-Disposition: filename=' . $this->ShortName() . $file);
    readfile($fullPath);
   // need something here to make the node not render further at all
}

Appreciate all suggestions on the right way to do this.  Should be able to do images with image/jpg as well.

If you have to replace the entire page content, then you will have to alter the page.tpl.php conditionally, You can implement hook_preprocess_page for checking for node id or node type, Then modify the content printed in page.tpl.php.


How to limit what is available for a role in Administration menu ? I am using Drupal 7 and installed the Administration menu. It works fine and I am really happy with it but after creating a new role, and also creating a new user for that role, he seems to have the entire menu available even though permissions are restricted.

To clarify, I removed permissions to flush cache and administer blocks. When he clicks those links, it says access denied but he can still click the links. How do I keep those links he cannot click from appearing in the menu at all?

Check if this user role is marked as the "Administrator Role" on User Settings.

There is also an option to rebuild the menu tree on Admin Menu settings...


How to display the path without alias? With Drupal 8 and Commerce 2.10

I created a php code to display the link of my store.

When I go to the link, it displays:

https://www.domaine.com/shop/name

I want to display without alias:

https://www.domaine.com/store/id

How to do ?

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

You have to set the option alias:

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


Change layout of a view 'page display' based on number of grouping field occurences Sorry about that rather specific title: hopefully my question will clarify itself with the following:

What data is on the table to work with

I have a View (page display) that lists nodes based on the main categories "Fruit" and "Veggies"
So I have two pages: 1 at www.mysite.com/fruit  and the other www.mysite.com/veggies

arg(0) is being used as a contextual filter to get the right nodes on
both those pages.
I'm grouping my nodes (grouping field dropdown in Style options) based on the taxonomy term they belong to (eg for "Fruit" > sweet and sour) to reflect their hierarchical place in the taxonomy structure (see below)

fruit
-- sweet(taxonomy term)
-- -- banana node
-- -- melon node
-- sour(taxonomy term)
-- -- lemon node

veggies
-- red (taxonomy term)
-- -- paprika node
-- -- onion node

What I would like achieve

I would like to be able to add different styling to a page that has only 1 main category (like the veggies - categorypage -> we only have the "red" subcateg there) as opposed to a page that has 2 or more main categories (like the fruit - categorypage -> we have 2 subcategs there: "sweet" and "sour")

What I have uptil now (it's working but I need to clean up my act/code)

As stated ... this already functions , but I would love to know:

if I followed Drupal protocols.
if there are better ways (more performant, cleaner code, easier)

I've got this in my template.php

/* Helper function so I can reach my specific display in the preprocess hook below*/
function <themename>_preprocess_views_view(&$vars) {
  if (isset($vars['view']->name)) {
    $function = __FUNCTION__ . '__' . $vars['view']->name . '__' . $vars['view']->current_display;

    if (function_exists($function)) {
     $function($vars);
    }
  }

// This is where I inject a custom CSS file in the case where I've got only 1 Main category (as explained above)
function <themename>_preprocess_views_view__need__page(&$vars) {
  $tidArr = $vars['view']->field['term_node_tid']->view->field['term_node_tid']->items;
  $terms = array();
  foreach ($tidArr as $key=>$tids) {
    $terms[] =  current(reset($tids));
  }
  $uniqueTids = count(array_unique($terms));
  if($uniqueTids < 2) {
      drupal_add_css(path_to_theme() .'/css/my_custom_css.css');
  }

}

Disclaimer: Heavy question , I know ... but hopefully clear enough so you can all understand what is going on , and what I'm trying to achieve.
Understand that I'm happy I got it working , but I would be even more happy if I could do it the Drupal "way" and have my code as lean and mean as possible.
thanx for taking the time.
    }

I think what you are trying to drupalize/ise this into is something along the lines of:

function YOURTHEME_preprocess_views_view(&$vars) {

  $view=$vars['view'];

  if (empty($view)) {
    watchdog('YOURTHEME', 'Rut roh Rastro....');
    return;
  }

  switch ($view->name) {

     case 'need':

        if ($view->current_display=='page') {

          $tid_arr = $view->field['term_node_tid']->view->field['term_node_tid']->items;
          $terms = array_keys($tid_arr);
          $number_tids = count($terms);

          if ($number_tids == 1) {
            drupal_add_css(path_to_theme() . '/css/my_custom_css.css');
          }

        }

        break;

     // any other views here

  }

}

with my basic comment being that you switch on the View's name in the preprocess function and do all your work in there instead of going out into another function.


How to get taxonomy by URL alias? I have a grade vocabulary with a 6. Class taxonomy term. The taxonomy page have an URL like
www.example.com/foo/6-class/bar and I can't find the taxonomy with the following code.

$grade = arg(2);
$term = taxonomy_get_term_by_name($grade)

It works when I use a string (e.g. 6. Class), but not with arg(2). How can I get the correct taxonomy with this URL alias? Problem might be, that it is a exposed filter and no contextual filter. But I can not change this fact.

Neither I can get the source path with the following code.

drupal_lookup_path('source', $_GET['q']);
drupal_lookup_path('alias', current_path());

I know this is a pretty old question but seems unanswered yet.
This Drupal 7 snippet will help you to load a taxonomy term but you need to know the name of the vocabulary it belongs to, lets say it is 'position'.
Ex. www.example.com/foo/6-class/bar

$term_path=drupal_get_normal_path('position/'.arg(1));
$tid = basename($term_url);
$term = taxonomy_term_load($tid);

If you know your url is an alias to your taxonomy term, just use

$term_path=drupal_get_normal_path(current_path());
$tid = basename($term_url);
$term = taxonomy_term_load($tid);

The drupal_lookup_path with source and uri approach did not work for you because probably that path is not an alias, or at least not for your taxonomy.

Hope this helps someone.


How to add an argument to a view programmatically? I want to add an argument to a view. I want to set this argument programmatically (not by url).

The field i want to filter is not directly in the view query, because this is a field on a node reference, so I cannot use hook_views_query_alter.

How can i can add programmatically an argument to a view?
I mean, which hook is better to do it?

You can use hook_views_pre_view and set arguments you want. For example

function hook_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'your_view_name') {
     $view->set_arguments(array('arg1', 'arg2'));
  }
}


How to translate $value in the output code of a view? I have created a view in which I'm retrieving a time format, whose output is printed by $value.

Here's my Value Code:

$node = node_load($data->nid);
$wrapper = entity_metadata_wrapper('node', $node);
$auction_timeout = $wrapper->auction_timeout->value();
$sub = $auction_timeout - time();
$dtF = new DateTime("@0");
$dtT = new DateTime("@$sub");
return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes');

And the Output code is:

<?php
    print ($value);
?>

The output is in English which is something like:

  35 days, 20 hours, 50 minutes

And I want it as

  35日、20時間、50分

I couldn't find how to translate it. Can anybody help me?

return $dtF->diff($dtT)->format('%a ' . t('days') . ', %h ' . t('hours') . ', %i ' . t('minutes'));


Query for email address already existing I want to customise registration form action in my drupal8 site.I want to check email address is already existing.I have tried with different queries.But not worked.Can anyone to help me to solve this issue?

Use this code to check if there is a user with provided email.

$account = user_load_by_mail($email);

if ($account) {
  // Do something.
  $form_state->setError(....
}

Besides, as I know in standard registration form there is already such validation.


Create new child field collection programmatically I have 2 field collections (Parent and child)

Parent Field collection: Test Student Info
machine name: field_test_student_info
Child Field collection: Marks
machine name: field_marks

In parent field collection have 1 field:

Field1: Student Name
machine name: field_student_name

In child field collection have 2 fields:

Field1: English Marks
machine name: field_eng_marks
Field2: History Marks
Machine name: field_history_marks

I have set field setting "unlimited" to child field collection (Marks). I just want to add new child field collection item programmatically.
I have tried below code but it's showing me error:

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\field_collection\Entity\FieldCollectionItem;

function CreateChildFC() {
  $node = \Drupal\node\Entity\Node::load(770);
  $load = FieldCollectionItem::load(207); // Loading child FC from parent FC i.e Marks
  $field_collection_items = $load->field_marks;
  $field_collection_item = FieldCollectionItem::create(
   [
    'field_name' => 'field_marks',
   ]
   );
  $field_collection_item->setHostEntity($node);
  $field_collection_item->set('field_eng_marks', '89');
  $field_collection_item->set('field_history_marks', '75');
  $load->field_marks[] = ['field_collection_item' =>   $field_collection_item];
  $node->save();
}

Error
The website encountered an unexpected error. Please try again later.
TypeError: Argument 1 passed to _field_collection_field_item_list_full() must implement interface Drupal\Core\Field\FieldItemListInterface, null given, called in /site/modules/contrib/field_collection/src/Entity/FieldCollectionItem.php on line 333 in _field_collection_field_item_list_full() (line 151 of modules/contrib/field_collection/field_collection.module).

You try the code:

<?php
use Drupal\field_collection\Entity\FieldCollectionItem;
use Drupal\node\Entity\Node;

[.....]

  $node = Node::load(7);
  $field_collection_item = FieldCollectionItem::create(
    [
      'field_name' => 'field_test_student_info',
    ]
  );

  $field_collection_item->set('field_student_name', 'Student Name');

  $field_mark_collection = FieldCollectionItem::create(['field_name' => 'field_marks']);
  $field_mark_collection->set('field_english_marks', '1231');
  $field_mark_collection->set('field_history_marks', '123');
  $field_collection_item->field_marks[] = ['field_collection_item' => $field_mark_collection];
  $node->field_test_student_info = ['field_collection_item' => $field_collection_item];
  $field_collection_item->setHostEntity($node);
  $node->save();

You need create new collection field  FieldCollectionItem::create(['field_name' => 'field_marks'])

You can set value to the file child in field parent collection, it is same you when set value field collection in node, here you dont's need set setHostEntity, it will understand is the field_collection_item

As the code above I also checked it, and it worked.

You can refer to it here

Goodluck


Drupal versus with Omni Update: Should I move from Drupal to Omni Update? Use Case

Current (aging) IT website built on Drupal 5.
Most people hate this website because the theme is awful and adding content is painful.
An upgrade to Drupal 6 and a theme / module updates are what are needed. (Not considering Drupal 7 until more modules are available.)
Some of our leadership thinks we need to switch platforms anyway.

Argument

What are the pros of sticking with Drupal versus switching to Omni Update?
What are some pro Drupal buzzwords that nontechnical manager-folk will understand?
What is your best argument for selling Drupal to a prospective client?

I think you might have answered your own question: "it will turn into a LOT of work if they decide to switch to the proprietary platform". Work = time = money, and that is manager-speak.


Status updates in organic groups disappear after a period of time After about 30 days or so, the activity streams under the Organic Group Home tab drop off or disappear. I have found a reference to this issue on Acquia Commons' community site.

I have checked the view activity_log_stream but do not see where we might adjust the length of time which content remains on the activity stream. Optimally, we'd like the content to disappear only after the Items per page attribute is met.

In /admin/settings/activity_log there is just the field to control this.

Note: Though each time we run a cron job, entries over 30 days still disappear. This is perhaps a bug? So our makeshift solution is to click the Regenerate Activity tag. This seems to behaves predictably.


How to inspect a css file generated by Less? I just get running Less in a drupal site. I was exited until I try to inspect a css file generated by a less file.

The line numbers in the generated css file don't match the the line numbers in the less file.

Even though this is very understandable since the css file is a generated file, this is a big problem to me. I'm very used to inspect (using Chrome) to look for the line number of the style of the inspected element,then I would go to css file to look for this line and make the changes I need.

Now with less this is imposible

How do you manage this?

There are extensions available for Firefox (sadly not for any other browsers that I can find).

There's the FireLess Plugin which is:

  a Firebug extension that makes Firebug display the Less filenames and line numbers of LessPHP-generated CSS styles rather than those of the generated CSS

Also, if you're able to switch to using SASS (which is quite similar), there's FireSass, which:

  allows Firebug to display the original Sass filename and line number of Sass-generated CSS styles.

There's nothing for Chrome at the moment (see Less/Sass debugging in Chrome Dev Tools/Firebug)


How can I update all content of a content type with a newly added field? I have a content type with a set of fields.

Hundred(s) of pieces of content have been created from this content type.

I recently had to go back and add a new field to the content type.

In order for all content of that content type that I previously created to show the newly added field, I have so far been going into each piece of content and adding in the field. This is going to take forever.

Is there another tool or process I can use to update all previously created content with the new field added to the content type?

if I understand correctly you need to update node in range of new date? right? so if this is the case why not use EntityFieldQuery() to list of this nodes then node_save() or field_attach_update() to update the new value.

if this is the case I'd be happy to give you some snippets to help you do this.


Content sharing issue My site allows users to create content and share them with their friends. The relationships are created using UR module. The content type itself has a "Share:",a User Reference field, where the user can select multiple users, from their list of friends.
Then there is a view, in which users can see the content created by others and shared with them. The problem is that, well, they cant see it, i cant get my head around the filter. What would be the easiest way to filter this? I've come up with this: if the currently logged in users name is in the contents share field, the data is shown. How to implement this in the view?
Any help would be greatly appreciated!

You want a Relationship on your View.

If you're displaying nodes, add a Relationship on the User Reference field that your node has. Then add a Filter for User = Current User, using the relationship you just created.


Create a rule at the event of "Cron maintenance tasks are performed"? I created a rule to be fired when "Cron maintenance tasks are performed".

Now I need an action to check delete all nodes of the content type: "Question" that have the field "Delete" set to "yes"

How can I do this?

you could use hook_cron_queue_info to create a task that sits in a queue and happens on a timer. This would account for the potentially long duration of the task you mention.


How to create custom forms to filter views results in Drupalgap I want to build a views page where user searches for a text (without auto-complete) by entering query in a text box and clicking a button on drupalgap, and I want to have flag links on the results
On the documentation page of drupalgap views exposed filters, http://docs.drupalgap.org/7/Views/Views_Exposed_Filters "building your own forms and constructing own URL parameters" is mentioned but there is no example of that. Is there any example/tutorial of usage like that?
Thanks in advance,

Update:
This is the function that I define my form:

function form_custom_form(form, form_state) {
      try {
        form.elements['name'] = {
          type: 'textfield',
          title: 'Kart No',
          required: true
        };
        form.elements['submit'] = {
          type: 'submit',
          value: 'Ara'
        };
        form.elements['my_markup'] = {
          markup: '

'
        };
        return form;
      }
      catch (error) { console.log('my_module_custom_form - ' + error); }
    }

This is the code which works:

function form_custom_form_submit(form, form_state) {
  form_value = form_state.values['name'];
  form.elements['my_markup'] = {
    markup: '

'
  };
  arac_getir2_pageshow();
}
/*catch (error) { console.log('form_custom_form_submit - ' + error); }*/

function arac_getir2_pageshow() {
  var path_to_view = 'arac_getir';
  views_datasource_get_view_result(path_to_view, {
    success: function (data) {
      if (data.nodes.length > 0) {
        var items = [];

        $.each(data.nodes, function(index, object){
          var node = object.node;
          items.push(
            l(node.title, '#') +
            flag_quick_link(
                    'ara_getir', // The flag's machine name.
                    'node', // The entity type.
                    node.nid, // The entity id.
                    parseInt(node.flagged) ? true : false // The current flag status.
                    )
            );
        });
        console.log(items);
        drupalgap_item_list_populate('#arac_getir2_view', items);

      }
    }
  });
}

This is the one which does not:

  function form_custom_form_submit(form, form_state) {
    form_value = form_state.values['name'];
    arac_getir_page();
  }

  function arac_getir_page() {
    try {
      var content = {};
      content['arac_list'] = {
        theme: 'view',
        format: 'ul',
        format_attributes: {
          /*'data-inset': 'true',*/
          'data-split-icon': 'star' /*the icon to use for the flag button */
        },
        path: 'arac_getir', /* the path to the view in Drupal */
        row_callback: 'arac_getir_list_row',
        empty_callback: 'arac_getir_list_empty',
        attributes: {
          id: 'arac_getir_view',
          'data-filter': 'true',
        }
      };
      return content;
    }
    catch (error) { console.log('arac_getir_page - ' + error); }
  }

  /**
   * The row callback to render a single row.
   */
   function arac_getir_list_row(view, row) {
    try {
      return l(row.title, 'node/' + row.nid) + row.field_kart_no +
      flag_quick_link(
        'ara_getir',
        'node',
        row.nid,
        parseInt(row.flagged) ? true : false
        );
    }
    catch (error) { console.log('arac_getir_list_row - ' + error); }
  }

  /**
   *
   */
   function arac_getir_list_empty(view) {
    try {
      return t('Kart bulunamadı');
    }
    catch (error) { console.log('arac_getir_list_empty - ' + error); }
  }

You could first create a custom form: http://docs.drupalgap.org/7/Forms/Creating_a_Custom_Form

Then in its submit handler build a Views Render Array and inject it into a waiting div placeholder element (markup widget) on the form:

http://docs.drupalgap.org/7/Views/Displaying_a_View/Views_Render_Array
http://docs.drupalgap.org/7/Forms/Form_Elements/Element_Markup

Or have the submit handler go to a page with arguments: http://docs.drupalgap.org/7/Pages/Page_Arguments

Then that's page's page_callback could build a Views Render Array and use the search string as a contextual filter to the View.


Minimally working end-to-end example of drush batch job execution I'm trying to make drush run my batch jobs. There's some amount of documentation at Processing batch jobs with drush, however, I can make no sense of it.

I would like to see real code, and the CLI requirements/instructions for running it, that when called by Drush, prints something trivial, such as "Hello world", once per operation.

I've written drush CLI commands. I've also written some Batch API processes. On each individual topic you've asked about there is alot of documentation.

I'm not sure why you want to use the Batch API specifically via Drush. The Batch API in part is used to avoid HTTP request timeout in long PHP processes. If you're using Drush from the command line -- you have no max_execution_time to worry about from php.ini essentially ...

How to use the Queue API (and Batch) from DrupalCampLA2012 I attended

which goes to the actual link for the slides

A batch tutorial from March 2012 I have have referenced in creating my own BatchAPI stuff in the past (site db was down so I linked to a google cache page)

EDIT: Have you looked into the Migrate source to see how they run Batch stuff from drush cli?


How to revolve TinyIMCE error 'The version of TinyMCE could not be detected'? I installed these modules: Wysiwyg, IMCE Wysiwyg bridge, IMCE.

Then downloaded the libraries from:

https://www.tinymce.com/download/ (developer edition, community doesn't even have a non minified imce.js file...)

Now the file structure is not the same as the instructions from Drupal Backend:

Extract the archive and copy its contents into a new folder in the      following location:
sites/all/libraries/tinymce

So the actual library can be found at:
sites/all/libraries/tinymce/jscripts/tiny_mce/tiny_mce.js

So I deducted I had to change folder structure from:

sites/all/libraries/tinymce/js/tinymce/tinymce.js

To:

sites/all/libraries/tinymce/jscripts/tiny_mce/tiny_mce.js

But still not working, I get this error:

TinyMCE (Download)  Not installed.
The version of TinyMCE could not be detected.

You need use the last dev version of Wysiwyg, you can read more about this here.

And you need read the Supported Editors Matrix.

I download the 3.5.11 version of TinyMCE from here and copy the tinymce folder to YOUR_SITE/sites/all/libraries/ so inside this folder you must have this:

So I have installed:

Wysiwyg 7.x-2.x-dev
TinyMCE 3.5.11

And it works ;-)


Add custom value in session How can I add value in drupal session. I am adding value using $_SESSION = 'my value', but once trying to print $_SESSION variable it return blank.

Drupal bootstrap takes care of session_start for you, so you should be able to define sessions like...

$_SESSION['my_data'] = 'my value';

You can also add the following in settings.php to determine the life span of the session

ini_set('session.cache_expire',     200000);


call mp3player field (CCK Field) in a page I Use MP3 Player module to play audio files. I'm looking for a PHP code to call MP3 Player from a specific node. (e.g. node 4) how can I do that ?

this code doesn't work:

<?php
$node = node_load(4);
print $node->field_audio[0];
?>

this is the result of print_r($node) in node 4.

stdClass Object (
[nid] => 4
[type] => story
[language] => en
[uid] => 1
[status] => 1
[created] => 1343931282
[changed] => 1343931282
[comment] => 2
[promote] => 1
[moderate] => 0
[sticky] => 0
[tnid] => 0
[translate] => 0
[vid] => 4
[revision_uid] => 1
[title] => 5455
[body] =>
[teaser] =>
[log] =>
[revision_timestamp] => 1343931282
[format] => 1
[name] => admin
[picture] =>
[data] => a:0:{}

[field_audio] => Array (
[0] => Array (
[fid] => 7
[uid] => 1
[filename] => audio.mp3
[filepath] => sites/default/files/audio.mp3
[filemime] => audio/mpeg
[filesize] => 3663455 [status] => 1
[timestamp] => 1343931251
[list] => 1
[data] =>
)
)

[last_comment_timestamp] => 1343931282
[last_comment_name] =>
[comment_count] => 0
[taxonomy] => Array ( )
)

From the readme.txt file of that module.

  Pop this code anywhere to insert an audio player:

if (module_exists('mp3player')) {
  print theme('mp3player', 'Default', $audio_file_url, $audio_title, $audio_artist, $description);
}


How to check in Rules the value of a field collection field contained in a user account? I want to give a specific user a price override on specific products. In doing so, I added field collection on the people account setting. This field collection has to two fields: product sku and price.

I also created a rule with this codes:

{ "rules_price_override" : {
"LABEL" : "price override",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
"ON" : { "commerce_product_calculate_sell_price" : [] },
"IF" : [
  { "user_has_role" : {
      "account" : [ "site:current-user" ],
      "roles" : { "value" : { "2" : "2" } }
    }
  },
  { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
  { "entity_has_field" : {
      "entity" : [ "site:current-user:field-price-override:0" ],
      "field" : "field_product_sku"
    }
  },
  { "data_is" : {
      "data" : [ "site:current-user:field-price-override:0:field-product-sku" ],
      "value" : [ "commerce-line-item:commerce-product:sku" ]
    }
  }
],
"DO" : [
  { "commerce_line_item_unit_price_amount" : {
      "commerce_line_item" : [ "commerce_line_item" ],
      "amount" : [ "site:current-user:field-price-override:0:field-regular-price:amount" ],
      "component_name" : "base_price",
      "round_mode" : "1"
    }
  }
]
}
}

But it only good for the first field collection value.

What will be the best way to make it loop, so that it can change its index as site:current-user:field-price-override:0 - end

I'm about sure that the machine name of your field collection field is site:current-user:field-price-override (your question doesn't state that explicitly), for which you do not have a "Entity has field" Rules Condition yet (you have site:current-user:field-price-override:0 instead).

Try adding a Rules Condition "Entity has field" (prior to being able to use it anywhere later on in your rule), which refers to your field collection field. Not sure why you have/need that site:current-user:field-price-override:0 Rules Condition, but you might not need that anymore.

You can then add a Rules Action which is simply a Rules "loop", and which iterates over each of the field collection items. And you will be able to use any of the typical tokens (in the replacement patterns).

For way more details about this, refer to "How to iterate over all field collection items in an eMail body using Rules?" (which also includes a rule in export format you may want to experiment with, if you only adapt some machine names of the used fields).


ubercart - Add sku to a product catalog title via tokenizing it or adding it to a view? I'm looking to add the sku in the product catalog view.

Thus producing this:

[title][sku]

Is there a way to tokenize it? I've looked around each field. It seems as the sku is not exposed in views as a field.

I can see SKU in views, see the screenshot below, so not sure if I'm missing something obvious about the question.


Not sure how to work with beanstalkd module I am looking to setup a queue system to upload large files (~150MB). For specific reasons we decided to do this using SFTP (phpseclib). After some research I came to the conclusion that I would probably need something like a work queue. I decided to go with Beanstalkd since there was a drupal module for it.

I have managed to get a Beanstalkd server running and add items to the queue.
But now I'm kind of confused as to how I would need to execute a specific script.

Can anyone help with this particular part of getting beanstalkd queue items to run in a non-blocking way?

Do I need to maybe write a shell script to run a php cli or am I looking at it all wrong?

I managed to figure it out.

Using hook_cron_queue_info, it is possible to define worker callbacks for queue items.

I then wrote the sftp upload script in the worker callback and then run the runqueue.sh script that comes with the drupal beanstalkd module to listen for ready queue items.


How do I get items of a field of type list? I have created a list field with 10 items(allowed values). Now I want to get that 10 items programmatically. How do I get them?

Better create a vocabulary of taxonomy terms populated with your items.Then you can use taxonomy_get_tree() function to retrieve all those items


Migrating images and files I am trying to migrate a Drupal 7 site to a Drupal 8 site. I already created my module for migration and I have a content type that has a title, field_picture and a field_text in Drupal 7.

I want to migrate it to Drupal 8 where field_text = field_description and field_picture is field_image.

I tried the following:

id: drupal7_fruit
label: "Test migration"
migration_group: drupal7
source:
  plugin: d7_node
  node_type: fruit
process:
  nid: nid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_description: field_text
  field_image:
    plugin: iterator
    source: field_picture
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height
destination:
  plugin: 'entity:node'
  default_bundle: fruit
migration_dependencies: {}

I could migrate description and title, but the image is never migrated.

What am I doing wrong?

EDIT

migrate_plus.migration.drupal7_fruit.yml

    id: drupal7_fruit
label: "Migrate Fruit Content Type"
migration_group: drupal7
source:
  plugin: d7_node
  node_type: fruit
process:
  nid: nid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_descricao: field_body
destination:
  plugin: 'entity:node'
  default_bundle: fruit
  migration_dependencies:
    optional: drupal7_image

migrate_plus.migration.drupal7_image.yml

 id: drupal7_image
label: Images
migration_tags:
  - Drupal 7
source:
  plugin: d7_file
  constants:
    source_base_path: ''
process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file

Edited my question because @Berdir in the comments said that images or files must have a different migration file but still can't migrate images. I restored my D8 site database to start all from scratch.

Thank you for Berdir's help but I noticed that I was missing some information on my drupal7_fruit migration file like the values for field_image and migration dependencies.

The working solution:

migrate_plus.migration.drupal7_image.yml

id: drupal7_image
label: Images
migration_group: drupal7
migration_tags:
  - Drupal 7
source:
  plugin: d7_file
  constants:
    source_base_path: '/var/www/username/drupal7/' # Full location of your drupal7 site
process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file
migration_dependencies: {}

migration_plus.migration.drupal7_fruit.yml

id: drupal7_fruta
label: "Migrate Fruit Content Type"
migration_group: drupal7
migration_tags:
  - Drupal 7
source:
  plugin: d7_node
  node_type: fruit
process:
  nid: nid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_description: field_body
  field_image: # Image field name in Drupal 8 site
    plugin: iterator
    source: field_photo # Image field name in Drupal 7 site
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height
destination:
  plugin: 'entity:node'
  default_bundle: fruit

migration_dependencies:
  required:
    - drupal7_image

Hope this may help anyone with the same problem in the future!


How do I display a Media entity reference field in a nested paragraph on a template? I have been working on this for 2 days and I can't figure it out. I hope someone can help me.
I have a paragraph (dinamic_columns_grid) that has an entity reference field to another paragraph (field_dinamic_column) This nested paragraph has an entity reference field to a Media image field (field_image). All the paragraphs have more fields but this is the one that is giving me problems.
I created a twig template for the first paragraph (paragraph--dinamic-columns-grid.html.twig) where I want to display the nested paragraph's fields individually. I know I could use {{ content.field_dinamic_column }} to display all of the results, and it does work, including the image field, but that's now what I want. All the fields in the code below are displaying correctly except the image field (field_image). I have tried everything but I can't seem to make it work. Any help will be appreciate.

        {% for key, item in content.field_dinamic_column %}
            {{ item['#paragraph'].field_html_content.value|raw }} / text field.It works
            {{ item['#paragraph'].field_hide.value|raw }} / select field. It Works
            {{ item['#paragraph'].field_image }} / Media image field. It doesn't work
         {% endfor %}

I like to be able to see the image or at the very least the url.
Thanks.

After many attempts I finally figure it out, thanks to the comments above and a little investigation. I think my problem was that I assume that the machine name I need it to use for my nested image field was the one I give when I created the content type but that's not the case, I had to use the field of the media type in my case field_media_image instead of field_image.Below is the working code.
{{ file_url( item['#paragraph'].field_image.entity.field_media_image.entity.uri.value ) }}


Save a node via javascript I want to be able to save a node when certain events happen in the browser. I.E the user changes tab. Is it possible to save a node in drupal using javascript?

Is there a javascript api tfor drupal? If not are there any contrib modules that add this? If it is custom code is needed is there an web service that can be called or would I need to role my own?

In order to achieve this on Drupal 7, you need to develop a custom module that does the following:

Register a menu hook that will act as the endpoint where your javascript will send the data for the node to be created.

Create a function that will be the callback of the hook and handle the actual creating and saving of the node. It can be something like this as mentioned in the answer above:

$data = json_decode($_REQUEST['title']);
$node = new stdClass;
$node->type = 'article';
$node->title = check_plain($data->title);
node_save($node);
echo json_encode(array('Status' => 'OK'));
drupal_exit()

Notice drupal_exit() is needed otherwise you get the whole page rendering.
In order to set other properties for example the body, you need to know the structure, it is usually something like

$node->fieldName[language][delta]['value'] eg, $node->body['und'][0]['value']

That's all it needs on the php side, now on the javascript side you will be needing to create an array containing the values for the node and submit it via ajax. Using jQuery it can be done like this:

jQuery.ajax(
{
    url:  Drupal.settings.basePath + queryPath,
type: 'POST',
dataType: 'json',
data:  {'data': JSON.stringify(queryParameters)},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
    console.log(JSON.stringify(XMLHttpRequest));
    console.log(JSON.stringify(textStatus));
        console.log(JSON.stringify(errorThrown));
},
success: function (data)
{
    console.log(data);
    }
});

Data can contain anything returned from php...

Have fun

Update:

A more general and concrete solution is available through the use of the Services module that allows you to define a REST api over the various content types you create. This way you don't need to write any custom code on the php side,


Help with basic hook for my first module I am having problems with understanding if my hook is activating/running. I have watched and read many things about hooks but until I get something to work I am very confused.

I'm trying to use the hook here:
http://api.drupalcommerce.org/api/Drupal%20Commerce/sites!all!modules!commerce!modules!checkout!commerce_checkout.api.php/function/hook_commerce_checkout_pane_info_alter/DC

/*  Hello World
*/
function commerce_admam_commerce_checkout_pane_info_alter(&$checkout_pane)
{
dpm("hi");
}

All I want to have happen on checkout is to see if that message shows up. I have tried other hooks as well. MY filename is commerce_admam.module and it's enabled in the backend. I can move the dpm() out of the hook and it fires off the message (everywhere though because its running it all the time)

dpm and dsm can be a little tricky in some hooks, and you may need to time a cache clear with a page reload to see them fire.

Better to use something like watchdog or actually alter the page content.

Your function looks good, so try this from the example module. More chance of seeing the effect:

function checkout_pane_example_commerce_checkout_pane_info_alter(&$panes) {
  if (!empty($panes['cart_contents'])) {
    // Change the title of the "Cart Contents" pane.
    $panes['cart_contents']['title'] = t('Your big wonderful shopping cart brimming over with shopaholic nonsense');
  }
}


Filtering date fields in Views - How can I test for NULL When I add a date field to the filter criteria, I get a choice of operators "Is less than", "Is less than or equal to" etc, but no way to test is or is not NULL.

How do I test for these conditions?

For User "Last access" or "Last login" dates the "Is empty (NULL)" option is not available.

For those particular dates, an alternative is to test for "Greater than 1970-01-02".


How can I alter a module's JavaScript? I need to alter the "Webform AJAX" module's JavaScript code.
Is this possible without hacking the module, and risking losing it all upon module updates?

You can use hook_js_alter() in a module. For example, this code replaces the jQuery library used by Drupal with the file present in the jquery_update directory.

function jquery_update_js_alter(&$javascript) {
  // Swap out jQuery to use an updated version of the library.
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';
}

The same can be done for inline JavaScript code. The differences are:

Instead of 'misc/jquery.js', the first index is a number
$javascript[$index]['data'] will contain the JavaScript code

This means that first you have to find the entry for the JavaScript code to replace, and then alter it. The following code should work in this case.

function mymodule_js_alter(&$javascript) {
  $old_code = 'The code to alter';
  $new_code = 'The new code';

  foreach ($javascript as $index => $info) {
    if (is_numeric($index) && $info['data'] == $old_code) {
      $javascript[$index]['data'] = $new_code;
      break;
    }
  }
}

As alternative, if you need to alter the library implemented by a module, you can implement hook_library_alter(). For example, this is the code implemented by the latest version of the jQuery Update module.

function jquery_update_library_alter(&$javascript, $module) {

  // We are updating just the system module. For all other cases we return.
  if ($module != 'system') {
    return;
  }

  $path = drupal_get_path('module', 'jquery_update');

  // Make sure we inject either the minified or uncompressed version as desired.
  $min = variable_get('jquery_update_compression_type', 'min') == 'none' ? '' : '.min';
  $cdn = variable_get('jquery_update_jquery_cdn', 'none');

  // Replace jQuery with the latest version.
  $version = variable_get('jquery_update_jquery_version', '1.5');
  jquery_update_jquery_replace($javascript, $cdn, $path, $min, $version);

  // Replace jQuery UI with CDN or local files. If from a CDN include all of jQuery UI.
  jquery_update_jqueryui_replace($javascript, $cdn, $path, $min);

  // Replace the jQuery Cookie plugin.
  $javascript['cookie']['js']['misc/jquery.cookie.js']['data'] = $path . '/replace/ui/external/jquery.cookie.js';
  // Noting the version based on git commit as no version number is available.
  $javascript['cookie']['version'] = '67fb34f6a866c40d0570';

  // Replace jQuery Form plugin.
  $javascript['jquery.form']['js']['misc/jquery.form.js']['data'] = $path . '/replace/misc/jquery.form' . $min . '.js';
  $javascript['jquery.form']['version'] = '2.69';

  // Replace files for jQuery 1.7 and up
  if (version_compare($version, '1.7', '>=')) {
    $javascript['drupal.states']['js']['misc/states.js']['data'] = $path . '/replace/misc/1.7/states.js';
  }
}

This is valid also for JavaScript code used by Drupal core, since for those JavaScript files, the System module implements hook_library(). (See system_library().)

hook_js_alter() can be used for any JavaScript file/code, even for files used by Drupal core. Between hook_js_alter() and hook_library_alter(), it is preferable to implement the latter, when the JavaScript files are exposed as library.


How to give pagination for Rest Service data I am using Rest Service and pull the data from another non drupal db.

I wrote custom module with two form elements and render that data (rest service call) and display using theme table.

I wrote  $form['pager'] = array('#theme' => 'pager'); for pagination.

Pagination is working only for data which rendered using db query. In my condition it's not working.

How can I add pagination for my table.

 function myForm($form, &$form_state){
 pager_array_splice($final_data, 10);
foreach($final_data as $key => $value){
     $source=explode('=',$key);
     $options[]=array(
        'Token_Source'=>$source[0],
        'Tokens'=>$value,
     );
}

$form['pagerTop'] = array('#theme' => 'pager');
$form['entities'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#attributes' => array('class' => array('entity-sort-table viewTable tokensTable')),
  '#empty' => t('There are no Notification ....'),
);
$form['pagerBottom'] = array('#theme' => 'pager');
return $form;
}
function pager_array_splice($data, $limit = 9, $element = 0) {
print_r($data);
global $pager_page_array, $pager_total, $pager_total_items;
$page = isset($_GET['page']) ? $_GET['page'] : '';

// Convert comma-separated $page to an array, used by other functions.
$pager_page_array = explode(',', $page);

// We calculate the total of pages as ceil(items / limit).
 $pager_total_items[$element] = count($data);
$pager_total[$element] = ceil($pager_total_items[$element] / $limit);
 $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element],     ((int)$pager_total[$element]) - 1));
 return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

$row = pager_array_splice($options, 10);

$form['pagerTop'] = array('#theme' => 'pager');
  $form['entities'] = array(
  '#options' => $row,
  );

please assign $row value in the theme table


Dynamically hiding/showing form fields I have created a custom module in Drupal 8. There should be some fields invisible by default; when a user clicks on More Options, the field should display. When user clicks on Fewer Option, the fields should be hidden again.

How can I achieve this in a Drupal 8 form?

You can easily do this with the Conditional Fields module.

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
  When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.


Multisite Module Update Being able to update the shared modules folder in a multi-site Drupal installation is amazingly easy, but I am wondering, what are some best practices when it comes to that?

Updating modules on a live environment when multiple sites are affected can be bad if a module has some sort of bug or if it's incompatible with something you were unaware of, correct? Usually we like to perform quality assurance on sites after a module update has been performed, but that starts to become a hassle once there are many sites under one core.

Assuming the sites/all folder is synchronized between development and live environments, pushing a site live is specially an interesting experience - since we want to make sure that all of the modules are updated. Sometimes these modules are in the shared modules folder, meaning it would affect every remaining multi-site as well. Then, in that case the only solutions I can imagine at the moment would be to either:

Push the site live without updating any of the shared modules - Perform updates on the live environment periodically when everyone is available to do Quality Assurance.
Perform module updates everytime a new site is pushed live. In this scenario, quality assurance would have to be performed on every site under multi-site - every single time a new site is pushed live.
Any input would be appreciated. Thanks for your help, guys!

I always run with a Dev mirror copy of the Live site and test all modules here before updating the live site with those modules, do this and test the site thoroughly. Make sure the dev and live environments are identical or as close to identical as possible.


Translation not working for custom user roles I am using the i18n module. I created 2 custom roles: venue user and customer user. When I log in as administrator user, the translation is working fine; when we log in either as venue user or customer user, the translation does not work.

How can I solve this problem?

You need to grant translation related permissions for the two roles you have created. For changing the permissions, go to /admin/people/permissions, then set the translation related permissions for the two roles.
If you want the two roles to translate content, then you need to grant Translate content permission for the roles.


Multiple modules extending form in OOP way, with no hook_form_alter() I know very well how hook_form_alter() is working in Drupal 7 and in Drupal 8, but the main topic here is how to do things OOP way.

How would you solve the following problem the OOP way?

Suppose you have a random form, for example the user login form.

custom_module_A adds a checkbox to  the form and a custom
validation handler
custom_module_B adds a textfield to the same form and another custom
validation handler

The OOP way of altering the form is:

intercepts the original UserLoginForm and directs to a CustomModuleNewForm- an extended class from user_login_form class
Write a class that extends the user login form

I am unable to "grokh" how this can be solved the OOP way, by extending the form in custom_module_A and not having custom_module_A as a dependency for custom_module_B.

Basically, I am looking for OOP hook_form_alter() replacement.

Good question. The alter hooks will eventually be replaced, not by extending form classes, but by symfony events. Events are coded in OOP and they have a proper priority handling. See https://www.previousnext.com.au/blog/alter-or-dispatch-drupal-8-events-versus-alter-hooks


Widget type radio buttons and N/A I have a field so-called "Status" in my custome contact type. It is a List (integer) and widget type is "Radio buttons". I added two values for allowed values list:

 0|Sold
 1|Available

Default value is "Available". But Drupal lists this as below:

 () N/A
 () Sold
 () Available

Why does Drupal add this unnecessary "N/A" to the radio buttons? I encountered this problem since D6. Now, I'm using the latest version 7.14. I'm still seeing this.

I know I can remove the "N/A" by writing a hook from a custom module.
Nonetheless, I don't want to write additional codes for this kind of small thing. When I use "Select list", it is ok with an option "-None-", but the radio button is ideally suited for the two options.

How can I remove it without installing additional module? Am I missing some functionalities from Drupal core interface?

Something like this should help.

(function($) {
  $('.form-radio[value=_none]').parent().hide();
})(jQuery);

http://drupal.org/node/1623360


How to add missing data selector in "Create new entity" rules action? I have created an activity log using the Message module. It is about Statuses module (for which I'm using the DEV version). When someone comments on a status update, the activity is logged, but it should be logged for the status update owner and not the current user.

Currently, when I create the rules action "Create new entity" in the rules setup, the only replacement pattern available in the data selector for "User for which to log" is 'site:current-user'. Here I want 'status:status-sender' and not 'site:current-user'. The owner of the status update must receive the notification and not the user who commented.

Message export

{
  "name" : "status_comments",
  "description" : "Status comments",
  "argument_keys" : [ "@status_comments_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@status_comments_user commented on your status",
        "format" : "plain_text",
        "safe_value" : "@status_comments_user commented on your status"
      }
    ]
  },
  "rdf_mapping" : []
}

Rules export

{ "rules_posted_statuses_comment" : {
    "LABEL" : "Posted a statuses comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "statuses" ],
    "REQUIRES" : [ "fbss_comments_rules", "rules" ],
    "ON" : { "fbss_comments_save" : [] },
    "IF" : [ { "NOT fbss_comments_rules_on_own" : { "comment" : [ "comment" ] } } ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "status_comments",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:status-comments-user" ],
          "value" : "[comment:commenter]"
        }
      }
    ]
  }
}

Note: This is strange because I have another message type with the event "user saves a status" and in its rules action, it shows all replacement patterns for statuses in data selectors

Looks like you're starting to hit the limits of the most recent (beta2) release of the Statuses module. Have a look at this variation of a custom rule, which is included in Comment nr 13 of issue nr 1693620:

{ "rules_user_commented_on_status" : {
    "LABEL" : "User commented on a status",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Statuses" ],
    "REQUIRES" : [ "fbss_rules", "rules", "fbss_comments_rules" ],
    "ON" : [ "fbss_comments_save" ],
    "DO" : [
      { "fbss_rules_load_action" : {
          "USING" : { "sid" : [ "comment:sid" ] },
          "PROVIDE" : { "status_loaded" : { "status_loaded" : "Loaded status" } }
        }
      },
      { "mail" : {
          "to" : "[status-loaded:sender:mail]",
          "subject" : "[comment:commenter:name] commented on your status",
          "message" : "Hi [status-loaded:sender:name],\r\n\r\n[comment:commenter:name] commented on your status [status-loaded:message-formatted]\r\n\r\n\r\nRegards,\r\n[site:name]"
        }
      }
    ]
  }
}

Even though this is not really the rule you're looking for, pay attention to the "to" field in the eMail being constructed. That to-field uses token ...sender:mail, which is close to the uid (I believe) of the "sender".

That very same comment in that issue also includes a patch (which I believe is committed to the current DEV version), clearly an improvement (not a bug fix ...) because it makes extra data available for subsequent Rules processing. This patch appears to be a prereq for the above rule to work: I tried to import that rule in a site using the beta2 version, but that import failed (and "I" do not want to use a DEV version, even using beta-versions is exceptional to me).

I suggest you either try to apply that patch in your current setup, or switch to the DEV version of that module. After you do so, continue with these extra steps:

Try to import that same eMail example, so that you have a sample rule that is close to what you'll need.
Expand your own rule, to also add such "load action" and then check if you have a similar token like that [status-loaded:sender:mail], which in your case should become something like [status-loaded:sender:name] or [status-loaded:sender:uid].

If you get that import of the eMail sample to work, then I would assume (have not tested it myself and leave that to you) that this comination of your rule with part of the eMail sample here is what you're looking for:

{ "rules_posted_statuses_comment" : {
"LABEL" : "Posted a statuses comment",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "statuses" ],
"REQUIRES" : [ "fbss_comments_rules", "fbss_rules", "rules" ],
"ON" : { "fbss_comments_save" : [] },
"IF" : [ { "NOT fbss_comments_rules_on_own" : { "comment" : [ "comment" ] } } ],
"DO" : [
  { "fbss_rules_load_action" : {
      "USING" : { "sid" : [ "comment:sid" ] },
      "PROVIDE" : { "status_loaded" : { "status_loaded" : "Loaded status" } }
    }
  },
  { "entity_query" : {
      "USING" : {
        "type" : "user",
        "property" : "uid",
        "value" : [ "status-loaded:sender" ],
        "limit" : "1"
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "message",
        "param_type" : "status_comments",
        "param_user" : [ "entity-fetched:0" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:arguments:status-comments-user" ],
      "value" : "[comment:commenter]"
    }
  }
]

}
}

Note the status-loaded:sender in the above rule! Which should be a token you can use because of the very first Rules Action added now.

Disclaimer: I have NOT (repeat NOT) tested this last rule (since I never use DEV versions of a module). Though chances are that by copy/pasting relevant parts of your original (exported) rule and the (exported) eMail rule it does work as it should.

Note: I'm about sure that the integrity check you got (when trying to import my updated rule, as you wrote in a comment to this answer) is because "status-loaded:sender" is not returned as a "User entity". While the Message module wants/expects the "param_user" to be a "User entity".

You might be able to "convert" that "status-loaded:sender", by adding a Rules Action "Fetch entity by property", whereas you would use "status-loaded:sender" as the property to do so. The entity type to be fetched should be, for sure, a "user" entity (not a "message"!). This Rules Action should be inserted after the first "fbss_rules_load_action".

The result of performing that extra Rules Action is then an actual "user entity" (a real entity), and that is what you might then use for that "param_user" (which should avoid the integrity check error).


I'm using Webform. How can I use JavaScript in it? I am using webform. I'm going to create to fields. First one should be taxonomy term name, and second one should be taxonomy term values. In this case I'm trying to use javascript. When you choose a category in first field, it should be seen categories acording first one. For example: when you choose "animals" category in first field, it should be seen "bear", "lion", "sparrow" and other categories in second. When you choose "fruits" category in first field it should be seen "apple", "bananas", "ananas" and other categories in second. How to solve this problem?

You should try Webform conditional module.

  This modules enhances the existing Conditional Rules of the Webform
  Module. It adds the ability to make components dependent on select
  components(i.e. listboxes, radio buttons, and checkboxes) that appear
  on the same page.

Screencast Demo

View a demonstration form


Does calling query() on a container prevent SQL Injection? According to this link, db_query is now deprecated, and should be replaced by calling query() on a container containing a service injected with a database connection.

How do you prevent SQL Injection when using query()? The docs only cover how to do so when using db_query(), which is deprecated.

Thanks.

What reported there for db_query() is still valid for the method that you should use. In short, use placeholders when building the query, instead of concatenating the query string with unsafe input (e.g. the input obtained from from the user).

In Drupal 8 procedural code, you would use \Drupal::database()->query() instead of db_query(), but you would still avoid using code similar to the following one.

$count = \Drupal::database()->query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = '. $_GET['user'])->fetchField();

The correct code would be the following one.

$count = \Drupal::database()->query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = :name', [':name' => $_GET['user']])->fetchField();


How do you set the alt attribute with the Media module widget? I've tried both 7.x-1/7.x-2 branches of the Media module and can't find a way to set the alt-attribute on a image field using the media-widget.

When I change to the image widget it's possible to set title/alt.

After one whole day of searching and patching without success I finally found out I only simply had to download and enable Token module to make Media correctly set images alt and title attributes when inserting images in CKEditor wysiwyg. I wonder since this is nowhere stated as an requirement. That's the bundle of modules it finally worked with:

media-7.x-2.0-alpha3
wysiwyg-7.x-2.2+46-dev + CKEditor profile (CKEditor 4.4.2.1567b48)
token-7.x-1.5

Now I even can use the default view mode to display the alt or title attribute below the image to use it as an image caption.