Some Drush master-branch commands report DB problem in Drupal 8 I use Drupal 8.0.0 in a Windows 10 home, WAMP environment.

When I run for example drush up, I get:

  The drush command 'up' could not be executed. Drush was not able to
  start (bootstrap) the Drupal database

Every action is done when I am in the sites folder (C:\wamp\www\sname>).
This is a brand new environment - I've only one DB named equally as it's user.

Update:

After I tried to follow this similar (but surly not identical!) thread, I added a fifth value to the Path Environment variable, restarted the Win CLI, and than when I ran drush up at the sites' folder, I got another, brand new error:

  wget nor curl executables found.

I need to further explore this but if you have an idea, please shoot...

Drush status

 C:\wamp\www\sname>drush status
 Drupal version         :  8.0.0
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  sname
 Database name          :  sname
 PHP executable         :  php.exe
 PHP configuration      :  C:\wamp\bin\php\php5.5.12\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:\drush-master\drush.php
 Drush version          :  8.1-dev
 Drush temp directory   :  C:\Users\Beni\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  C:\wamp\www\sname
 Site path              :  sites/default
 Sync config path       :  sites/default/files/config_mkuaR5uFQ7VCjh1_FFBuZzWXkUsz-sA7Klv4HO_2yLJG33wfJJabdavO7QKzyIRWiQoWA3IJbg/sync

Drush sql-conf

C:\wamp\www\sname>drush sql-conf
Array
(
    [database] => sname
    [username] => sname
    [prefix] => Array
        (
            [default] =>
        )

    [host] => localhost
    [port] => 3306
    [namespace] => Drupal\Core\Database\Driver\mysql
    [driver] => mysql
)

Drush is giving a very accurate error message

  wget nor curl executables found.

You can either install Curl separately as benos suggests above or install more Unix tools. Since you might need Git anyway, why not install Git for Windows? Then you get a proper Bash prompt. If you prefer to use Command or Powershell you can select to update the PATH variable when installing so Git (and the Unix tools) are available there too.


Can I register an additional namespace to point to the modules folder In Drupal 8 is it possible to register an additional namespace which points to the modules folder in addition to the \Drupal namespace?

e.g.: MyOwnNamespace\{module_name} to point to $path_to_module/src? I am asking this, because I would like to better understand how today's class design will affect my migration process to Drupal 8 one day.

This was a follow up question from my original thread regarding namespacing.

As suggested by another user I split this off into a separate question thread, but the question has been answered in the original thread already.

Splitting my comment over there into a separate answer then ;)

You can, yes, see system_register() and drupal_classloader_register(). Those helper functions hardcode "Drupal\" as they are all about modules, but you could get the class_loader service directly.

As @Clive said there, I would not recommend doing it for your own classes, there isn't really a reason to do so, unless you're including an external library.

External libraries is a different story, that can be useful. As already commented in How to autoload classes from a 3rd party PHP library in Drupal 8, if you do not want to depend on Composer Manager, then you can implement your own autoloader service and register them either by loading a composer-style autoload.php, or if you have it available in a different way, by directly registering it in the cloassloader service.


Code sample confusion I work with Drupal almost everyday. I am constantly scouring the web for help on my current Drupal project. I come across many code examples and samples. I'm wondering how the code relates to Drupal from a module standpoint. Does anyone create a "general" module to add and interact with their Drupal site? Like a gateway to actually code things in their Drupal site instead of using the countless forms and views that encompasses normal Drupal development. Or am I getting it all wrong and the code examples are for specific modules that people are making?

A couple of code examples I come across and think to myself - "This is very general. I would like to use this but do I need to make an entirely new module?" are:

<?php
global $user;
print_r($user);
?>

or

function HOOK_views_api() {
  return array(
    'api' => 3.0,
    'path' => drupal_get_path('module', 'HOOK')
  );
}

function HOOK_views_default_views() {

  // Paste code form views export.

  $views[$view->name] = $view;
  return $views;
}

It seems like a lot of extra nonsense to create an entirely new module just to add some simple programming functionality to the site and to take advantage of the Drupal API, and to do this every time I want to program something instead of work with the UI.

Sorry for such a weird and general question but I'm just trying to wrap my head around it. Let me know if I'm completely wrong too.

Thanks!

You are headed into right direction: almost all websites I work on, have one main module that contains general customizations and provides the base for additional custom modules.
I find that this is absolutely necessary if you want to keep the sanity in the long run, especially if the project can potentially grow.

Small fixes are often faster and easier to maintain this way, rather than just adding more modules and making the configuration more complex.

I created a boilerplate module that we use as "Main" module for almost every Drupal installation.
You can see it here.

Most of the generic implementations / integrations (views, rules, webform, drush, helper functions, etc.) are there already, and it's much easier to just remove what you don't need.

On a related note, the same can be said for new Drupal installations. After creating a lot of Drupal websites for real projects and testing, you will realize that there are certain sets of modules and settings you want to have as a starting point. This is solved the best through installation profiles.

Here is a default installation profile that we use in almost every website, as well as for testing.

Hope this helps.


The requested page could not be found error appear in page but page is render correctly-drupal 7 i had create one block in my custom module, which display in "CONTENT" region, only on "currant-trustees" page.

when i access url "localhost/drupal/currant-trustees" page is render correctly, but with error "The requested page "/drupal/currant-trustees" could not be found." and also page title is page not found.

It sounds to me like you only want to show said block on that page and nothing else. You might be better off implementing hook_menu() to register a callback (a page) which displays custom content, instead of creating an empty page and showing a block on that.

It might look something like this:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['currant-trustees'] = array(
    'page callback' => 'MYMODULE_currant_trustees',
    'title' => 'Currant trustees',
    'type' => MENU_CALLBACK,
  );
  return $items;
}
function MYMODULE_currant_trustees() {
  $content = 'This is where your content should go, just copy the code from the block content';

  return $content;
}


How do I render user Login block in main menu? I wrote the following code but I see only 'array' word.

function mytheme_menu_tree__primary(&$variables) {
   return '
' . $variables['tree'] . module_invoke('user', 'block_view', 'login')['content']
    . '
';

}

Block content can either be a string or a render array. As such you need to run it through render:

$block_content = module_invoke('user', 'block_view', 'login')['content'];
return '
' . $variables['tree'] . render($block_content) . '
';

It's worth bearing in mind that the user login form isn't wrapped in
 tags, so unless you're altering the markup for that form elsewhere, your code will produce invalid markup.


How do I show the number of nodes using a taxonomy term? Somebody asked Views and node count for taxonomy terms. I am trying to do the same, but with Drupal 8.

I follow the steps reported in that question, and I get a count of the taxonomy term (say "fruit"), but when I click on it there is a page that lists "fruit" multiple times, instead of listing the pages themselves.

If I do not do a count. then when I click on the taxonomy term I get the correct listing page (e.g. apple, orange, pear).

Can anyone help me with this?

The following worked for me in Drupal-8.0.6.

Note that for some reason 'Content NID' is not offered as a field for the 'Content with term' relationship, so I used UUID instead and it worked.

Create a Taxonomy Term view (with a field Taxonomy term: name, usually linked to the term page)
Relationship > Taxonomy term: Content with term (will be called node).
Advanced: Use aggregation: Yes
Add Field > Content: UUID with relationship node
Aggregation type for UUID = Count

You may have to play with COUNT vs COUNT distinct

If you want tbe count to appear in brackets like this:

linked_term (count)

On UUID field use Rewrite results:

({{ uuid }})

Note that it is using the new Twig template language notation.


Paragraphs from sub_process I need to migrate a json feed with following example structure;

{
   "data":[
      {
         "id":"11028",
         "first_name":"Foo",
         "last_name":"Bar",
         "functions":{
            "group_function":{
               "data":[
                  {
                     "group":"1",
                     "function":"Scrummaster",
                     "active":"1"
                  },
                  {
                     "group":"2",
                     "function":"Developer",
                     "active":"0"
                  }
               ]
            }
         }
      },
      {
         "id":"11029",
         "first_name":"John",
         "last_name":"Doe",
         "functions":{
            "group_function":{
               "data":[
                  {
                     "group":"1",
                     "function":"Project manager",
                     "active":"1"
                  },
                  {
                     "group":"2",
                     "function":"Project owner",
                     "active":"1"
                  }
               ]
            }
         }
      }
   ]
}

For this, I was thinking of having a teammember node, and a teamfunction paragraph type for the functions for each team member.

If i understand migrate api correctly, i create 2 migrations for this. One for the node and one for the paragraphs.

How can I iterate over the group_function/data array within my paragraphs migration?

I tried:

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  headers:
    Accept: 'application/json; charset=utf-8'
    Content-Type: 'application/json'
  urls: example.com/team.json
  item_selector: data/functions

But I get following response on a 'drush ms':
Could not retrieve source count from team_function: Passed variable is not an array or object

How would you do this?

You could also create a process plugin to create the Paragraph inline with the record you are migrating. I can't do piecemeal migrations in my case. The project has about 100,000 nodes and no data structure to 'create' Paragraphs out of. Even if I could, I don't want to have to run that dozens of times to get a full set of data.

Anyway.

Here is a real example:

<?php

namespace Drupal\mymodule_migration\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
use Drupal\paragraphs\Entity\Paragraph;

/**
 * @MigrateProcessPlugin(
 *   id = "published_author_paragraph_item",
 *   handle_multiples = TRUE
 * )
 */
class PublishedAuthorParagraphItem extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $paragraphs = [];

    foreach ($value as $item) {
      $paragraphs[] = $this->createParagraphItem($item);
    }

    return $paragraphs;
  }

  /**
   * {@inheritdoc}
   */
  public function multiple() : bool {
    return TRUE;
  }

  /**
   * Generates a paragraph item entity.
   *
   * @param array $value
   * @return array
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \Drupal\migrate\MigrateException
   */
  protected function createParagraphItem(array $value) : array {
    $paragraph = Paragraph::create([
      'type' => 'paper_authors',
      'field_paper_author' => [
        'target_id'  =>  $value['user_id'],
      ],
      'field_paper_published_name' => [
        'value'  =>  $value['name'],
      ],
      'field_paper_disclosure' => [
        'value'  =>  $value['disclosure'],
        'format' => 'basic_html',
      ],
    ]);

    $paragraph->save();

    return [
      'target_id' => $paragraph->id(),
      'target_revision_id' => $paragraph->getRevisionId(),
    ];
  }
}

In my migration definition yaml:

  _authors_shim:
    plugin: generate_authors_array
    source: author_array
  field_paper_published_authors:
    plugin: published_author_paragraph_item
    source: '@_authors_shim'

generate_authors_array is another process plugin I use to massage the data for the plugin code above. This paragraph type has a user reference, a plain text field and long text field. The passed value is an array of arrays, so this will in fact create multiple paragraph deltas for the paragraph field I am filling. It also rolls back properly.

I had tried to get this to work with sub_process at first, but could not get the paragraph field to populate at all until I went this route. I believe this is due to paragraph fields hold references to their stored entities (target_id, target_revision_id).


How to select a custom block and region according to a view I have a view / display page that needs to be displayed in a specific html - page format.
I did a html--viewname.tpl.php and page--viewname.tpl.php to display my view.

Within page--viewname.tpl.php I call print render($page['content']); to render my view.
All is working except that block.tpl.php and region.tpl.php are called by drupal system to wrap the view content adding several html tags (div)  that I don't want.

I expected to use function MYTHEME_preprocess_block(&$variables) to ask drupal to use a custom block.tpl.php file, but within this function I didn't find the way to know if the function is called to render my viewn or anything else.

When dealing with a page view you can use the views_get_page_view() function, to get the view object for the current page, like this:

/**
 * Variable preprocessor for the block template.
 */
function MYTHEME_preprocess_block(&$variables) {
  // If we are on a views page display.
  if ($view = views_get_page_view()) {
    // If we are on the MYVIEW view.
    if ($view->name == 'MYVIEW') {
      // Add the view object to the variables for use in the template (if you need it).
      $variables['view'] = $view;

      // Use a custom block template for this specific display (if required).
      $variables['theme_hook_suggestions'][] =  "block__{$view->name}";

      // Add your block customisations for this specific view (if required).

      // If we are also on the MYDISPLAY display of MYVIEW.
      if ($view->current_display == 'MYDISPLAY') {
        // Add your block customisations for this specific view and display here (if required).

        // Use a custom block template for this specific display (if required).
        $variables['theme_hook_suggestions'][] =  "block__{$view->name}__{$view->current_display}";
      }
    }
  }
}


Flood control IP bypass whitelist I am utilising Services to open up some login resources on my site and as a result if multiple users incorrectly try to sign in the entire external website will be blocked because of flood control.

Is there a way to add an IP whitelist to the flood so that there can be an unlimited number of requests from those IPs without them being blocked?

Try flood_unblock module and flood_control I think both will help you with your requirements, choose the best based on your use case.


Returning Values from Tableselect Form with AJAX Objective:

To combine AJAX Autocomplete with my Tableselect Form to create a key for users to select imported products that don't match existing products within your Drupal site. This new billing module would make it possible to use a specific 3rd party billing service.

Issue:

I am unable to get the following code to return the values inserted via the AJAX row. The array continues to send back the array keys of the row as both keys and values.
Here is what the original selection is:

And here is the returned values:

As you can see the rows selected have their array key listed as the value on return, where as the non selected row has the value 0.

Question: How do you change the return value so that it is the value that was selected on my AJAX form field?

function Test_product_form($form, &$form_state)
{
  $form_state['page_num'] = 2;

  $form['Markup'] = array(
    '#markup' => t('Please select and synchronize Test Subscription Offers with your Drupal Commerce Product SKUS below:') . '
' . '
'
  );

  foreach ($form_state['sub_offers'] as $key => $offer) {
    if ($offer['Status'] == 'Active') {
      $product = commerce_product_load_by_sku($offer['OfferCode']) ? commerce_product_load_by_sku($offer['OfferCode']) : FALSE;

      if ($product === FALSE) {
        $rows[] = array(
          'Test Subscription Offers' => array(
            'data' => $offer['OfferCode'],
            'id' => 'row' . $key . '-aso',
            'class' => 'col-aso'
          ),
          'Drupal Product SKUS' => array(
            'data' => array(
              // drupal_get_form('commerce_product_line_item_add_form'),
              '#type' => 'textfield',
              '#title' => t('Product SKU'),
              '#description' => t('Enter the SKU of the product to add to the order.'),
              '#autocomplete_path' => 'commerce_product/autocomplete/commerce_product/line_item_product_selector/product',
              '#size' => 60,
              '#maxlength' => 255,
              //In order for AJAX within the Rows of tableselect form you must declare the
              '#id' => $key . 'product_textfield'
            ),
            'id' => 'row' . $key . '-dps',
            'class' => 'col-dps'
          )
        );

      } else {
        $rows[] = array(
          'Test Subscription Offers' => array(
            'data' => $offer['OfferCode'],
            'id' => 'row' . $key . '-aso',
            'class' => 'col-aso'
          ),
          'Drupal Product SKUS' => array(
            'data' => array(
              '#type' => 'link',
              '#title' => $product->sku,
              '#href' => 'admin/commerce/products/' . $product->product_id
              // '#options' => $l_options,
              // '#suffix' => ' ' . theme('mark', array('type' => node_mark($node->nid, $node->changed))),
            ),
            'id' => 'row' . $key . '-dps',
            'class' => 'col-dps'
          )
        );
      }
    }
  }
  $hinput = array(
    'Test Subscription Offers' => 'aso',
    'Drupal Product SKUS' => 'dps'
  );

  foreach ($hinput as $hkey => $hvalue) {
    $header[$hkey] = array(
      'data' => $hkey,
      'id' => 'head-' . $hvalue,
      'class' => 'col-' . $hvalue
    );
  }

  $options = array();

  foreach ($rows as $key => $row) {
    $options[$key] = array(
      'Test Subscription Offers' => $row['Test Subscription Offers'],
      'Drupal Product SKUS' => $row['Drupal Product SKUS']
    );

  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    //'#js_select' => TRUE,
    '#multiple' => TRUE
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array(
      'Test_payment_submit_step_two'
    ),
    '#validate' => array(
      'Test_payment_validate_step_two'
    )
  );
  ddl_once($form);
  return ($form);

}

Short answer: you cannot use tableselect for submitting form elements.

Longer answer: the tableselect is for selecting one or multiple rows for further processing. You can check this through your submit handler only receiving one value for each row.

See http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#tableselect (it links to a full example on http://drupal.org/node/945102#drupal7).

If you really need a table form you could use dwillcox suggestion to use a theme function to render your form as described http://drupal.org/node/1587968

I'm not sure but have you thought about multiple forms on one page? That is each line from your tableselect attempt has it's own form. For this to work you need to implement a hook_forms(). I've used this for annotate module.

Some arguments about tableselect versus theming a form:

As table select adds radio or checkboxes it changes the complete form thus its meaning. The bad implementation of Drupal is it renders the form elements thus making the complete page looks like a form.
Theming your form is ugly as the exercise from http://drupal.org/node/1587968 shows.

Some nitpicking one your code:

mixed case function names : violation of the coding standards
mixed case array keys:  this is not expected by most coders.
swapped the key and value for $hinput which makes it hard to maintain.

Let us know what solution you took.


Help with Drupal.behaviors and AJAX refresh After a pause, I've been working on my Drupal 7 site again, and I have stumbled upon a minor problem regarding JavaScript and Ajax.

Thanks to this great website, I've learned of Drupal.behaviors, and I tried implementing my JavaScript code with it, so it shows up after an Ajax refresh within a view.

(function ($) {
Drupal.behaviors.borderfarba = {
    attach: function (context, settings) {

        var nmbr = 1;

        $(".moviescreenss",context).each(function () {

            var clrclass = "clr" + nmbr.toString();
            $(this).addClass(clrclass);
            addborder(clrclass);
            nmbr++;
        });

        function addborder(clrclass) {
            $("." + clrclass + " img").insetBorder({
            borderColor: get_random_color(),
            inset: 5
            });
        }

        function rand(min, max) {
            return parseInt(Math.random() * (max - min + 1), 10) + min;
        }

        function get_random_color() {
            var h = rand(40, 130);
            var s = rand(30, 75);
            var l = rand(40, 60);
            return 'hsl(' + h + ',' + s + '%,' + l + '%)';
        }
    }
};

})(jQuery);

I'm not that experienced with JavaScript, and I'm sure there are many possible improvements with the core code itself (e.g. the way functions are called).

What it does is add the jQuery inset border effect to every image link generated by the Views module, and color them with a random color within a specified range from reddish to green. (I somehow implemented this with a for-loop that adds a new "class+1" to each image, and the random HSL generator I found somewhere online.)

After adding the Drupal behaviors, the inset borders are still there after the AJAX action, but they are static and the hover effect is gone.

* UPDATE *
I have noticed this only happens afte clicking on a submit button. For example when using the VIEWS pager in ajax mode, the javascript applies fine

Any help would be greatly appreciated, as I'm certain it will help me understand JavaScript scripting better, besides new Drupal techniques

Well it seems I have found a solution :-)

I needed to add 'context' to the function of border adding itself

so this

 $(".moviescreenss").each(function () {

becomes this

 $(".moviescreenss",context).each(function () {

and now it seems to work fine :-)

Still need to see if I can make the whole code more efficient, I'll go to stackoverflow with this and update here if I get anything better


Why different available updates in Drush to admin/reports/updates? e.g. in the GUI, I'm told (after running admin/reports/updates/update) that I can update 10 modules. But drush rf; drush up tells me that only three updates are available. Specific example: the GUI says I can update to Views 7.x-3.3, but drush up views says "no code updates available."

I usually prefer to use drush to do the updates since I don't want to pass credentials to my server's user account over the unencrypted web!

But I don't get why drush should report update status differently? Can anyone enlighten me?

Think it was using an old (i.e. Debian Squeeze's) version of Drush. Solution:

Add backports to sources.list

#
# squeeze backports
#
deb http://backports.debian.org/debian-backports squeeze-backports main contrib non-free

Then apt-get install drush=4.5-2~bpo60+1

Your version number may vary. Check apt-cache policy drush to see what versions are available.


Views Block Doesn't Show on Views Page I have a Views Page that displays content from articles matching a particular criteria.  That views page works as expected.

I also have a views block that is supposed to pull related content from the article (think taxonomy, but I am using content types instead).  I have placed this block on all pages (no exclusions) on the right sidebar (Garland).

My content URL paths are set up as such:

example.com/section/page-name

My views page is set up as:

example.com/section

When I access the article directly via .com/section/page-name, the block shows up properly with all of the correct relevant links.  This means I have configured my relationships and context filters correctly.

When I hit my views page and render the content there, the content gets rendered, but the block never shows up. (Just for grins and giggles, I put a test block with some garbage and it shows up every time; views page and article)

I am assuming it is due to passing a filter or something in the URL, but I am just assuming and even if I was right, I have no idea how to pass that info to the block so that it gets rendered.

A point in the right direction here would be greatly appreciated!

This sounds a little like it's due to your contextual settings. Not sure if you set these based on some info you found on the net, but the settings given online can lead to your view block not rendering content because you are currently looking at that exact content to begin with.

The thought behind this is for example if you load a bunch of articles of the same content-type, that it will not list the same article in that list etc.

What you CAN try is to go into your views block (which is causing trouble) and under "advanced" set a simple "Global Text" under NO VIEW RESULTS BEHAVIOUR saying something like "Cannot load" or similar, to look if the block loads now with that message. If that is the case then the issue is more than likely in your contextual filters or in the field filter settings.


Controlling a dependent field in a multi-instance paragraph The fields below are part of the node/add node/edit forms of my custom node type.

The paragraph field_para_city contain one field_city. (I later need to add other fields in the paragraph).

The user can add multiple instances from field_para_city.

field_city has an allowed_values_function defined in a YML file, which returns all possible cities from all countries.

I created a class MyNodeTypeForm extends NodeForm, with a public function buildForm(). This function adds AJAX to field_country so that when it changes (i.e. the user chooses a country) it (re-)populates all the existing instances of field_city (inside the field_para_city instances) with corresponding list of cities (e.g., London and Cardiff for the UK).

In MY_MODULE.module, I added the following so that the above code is executed on the node/add and node/edit forms.

function MY_MODULE_entity_type_alter(array &$entity_types) {
  $handlers = $entity_types['node']->get('handlers');
  $handlers['form']['default']  = 'Drupal\MY_MODULE\Form\MyNodeTypeForm';
  $handlers['form']['edit']     = 'Drupal\MY_MODULE\Form\MyNodeTypeForm';
  $entity_types['node']->set('handlers', $handlers);
}

All works fine, except when the user add or remove instances of field_para_city ("Add city" or "Remove"), then all instances of the field_para_city are refreshed and field_city instances inside them are reset to the allowed values (all cities), ignoring the state of field_country.

The user would then need to re-select from field_country to get the correct cities again.

I found that although adding/removing a field_para_city triggered the above mentioned buildForm() function, the $form_state->getValue('field_country') was then empty, unlike when buildForm() is triggered through the field_country AJAX.

I tried to capture the state of field_country in the field_city's allowed_values_function, so that the allowed options are dynamically and directly set based on the user choice of country, but $form_state was not recognised there.

I know this is an incorrect approach!

What is the correct better approach to implement this simple use case?

I managed to make it work using a different approach; instead of overriding the NodeFrom, I used hook_field_widget_WIDGET_TYPE_form_alter and edited the subform array there.
Example:

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function MY_MODULE_field_widget_entity_reference_paragraphs_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context)
{
  //Logic to exclude other Paragraph types
  if ($element['#paragraph_type'] !== 'YOUR_PARAGRAPH_TYPE'){ //e.g. cities
    return;
  }
  $element['subform']['field_places']['#states'] = [
    'visible' => [
      [
        //It worked for me with the ID of the select, I think you can use the name also
        '#edit-field-cities-0-subform-field-city' => array('value' => 'Cairo'),
      ]
    ]
  ];
}

When I add another paragraph, the ajax is fired and the selection is still preserved.
I haven't tried with other Ajax fields present though.


Commerce, different price based on quantity Is that even possible?

I read that Drupal 7 has some discount modules for that, but Drupal 8 doesn't have anything. Is that true? And maybe someone can point me in the right direction how to achieve this goal...

I have found this post: Drupal Commerce - product attribute price based on quantity which suggests using https://www.drupal.org/project/commerce_price_table module but nothing for Drupal 8.

You can set a Promotion based on Product's quantity if that's what you're looking for. Just give a go to commerce_promotion module (included in Commerce 2.x core) and enable set conditions as on the picture below.


Theme CSS won't load in a D8 theme I'm creating a new D8 theme and am having trouble making Drupal load the CSS that is a part of my theme. I have disabled cache and am sure I'm getting the up-to-date output.

Here's my mytheme.info.yml:

name: Mytheme
type: theme
description: 'This is a description.'
core: 8.x

libraries:
  - mytheme/global-styling

libraries-override:
  system/base: false

regions:
  header: Header
  content: Content  # the content region is required
  menu_primary: 'Menu - Primary'
  menu_secondary: 'Menu - Secondary'
  footer: Footer

Here's mytheme.libraries.yml

global-styling:
  version: 1.0
  css:
    theme:
      css/global.css: {}

and this is the top of my html.html.twig file:

<!doctype html>
 <html lang="en">
 <head>
   <title>{{ head_title }}</title>
   <head-placeholder token="{{ placeholder_token|raw }}">
   <css-placeholder token="{{ placeholder_token|raw }}">
   <js-placeholder token="{{ placeholder_token|raw }}">
   {{ page.head }}
   {{ page.styles }}
   {{ page.scripts }}
</head>
...

The content in the YAML files is not tabbed, spaces are used.

I already spent several hours trying to figure out what's wrong and why the global.css is not being linked in the header of the html page, but I have no idea. I'll be gratefull for any help.

EDIT: I found out that my CSS do load when I use this:

{{ attach_library('mytheme/global-styling') }}

but I thought the point of referring to global-styling inside mytheme.info.yml was that I don't have to do that. Did I understand that correctly?

Try this. I am using this in my base theme, and it works:

global-styling:
  version: VERSION
  css:
    base:
      css/YOURCSSFILE.css: {}


Unable to create newsletters I am logged in as user/1 and have created a News content type with publishing options as "Use as simplenews newsletter". I believe all the permissions are correct.

When I try to add new content using this content type I see these at the top of the page:

Add this newsletter issue to a newsletter by selecting a newsletter from the select list. To send this newsletter issue, first save the node, then use the "Newsletter" tab.
Set default send options at Administration > Configuration > Web services > Newsletters.
Set newsletter specific options at Administration > Content > Newsletters.

Re: Add this newsletter issue to a newsletter by selecting a newsletter from the select list. To send this newsletter issue, first save the node, then use the "Newsletter" tab.
I cannot see a "select list" on my create news page.

Re: Set default send options at Administration > Configuration > Web services > Newsletters.
I have created a newsletter category called "Ad Hoc"

Re: Set newsletter specific options at Administration > Content > Newsletters.
I have selected the All newsletters option from the dropdown menu. But no newsletters are available at the bottom of the page...

I am unable to get to Configuration > Simplenews as per the readme file.

What am I missing in order to be able to create News (newsletters)?

Workflow is the following:

Create category admin/config/services/simplenews
Add newsletter node/add/simplenews (Choose category beneath body)
go to node/%/simplenews and send it


separate the page title from page content I am using {{ page.content }} to print all my page content. It is printing my all content but I want to remove title from this content and print it separately in different div structure (without using  page.content). Currently its taking drupal default structure. Is it possible?

as @Hodba Khalaf mentioned in comment Page title is a block go to admin/structure/block a block called Page title added by core

But you can render page content without specific field in twig by using without filter for example you can render page content without page title try something like:

    {{ page.content|without('bartik_page_title') }}

Note : in the example above page title block element is bartik_page_title because i use bartik theme so it could be different in your case, dump the page.content to get the key of your title page.


How to check with Rules if a new element has been added to a list in a node? I'm using the Rules module and I would like to make a rule to check wheter a new element has been added to a list in a node.

First I have tried "List Count comparison" but it can only compare a list to an integer, then I have tried with a custom php code condition but I have troubles with getting the right data. i don't understand if i'm missing something and there is a simple way or it can be done only with custom php code (in which case i'd like to know how to correctly do it, it's worth telling that the list is an entity reference)

This is the PHP code i have tried. The event is "After the update of an existing content of type Q&A", so I have $node and $node_unchanged available. The field is called field_lista_gestori and contains a list of users.

$gestoriCount=count($node->field_lista_gestori)>count($node_unchanged->field_lista_gestori);
return $gestoriCount;

But then I have discovered that field_lista_gestori just contains a number (which I think is the reference ID) and I haven't made any other attempts after this.

You're counting the wrong thing...item data is a bit further down the rabbit hole (inside the language array):

$count_new = count($node->field_lista_gestori[$node->language]);
$count_orig = count($node_unchanged->field_lista_gestori[$node->language]);


Add a custom handler method to a view? How can I add a custom handler method to a view ?

For example, i add a custom handler in hook_views_query_alter like this:

$this->view->addHandler('page_2', 'filter', 'node__field_subsidiary', 'field_subsidiary_type_value', [], 'custom_handler_subsidiary_type');

how I manage the handler logic?

Can you provide a little more information about what you are trying to do?

Regardless, you would need to create a subclass that extends views_handler_field (more info on that here https://api.drupal.org/api/views/handlers%21views_handler_field.inc/class/views_handler_field/7.x-3.x)

If you're trying to modify the output of an existing field, you would need to use a hook_views_data_alter (https://api.drupal.org/api/views/views.api.php/function/hook_views_data_alter/7.x-3.x) and change the handler specified in the $data array. Like so:

$data['table_name']['field_name']['field']['handler'] = 'hook_my_custom_handler_class_name';

This function hook should live in your module's hook.views.inc file within the 'views' folder in your module's root directory.

Your new handler class should be in a new file named the same as the class with .inc as the file type. That file should be added to your .info file using files[] = path_to_.inc_file

In your .module file, you would need to specify the views API:

function hook_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'hook') . '/views',
  );
}

If you're still struggling, I found this video tutorial very useful https://www.youtube.com/watch?v=biKxw5iEzsY

I got caught out with spelling mistakes when doing this so check all your code!


Possible to create fields without admin? Possible Duplicate:
  Assign Fields programatically to custom node defined by custom module

Is it possible to create fields in code without using admin in Drupal 7?

Yes. Since fieldable things in D7 are called "bundles", you essentially 1. create the field and 2. attach it to the bundle that uses it (could be a content type, etc.) I wrote this function to quickly create and attach fields in my module's .install file:

function _add_field_to_bundle($field_name, $cardinality, $type, $label, $entity_type, $bundle, $field_settings=array(), $instance_settings=array()) {

  $new_field = array(
    'field_name' => $field_name,
    'cardinality' => $cardinality,
    'type' => $type,
    'settings' => $field_settings,
  );
  field_create_field($new_field);

  $field_instance = array(
    'field_name' => $field_name,
    'label' => $label,
    'entity_type' => $entity_type,
    'bundle' => $bundle,
    'settings' => $instance_settings,
  );

  field_create_instance($field_instance);
}

To use this function to attach a thumbnail image field to a (node) content type:

_add_field_to_bundle('field_thumbnail', 1, 'image', 'Thumbnail', 'node', 'content_type');


Behat, Selenium and Chromedriver CI errors I am working on a Behat setup with Selenium and Chromedriver for running Behat tests for a Drupal 7 setup.

I am getting:

  exception ‘WebDriver\Exception\UnknownError’ with message 'Timed out
  waiting for driver server to start.

Above this error, i am also seeing:

  21:46:42.198 INFO [ActiveSessionFactory.apply] - Capabilities are:
  Capabilities {browser: firefox, browserName: chrome,
  ignoreZoomSetting: false, name: Behat feature suite, tags:
  [railsonfire_5e8a4d2e-8ba4-4…, PHP 5.6.34]} 21:46:42.199 INFO
  [ActiveSessionFactory.lambda$apply$11] - Matched factory
  org.openqa.selenium.remote.server.ServicedSession$Factory (provider:
  org.openqa.selenium.chrome.ChromeDriverService)
  /home/rof/src/bitbucket.org/myorganisation/myproject/chromedriver: 1:
  /home/rof/src/bitbucket.org/myorganisation/myproject/chromedriver:
  Syntax error: “(” unexpected 21:47:02.201 ERROR
  [OsProcess.checkForError] - org.apache.commons.exec.ExecuteException:
  Process exited with an error: 2 (Exit value: 2)

I am running:

java -Dwebdriver.chrome.driver=./chromedriver -jar selenium-server-standalone-3.10.0.jar 2>&1 &

to start selenium with chromedriver in my pipeline.

I am downloading and unzipping chromedriver like so:

  –2018-03-19 20:39:43--
  http://chromedriver.storage.googleapis.com/2.35/chromedriver_mac64.zip
  Resolving chromedriver.storage.googleapis.com
  (chromedriver.storage.googleapis.com)… 172.217.7.176,
  2607:f8b0:4004:80c::2010 Connecting to
  chromedriver.storage.googleapis.com
  (chromedriver.storage.googleapis.com)|172.217.7.176|:80… connected.
  HTTP request sent, awaiting response… 200 OK Length: 5508030 (5.3M)
  [application/zip] Saving to: chromedriver_mac64.zip

  100%[======================================>] 5,508,030 --.-K/s in
  0.04s

  2018-03-19 20:39:44 (120 MB/s) - chromedriver_mac64.zip saved
  [5508030/5508030]

  Archive: chromedriver_mac64.zip inflating:
  /home/rof/src/bitbucket.org/myorganisation/myproject/chromedriver

My behat.yml file used for CI

default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
     filters:
      tags: "~@wip"
  extensions:
    Behat\MinkExtension:
      goutte: ~
      javascript_session: 'selenium2'
      browser_name: 'chrome'
      selenium2:
      wd_host: 'http://127.0.0.1:4444/wd/hub'
    # Should be removed once
    https://github.com/Behat/MinkExtension/pull/311 gets into a release.
      capabilities:
        marionette: null
    # Remove STOP
    base_url: 'http://127.0.0.1:8080'
  Drupal\DrupalExtension:
    blackbox: ~
    api_driver: 'drupal'
    drupal:
      drupal_root: '${project.basedir}'
    text:
      username_field: 'Gebruikersnaam'
      password_field: 'Wachtwoord'
      log_in: 'Log in'
      log_out: 'Uitloggen'

Please ignore the ${project.basedir}, this gets replaced with the phing build target.

Ps: Also note that locally all behat tests run perfectly fine.

All suggestions welcome!

Apparently Codeship, the CI provider that I am using, had a different version of chromedriver that conflicted with my setup.
Running chromedriver 2.35 fixed the problem.

Many thanks Aswini K for the effort provided though!


How to add a class to the  link elements within a Multiple Values field in a View? I have a Views field (in this case, taxonomy term references) with Multiple Values set to "Display all values in the same row", using the Link formatter and a seperator. I want to add a class to each "multiple values"  element within this one field. My output currently looks like this:

  Some name
  ,
  Another name

I simply want to add classes to the multiple links within the field (and not the the wrapper), like this:

  Some name
  ,
  Another name

While my fields are taxonomy term references ideally I'd like to know how to do this with any of the many fields that use the "Link" formatter.

Note that this field is included with other fields using a replacement pattern in a custom text field, which unfortunately seems to prevent field tpl.php options from working.

This seems like it should be simple, but I can't find a way even after trying all these things:

Every combination of Views  Multiple Field Settings (which contain no means to add a class) and Style Settings (which only affect the field wrapper, not each of the multiple items)
Reading about twenty related questions on here, none of which combine all the elements in my question (CSS class, views, multiple value field), I couldn't find anything that actually works, and the only suggestions that sound like they might work were to use Display Suite, which is a great module but way too big an added overhead for something so minor as adding some classes to some links, or giving up, cheating and adding the class client-side in jQuery, or brute force with Views PHP. Most answers don't apply to Multiple Values fields (even when the asker specified such). This suggestion based on hook_preprocess_field looks perfect, but it doesn't get called from Views.
Hacking through the objects available in hook_preprocess_views_view_field() and hook_views_view_field__[view_name]__[view_style]__[field_name](). The former seems to treat multiple field items as a lump and not allow changes to each, the latter, when trying to do something like this, just wouldn't change anything at all
Scouring Views and Drupal Core's tpl.php files, and Views' handler for links. No changes here seemed to make any difference.
Checking the Views issue queue. I found a feature request and non-committed patch, adding the ability to set a class like this - but it only applies to multiple field items that are set to be a list item, not seperator-separated items.
I've considered creating a custom Views field formatter, but that seems like a terrible solution given that I'd simply be duplicating the existing Link formatter then adding a class. I've looked for a way to hook in to an existing formatter but haven't found one.

Just rewrite the lot with appropriate Replacement Patterns.

In Views:

Rewrite Results:

Rewrite the output of this field : Tick
Text : Add as appropriate, ie [field_link-title]
Output this field as a link : Tick
Link path : Add as appropriate, ie [field_link-url]
Link class : Add as appropriate

Above assumes your multi-value field is Link.

If any other field you can just Rewrite with output as link, link path and link class.

THERE does not seem to be a way to write the other original attributes back into the link. They can be obtained from a Replacement Pattern, but there is no form input to add them back.


SQL Error when updating to utf8mb4 I have successfuly followed the instructions on the Drupal page for updating uft8mb4 except for 1 table which is pulling up the below errror:

https://www.drupal.org/node/2754539

Error
SQL query:

ALTER TABLE `file_managed` CONVERT TO CHARACTER SET utf8mb4 COLLATE
utf8mb4_general_ci
MySQL said: Documentation

#1062 - Duplicate entry 'public://listings/4232.jpg' for key 'uri'

What do I do to be able to complete the updating?

The field uri has to be unique within the file_managed table. Apparently, in your old database (before updating to utf8mb4) this index was not created or not active and so your table got "corrupt".

Fix this by renaming the uri field of one of the records that refer to public://listings/4232.jpg to e.g. public://listings/4232_0.jpg and copying the image /sites/default/files/listings/4232.jpg to /sites/default/files/listings/4232_0.jpg (assuming that public:// refers to /sites/default/files/).

Note: just deleting one of the duplicate records will result in image/file fields pointing to no longer existing managed files, so better duplicate the file as described above.

If, afterwards, you want to get rid of those duplicate images, you can use my module duplicate images :)


How to create a field that references a Views Block display in D8? In D7, using the blockreference contrib module, you could add a field to a node (say) that allowed the user to reference a block. When viewing the page the referenced block's rendered content would be included.

This was great for including widgety stuff on a per-page basis, especially when combined with the Paragraphs module.

I have a View which defines a number of Block displays. I want to reference a particular one from a node and I'm struggling to do this in D8.

When creating the reference field, I'm offered various things under the "References" optgroup, but none include Block. I tried "References » Other..."
which seemed to be the generic entity reference that I thought would work.

Next I'm asked what type of entity to reference, which is split between content and config. I suppose this is config since a view is config, even if its config that provides content (ouch my brain). Under Config I see block. Great! I want it to reference a block.

However, after selecting that I cannot seem to reference the block created by my view - switching the form display to select list to see what is available I see all sorts of stuff (some, like "primary admin actions" apparently repeated 4 times?!) but NOT the view's blocks.

The other option that looked relevant for "which entity to reference" is View. But if I do that I just get a link to the view's edit screen.

I've since found that if I place the block in the disabled section, then I am able to reference it.

So is there a better way to reference a block or do I have to do this odd thing of create a block » place as "disabled" » reference. Alternatively, is there an explanation why having to do things this really confusing way brings an important benefit to site building that I ought to understand?

Thanks in advance.

Things are confusing because that's how entity reference works. All those things are entities, so they are technically referencable. As you found, block are actual block placements, which is not what you want. And view doesn't allow to select the display, so for your case, that's also not what you want. Drupal 8 core simply can't do that without custom code or a module (yet).

You either need a contrib module like Viewfield, but that doesn't have an official 8.x release yet. The blue box points to the contrib tracker issue, which in turn points to https://www.drupal.org/node/2220929, which has a link to a github repository where someone did an initial port. If and how well that is working already, I can't say.

An approach that would require a bit of custom code would be to have a list field with a few options ( since you don't want to allow all views anyway..), and based on that, there needs to be a bit of code that loads and calls the view and displays the results.


Include Json file into Twig template I'm trying to run this library ParticleJS which requires me to download a Json.

I added this file into theme/libraries.yml this way:

global-js:
  js:
    assets/js/particles.min.js : {}
    assets/js/particles.json : {}

But that gives me this error:

  Refused to execute script from
  'https://www.example.com/themes/nexus/assets/js/particles.json?pem8cm'
  because its MIME type ('application/json') is not executable, and
  strict MIME type checking is enabled.

So I'm added:

<script src="themes/nexus/assets/js/particles.json"></script>

And it is giving me the same error.

Can someone help me with this problem, please? How should I include any other file into twig templates? Thank you

You need use hook_page_attachments_alter

function mytheme_page_attachments_alter(&$attachments){
  $attachments['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // set attributes like src to load a file
      '#attributes' => array('src' => '/themes/mytheme/assests/js/particles.json'),

    ]
  ];

}


Restrict User Role from Unpublishing Content I'm attempting to restrict a certain role from being able to unpublish content of a certain content type but I can't get it to work correctly. They need to be able to publish but not unpublish this content.

If "Administer Content" is checked they seem to be given permission to publish/unpublish any content types. If it's unchecked and I attempt to defer to the individual publish/unpublish permissions for that content type they lose the option to use the "Publish" checkbox when editing nodes of that type.

Am I missing something or doing something wrong?


How to export the config files of a content type to a module? I have a custom module. I created a content type and added some fields to that content type. I also enabled the layout builder on the manage display of the content type

Then I run drush -y cex to export the config files.

Then I copy all the config files related to my content type to the module's config/install director

Now if I make some changes to content type, their config files should be added/updated/exported in/to the module's config/install directory and should not be added to the site's default sync directory.

Is this possible?

You can do exactly this with the Features module.

  Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it contains additional information in its info file so that configuration can be checked, updated, or reverted programmatically.

While ignoring the related config from configuration management with Config Ignore at the same time. Which also takes wildcards so you don't have to enter every single config object by hand.


How do I theme the secondary menu? The following code allows me to print the secondary menu.

<?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => 'menu nav navbar-nav secondary hidden-xs'))); ?>

I get the following output.

link 1

link 2

link 3

Now, I need to add dropdown to the last menu item but I have no idea how to do it. Any guidance much appreciated!

You can theme secondary menu using THEME_links__system_secondary_menu like the following:

function THEME_links__system_secondary_menu(&$vars) {
  // Get links:
  $links = $vars['links'];
  // Get the index of last menu item.
  end($links);
  $last_ele_index = key($links);
  // Here do your logic by change ...
  // $vars['links']['$last_ele_index'];
}


Disable ajax history except for some views I use Views Ajax history so that customers keep track of a search when they navigate from a view with exposed filters to a product, and then back to the view.

But in other parts on the website, this generates unwanted things, such as node?page=1 / node?page=2 and so on at homepage, whenever using pagers of blocks views.

I performed a huge SEO audit, where these paths are pointed as undesirable, also when you go back with browser buttons it can take 10 clicks before you reach precedent page, not very UX friendly.

But after thinking about it, I really don't know how I could limit ajax history to my products views. Any suggestion welcome !

My bad, Views_ajax_history is such a minimalist module in fact !

To avoid hacking it, hook_js_alter did the trick :

/**
 * Implements hook_js_alter().
 */
function example_js_alter(&$javascript) {

  if(arg(0)!='taxonomy' ) {//my products views are taxonomy lists

    $history_js = libraries_get_path('history.js') . '/scripts/bundled/html4+html5/jquery.history.js';
    $views_ajax_history = drupal_get_path('module', 'views_ajax_history') . '/views_ajax_history.js';
    $views_ajax_history_2 = array('viewsAjaxHistory' => array('onloadPageItem' => isset($_GET['page']) ? $_GET['page'] : 0));

    unset($javascript[$history_js]);
    unset($javascript[$views_ajax_history]);
    unset($javascript[$views_ajax_history_2]);

  }
}


Override comment.tpl.php file with theme Objective:
Override comment.tpl.php file output in drupal core modules.

Assumption:
My best guess is that I need to create a comment-[type].tpl.php file in my themes folder.

Requirements:

template.php can not be used
need to replace default comment.tpl.php html output

Questions:

how do i find the so called type of the comment for the tpl file?
is this the best way to change the html output of the file?
is there another way to change the output with the type or using template.php?

Links: http://drupal.org/node/190815

You should be able to override Drupal's default comment.tpl.php file by copying it from /modules/comment into your theme directory. From there, edit the file as needed. Then clear the cache (on the Admin > Site configuration > Performance), so that the theme cache will get rebuilt and your new theme file will get recognized.

You would only need to rename comment.tpl.php to comment-[type].tpl.php, if you wanted to override comment theming differently for different node types.


Field Collection Value field is not deleting correctly(using programmatically) I have installed a field collection module in my D7 site.
There is a multifield(unlimited) field collection with 3 field collection items.
I need to delete the field collection programatically.

i use

$field_collection_delete = $node->field_accommodation['und'][$j]['value']  ;
entity_delete_multiple('field_collection_item', array($field_collection_delete));

$j is a for loop increment value(0,1,2...) to remove field collection

but when i run the code the value in the field collection item deleted(deleted from the db table) but
the field collection field i added in the content type is still in the database as none value.

I need to delete that too programmatically.

You need to unset the field from node first!

unset($node->field_accommodation['und'][$j]);


Grabbing $_POST data Background

A quick summary of where I stand right now:

We have a low traffic site here that was redone in Drupal about 8 months ago, before I was in the picture. An external design firm sold the owners on the technology as a way to enable non-programmers to update site content easily. Unfortunately, they did it wrong - they built our theme in-place over the Bartik theme instead of subclassing it, things like login boxes are written directly in the Basic Page Body textareas that our non-programmers are supposed to be updating, on and on and on beyond what's relevant to this post. Had I been here when it was forked over, I'm not even sure I would have taken delivery.

I've been meaning to pick up Drupal one of these days to go in and try to refactor this hot mess, but the non-Drupal work that actually keeps us all employed around here has prevented that.

Fast forward to now. I've got a feature request for the Drupal site that they want ASAP. It's a very simple application. Given the rush, I decided to develop the application as a straight PHP app to monkey patch onto the Drupal site. Based on some forms I had to maintain within the Drupal frontend (not using webforms, mind you) that I am able to $_POST back to some non-Drupal PHP with, I thought I could get away with this.

Now as I am trying to integrate my super vanilla PHP code into our Drupal environment I am running into all sorts of problems. At first my $_SESSION array wasn't persisting from page to page but I was able to figure that part out on my own by googling.

TL;DR: The question

Where I am stumped is with my $_POST array. I POST form data (an honest to God, completely naive HTML form) from one non-Drupal .php file to another non-Drupal .php file and it never arrives. The right way to do this - and the way it will get redone someday - is clearly to use the provided Drupal APIs for building forms.

Unfortunately, I am in such a position that there is absolutely, positively no time to rewrite this the right way today. With that in mind, is there a way to pass this POST data directly to the php file I am using for form processing?

EDIT:

It looks like maybe I am getting redirected internally and the data is not coming along for the ride. Could this be it? If so, it looks like Forms specified using the API Drupal provides can do something like :

$form['# redirect'] = false;

to prevent their being redirected. Is there some perhaps hidden input field I could pass in with my non-Drupal forms to accomplish the same thing?

To tackle your exact question, let me first tell you that what happens in the form is the correct thing.

When you submit the form, it takes data, validates it and calls appropriate submit handlers to take care if the rest.
The form, once its routing is completed, does a 302 redirect to the same location so a browser F5 hit does not resubmit data.
It's a general practice to avoid double submissions.

You will need to make a module that alters the form using hook_form_alter and alter the form.

You can change form's action URL to the other PHP file or add an extra submit handler that posts data to the other raw php file using drupal_http_request.

You will find sanitized and structures data in $form_state['values'] (second param of a submit handler is usually called $form_state).
$_POST is also available at this stage.


Migrating a huge live drupal 6 site to drupal 7 Server I am having a drupal 6 based news site with almost 600 thousand nodes. We are currently building a new site on drupal7.

What are the ways to migrate the content from old to new?
What are the best practices?
What are the know issues?
Can data be migrated in chunks?

I did alot of reading online, didn't find anything to give me confidence. Hopefully there will be people here who have hands on experience in this.

This topic is already well covered in the Drupal documentation.


Allowed Values in Drupal I am using Drupal-6. I Created CCK Field with Select Box with content type name as list_porducts.

i am  fetching products from external url . Here is my code

$key=array();
$flowervalue=array();
for($i=2;$i<=150; $i++) {
        $url="http://testurl.com/test/node/".$i.".jsonp";
        $timeout=0;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        $data = curl_exec($ch);
        $jdata=json_decode($data);

            if($jdata->type=='product') {
                $key[]=$jdata->nid;
                $flowervalue[]=$jdata->title." ".$jdata->field_petals_code[0]->value;

            }

}
$res=array_combine($key, $flowervalue);
return $res;

which is running properly. Now Problem is this is Quite slow. and i guess it is running for all page load.

Any Idea how to do this.

Thanks

Store the result into a session like below

function get_all_products() {
  $prod = get_products();
}

function get_products($reset = FALSE) {
  $res = $_SESSION['products'];
  if(empty($res) || $reset) {
    $key=array();
    $flowervalue=array();
    for($i=2;$i<=150; $i++) {
            $url="http://testurl.com/test/node/".$i.".jsonp";
            $timeout=0;
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
            $data = curl_exec($ch);
            $jdata=json_decode($data);

                if($jdata->type=='product') {
                    $key[]=$jdata->nid;
                    $flowervalue[]=$jdata->title." ".$jdata->field_petals_code[0]->value;

                }

    }
    $res=array_combine($key, $flowervalue);
    $_SESSION['products'] = $res;
  }
  return $res;
}

Else if you want cache the  $url="http://testurl.com/test/node/".$i.".jsonp" enable the page caching in drupal.


How to re-create a notifications 'inbox' similar to the one here at stackexchange? I'm looking for a simple way to let users know when new content (comments mainly) has been submitted to nodes they published or commented on and groups they are members of.
Is it possible to groupe that new content within a view ?
The ideal scenario would be to have something that works like stackexchange's inbox in the upper left side of the nav bar with the badge showing the number of new notifications.

I'm using drupal 7 with basic content types and organic groups 7.x-2.9

Any suggestions are welcome.

You could use the Menu Badges module for such notifications, which you can add to any menu item and/or menu tab of your choice. In your case something like "New comments" seems like one, out of a few, appropriate menu item (or menu tab).

Here are some details about it (from its project page):

  Provides a method for adding iOS-style badges to menu items. (see screenshot)

  Adding Badges to Menus

  Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.

  Adding Badges to Tabs

  For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.

  Badge Types

  The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, by using this integration you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

However, there is a small caveat: if you really want the actual number (shown in the red circle) to be accurate, make sure you have some field in your view that will actually correspond to the "new" part of your question. To better explain this: have a look at the "tracker" view (disabled by default), which has the field "Content:Has new content" (or variation: "Content:Has new comments"). This is a perfect field to use if you want to use Menu Badges to get notified whenever there is new content (or variation: new comments).

If you don't have such "new" indicator, then you basically have 2 variations to get around that:

You give the user the option to selectively mark those entries so that they are no longer included in the counter. It takes a little effort to implement such option, but the tutorial about "How to allow users to manage their own Message Stack messages?" explains how to use the Flag, Rules and VBO modules to get it to work.
When the user visits the menu link (or menu tab), you "mark" all of the entries included in the Menu Badges counter as "no longer new". That should make the counter disappear entirely. The anser to "How to make menu badges count disappear after the page is viewed?" details the steps how this can be implemented.

Video tutorials:

Defining Menu Badges with Views in Drupal, from the module maintainer, which shows how to use it for a custom view with a menu tab "unpublished content" within admin/content.
Drupal 7 Menu Badges Module.


What to do when Drupal views module doesn't output what you want? When a user search for a word the view should output its translation and any other vocabs that might be similar to it ( using Taxonomy terms ).

This works as the following:

The similar vocabs are actually another view that I pass ( Taxonomy ids ) to its URL as a contextual filter and it outputs all words that has the same Taxonomy term or terms. This view a lone by it self works fine when you pass Taxonomy terms manually. It doesn't produce any duplicates since I handled that by choosing 'Query settings: DISTINCT' and using aggregation.

However when I combine it with the other view and pass the Taxonomy terms using the Views UI it produce duplicates.

What should I do? Is there a way to write the view code manually or something like that?

Is there a way to write the view code manually or something like that?

You could easily setup a menu route and controller (or page callback in D7) to serve the same purpose. The controller would execute the query (provided by you) and return the results / page output as a renderable array.

However, there are many variables in between, so it would be hard to provide all the code.

Here is a walkthrough for D7 to starting to code your own route and callback: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x

Here is one for D8:
https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

It would be a good opportunity to learn how to extend Drupal and 'take control' when you don't get the result you want with Views, or, just to have more control in general.


Compute price based on order item fields Is it possible to get the order items fields in a price resolver using Drupal 8 and Commerce 2.x?

Indeed, the resolve method in a price resolver only allow to access the purchased entity, quantity and context.

public function resolve(PurchasableEntityInterface $entity, $quantity, Context $contex) {}

I would like to:

Define some custom fields in an "Order Item Type" (In my case the fields are dates.)
Expose those fields in the add-to-cart form
Define product variation and product that uses that custom order item type, to have my custom add-to-cart form
Compute the purchased product price (in a custom Price resolver) according to field values provided in the add-to-cart form

I could use product attributes to achieve that, but unfortunately the values entered in the order item fields are not finite.

Notes

This looks similar to  https://www.drupal.org/project/commerce/issues/2836221, but I additionally need the entered field values to compute the final price
The answer in Update commerce price field with another custom field in Drupal 8 does not apply because I cannot define a finite set of values and create variations

How do I implement this in Commerce 2.x? Did I misunderstand something?

thanks in advance

The short answer: No

Why:

In the Drupal Commerce Slack Channel, I asked whether it would be possible to add Order Item to the Context class. This was the response:

  price resolvers are also called by regular price formatters the whole
  point of the context is to provide known information when the order
  item is missing

  so changing that would be a big API change if you need order item
  data, for now use an order processor instead

How to solve the issue:

Replace YOURMODULE with the name of your custom module.  The Priority value is used to prioritize what order processors get called first.  You need to look at other order processors and figure out when yours should be called and set the priority value appropriately.

In YOURMODULE.services.yml

services:
    YOURMODULE.order_processor:
    class: Drupal\YOURMODULE\OrderProcessor
    arguments: []
    tags:
      - { name: commerce_order.order_processor, priority: 110 }

In YOURMODULE\src\OrderProcessor.php

<?php

namespace Drupal\YOURMODULE;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\Entity\OrderItemInterface;
use Drupal\commerce_order\OrderProcessorInterface;

class OrderProcessor implements OrderProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function process(OrderInterface $order) {
    $order_items = $order->getItems();
    foreach ($order_items as $order_item) {
      if ($order_item->bundle() == 'YOURCUSTOMBUNDLE') {
        // YOUR LOGIC TO FIGURE OUT $calculated_price
        $price = new Price($calculated_price, $currency)
        // Set to TRUE if you want to override unit price.
        $order_item->setUnitPrice($price, FALSE);
      }
    }
  }

Hope this helps!


Drupal 8: how to generate options based on Ajax callback In Drupal 8, I want to generate options of second select-box based on Ajax call of first select-box. The result generate a third new select box but I don't need to generate a new one. I want to replace the options of the second select-box. Please see my codes below:

public function buildForm(array $form, FormStateInterface $form_state) {
$form['example_select'] = [
  '#type' => 'select',
  '#title' => $this->t('Select element'),
  'wrapper' => 'first',
  '#options' => [
    '1' => $this->t('One'),
    '2' => $this->t('Two'),
    '3' => $this->t('Three'),
    '4' => $this->t('From New York to Ger-ma-ny!'),
  ],
  '#ajax' => [
    'callback' => '::myAjaxCallback',
    'disable-refocus' => FALSE,
    'event' => 'change',
    'wrapper' => 'edit-output',
    'progress' => [
      'type' => 'throbber',
      'message' => $this->t('Verifying entry...'),
    ],
  ]
];

$form['example_select2'] = [
  '#type' => 'select',
  '#title' => $this->t('Select element'),
  '#prefix' => '
',
  '#suffix' => '
',
  '#options' => [
  ],
  '#ajax' => [
    'callback' => '::myAjaxCallback2',
    'disable-refocus' => FALSE,
    'event' => 'change',
    'wrapper' => 'edit-output',
    'progress' => [
      'type' => 'throbber',
      'message' => $this->t('Verifying entry...'),
    ],
  ]
];
return $form;
}

public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  if ($selectedValue = $form_state->getValue('example_select')) {
    $arr = array('1' => 'Nice way', '2' => 'Good way');
    $form['example_select2']['#options'] = $arr;
  }
  return $form['example_select2'];
}

The below code is working well forme.

public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  if ($selectedValue = $form_state->getValue('example_select')) {
    $arr = array('1' => 'Nice way', '2' => 'Good way');
    $form['example_select2']['#options'] = $arr;
  }
  $form_state->setRebuild(TRUE);
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand("#first", ($form['example_select2'])));
  return $response;
}


How to save the webform data to custom table? I designed a student registration form using webforms module. My requirement is to save data from the form to table student. How can i achieve this? Is there anyway to mention this in configuration file?

You can add custom submit handler to your Webform through hook_form_alter for inserting it's data into your custom table.

To achieve it check the below example.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;

function MODULE_NAME_form_alter(&$form, $form_state, $form_id){
  if($form['#form_id'] == "YOUR_WEBFORM"){
    $form['actions']['submit']['#submit'][] = 'YOUR_CUSTOM_FUNCTION';
  }
}

function YOUR_CUSTOM_FUNCTION(&$form, $form_state){
  $query = Database::getConnection();
  $query->insert('YOUR_CUSTOM_TABLE_NAME')->fields(
    array(
      'FIELD_NAME_IN_TABLE' => $form_state->getValue('FIELD_NAME_IN_FORM'),
    )
  )->execute();
}


What is the mechanism behind class comments? * @QueueWorker(
 *   id = "my_module_image_style",
 *   title = @Translation("Generate image styles"),
 *   cron = {"time" = 60}
 * )

And more specifically what is the effect of

 cron = {"time" = 60}

The class comments are Annotations :
What is Annotation mean ?

In general according to techopedia.com

  Annotation is a term used in computer programming to refer to documentation and comments that may be found on code logic. Annotation is typically ignored once the code is executed or compiled.

In Drupal According to Annotations doc page:

  Annotations for class discovery and metadata description.
  The Drupal plugin system has a set of reusable components that developers can use, override, and extend in their modules. Most of the plugins use annotations, which let classes register themselves as plugins and describe their metadata. (Annotations can also be used for other purposes, though at the moment, Drupal only uses them for the plugin system.)

A lot of frameworks use annotations too like symfony use it in many contexts like creating routes using annotations here.

For the annotation example you put in your question is for QueueWorker plugin:

cron = {"time" = 60}

the definition of cron property QueueWorker::$cron according to QueueWorker::$cron it mean:

  time: (optional) How much time Drupal cron should spend on calling this worker in seconds. Defaults to 15.


how to migrate multiple taxonomy terms with entity lookup plugin Im using the code below to migrate a taxonomy term with multiple values and I get this error below.  is there a way to migrate multiple taxonomy terms with this plugin? :

InvalidArgumentException: Placeholders must have a trailing [] if they
are to be expanded with an array of values. in              [error]
/var/www/html/docroot/core/lib/Drupal/Core/Database/Connection.php:744

field_states_operating_in:
    - plugin: entity_lookup
      source: field_states_operating_in
      entity_type: taxonomy_term
      value_key: name
      bundle_key: vid
      bundle: states_operating

The field that you're migrating has multiple values and you're trying to run entity_lookup as though it has only one. I think you just need to make sure you're iterating over the values with the sub_process plugin.
Using this issue post as a reference, along with the docs for entity_lookup:
field_farbzuordnung:
    plugin: sub_process
    source: field_farbe
    process:
        target_id:
        plugin: entity_generate
        source: value
        value_key: name
        bundle_key: vid
        bundle: alle_farben
        entity_type: taxonomy_term
        ignore_case: true

...I think you'd want to do something like
field_states_operating_in:
    -
      plugin: sub_process
      source: field_states_operating_in
      process:
        target_id:
          plugin: entity_lookup
          source: target_id
          entity_type: taxonomy_term
          bundle: states_operating
          bundle_key: vid
          value_key: target_id

I'm not entirely sure that the source and value_key are correct but I think this should get you most of the way there.


Having trouble understanding private files in Drupal 7 I'm trying to set up private files on Drupal 7 using Organic Groups. So far, I have

(1) one group type that although I appear to have set it up as such

(2) have private files set up in as below. (The webroot is /var/www/html.)

(3) Ensured the link on the OG's page is /system/files/test.example.doc,

(4) I inspected the database entry and this appears to be good.

MariaDB [s7data]> select * from file_managed \G

*************************** XXX. row ***************************
      fid: 357
      uid: 103
 filename: test.pwww_.doc
      uri: private://test.pwww_.doc
 filemime: application/msword
 filesize: 9
   status: 1
timestamp: 1460390385
     uuid: 3a9877fc-77b2-47bc-8d4f-e8bc349f4c74

I am still able, using this link path do download that doc in a new browser without being logged in. In effect, this file is not private and does not require an authenticated session to download.

Question: Did I miss something? How does one set up private files correctly on Drupal 7?

Whenever possible it's recommended that you choose a directory located
  outside of your Drupal root folder (or actually outside your web
  root), which may be tricky if you are on a shared host. If you do have
  access though, you can choose a private directory which will be on the
  same level as your web root directory (often called public_html or www
  or similar).

From Working with files in Drupal 7 and Drupal 8.

The best practice is to place your private files outside of your webroot, so they should not be inside /var/www as that would make them accessible over the web. Place them in /var/somefolder instead, make sure your webserver has read write access to that folder. After that you should only be able to access them via /system/files/test.example.doc and it should not work for anonymous users.

UPDATE:

Above is based on the assumption you were accessing the file via example.com/drupal-private-file-system/test.example.doc. this can be prevented by using the linked best practise guide.

If an anonymous user can access your files with on url like example.com/system/files/test.example.doc you have a problem with your permissions and anonymous users are given the permission to download private files.


Adding javascript to admin view and user view I have a form with a text plain long description field. Added Javascript to limit the amount of characters allowed in the field.

(function($){
    $("#edit-field-busines-0-value").attr('maxlength','500');
})(jQuery);

It works for the Authenticated users view, but not for the Admin users view? How can I have this work on the Admin view also?

Is it possible that this library is being pulled in by your public theme, but not by your admin theme? Authenticated users probably are maybe not seeing the edit from in the context of your admin theme, like admins are. If so, add the library to your admin theme too (you can create a sub-theme of Seven and add it there).


User gets first x units of a product free, then has to pay per unit thereafter I am wondering if anyone can point me in the right direction. There is only a single product type on my site, however I want every user to get 1000 "point" credit every month. They can buy 1 product for each credit.

I am assuming some kind of checkout system is also necessary, but the payments only have to be through paypal or something similar.

any suggestions?

You will probably want to look at the Userpoints API (http://drupal.org/documentation/modules/userpoints) and possibly utilized Rules in conjunction with an eCommerce solution like UberCart.

Or, if you don't need to actually take payment in money at all, there is a Userpoints Contrib module for facilitating points in conjunction with downloads.

userpoints-download
Users lose or gain points when the download attachments (requires site to be configured with private download method).


How to disallow users with a username containing test to login? I created a module but I'm looking to have this module to intercept a user log in. I want to prevent any users with "test" in their login name from using the site. Is there a way to do this?

Custom username validation would be an option

  allows to define a validation pattern for the username on registration. it's also possible to customize the error message on validation failure.


How to group fields in views Newbie here!

I have created a view with some fields and i want to group some of the fields in one wrapper and remaining in another wrapper and also want to change the structure i.e. adding own wrappers and classes.

Thanks.

To add and then group fields in views, you can do the following (if not using a view mode/template).

Add all the fields you need, and mark each of them "Exclude from display".

Add another field of type 'Custom text'. DO NOT exclude this one.

Click on the 'Custom text' field to open its options.
Inside the textarea there, you can input custom html using the tokens from the fields above to populate it. You can find the values you'll need for replacement if you click on the "Replacement patterns" dropdown just below the textarea.


How to output multiple files url entities on twig? I have a file entity field that I can upload multiple files and I'm trying to render or display it inside my node twig template. The code below is what I'm trying to make it display. Tried clearing my cache but it still shows empty.

I can display the url/uri of a single file upload but I can't seem to figure out how I can display multiple upload files url/uri in the loop.

Single file here:

Download File

Multiple files Here:

{% for key,value in node.field_upload_file.value %}
  Download File
{% endfor %}

Is this a way to display multiple upload files url/uri in the loop? Please suggest to me.

You can try to loop over the field items:

{% for item in node.field_upload_file %}
  Download File
{% endfor %}


How to remove old revisions product? How to remove old revisions product? I have a lot of old revisions of products. They must be removed. How?

Drupal Commerce does not provide a UI nor function for this actually. However, we can look at how the Node module does it and run the same function, just adjusted.

From node.pages.inc, there is a function to delete a specific Node revision.

But that is only for a specific revision ID. Here's an adjusted function that loads a products revisions and purges them.

/**
 * Deletes a node revision.
 *
 * @param $revision_id
 *   The revision ID to delete.
 *
 * @return bool
 *   True on success, false if not.
 */
function commerce_product_revision_delete($revision_id) {
  if ($revision = entity_load('commerce_product', NULL, array('revision_id' => $revision_id))) {
    $revision = reset($revision);
    // Prevent deleting the current revision.
    $commerce_product = commerce_product_load($revision->product_id);
    if ($revision_id == $commerce_product->revision_id) {
      return FALSE;
    }

    db_delete('commerce_product_revision')
      ->condition('product_id', $revision->product_id)
      ->condition('revision_id', $revision->revision_id)
      ->execute();
    field_attach_delete_revision('commerce_product', $revision);
    return TRUE;
  }
  return FALSE;
}

Basically the trick is ensuring you load the revision and then delete it's record and invoke field_attach_delete_revision so the old field data gets purged.

I created an issue in the queue for this: https://www.drupal.org/node/2660056


Can you bulk enable comments? I have a whole bunch of nodes (all the same type), and I'd like to turn comments on for all of them (the client changed their mind about commenting after all of the data was added).

I've found notes that suggest that if I do something like:

update node set comment = 2 where type = 'foo'

then it should turn commenting on for all the nodes of type foo. However, this doesn't seem to work in Drupal 7, and the notes on drupal's site only specify 5 and 6.

I tried flushing caches and bouncing apache after making the change, and still can't see comments coming back on. Did this change in Drupal 7?

I'd also recommend Views Bulk Operations. You could create a view with a filter of that content type and add enable comments as an action. Then it offers you to select all.

Quite the useful admin tool.


Selecting from a column in a joined table in Views I've got two tables: {students} and {student_names}. Students is the base table, with a primary key of {students}.sid. Student names is the joined table, and has a key of {student_names}.sid.

I've defined my join in hook_views_data:

$data['students']['table']['join']['student_names'] = [
  'left_field' => 'sid',
  'field' => 'sid',
];

I want to select the given name of the student from the joined table. I've defined the field as follows (again in hook_views_data()):

$data['students']['given_name'] = [
  'title' => t('Given name'),
  'help' => t('The given (first) name of the student'),
  'field' => [
    'handler' => 'views_handler_field',
 　　'click sortable' => TRUE,
  ],
  'sort' => [
    'handler' => 'views_handler_sort',
  ],
  'filter' => [
    'handler' => 'views_handler_filter_string',
  ],
  'relationship' => [
    'base' => 'student_names',
    'field' => 'sid',
    'handler' => 'views_handler_relationship',
  ],
];

I'm getting this error:

  Column not found: 1054 Unknown column 'students.given_name' in 'field list'

How can I tell views that the column is in the {student_names} table and not the {students} table?

I solved my own issue.

I needed to expose the joined table to views as well. So on top of setting up $data['students'], I also needed to set up $data['student_names'], with a join back to the original table. Here is my hook_views_data() in its entirity:

$data['student_names']['table'] = [
  'group' => t('Student'),
  'base' => [
    'field' => 'sid',
    'title' => t('Student'),
  ],
  'join' => [
    'students' => [
      'left_field' => 'sid',
      'field' => 'sid',
      'type' => 'inner',
    ],
  ],
];

$data['student_names']['given_name'] = [
  'title' => t('Given name'),
  'help' => t('The given (first) name of the student'),
  'field' => [
    'handler' => 'views_handler_field',
    'click sortable' => TRUE,
  ],
];

return $data;


Duplicate Results Using Views, loosing results using (File) File: Content using Thumbnail image I’ve got a “views” question. I have a view that is using File Usage: File under advanced > relationships and (File) File: Content using Thumbnail image. In that later relationship, (File) File: Content using Thumbnail image , when require the relationship is checked, I loose nodes that don’t have thumbnail images, when it’s not checked, I get duplicates (the content type holds a thumbnail and a header image and for some reason it returns a result with the thumbnail and a duplicate result with the header image instead of the thumbnail) - Anyone got any idea how I can get both the ones with the images and without, and not have duplicates?

I tried Other > Use aggregation and Query Settings > Distinct (and pure distinct) and didn’t have any luck either

Why you don't get in the view the field that has the image and display it as thumb("image style").
That "Content using Thumbnail image" i guess it load every image with an "preview" from the respective node.


How to highlight views result? I have a view that shows me a list of images on the front page. Each of those images has its category. Now i need to add exposed filter with categories that allow users to choose images by categories. BUT I want to show all images and just to highlight (by adding CSS class for example) the exposed filter results. Is it a way to do it?

I'm using Drupal 7.

You will need jQuery to make this work but it shouldn't be too complicated. Basically the exposed filter acts as the degraded (non-javascript) version as well as giving you all the possible category options.

$('.views-exposed-form .views-submit-button input').hide();
$('.views-exposed-form select').change(function(event) {
  // Clear previous highlights
  $('.highlight').removeClass('highlight');

  // Get the selected category
  var selectedCategory = $(this).find('option:selected').text();

  // Use the category name to find items on the page
  $('.views-field-term-node-tid .field-content a:contains(' + selectedCategory + ')').parents('.views-row').addClass('highlight');
});

I made this example with a view with fields and the "Content: All taxonomy terms (All taxonomy terms)" field limited by taxonomy. If you use a different method of creating the view you will want to change .views-field-term-node-tid .field-content and probably also the .parents('.views-row') which is what gets highlighted.

You'll also probably want an additional selector in front of all the .views-exposed-form selectors in case you add more exposed forms to you sight such as $('.my-view .views-exposed-form')...

I also made this to trigger on the select change, but you could do it when clicking the Apply button (which you would obviously not want to hide then).

If you exposed filter is a multiple select you can add an each() to the end of $(this).find('option:selected') and loop through getting the text and setting the highlight.


How can I use a media field in a custom form? I tried something below, which is not working in drupal 8.

$form['upload_documents'] = [
  '#type'          => 'media',
  '#tree'          => TRUE,
  '#title'         => t('Upload your documents'),
  '#default_value' => ['fid' => $default_value],
  '#media_options' => [
    'global' => [
      'file_extensions' => 'pdf doc docx',
      'types'           => ['document'],
    ],
  ],
  '#attached'      => [],
  '#extended'      => TRUE,
  '#required'      => TRUE,
];

I found the answer to create the media autocomplete field like below.

// $id is your media ID.
$media = \Drupal\media_entity\Entity\Media::load($id);

$form['upload_doc'] = [
  '#type'          => 'entity_autocomplete',
  '#target_type'   => 'media',
  '#default_value' => $media,
];


Add Location CCK field and instance programmatically to content type in Drupal 7 How does one add a Location CCK field and instance programmatically to a content type in a Drupal 7 module install? I am mainly concerned with what params need to be given to the field_create_field and field_create_instance functions, assuming it is created in the same way as core fields? I've put some examples of the params I give to these functions in creating core fields (in case this helps):

An example of the params given to field_create_field:

'field_property_price' => [
    'field_name' => 'field_property_price',
    'label' => $t('Price'),
    'cardinality' => 1,
    'type' => 'text',
    'module' => 'text',
    'length' => '20'
];

An example of the params given to field_create_instance:

'field_property_price' => [
    'field_name' => 'field_property_price',
    'label' => $t('Price'),
    'cardinality' => 1,
    'required' => true,
    'widget' => [
        'weight' => '0',
        'type' => 'text_textfield',
        'module' => 'text',
        'active' => 1,
        'settings' => [
            'size' => '20',
        ],
    ],
],

Thanks for reading.

Never mind I figured it out. The following params work (note that the entity type and bundle params are also needed, but for my own usage I add these later).

For field_create_field:

'field_property_location' => [
    'field_name' => 'field_property_location',
    'label' => $t('Location'),
    'type' => 'location',
    'module' => 'location_cck',
    'settings' => [
        'location_settings' => [
            'form' => [
                'fields' => [
                    'name' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 1,
                    ],
                    'street' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 2,
                    ],
                    'additional' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 3,
                    ],
                    'city' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 4,
                    ],
                    'province' => [
                        'collect' => 1,
                        'widget' => 'autocomplete',
                        'default' => '',
                        'weight' => 5,
                    ],
                    'postal_code' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 6,
                    ],
                    'country' => [
                        'collect' => 1,
                        'default' => 'gb',
                        'weight' => 7,
                    ],
                    'locpick' => [
                        'collect' => 0,
                        'weight' => 20,
                    ],
                ]
            ],
        ]
    ],
],

For field_create_instance:

'field_property_location' => [
    'field_name' => 'field_property_location',
    'label' => $t('Location'),
    'required' => true,
    'widget' => [
        'weight' => '0',
        'type' => 'location',
        'module' => 'location_cck',
        'active' => 1,
    ],
     display' => [
        'default' => [
            'label' => 'above',
            'type' => 'location_default',
            'weight' => 0,
        ],
    ],
],

There are more params you can fiddle with but these are the ones that suited my needs. To figure the params (and to figure out params for other fields like this in future), first add the fields manually to the content type with the desired settings in the Drupal backend. Then in the command line go to the projects root directory and used drush eval "print_r(field_info_fields())" to see all the fields added and drush eval "print_r(field_info_instances())" to see all the field instances added.

Mirror the data and structure from the print out to use in the field_create_field and field_create_instance functions as I've done above.


How do I update a Drupal distribution to a newer version? I am looking at using http://drupal.org/project/commons , but I am not sure how easy it is to update a distribution when a new version comes out.

Also, can I use drush to do it, or do I have to manually download and unpack the distribution?

With drush for commons 7.x you can do:

drush up drupal -y
drush dl commons -y
drush updatedb -y


I'm new to object oriented php. Trying to query database but not getting any results I am trying to query a table in my DB and am not able to get any results back.  Here is the code I am using:

function get_agent_info($agent) {
        $query = db_query("SELECT * FROM tls_connect_stage_timer WHERE '".$agent."' IN ('start_processing_agent' || 'end_processing_agent')");
        $rows = array();
        foreach ($query as $result) {
            $rows[] = array(
                $result     -> applicant_id,
                $result     -> stage,
                $result     -> event_start,
                $result -> event_end,
                $result     -> start_processing_agent,
                $result     -> end_processing_agent,
                $result     -> start_request_ip,
                $result     -> end_request_ip,
                $result     -> gwf,
            );
        }
        print_r($rows);

    }

I have already used a method like this to get info:

$results = db_query("SELECT * FROM tls_active_applicants WHERE `".$searchParams."`='".$input."'");
$rows = array();
                 foreach($results as $result){
                    $rows[] = array(
                        $result -> first_name,
                        $result -> last_name,
                        $result -> gwf,
                        $result -> visa_type,
                        $result -> current_stage,
                    );
                 }

The second one works fine, where with the first one, if I print_r($rows) it returns an empty array.  Why is the foreach loop starting in the first example but not the second?  I've tested the query, and it works fine. Also any links that could help me understand how the foreach loop is working would be greatly appreciated.  I assumed that since it's saying $query as $result, I would be able to pull a single value saying something like $query->stage but that didn't work.  I'm assuming because there are several entries I would need to do something like $query[0]->stage but I don't really know how that works when it comes to calling properties..

I won't address your question specifically...because you're doing it wrong, and that should stop here :)

This is very, very bad:

db_query("SELECT * FROM tls_connect_stage_timer WHERE '".$agent."' IN ('start_processing_agent' || 'end_processing_agent')");

You should never concatenate data into an SQL string, you'll leave yourself ripe for injection attacks.  This one is even worse:

db_query("SELECT * FROM tls_active_applicants WHERE `".$searchParams."`='".$input."'");

As you're liable to injection attacks from both the field name and the argument.

If you want to use dynamic field names you should use the SelectQuery class, accessible via db_select(). E.g.

$values = array('start_processing_agent', 'end_processing_agent');
$query = db_select('tls_connect_stage_timer', 't')
  ->fields('t')
  ->condition($field_name, $values);

$rows = $query->execute()->fetchAll();

You'll need to make some changes to the above for your specific query, but that's the general idea.