How to override existing plugin? Considering Drupal\search_api\Plugin\views\query\SearchApiQuery class, I want to override shouldAbort() method there.

I have tried to create a new plugin class in my custom mod:

namespace Drupal\my_mod\Plugin\views\query;

use Drupal\search_api\Plugin\views\query\SearchApiQuery;

/**
 * Defines a Views query class for searching on Search API indexes.
 *
 * @ViewsQuery(
 *   id = "search_api_query",
 *   title = @Translation("Search API Query"),
 *   help = @Translation("The query will be generated and run using the Search API.")
 * )
 */
class MymodSearchApiQuery extends SearchApiQuery {

  /**
   * @inheritdoc
   */
  public function shouldAbort() {
    //do something fancy
  }
}

But it seems to not work. How can I do it properly?

What you want to do, is to make views use your class instead of the the one solr module provides. Defining your own plugin wont help.

Instead you can use hook_views_plugins_query_alter to specify the plugin class.


Using Migrate API with a multi-page / paginated source I have a working module pulling a JSON feed into Drupal 8 using the Migrate API. However, the feed is paginated, and I am only getting the first page of results.

For example:

{
    "meta": {
        "count": 58964,
        "next": "http://api.example.com/endpoint/?page=2",
        "previous": null
    },
    "data": [
        {
            "id": "id:1",
            ...
        },
        {
            "id": "id:2",
            ...
        },
...

I need to go through all pages import them all, but I can't see how to tell Migrate to iterate through the pages.

One option is to use a two-step process: first download all the data to a local file and then import that into Drupal. It would be nicer if Drupal 8 Migrate API could fetch and import all the pages itself.

https://www.drupal.org/node/2640516 is the issue to add this support to migrate_plus.

In the meantime, in a case where I knew up front how many pages there were, I simply listed the pages in the urls configuration:

source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls:
    - http://www.example.com/api/search?query=blahblahblah&rowlimit=500
    - http://www.example.com/api/search?query=blahblahblah&rowlimit=500&startrow=501
    - http://www.example.com/api/search?query=blahblahblah&rowlimit=500&startrow=1001
...


How to add a view with contextual filters in a panel I created a view with some contextual filter and relationships. When i add this view to a menu tab from a node, the view is working ok.
But when i add this view to a panel, it gives me the message that there are no items added yet (my own custom text when the view is empty).

Like it should be:

And how it is through panes:

Can somebody help me with this? Tnx!

I added %1 to arguments and it seems to be working now. But can someone explain what this is exactly? I don't really understand why its working with this.


Using composer - basics with localhost Mamp My goal is to try updating drupal/core with Composer and to learn composer basics. Composer is installed on OS X. From terminal i can run

My-MacBook-Pro:~ osxuser$ composer
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.4.1 2017-03-10 09:29:45

Usage:
command [options] [arguments]...

So how do I make composer find my drupal8 install in Mamp?

I have tried both:

composer -d, --working-dir=/Applications/MAMP/htdocs/test_d8

and

cd /Applications/MAMP/htdocs/test_d8

If I am running several drupal 8 installs in /Applications/MAMP/htdocs/ how do I tell composer witch one to work on?

From what I've red you don't need drush any more. I am not sure Composer has all it needs to work with Drupal 8 either.

composer show
symfony/css-selector      v3.2.6  Symfony CssSelector Component
symfony/dom-crawler       v2.8.13 Symfony DomCrawler Component
symfony/finder            v3.2.6  Symfony Finder Component
symfony/polyfill-mbstring v1.3.0  Symfony polyfill for the Mbstring extension

composer diagnose
Checking composer.json: WARNING
No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.
require.symfony/dom-crawler : exact version constraints (2.8.13) should be avoided if the package follows semantic versioning
Checking platform settings: WARNING
The OpenSSL library (0.9.8zc) used by PHP does not support TLSv1.2 or TLSv1.1.
If possible you should upgrade OpenSSL to version 1.0.1 or above.

Checking git settings: OK
Checking http connectivity to packagist: OK
Checking https connectivity to packagist: OK
Checking github.com rate limit: OK
Checking disk free space: OK
Checking pubkeys:
Tags Public Key Fingerprint: ---numbers here---
Dev Public Key Fingerprint: ---numbers here---
OK
Checking composer version: OK

Can someone point me in the right direction here? Do I need to use/install other composer submodules/libraries?

Is it possible to do some sort of composer update drupal/core --dry-run as a test?

Posting as an answer instead of a comment.

You run Composer from the project directory, which is where your composer.json and .lock file (which will get generated for you) lives.

I can work on any project at any time in the CLI by cd ing to the project I want to work on. Composer understands that this is the working directory in that execution.

So, no matter where you are in your server, Composer will execute in the directory you are currently in.


Drupal Registration Module Email Registrants tab The character count for the subject field in email registrants is 40 characters and that is hard coded into the module.

I need some guidance for figuring out how to change that. I am not a hard core developer and do not know the best way to change that without going into the module code.

Can anyone help guid me to what could be done?

Thanks
Tim

EDIT***
I am in Drupal 7 Registration module 7.x-1.3.
Under Manage Registration/Email Registrants/ - there is a subject field. In the modules registration.forms.inc file on line 354 it the character limit size set to 40.

I am trying to figure out how to change it without editing the module code.

Thanks

Not being a developer I had to figure this out using hook_form_alter. Too some digging and a little help.

function ecg_registration_form_registration_registrations_broadcast_form_alter(&$form, &$form_state) {
  //dpm($form);
  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#description' => t('The subject of the message.'),
    '#required' => TRUE,
    '#size' => 80,
    '#maxlength' => 80,
  );
}

Hope that helps someone.


How to apply xss filter on a csv file I have a CSV file from which I am importing some data. Should I need to apply XSS filter? How do I achieve this?

   while (!feof($handle)) {
    $data = fgetcsv($handle);
    $path[] = $data[0];
    $title[] = $data[1];
    $description[] = $data[2];
    $abstract[] = $data[3];
    $keywords[] = $data[4];
}

Well to my knowledge Drupal doesn't mind the input/import data that much, as long as it's rendered in a secure way.

  So what we really have to do is make sure that, regardless the data, its content can never be interpreted as SQL. To do this, we use the escaping functions provided by the database API. We do this escaping in the database layer and not directly after receiving input as it may not be the only escaping (or filtering) we have to do. - https://www.drupal.org/node/101495

Just my 2 cents :)


user pictures not showing up in posts & comments I am using a custom theme and it is not showing user pics in comments.

When I compared 'Appearance > Settings > Toggle display settings' of my theme with Bartik, if found that "User pictures in posts" & "User pictures in comments" is missing in my theme settings.

I don't understand what I am missing in my theme. Please suggest.

comment.tpl.php is the template file which controls the view of comments in a page. You may search for this template file in your theme and edit it according to your requirement.

If you would like to customize the comments display for a specific content type the template file would be comment--node-[type].tpl.php


How to load a library only once, or how to check if a library has been loaded? I am making an asynchronous single page application in Drupal 8. So far everything is working nicely. However, it has a lot of libraries that are needed for a lot of different things, depending on what the user decides to do.

The libraries are different depending on which content type is loaded. I want to only load the library ONCE when a user loads a content type for the first time.

Using the below code the library is attached every time the content type gets loaded. Leading to multiple instances of each library.

function mytheme_preprocess_node(&$variables) {
    $node = $variables['node'];
    switch($node->getType()){
        case 'nodeone':
            $variables['#attached']['library'][] = 'mytheme/liba';
            break;
        case 'nodetwo':
            $variables['#attached']['library'][] = 'mytheme/libb';
            break;
        case 'nodethree':
            $variables['#attached']['library'][] = 'mytheme/libc';
            break;
        default:
            break;
    }
}

I can't do a preproccess_page as the content types are loaded asynchronously and would imply loading everything at once. I can't attach the library to the twig template as again, it happens at the node level, not the page. I have tried to attach the library to a view template, but the same issue remains, it gets loaded multiple times.

If I could do some form of check to see if the library has already been loaded, I think that would be sufficient.

EDIT: Sorry didn't see you were doing it via AJAX, my below example might not be the same. But the theory of the JS triggering multiple times rather than the actual files loading might still be valid

I don't think it's the piece of code you've showed is causing your issue. Is the  library files definitely getting loaded multiple times into the source code? Or is it that the effects of the library are happening multiple times? (e.g. a JS being trgiggered multiple times) as thats a different issue

Drupal handles this situation and when it aggregates all the required libraries so any duplicates are removed. For example I'm just working on a news listing page that has 10 nodes coming out and just replicated your code to print "hi" add a library and the "hi" comes out 10 times but the library files only once


Field type Entity Reference as select list but based on value I want field with entity reference showed as select but based on value from the another field in the same form [radio button field]
for example the entity reference field will list these values

-entity 1
-entity 2
-entity 3
-entity 4

and the field radio button will hold countries like so:

-England
-Germany

notice that the entities reference (Content Type) has field called country, so when i check the
value "England" i want the field entity to be filtered based on England for ex:
-entity 1 & -entity 4
and same if i clicked Germany.

is that applicable in Drupal 7 even by Views module, or i have to do it custom !?

You can use Dynamic dependent fields module.

Project page says:

  Makes field value or options depend on other field values when editing
  entity.


How to set a new password using a module? I'm sending out mails to existing users telling them their username and password with tokens.

Because there is no way to access the user's password (fortunately!), I'm simply setting a new password. But It seems not to work at all.

This is what I've tried so far:

// Include the password.inc file to use hashing functions
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

// This is my user account (dummy function)
$account = get_some_user();

// Generates new random password of length 12
$password = user_password(12);

// Prepares the new user object and hashes the password
$edit = array();
$edit['revision'] = 0;
$edit['pass'] = user_hash_password($password);

// Saves the user object
user_save($account, $edit);

// Do stuff with password...

But this does not really work. The password hash gets changed in the $account[pass] field, I've checked that, but I can't login using the new password.

What did I miss?

Okay, I was trying to make it more complicated than it is.

The user_save() function already hashes the password. This works:

// Prepares the user object with new password
$edit = array();
$edit['revision'] = 0;
$edit['pass'] = $password;

// Saves the user object
user_save($account, $edit);

There is no need to include the password.inc and to use user_hash_password().


problem in passing Data ajaxly I want to do some tasks with ajax in drupal, in client side I passed data with

                jQuery.ajax({
                    url: '/rest/session/token',
                    method: 'GET',
                    success: function (token, status, xhr) {
                        var postData = {}
                        postData= {'name': 'user','pass': 'pass'};
                        jQuery.ajax({
                            url: "/mylogin",
                            method: "POST",
                            data: postData,
                            dataType: "json",
                            headers: {"Accept": "application/json", "X-CSRF-Token": token, "Content-Type": "application/json"},
                            success: function (data, status, xhr) {
                                console.log(data);
                            }
                        });
                    }
                });

and  ccording How to get $_POST parameters in my controller I try to catch posted data with

public function login(){
    //return new JsonResponse( \Drupal::request()->request->all()); // form param);
    return new JsonResponse( \Drupal::request()->request->get('name')); // form param);
}

I reutrn empty, ( JsonResponse work correctly, I test it with example data ).

what is the problem and why I can't get Posted data in my controller's method?

If you're POSTing a JSON string, it won't be available as key/value pairs in Symfony's request object.

You could parse it yourself:

$json_string = \Drupal::request()->getContent();
$decoded = \Drupal\Component\Serialization\Json::decode($json_string);
$name = $decoded['name'];


How to get the correct reference to this item? I'm writing a hook for a form but do not get the correct reference. What do I wrong?

  if($form_id == "entityqueue_subqueue_edit_form") {
    foreach ($form[eq_taxonomy_term][und][items] as $row => $rowinfo) {

      dpm($rowinfo[target_id]);
      if ($rowinfo[target_id][value] == 94){

        unset ($form[eq_taxonomy_term][und][items][$row]);
      }
    }
  }

The correct reference is:

  if ($rowinfo['target_id']['#value'] == 94)


How to use ddblock to create slideshow? I am having problem creating slideshow with DDBlock

Created a new block 'DDBlock1' from 'admin/structure/ddblock'
    Cannot configure Block: Selected "Input Type" as "Content Type" but under "Content Type" drop down box, only option is "None" (as shown)

I am stuck here - how do I direct DDBlock to pick images from an Image field in a content type I have??

Have you noticed that the help text says

  Only content types enabled in the settings tab of the ddblock module will show up here

?

As far as I can tell from your question, you haven't enabled your content type, and thus that's likely your problem.


Module for putting blocks in menus Is there any module that allows me to put a block in a menu?
I wanted to add some related content, or a big image about the link.

Sure; these are called 'megamenus' or 'meganavs' and there is a module directly for this: the Megamenu module.

  Mega menus are a type of drop-down, which seeks to overcome some of the usability drawbacks to traditional style drop-downs. Primarily, mega menus have two advantages:

  The information architecture of your navigation is made clearer and is visible all at once
  The amount of clicking, searching, and navigating is reduced

  This module allows you to build mega menus by leveraging jQuery and the existing Drupal menu system. Megamenu takes a Drupal menu that is 3 levels deep, and converts it into a categorized 3-level mega menu, which is placed into your site as a block.

The 7.2-x branch allows "embeded blocks within mega menus"


Setting a variable as a class (using set classes) in a region template I am attempting to set a common class if any preface region in my theme appears. I am trying to render this with a variable using set classes = [] in the region template in my theme.

So far I have set a variable in a preprocess region like this:

function gratis_preprocess_region(&$vars) {
  // Check to see if any of the preface regions have content and if so
  // Set a common var for use as a class in the region template.
  if (!empty($vars['page']['preface_first']) || !empty($vars['page']['preface_second']) || !empty($vars['page']['preface_third'])) {
    $vars['preface_region'] = '';
  }
}

Then in my theme's region template I attempt to render the variable within the set classes area.

  set classes = [
    'region',
    'region-' ~ region|clean_class,
    region == preface_region ? 'region-preface'
  ]

I am pretty sure I am not doing this the correct way though and it does not work.

It seems the way to do this was to create a theme hook for all preface regions and then it can have its own template. So first I create an alter preprocess function in my theme's .theme file.

function MYTHEME_theme_suggestions_region_alter(&$suggestions, $vars, $hook) {
  // Print the $vars.
  kint($vars);

  // Define a var for the #region.
  $preface = $vars['elements']['#region'];

  // Now check for any of the three preface regions and create a theme hook.
  if ($preface == 'preface_first' || $preface == 'preface_second' || $preface == 'preface_third') {
    $suggestions[] = 'region' .  '__' . 'preface';
  }
}

Next, voila, when I look at Twig debug, I see a suggestion for my new theme hook.

   * region--preface.html.twig >> **** This is the new template from the alter
   * region--preface-second.html.twig
   x region.html.twig

Now I can create a common template for all three preface regions with region--preface.html.twig.

Then in the new template, I print the classes like so:

 {%
set classes = [
'region',
'region-preface',
'region-' ~ region|clean_class
]
%}

This gives me exactly what I set out to do and prints this HTML:

<div class="region region-preface region-preface-second">

Now I can use .region-preface for common theming / HTML for any of the three the preface regions.


How to allow an OG group admin to create and add a user to a group? I have a situation where our D7 site is connected to a LDAP server (with LDAP) module. However, I need a way to allow an Organic groups administrator to add a user (who has not yet logged in) and automatically enroll that user in that same group.

How might I address this?

My first thought is to just build a form where the OG admin adds the user name to a queue. When that user finally logs in, I would use the user_save() hook to add them to the appropriate group.

I found a round about way. I made my own form with two values and a user_access('administer group') check. The first value is the group id and the second is the user name.

In the myform_form_submit(), if the user name exists in the users table, I run og_group to subscribe that user. If the username does not exists and the user has not logged in, I add them to a queue as a key value pair of username and group id.

When the user logs in, hook_user_login() searches through that queue to find any instance and if so, subscribes them to that group.


Using nested node content type template files Using Drupal 7 I have setup a structure in which a widget_set content type has a node reference field that allows the user to choose nodes of the content_widget content type.

The template files are node--widget_set.tpl.php and node--content_widget.tpl.php

Inside the node--widget_set.tpl.php template, I call print render($content); and was hoping to have the output be formatted as specified in node--content_widget.tpl.php, but I just get output that seems to ignore the content_widget template.

Is that the expected behavior?  I could just pull the code from the content_widget template into the widget_set template but I have a bunch of content_widget types and wanted to keep them all separate.

Thanks.

Assuming you want the structure to be something like this:

ie, render the template inside the the other template, and assuming you have named your templates properly, put them in your theme, and cleared the theme registry (or cleared all caches), you need to set the display settings appropriately.

In the Manage Display settings for Widget Set, find the Content Widget field, and adjust the settings:

Set the Label as you need
Set the Format to Rendered entity
The click the gear, and adjust the settings.  You can pick the view mode (full, teaser, etc), whether to show links or not, and potentially other settings that modules have defined.

Note that this does assume your node-to-node fields are using Entity References and not Node References.

Then you should get output to use nested templates.  Using Entity View Modes and Rabbit Hole also come in very handy when you do things like this on your site.


How do I select a table using a variable with db_query()? I'm trying to find records from a table based on a variable that is grabbed from user submission. This is my query:

$field = t('field_data_' . variable_get('tabbed_content_field'));
$fieldValue = t(variable_get('tabbed_content_field') . '_value');
$query = db_query('SELECT :fieldValue FROM {:field}', array(':field' => $field, ':fieldValue' => $fieldValue));

However, whenever I run this query I get the following error:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
  You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near ''field_data_field_news_release_date'' at line 2: SELECT
  :fieldValue FROM {:field}; Array ( [:field] =>
  field_data_field_news_release_date [:fieldValue] =>
  field_news_release_date_value )

I can retrieve the records successfully with:

$query = db_query('SELECT ' . $fieldValue . ' FROM { ' . $field . '}');

However, as I understand it this would be insecure.

Does anyone know why the first query won't work?

This is one of the reasons the new query builder exists in Drupal 7, so you can dynamically substitute parts of the query:

$table_name = 'the_table';
$field_name = 'a_field';
$query = db_select($table_name)->fields($table_name, array($field_name));

Using db_query() you only get parameter replacement, which would only be applicable to substitutions in WHERE conditions. This means that you cannot use db_query() to replace table names, the names of fields selected, etc., only WHERE conditions.

Have a look at the db_select() docs for more in-depth examples, including how to add conditions to the dynamic query.


Theming user-edit form drupal 6 After installing tons of modules like guestbook, subscriptions etc. It also added tons of settings on user/$uid/edit page. How can I disable or rearrange them?

I guess theme_fieldset() would help me, but I have no idea how to use it correctly. And where to print_r($form) and in which template?

devel themer will help you understand what you can over ride and what variables are available.

hook_form_alter() can be used to trim fields that you don't want and to re order the form, put things into groups etc.


Are there any Drupal 7 modules for creating organizational charts? Are there any Drupal 7 modules for creating organizational charts? So far I have only seen one for Drupal 6.

Any solution you might have used to incorporate organizational charts in Drupal 7 will be appreciated.

The Google Charts module for Drupal 7 now has support for organizational charts.


Drupal 8: How to retrieve field values when i use loadMultiple to load multiple node ids I am loading multiple node ids like below

$node_storage = \Drupal::entityTypeManager()->getStorage('user')->loadMultiple($nids);
foreach ($node_storage as $node){
  $value = $node->get('field_merchant_id')->value;
}

After this, I am getting an object and I don't know how to access my values. I have used get('field_name')->value but its saying Error: Call to a member function get() on array. How can I get an array that contains all values of one specific column from all nodes?

You should do like

$node_storage = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($node_storage as $node){
   $field_merchant_id = $node->get('field_merchant_id')->value;
}

Here you are using "user" which should be replaced by "node" to access node values.
And also to access "field_merchant_id", you need to get that from $node.


drupal module secure pages toggles between http and https on reload I am using the secure pages drupal module to enable https for some of the pages , but i have noticed one bug in this , each time i reload the page its toggling between http and https, and if i go from a secure page to another secure page(ex: login to registration which are bith secure according to settings) the destination page will be in http but if i refresh it toggles between secure and non secure , a similar issue is reported here

The source of the problem could be in several places, depending on which webserver you're using, how it's configured, etc.

Are you using Apache with mod_ssl?  NOthing else 'in front', like nginx doing the SSL handshaking instead?

In any case, I'm guessing that your webserver's not consistenly serving up the required server var.  In 'securepages.module', there's a check for

return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? TRUE : FALSE;

Not knowing your webserver config, find out what your webserver is doing.  add,

<?php
 phpinfo();
?>

to your pages and look to see what the values of

$_SERVER['HTTPS']
$_SERVER[SERVER_PORT]

are.  Or simply print them out directly ...  Check if/how those values toggle on page refresh.

I'm suspicious of caching, too.


Output the "Body" field with markup using Views PHP to be used in Views Datasource (JSON) We are creating an API using Views/Views Datasource and we want to output the Body field with markup already in the field not plain text. How can we do this?
This Views_PHP approach just outputs the standard Body field as text.

$nid = $row->nid;
$node = node_load($nid);
$display = array('type' => 'ugc');
$output = field_view_field('node', $node, 'body', $display);
print render($output);

On the example below the @papermill should be a link if this was rendered on the front end.

No need for Views PHP, in the settings for my JSON putout it ticks Plaintext output by default!

UPDATE: this does answer the question but we can no longer render our REACTJS App on the front end because i presume of some kind of encoding issue with some characters inside the Body field?


How to display a views block on pages with a specific combination of URL patterns? I'm using the Group module (1.0-alpha7) on a Drupal 8.1.5 and I want to display a view of recent article in my groups.

I want to display the view on groups page (mywebsite/group/x where x is id of group) but only this pattern of URL. For example when I create an article in a group the URL is : mywebsite/group/x/node/create/article and I don't want to show the view on this page.

I'm trying to use Blocks Visibility Groups module module to do it but for the moment I don't find the conditions to make it work.

Using the Block Visibility Groups module, perform these steps:

Define a new Block Visibility Group, say you name it "Group pages".
For this newly created *Block Visibility Group" (named Group pages"), add 2 conditions by selecting a condition related to the "Request path", which look like so:

Return true on the following pages: group/*.
Do not return true on the following pages: group/*/node/create/article (not sure if you want the /article suffix to be added, pick what fits your content types).

If you also want to show the Global Blocks, then mark the Show Global Blocks as checked.
Use the Place block button to place the Views block in the theme region of your choice.

Notes:

if you're not familiar yet with this module, then have a look at the video about Block Visibility Groups - Drupal 8 Blocks but Better.
if this question was about D7, I'd use the Rules block visibility module and specify similar Rules Conditions (based on the same current paths).
don't get confused with all the Group-stuff (the Group module, versus the Block Visibility Groups module ...)


How I can view facet view key? I have module where used this code:

$variables['facet_metal_level'] = module_invoke('facetapi', 'block_view', '8Ratyom2YlpSn79FmHOAv8S1HaSXS6HJ');

How and Where I can find this view key '8Ratyom2YlpSn79FmHOAv8S1HaSXS6HJ' ?

It's delta of block.
You can receive it via this code:

$delta = facetapi_hash_delta(facetapi_build_delta('SEARCHER@MACHINE_NAME_OF_SEARCH_INDEX', 'block', 'MACHINE_NAME_OF_FACET'));

Example:

$delta = facetapi_hash_delta(facetapi_build_delta('search_api@fr_node_index', 'block', 'field_price'));


including forms in hook_view Is it possible to include forms and have it be submitted when viewing a node type?  A good example is the default 'Add Comment' module.  When you view a node, there is a link you need to click on to leave a comment.  This link essentially takes you to the comment form.  Is there any way to do like Youtube.com where you can have the comment form textarea box in the node view?  It just seems silly to have to make your users click a link to 'add comment'.

For example, the below does nothing in my custom module when viewing a node:

function Mymod_view($node,$teaser=false,$page=false) {
  $node->content['name'] = array(
    '#type' = 'textfield',
  );
  // hitting submit does nothing. NOTHING!
  $node->content['submit'] = array(
    '#type' => 'submit',
    '#value' => 'SUBMIT',
  );
  return $node;
}

You can create forms everywhere you want.

Your code adds form elements without a surrounding  element. That makes it useless.

Define your form in a separate function and call drupal_get_form('your function name') to make it working. See the form generation doc for a full description.


How to fix Feature with Panels I am managing a website that makes extensive use of panels. I had a "system" panel page with Title = 'Registration Template' and a path of 'registration/%registration'.

Somehow, in updating the features on the LIVE site, I managed to loose this panel page. It is not available on the LIVE site. I can recreate a feature with "registration_view_panel_context" this under Page Manager.

But when I move this feature to the live site, it does not become available to me as a panel. It is included in the feature, but the feature is overridden. I am unable to "revert" the feature.

Despite being labeled as a "system" page, the 'Registration Template' is not available to me.
As a "system" page, I do not have the option of exporting it from my local site.
And when I try to revert the feature on LIVE - nothing happens.
If I try to create a new panel page on LIVE with this path - "registration/%registration" I get a message "that path is already in use. This system cannot override existing paths."

This panel page is still available to me and works on my local site, but I can't figure out how to move it back onto the LIVE site.

Any ideas?

EDIT: Solved this problem myself (not myself, but with local help :-)
See below for answer.

It turns out I needed to recreate this "system" page as an "existing page" using the - Page Manager Existing Pages - module (drupal.org/project/pm_existing_pages). I am not entirely sure why, but this solved my problem.


Using the Migrate Source CSV plugin to migrate images I'm currently importing nodes from a Drupal 7 to Drupal 8 site, using this very helpful tutorial: https://www.drupal.org/docs/8/upgrade/using-the-migrate-source-csv-plugin I have found a fairly good way to import fields. My only stumbling block at the moment is images. I'm finding it very hard to find anything about how I would manage importing of images, whether if I give it the path of the old images it can import from there, or if I give it a file name, then put the image somewhere, I have tried both so far and the image field always just ends up blank in the new nodes that are created. I've got my head around using the above links approach so if anyone has a solution that fits with that, that would be great!

You'll need to run a migration of all the files you want first. The file_copy process plugin is going to be your best friend for this part.
To get you started,

id: image_migration
destination:
  plugin: 'entity:file'
process:
  uri:
    plugin: file_copy
    source:
      - file_source_uri
      - file_destination_uri

Once you have your files migrated, it's actually very easy to tell your image field about the file

process:
  field_image:
    plugin: migration
    migration: image_migration
    source: image_id

A couple notes:

image_migration refers to the migration that imports your images. Make sure to change it if you use a different name.
image_id needs to be the key from the image migration. It will be mapped to the new file created during that import.

Very Useful Guide


create bilingual language site with drupal 6 i want to build a multi-language site (Chinese and English). From the documentation, I know I should install the Internationalization module, so i installed it, but there are some parts on my site that are not translated.

There are some parts as the following in every page (the Chinese version):

<a href="<?php print $base_path ?>" title="<?php print t('Home') ?>">测试公司

How do I translate 测试公司 when English is the set language?

On every page's top right part, there are some parts as the following:

  设为首页 |&nbsp;添加收藏  |&nbsp;简体中文&nbsp;English

How do I translate 设为首页, 添加收藏 and  简体中文 to English, when the user access http://example.com/en?

I know I can put that content in a block, then translate it, but it's too weird.

Is there a simple way to get that?

ps:  why this one that i can't translate(english-->chinese)? the code is used to alter the conntact form . $form['mail'] = array( '#title' => t('E-mail'), '#type' => 'textfield', . when i searched the E-mail in the translate interface, i can't find it,but  when i changed E-mail to test. then i can search it. why? thank you.

You must use the t function on all text if you want translate it directly throw the admin panel.


Same Image in Multiple product with feeds I like to upload a lot of commerce product from a csv file and I have one image for multiple product. I am importing images from a subdirectory of files, the field is in the csv: public://productimages/PRODNUM.jpg.
It is working very nice, but when I use the same photo for multiple images it is makes a new image for every product. (PRODNUM.jpg PRODNUM_1.jpg PRODNUM_2.jpg PRODNUM_X.jpg)

I like to use the same image for same products if the name is same.

I tried filefield path filefield source but not helped. If it possible I do not want to use the media module.

If the images in the same place where the field is waiting for it the images will not multiple.


Can't update custom module I need to add some tables to the database in a new module version. I created a hook_update function:

function bundles_update_7000()
{
    ...
}

But for some reason my module is missing in the updates list in the admin interface. When I run:

drush pm-update bundles

it writes: "No code updates available."

What could be the issue?

You need to run drush updb, not drush pm-update. And you don't specify the module name.  So just:

drush updb


How do I configure the Services OAuth sub-module? The Services module is about to release its new 3.0 version for both D6 & D7.
There's an OAuth sub-module to Services that adds a new OAuth UI within the Services configuration UI.

Does anyone know how to configure that UI?

I'm expecting the Services developers will write something up, but given that they are working hard on the official release, the documentation will be the last thing done. In the mean time, if anyone has figured it out from prior familiarity with OAuth, please share your knowledge to us less informed. (As in explaining it to someone who has not used OAuth before.)

There is a handbook page covering testing Oauth based services at http://drupal.org/node/942866 . This does assume that you have some familiarity with both oauth and the drupal oauth module.

The basic workflow as far as implementation goes is:

Set up an oauth context.
Set your service to use oauth authorisation
Configure the authorisation for all your resource operations.
Configure one or more oauth consumers

For testing you're probably going to have to write your own client code which generates the oauth signature and then passes that with your service requests.

For learning more about Oauth itself I recommend you start by reading this guide which is fairly comprehensive -
http://hueniverse.com/2007/10/beginners-guide-to-oauth-part-i-overview/


How do I attach an existing file to a node? Here's my problem. I have a D6 site which has been in production for a number of years, and in consequence has used various methods (and modules) for displaying images within body text of book pages. The latest of these modules is IMCE. Up to now (unless I've missed something), none of these mechanisms had any management of the links to images incorporated in the body text. As a result, I have a lot of links pointing to various places in my files directory,

With the arrival of Drupal 8, I've discovered "managed files" and the possibility of using "Inline Images" with CKEditor, such that files in the body text are properly managed, and you get a display in the Files listing of where the images are used.

Since this suits my use case fine, I think I don't need any alternative modules any more. However, here comes the problem: having migrated the site from D6 to D8, the physical directory where the files are kept has changed and since all the files have been copied over, all the body text links are broken.

What to do? Well, I decided to write a drush command which would look through all the body texts that contain <img> tags, extract the image file references, find the real file, create a managed file entity, attach that entity to the node, change the <img src="my file ref"> and save it back to the body.

Thanks to Berdir's friendly advice, I abandoned the original idea of using SQL to go directly through the table, and decided to have a go at Entity Queries instead (first time ever!). So we have this:

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'book');
$entity_ids = $query->execute();
foreach($entity_ids as $nid) {
  $node = Node::load($nid);
  $body = $node->get('body')->getValue();
  $body_text = $body['value'];
  $summary = $body['summary'];
  $format = $body['format'];
  }

So far so good. I won't bore you with the details of how I extract the file name and directory, but I can do this. So now I want to create and save a file entity, and then attach it to the node. This code creates the file entity (but see Berdir's answer below, not everything is necessary here):

    $file_name = end(explode("/", $src));
    $file = entity_create('file');
    $file->setFilename($file_name);
    $file->setFileUri('public://images/'.$file_name);
    $file->setSize($size);
    $file->language('en');
    $file->isNew();
    $file->setTemporary();
    $file->save();

(I confess that I'm really struggling to get my head round the Drupal 8 API and object programming...).

This actually works, it does create a temporary file entity which shows up properly in the Content list (except the MIME type is missing, that needs adding).

However, this is probably not the way to go because there surely must be some mechanism for creating the file entity and attaching it to the node without going through all this - just as CKEditor does when you add an inline image.

I've tried getting a list of all the methods proposed by the Node class, and thought maybe $mynode->referencedEntities() would show me the way - but this doesn't include inline images (I tried with a new test node that does contain an inline image, and it doesn't show here). Should it perhaps appear via a link to the body text as a field entity? And if so, where to go to get this information, and manipulate it?

I have found this in the Editor core module, perhaps this is the way to go?

function _editor_record_file_usage(array $uuids, EntityInterface $entity) {
   foreach ($uuids as $uuid) {
    if ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid)) {
    if ($file->status !== FILE_STATUS_PERMANENT) {
      $file->status = FILE_STATUS_PERMANENT;
      $file->save();
    }
  \Drupal::service('file.usage')->add($file, 'editor', $entity->getEntityTypeId(), $entity->id());
    }
  }
}

A few things..

You should avoid raw sql queries against entity tables, they are managed and it is not guaranteed that the structure will always break. Use entity queries and then load the entities using Node::loadMultiple() for example, or $storage->loadMultiple().

A few lines of your existing code are not necessary. the size is calculated, language() is a getter that has no arguments, it is automatically new.

To set the uid, you can use setOwner($user) or setOwnerId($uid), and there are corresponding getter methods on the node objects, so once you load them, you can just set it from the node with $file->setOwner($node->getOwner())

However, that seems to be a completely different question than what you have in the title. That just syncs the owner (which is not that important, not for public files at least). It doesn't do anything to connect them to the node. To get the usage tracking, you can rely on what Drupal does by default if you include the UUID as an data attribute. I don't remember the exact name right now, just manually add an image with CKEditor and you'll see it in the source code. If that's there then Drupal does it for you automatically.


Theme call for block returning as an empty string I have a call for a block generating that is returning an empty string when it should be returning with generated content. I have cleared out the theme cache and the results remain the same. I've gone through most of the documented steps on the official docs and am pretty baffled as to why it isn't working as intended.

Here is the code from generic.module

/**
 * Implements hook_block_info()
 */
function generic_block_info() {
  $blocks['gen_1'] = array(
    'info' => t('Project Information'),
  );
  return $blocks;
}

/**
 * Implements hook_theme()
 */
function generic_theme() {
  return array(
    'block_projectinfo' => array(
        'variables' => array(
            'completionPct' => NULL,
        ),
        'file' => 'theme/block-projectinfo'
    )
  );
}

/**
 * Implements hook_block_view()
 */
function generic_block_view($delta = '') {
    global $conf;

    switch ($delta) {
        case 'gen_1':
            $block['subject'] = t('Project Status');

                 $variables = array(
                  'completionPercentage' => 45
                     );

            $block['content'] = theme('block_projectinfo',$variables);
            break;
    }
    return $block;
}

Theme

<?php

/**
 * @file
 * Provides rendered output of the Project
 */

?>

            Percent Complete
            <?php print $completionPct; ?>%

Assuming your template file can be found at theme/block-projectinfo.tpl.php, you just need to change the file property to template in hook_theme():

function generic_theme() {
  return array(
    'block_projectinfo' => array(
        'variables' => array(
            'completionPct' => NULL,
        ),
        'template' => 'theme/block-projectinfo'
    )
  );
}

file is

  The file the implementation resides in. This file will be included prior to the theme being rendered, to make sure that the function or preprocess function (as needed) is actually loaded; this makes it possible to split theme functions out into separate files quite easily.

And refers to situations where you implement a theme_foo() function, rather than a template file.


Is there an option to somehow display all nodes that that doesn't have a menu link? As almost all users here know, you can set up a menu link to each node from the "Menu settings" tab in the node's edit form.

Is there an option to show all nodes that don't have a menu link?

I tried to create a view and use the filter criteria to achieve that, but no relevant filtering option appeared for me there.

I think the best approach to handle this would be to get all of the menu items, and the nodes associated to them.  Then perform a EntityFieldQuery on nodes.  Making sure that your query includes a 'NOT IN' condition, and use the ids from the nodes you discovered in the menu as the values.

This would return all nodes not in your menus.


Display a link to create new content when content missing (via Contextual Filters)? I'd like to give users the option to create new content when a certain contextual filter is missing on a panel.

e.g. I have my reviews on a panel. When a review is missing I'd like it to display a block/link to submit a new review.

However my only options are to hide the view, give a summary etc.

How do I do this?

I've found the option for 'No Results Behaviour', but I can't hook into the contextual filter (and then use a relationship to grab a term name). I've also found this work around:

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

But I'm struggling to re-write the code to pull the term name out of the term id in the contextual filter.

Here I suppose you have added an argument in panel path. You can assign any context to your argument, eg Node: Id. It can be Term as well.

Assign any context to argument like :

Add a visibility rule if Context exists to your view and not exists to custom pane.


How can I alter the form to add a new validation handler? I'm on Drupal 8. I have created a new media bundle (permissions_json) which can be created from /media/add/permissions_json, where administrator user can upload specifically formatted JSON files, and I can upload to it all fine and dandy.
I'd like to validate the file uploaded and rename it. The problem is that I can't find a way to hook into the form. Implementing hook_form_FORM_ID_alter() with gp_mcs_media_permissions_json_add_form_alter() or gp_mcs_form_media_permissions_json_add_form_alter() doesn't have any effect. Even the following implementation didn't have any effect.
function gp_mcs_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}

If I put a simple exit() on the module's page stops the website, so the file is accessible. I just can't figure out how to add validation to this add media form.
How can I alter the form to add a new validation handler?

The form ID for an entity is a string that is usually returned from EntityForm::getFormId(), if the class used for the form doesn't override that method.
This means that, by default, the form ID follows the <entity>_<bundle>_<operation>_form schema, where the <operation> part is omitted, when operation is default.
Since the Media module doesn't have a class that overrides EntityForm::getFormId(), the correct ID for the form that creates a new Media entity whose bundle is permissions_json is media_permissions_json_add. This means that a module whose machine name is gp_mcs can alter that form by implementing hook_form_FORM_ID_alter() with a function named gp_mcs_form_media_permissions_json_add_alter. (Note that the form ID is between form and alter.)


No images, content, or theme after site migration from dev server to nginx on ubuntu I have recently worked on a site for a client and worked on an acquia devdesktop to make changes on a Windows machine.  The production site is on a linux server and I am trying to deploy the site on a digital ocean ubuntu server running nginx. For some reason my file and folder permission are completely messed up. I have gotten the site to the point where some images show up, but my themes and content are still behaving strangely. I followed what I thought was the procedure:

Set up a clean installation.
Migrate the database
copy the sites folder
run the update script

I ran though a series of issues with folder permissions, and was able to squash most of the bugs. I don't get any meaningful to me warnings in the admin/status/reports, and near as I can tell I've tried to follow the correct permissions for files and folders.

site --> 775
site/default -->775
site/default/files --> 775

UPDATE: So, I guess part of the issue had to do with an .htaccess file htaccess file issues, but I still had a mess of warnings regarding the folder and ownership permissions. I guess the environments are really unfriendly to one another. This a big site with 85+ modules enabled. The annoying part is that I could only piece together the diagnoses from the php warnings. I finally hit a wall a WSOD.

Try to give more information about the files/directories.  What user/group owns the files?  You should also make sure you know what user nginx is running on.  Try these commands for debugging:

ls -l for printing details about file permissions and ownership

ps -ef to check running processes to see if any user stands out (like www-data or www, figure out which user nginx uses)

Files in sites/default/files should be rw- permissions, and directories in sites/default/files should be rwx permissions.  rw- is 6 and rwx is 7.

The file:
-rw-r--r--  1 ubuntu www-data     468 Dec 10 15:59 test.php is owned by the ubuntu user and the www-data group. The ubuntu user can access the file with read/write, and the www-data can only read the file.  If this file were in sites/default/files it would be a problem, because the webserver wouldn't have rights to remove it.


#default_value Not Working In Select Field First off, I have tried to do my homework before coming here. I have referenced this, and this and I still cannot get my code to work.

I am simply trying to set a default value in a select form field on a Drupal 8 block configuration form. Here are the relevant parts of my code:

$options = array(
  'test' => 'value',
  'random' => 'string',
  'kiwi' => 'pear',
);

$form['menu_selected'] = array(
  '#type' => 'select',
  '#title' => 'Test Title',
  '#description' => 'Test Description',
  '#options' => $options,
  '#default_value' => 'random',
);

The $form then gets returned as per usual in a block build. Everything else works in the form; The options populate, the description and title display. The only thing that doesn't work is the default value. I have tried using keys and values. I even saw a comment that said to use '#value' instead of '#default_value' and still it didn't work. Can someone please tell me what I'm doing wrong? I can provide more code if needed.

On Drupal 8 form, I was having an issue with Firefox that was caching the value of a select field, selected by the user before refreshing the page.

It was basically overriding the #default_value of the field.

My solution was to Turn Off Form Autocompletion (https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion).

You can do it at the level on the input if that's an input, but since it was a select in my case I had to do it at the form level :

$form['#attributes']['autocomplete'] = 'off';


How do I pass parameters to a service? How can parameters be passed to service? I have a class that I would like to change to a service and load other services from the container. What I don't understand is how to deal with other parameters in the constructor when calling the service.

For example, I have a CustomService class.

public function __construct(QueryFactory $query_factory, EntityTypeManagerInterface $entity_type_manager, param1, param2) {

    $this->entity_query = $query_factory;
    $this->entity_type_manager = $entity_type_manager;

    $this->param1 = $param1;
    $this->param2 = $param2;

  }

public static function create(ContainerInterface $container) {
   return new static(
       $container->get('entity.query'),
       $container->get('entity_type.manager')
    );
}

How can I instantiate the service I would instantiate with \Drupal::service('CustomService')? It does not work for me; it only works when I remove the custom parameters from the constructor.

This might be a wrong approach, but I'm new to Drupal 8 and would like to use proper coding with dependency injection.

Just add a new parameter in the constructor declaration, and get the service from $container.

public function __construct(QueryFactory $query_factory, EntityTypeManagerInterface $entity_type_manager, CustomServiceInterface custom_service) {
    $this->entity_query = $query_factory;
    $this->entity_type_manager = $entity_type_manager;
    $this->custom_service = $custom_service;
  }

public static function create(ContainerInterface $container) {
   return new static(
       $container->get('entity.query'),
       $container->get('entity_type.manager'),
       $container->get('custom.service')
    );
}

Notice that all the parameters the constructor gets are the ones passed in new static(). I removed $param1 and $param2, since there aren't equivalents in the static() call.

As for passing parameters to the custom.service service, you cannot with $container->get('custom.service') nor \Drupal::service('custom.service') since both the methods accepts only the service ID as parameter. The service needs a method to set its properties; in that case you could use the following code.

public function __construct(QueryFactory $query_factory, EntityTypeManagerInterface $entity_type_manager, CustomServiceInterface custom_service) {
    $this->entity_query = $query_factory;
    $this->entity_type_manager = $entity_type_manager;
    $this->custom_service = $custom_service;
    $custom_service->setParam1($param1);
    $custom_service->setParam2($param2);
  }

public static function create(ContainerInterface $container) {
   return new static(
       $container->get('entity.query'),
       $container->get('entity_type.manager'),
       $container->get('custom.service')
    );
}

You could also use the following code.

public function __construct(QueryFactory $query_factory, EntityTypeManagerInterface $entity_type_manager, CustomServiceInterface custom_service, $param1, $param2) {
    $this->entity_query = $query_factory;
    $this->entity_type_manager = $entity_type_manager;
    $this->custom_service = $custom_service;
    $custom_service->setParam1($param1);
    $custom_service->setParam2($param2);
  }

public static function create(ContainerInterface $container) {
   return new static(
       $container->get('entity.query'),
       $container->get('entity_type.manager'),
       $container->get('custom.service'),
       'param1 value',
       'param2 value',
    );
}


The test case is not recognized by the Simpletest module I am using Drupal 7, and the latest version of the Simpletest module. I have written a test case like the following one:

class SimpleTestDemoTestCase extends DrupalWebTestCase {
  function setUp($modules = array()) {
    parent::setUp('simpletestdemo');
  }

  public function getInfo(){
    return array(
      'name' => 'Simpletestdemo testcase',
      'description' => 'Simpletestdemo testcase desc',
      'group' => 'Simpletestdemo'
    );
  }

  public function testBlockView() {
    $simpletestblockview = module_invoke('simpletestdemo','block_view);
    $this->assertTrue(t('Simpletest Demo'),$simpletestblockview['title']);
  }
}
?>

This does not get recognized by the Simpletest module. Is there anything wrong in this test case?

As srihita pointed out in a comment, you need to add the file which contains the test class to the files[] array in your module's info file like this:

files[]=yourmodule.test

Then, let it rebuild by submitting the modules page or use the "Clear information" (or similar, not sure about the exact label right now) at the bottom of the Testing page.

Also, you're code is missing a ', but that might be a copy/paste error.


How to calculate the sum of a list of integer in Rules In a Rules component I have a list of integer (as variable data type). I have to calculate the sum of items and to expose the result. Any suggestions?

I found the solution.

Add a variable (integer) "total", for example.
Loop the list of integers:

Calculate a value, input 1: [total], input 2: [line-item], return: "result".
Set a data value, data: [total], value: [result].

Outside of the loop, the [total] value is still available.


Why is my form_token missing when i'm not logged as admin? I'm in charge of multiple Drupal 8 website and with some of them, the hidden field form_token is non-existent when I'm using the website anonymously.

Everything works fine when I'm logged in.

I'm sure everything was working before the quarantine but I didn't check before updating to 8.8.6

I tried deleting the custom twig templates of the webform and I checked my theme.theme

webform version is 8.x-5.13 for some and 8.x-5.16 for others.

The problem comes from the antibot module.

For some reason that I don't know, when I am not logged in, the module considers that I do not have javascrip enabled and overrides the form_token field which is required to submit the form.


Restrict coupon for same shipping address (or user creating multiple email ids) We have scheme “Register & Earn Coupon of Rs. 200”
Some users create multiple gmail accounts to avail multiple coupon.
They get the order shipped at the same place.
Is there a solution available to handle this?

There is surely a way to block this, you can alter the forms and add validations. But do you really want one to one mapping between shipping address and user account?

What if the old user wants to purchase the same product again, or a new user signing up stays in the same apartment?

Maybe you need to review your business rules and figure out a better way to restrict this behaviour.

Maybe IP address?


Fixed Block Position CSS Problems Hello i was using the floating Block module to keep my right hand main menu in a fixed position as a person scrolls down the page. Then i deceided that maybe its overkill just for one menu and i have tried it with css.

#sidebar-left {
 position: fixed;
    top: 0
float:right;
  right:20px;
  width:110px;
}

My theme is fixed width but im getting differant results when viewed in differant screen resolutions.  I was wanting the block to just appear to the right of the the 2nd right hand block (with the logo). Try as i might though im struggling to achieve it.

You can view my site (and the right hand menu) here-
http://onlinebanter.com/welcome

Can anyone help me achieve this?

Thanks

I think ive sorted it with

margin-left: 845px;
    position: fixed;
    top: 0;
    width: 110px;

Thanks


In simple words please, what is the "Rendered file" image-format? I've tried to Google the term "Rendered file" "Drupal" to have some clear data about this image-format and what makes it even possible for choosing (I guess, a module I installed for another purpose that does it), but that data I found wasn't clear and didactic enough for me.

My only aim is to use Drupals image API with the monumental module Insert. The display should be "Hidden" for the field (so it would not be duplicated when the image is inserted to the CKeditor). But I ask to know anyway, and that people to come will have a better clearer answer for what is the "Rendered file" format.

Please give the shortest, clearest definition you can, for this term, and in the end, some words about it's connection to the Views module. Thx,

Since Drupal 7 Images can be rendered the same way as any other entity. Images are a special case of a file and file is a fieldable entity.

Fields can be added to the entity and how the fields are displayed can be configured here:

admin/structure/file-types/manage/image/display

But most times you don't want a rendered file, but a resized image. That is provided by the module "image" in core and if enabled you can configure image styles and use this in node displays and views.


node reference fail before submit I have custom_form, with Node_reference field.. When I add Any node and leave some require field then I submit .. the Node_reference fail and become [nid:und]

function custom_form_alter(&$form, &$form_state, $form_id) {
   $content_type_forms = array('register_node_form', 'session_node_form');
 if (in_array($form_id, $content_type_forms))
 {
 if(empty($form['field_event_ref']['und'][0]['nid']['#default_value']))
 {
 $form['field_event_ref']['und'][0]['nid']['#default_value'] = arg(3);
 }
 $form['field_event_ref']['und'][0]['nid']['#disabled'] = True;
}
}

if ($form_id == 'register_node_form'){
    global $user;
    if(isset($form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'])){
       $nid = $form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'];
    }  else {
    $nid = $form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'] = arg(3);
    }
     $form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'] = $nid;


Implementing search for a view I have a view containing objects of a custom content type. Could anyone please tell me how I could allow my users to search only objects that have certain attributes? Some sort of like "Show me objects that are located in X, have a size of Y and colour Z".

Create and expose filter in the view. This is not a full blown search but might be sufficient for your needs. If you need more advanced functionality, try Apache Solr Search Integration.


Product display and taxonomy term ID filter (with depth) I have a view for nodes that show my products by product reference field.
All of these products tagged with "Catalog" vocabulary.
I have added a reference to the field_product in the view.

Is there any way to use contextual filter «has taxonomy term ID (with depth)» for this view?

Clone the default view called "taxonomy term" and start from there.
Add a relationship to your product, and save.
Add fields as you like.


Drupal Commerce: Authorize.net payment from manual order I would like to handle manual phone orders from my Drupal Commerce site.  But the Authorize.Net rule does not appear in the Payment tab for admin/manually created orders.  It even disclaims this for the SIM/DPM rule I'm using.

So what do I do?  I sense this has something to do with a requirement of SIM/DPM being that credit cards aren't stored locally.  That's ok with me, I just need to run the credit card they gave me on the phone, I don't need it stored.

I really just need to be on the payment step of the checkout form for them.  What is it about the SIM/DPM limitation that prevents me doing that step from the admin page?

It's really just a simple matter that the payment terminal form doesn't fully imitate the checkout form on the front end, so redirected payment methods or direct post payment methods are not going to be supportable there.


Display taxonomy term description within the content page I've a content type with some fields, one of the field is associated with a taxonomy and it has some terms (each term has its own description). Here, when I input the field with the terms and submit the content. The content page appears as:

[title] : title of the content.

[field1] :

[field2] :

[taxonomy] : [term1]

             [term2]

             [term3]

The content page is viewed with all the fields and taxonomy terms with an anchor/link. I would also like to include the description in its display as

[term1] : [description]

[term2] : [description]

[term3] : [description]

Any Ideas on how to get this done.

You can do this with the display suite module. Install and enable the ds module. Then you will have a new 'Rendered taxonomy term' formatter. Go to the 'manage display' option for the content type you created. Just select the 'Rendered Taxonomy Term' for the format for your taxonomy field and you will get the description displayed.


How to apply patches that are created in core-dev Noob here. I'm trying to apply patches to my website, but it's keeps skipping because the version of the patch is for DEV. For example, I want to apply a patch to Core like this issue: https://www.drupal.org/project/drupal/issues/2579343.
How should I apply patches that are in core-dev?
Thanks!

If the patch weren't already committed, you would need to reroll the desired patch against your Drupal Core version. This can be done by cloning the git repository of Drupal Core and generating a patch against the relevant revision of your version of Drupal.
The Drupal Core git repository can be found at https://www.drupal.org/project/drupal/git-instructions
See Making a patch on how to create a patch.
However in this case we can see that the issue has already been marked as "Fixed" and the patch of comment #19 was committed, so if you are on Drupal Core 8.1.x or up, you should already have the changes from that patch on your Drupal site.


Jquery silent error in drupal 7 I'm trying to use an uncotroversial piece of code to change the background color
of a div when the mouse hovers over it.

Currently, my install of drupal refuses to register the hover event, I have tried substituting my code with a console.log('hovering') and I still get nothing.

here is the code. http://jsfiddle.net/tmXfW/2/

( function($) {
        var msg = $().jquery;
        console.log(msg);
        $('div.quicklink-row').hover(function() {
                $(this).addClass('blue-link');
        }, function() {
                $(this).removeClass('blue-link');

        });
})(jQuery);

You should wrap your functionality in a Drupal Behavior. This will make it work even if elements on the page change via ajax and whatnot.

So the following:

(function($) {
  Drupal.behaviors.myCustomModule = {
    attach: function() {
      //var msg = $().jquery;
      //console.log(msg);
      $('div.quicklink-row').hover(function() {
        $(this).addClass('blue-link');
      }, function() {
        $(this).removeClass('blue-link');
      });
    }
  };
})(jQuery);

But aside from that.... why are you using Javascript for something that can be done so simply with CSS?

div.quicklink-row:hover {
  background: #00F;
}


How do I enable rich text editing on all my long text fields? I have a node with 3 long text fields and I want to make rich text editing available on them all. So far all my experiments with Wysiwyg have only resulted in one of the long text fields getting an editor. So what editor/configuration will give me rich text editors on them all?

Now they are all working. I think what happened is that since I have posted the question I have rebooted Apache and MySQL (as well as I may have cleared a cache or two) and that fixed the problem. I've tested a few editors, and now they all seem to work across multiple text areas.


Views footer include twig Is there any way to include an if condition in views footer. I have to check the total rows

{% if [view:total-rows]  > 6 %}

View AllEvents

{% endif %}

But this is not working.

What is the name of your template file? Depending on what template you use,

{% if view.total_rows > 6 %}
  <div ...
{% endif %}

should work.


Issues with Term Reference and Multilingual Taxonomy The issue:

We have a multilingual Drupal 7 website which allows users access to a content type e.g. Blog - where they can use /node/add/blog and node/*/edit in their chosen language
A taxonomy has been created called category which has been set to 'Localize' under MULTILINGUAL OPTIONS >> Translation mode
Terms listed under category have been translated to FR, DE, NL etc.
On the content_type Blog - a term reference has been set up to reference the category taxonomy, with a select list widget being used.
When visiting e.g. www.multilingual-site.com/node/add/blog (default site language is EN) - the dropdown list shows all the terms.
When visiting e.g. www.multilingual-site.com/fr/node/add/blog or any other language e.g. /de/ or /nl/ etc the dropdown list is blank - the translated terms do not appear.

In an attempt to create the option list ourselves - using hook_form_alter() with taxonomy_get_tree($vid) as suggested here https://drupal.stackexchange.com/a/64666/5253 - when trying to dpm the output
the array is empty for every language other than the default EN.

Can anyone offer any direction? Thanks

Turns out we needed to unselect 'Select taxonomy terms by language' - found admin/config/regional/i18n/select - hope this helps someone. More reading at: https://drupal.org/node/1868418 #2


Undefined index message in drupal When editing a view, I get the following message in the popup.

  Notice: Undefined index: advertising_block in eva_plugin_display_entity->options_summary()
  (line 41 of/.../sites/all/modules/eva/eva_plugin_display_entity.inc).

This view contains 2 displays: a view attached and a block (called advertising_block). This error message appeared both before and after deleting the "advertising_block" to which it seems to refer.

Any idea of what may be causing this error message and how to fix it?

Basically, the EVA module is getting called with a bundle 'advertising_block' that it doesn't know how to handle. If you used to have a block named 'advertising_block', that would be a suspect.

The way to solve this is to (with devel installed) use the approach in webchick's Quick and Dirty Debugging. Right before line 41 of/.../sites/all/modules/eva/eva_plugin_display_entity.inc, make a temporary hack.

First, install and enable the devel module.

The code there is:

  foreach ($this->get_option('bundles') as $bundle) {
    $bundle_names[] = $entity_info['bundles'][$bundle]['label'];
  }

so we'll change it to

  foreach ($this->get_option('bundles') as $bundle) {
    if ($bundle == 'advertising_block') {
        dpm(debug_backtrace(), 'Bundle advertising_block being requested');
    }
    $bundle_names[] = $entity_info['bundles'][$bundle]['label'];
  }

Now when we hit that page, we'll see the backtrace (who called this thing, maybe why), and will have a path forward.

When you're through with this debugging code, don't forget to revert to the original code and disable devel module.

And remember that debugging like this should be done on a local dev site, not on production. Some more strategies are at randyfay.com/debugging


Alter checkboxes values in a webform How can I alter the key/value items of a checkboxes component in a webform?
I've followed this answer and I successfully altered a select list component for both render and submission.
I'm trying to do the same with a multiple choice component, but although the form is rendered correctly, the values are not saved on submission.
This is my code:

function my_form_webform_client_form_30_alter (&$form, &$form_state) {
    $form = mycustom_form($form);
}

function mycustom_form($form){
     $form['#validate'][] = 'mycustom_webform_validate_form';
     $form['#submit'][] = 'mycustom_webform_submit';
     dpm($form['submitted']['code']['#options']); // ('0'=>'a value', '1'=>'another value');
     $codes = array('foo', 'bar');
     foreach ($codes as $key => $value) {
        $form['submitted']['code']['#options'][$value] = $value;
     }

return $form;
}

function mycustom_webform_validate_form($form, &$form_state) {
dpm($form_state['values']['submitted']);
// selecting all checkboxes I get all the four values
}

function mycustom_webform_submit($form, &$form_state) {
  drupal_set_message('<pre>' . print_r($form_state, true) . '</pre>');
// only 'a value' and 'another value' are submitted
}

UPDATE
I even tried to add some values to the initial form and manipulate them programmatically.
The submission result is like no manipulation was done.
I update my code for a better explanation.

UPDATE 2
I've tried dumping the submitting form.
I updated my code with the results.

UPDATE 3
I confirm that removing the "Multiple" flag from the component, causes the issue to be fixed.
Unfortunately I need a multiple answer, so I can't remove it.

UPDATE 4
This is another solution I'm trying, using hook_webform_select_options_info():

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

   if (function_exists('_mycustom_users_options')) {
        $items['code'] = array(
        'title' => t('User codes'),
        'options callback' => '_mycustom_users_options',
      );
 }

  return $items;
}

function _mycustom_users_options() {
  $output = array();
  $codes = mycustom_user_codes(); // <- these values are based on logged user
  foreach ($codes as $key => $value) {
    $output[$value] = $value;
  }
  return $output;
}

function mycustom_user_codes() {
      $result = // a db query based on user id;
      while($usercode = db_result($result)){
         $output[] = $usercode;
      }

      return $output; // array({[0] => 'a value', [1] =>'another value'})
}

I've just tested the following code out locally and it "works", with the exception that when I view the submission results as an administrator, I see the original keys and not the keys that were altered when the form was displayed (which is what I would expect).

function my_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_12') { // yours is different
    // 'options' is the component name for a multiple-checkbox component.
    $form['submitted']['options']['#options'] = array(
      1 => 'Foo',
      2 => 'Bar',
    );

    $form['#submit'][] = 'my_custom_submit';
  }
}

function my_custom_submit(&$form, &$form_state) {
  dpm($form_state);
}

dmp($form_state) showed me that the checkbox I had picked was indeed the one that was checked, and when I look in the database in webform_submitted_data I can see that the record  shows the proper value that I checked:

nid sid cid no data
12  12  2   0  2

where data = 2 shows the checkbox that I picked in my altered options (I picked "Bar").

Since the subsequent submission display is going to show the keys as they currently exist, it's showing me that I picked the original value for option #2. If I change that to "apples" in the component and then refresh the submission, it shows the 2nd option as "apples". So I could follow this up with another hook_webform_submission_render_alter() or hook_webform_submission_load() to change the options being displayed on submission view so as to be appropriate to who the user was that filled out the webform.

My suggestion would be to instead build your own form, since it sounds like you have more than one dynamic aspect for what you need, and store the data that will be dynamic as a serialized array in a 'data' column in your own table.


Is it possible to disable (or reject) selection of parent terms in taxonomy reference fields at node creation or edit? for instance, for a particular Vocab. and User Role..

Is it possible to achieve that in code? That parent terms will be rendered only as labels and not checkboxes?

Thanks.

Taxonomy Term Reference Tree Widget allows you to disable the selection of parents. Hope this helps you out.


Mark a taxonomy term as "deprecated" I have a taxonomy vocabulary "categories", and decide that one of the terms should no longer be used (because I introduced another field which covers this information).

I could delete the term, but then some existing content would no longer have a category.

What I would like is to "deprecate" the term, such that

existing content can continue to reference the term.
the term is still visible in things like search facets.
the term can no longer be assigned in a term reference field.
(optional) editing an existing node which references the old term will fail form validation on save, and force to change the term.

Termsatus module can help you.

This add a status "publis" or "unpublish" on terms like nodes, and is handled by permission (that can solve first three points), views, etc.

I think the optional point need a custom code using hook_node_validate check the status of term an send the custom error message attached to the field.


How do I create a jump link to a paragraph item? I'm trying to create a jump link to the paragraph item. This is what I tried

create a compact display of the page just printing out a title and short summary.
using the advanced text formatter I created a link in this index

It takes me to the paragraph page. I figure that I can use a token in the advanced text formatter to create an anchor link from the compact display to the detailed display. Then I have to work out how to add the anchor to the detailed display.

How do I create a link with the delta as the anchor e.g. /abc/test.html#1?
How do i create the anchor on the detailed display?

Perhaps Paragraphs Table of Contents module is good enough for what you describe.
From the project page

If you have long pages on your site, then it helps visitors if you can provide in-page navigation, or a table of contents.
If you build your long pages with the Paragraphs module, then you can use Paragraphs Table of Contents to provide the in-page navigation. There is one link in the table of contents (ToC) for each paragraph on the page.


Entity Validation API: Retrieve parent field entity while validating I'm using the Drupal 8 Entity Validation API. I've implemented my Constraint and ConstraintValidator classes and added them as a constraint against the relevant entity field.

If I understand the validate method signature for ConstraintValidator correctly, I'm given a list of fields ($items) and the constraint ($constraint). However, I need to retrieve the parent entity in my logic.

How can I get the parent entity while with the validation API?

By using FieldItemList::getEntity like in this core validator:

Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator:

class UniqueFieldValueValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    if (!$item = $items->first()) {
      return;
    }
    $field_name = $items->getFieldDefinition()->getName();
    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $items->getEntity();

The first argument of a validate method is of mixed type. For the Drupal Entity Validation API this can be a field value, a field item list or an entity, depending on where you add the constraint.


Adding a Block Into Region Using several different themes, I'm looking to add a generic region to the bottom of each "content" section of my webpage. The code I have so far is. . . . with Social Share being the name of the block.

If you have all of these different themes enabled (and you aren't using something like Panels), then you can simple edit this from the Block administration page (admin/structure/block).

If you want this to be completely removed from configurability, then I would recommend either doing a preprocess function for the content region (or hard-coding, ick, your custom HTML into the region itself).


How Specify the class name of our columns in Responsive Grid View? I'm trying to build a responsive Views grid using views responsive grid module. But added fields in the view is not visible.

I'm confused in adding grid class.Please anybody guide me to set class name, so that fields can be seen in the grid?I have attached screenshot of my settings below.

For Wrapper do not use <div> you need to use a name. Ex: magazine_grid_wrapper


Install Meta Tags and Meta Tags Quick modules on the same site Short: Are Meta Tag and Meta Tag Quick incompatible modules?

I am configuring a site that has Meta Tag Quick module but it doesn't allow me to have a meta description tag. It creates an Open Graph description meta tag instead.

Then I want to install Meta Tag module but I am afraid of my site crashing or some error. I know I have to do a backup, and I did.

Couple of things to mention.
Meta Tags Quick does have a meta description field - check the module settings and enable the field for the content types.

Metatags and Meta Tags Quick can be installed on the same site - I've done this successfully (I do suggest testing on a mirror development site first). Bear in mind the two modules will duplicate some fields so you need to decide which fields you want each module to use.

The data cannot be imported from one module to the other however - maybe running SQL commands, but not from Drupal admin


force image style generation on save node I've got still my problem described here Image style, reuse image in field collection item but i gave up to get a solution.

A workaround which came up in my mind is to force the generation of imagestyles on nodesave. are there any possibilites to do so?

Yes - you can implement hook_node_insert() and hook_node_update() in a custom module and create the images there using image API functions. For example

function MYMODULE_node_insert($node) {
  // Get some field items from a field called 'field_photo.
  if ($image_items = field_get_items('node', $node, 'field_photo')) {
    $image_item = array_shift($image_items);

    // Load the associated file.
    $file = file_load($image_item['fid']);

    // An array of image styles to create.
    $image_styles = array('style_1', 'style_2');

    foreach ($image_styles as $style_name) {
      // Get the location of the new image.
      $derivative_uri = image_style_path($style_name, $file->uri);

      // Create the image.
      image_style_create_derivative($style_name, $file->uri, $derivative_uri);
    }
  }
}


Theme Hook Suggestion for Drupal 5 I wonder if any still remember how to override a particular node in Drupal 5 ? I have tried out several ways but didn't work. Couldn't find such info any more on google.

node-13.tpl.php

node--13.tpl.php

In Drupal 5 you need to add the suggestion yourself by placing this function in your theme's template.php:

function _phptemplate_variables($hook, $vars = array()) {
  switch ($hook) {
    case 'node':
      $vars['template_files'] = array('node-'. $vars['nid']);
      break;
  }
  return $vars;
}

Once that's done you'll be able to use node-13.tpl.php (note the single dash).

Source: Separate node template for a specific node.


Is there any backport of "Grouped filters" available in Views 6.x-3.x branch? In Views 3 (Drupal 7), there is a nice feature when you expose a Views filter, you can select
"Grouped filters" option and define a set of conditions.

Is there any module that backports this feature to Drupal 6 Views 3.x branch?

Yes you can do it with Advanced Exposed Forms for views 3 version

  Advanced Exposed Forms (AEF) provides fine grained dynamic data
  filtering by allowing the "joining" of views exposed filters into
  groups. AEF provides AND/OR operators between individual exposed
  filters and between groups of exposed filters. Use AEF to drill down
  from large amounts of data to specific data sets.


E-Mail functionality for moderators I would like to allow moderator to send an e-mail to choosen user. The e-mail will be sent when the moderator observes a mistake made by the user. After that, moderator sends email with warning. How can I do it?

A simple solution would be, to give the moderators role the permission to use the users' individual contact forms ( in http://example.com/admin/people/permissions )

The messaging and notifications modules might have more functionality, however, they are still in alpha for drupal 7, so I would use them with great caution.


Getting the number pad to show up for text fields I would like to make entering data easier for my users who use the mobile version of my site. I've been searching around both Android and Drupal documentation and eventually found this: https://stackoverflow.com/questions/3372380/how-to-force-keyboard-with-numbers-in-mobile-website-in-android

Which says that using

<input type="number" />
<input type="tel" />

will bring up the number pad for the user.

I would like to figure out the best way to change all of my integer and decimal fields to have type="number".

I'm aware of doing a hook to do this but I have a lot of fields which are numbers and I was wondering if there was a more effective way to change ALL the fields rather that me writing a line for each of the fields. Maybe if I had an array of all the fields and then programically went through all the fields in the array?

Thanks

hook_field_widget_form_alter

  Alter forms for field widgets provided by other modules.

or use hook_field_widget_WIDGET_TYPE_form_alter to hook into the Number field specifically.

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function mymodule_field_widget_number_form_alter(&$element, &$form_state, $context) {
  $element['#type'] 'number';
}


Prompt registration based on number of free articles read When an anonymous user reads 3 free articles, the system should prompt them that they have reach the limit of free articles, and they now need to register to read more.
How can i achieve this. I have just started writing modules. Any help would be beneficial. Thanks in advance

It seems you're looking for the Node Access module

  Nodeaccess is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.

Image from module page


How to set variables in an installation profile? I cannot find any documentation on the variables[] array in an installation profile info file. I can set some variables successfully in that file and others give me an invalid format error when I visit the settings page to check them after the install. The ones that I would like to set are:

variables[site_403] = <front>
variables[user_cancel_method] = user_cancel_block
variables[update_check_frequency] = 7
variables[update_notification_threshold] = security
variables[update_notify_emails] = myemail@example.com

In Drupal the source it looks like update_notify_emails is probably an array. Is there a way to make this setting an array via this .info file? I am trying to set these using the info file or the install hook rather than exporting the variables as features using a strongarm.inc due to these best practice recommendations linked on this distribution developers guide page.

You should be able to set these in the .install file in your profile. I've struggled with this well, and the .install seems to be the best way to do it.

<?php
/**
 * Implements hook_install().
 *
 * Performs actions to set up the site for this profile.
 *
 * @see system_install()
 */
function customProfile_install() {
  /*
    Other cool functions...
   */

  variable_set('site_403','<front>');
  // etc....
}


How to save entire term lineage I need to save term lineage in Drupal 8, not only the deepest term. I know there are modules like Hierarchical select, Simple hierarchical select or Client-side hierarchical select but these are not for Drupal 8, or not solves "save term lineage" functionality.

I need to get my "nodes" visible on both child term and parent term pages too. I know, I can use the "Content: Has taxonomy term ID (with depth)" (under contextual filters) functionality in "views", but it slows the database queries very much. Or maybe I'm doing something wrong.

Is there some reasonable solution?

Thank you!

EDIT: The hierarchy is very simple. Only two-tiered: Country / City.

Can someone help me to re-save my nodes with "lineage" structure? For example, using the TermStorage functions listed below?

Depends on your understanding of reasonable. Until hierarchical select or similar modules become available you could save the parent terms programmatically on node save - the code probably wouldn't exceed 30 lines or so, especially when you don't have many taxonomy fields where you want to do this.

You can access a term's parents with the following code utilizing TermStorage:

$parents = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($termId);

Then you only need to go recursively through the tree and grab all parents (if your terms can have more than one), get their ids and set them in the node you want to save.


Warning message and URLs not found on menu items My question is in relation to a Mamp issue Im having.

Installed Mamp on my MacBook, loaded the database off my live Drupal 7 site, downloaded and copied the Drupal files on the live site to Mamp htdocs, changed the Drupal config settings (db, host, user, password) to use Mamp site, but it displays the home page, with the warning messages below, and if you click on any menu item it displays URL not found. Any ideas what Im doing wrong?

Ive tried using the latest Drupal 7 core, and also using the same Drupal files as the live site, but I get the same result.

Warning message on Home page:

Warning: "continue" targeting switch is equivalent to "break".
Did you      mean to use "continue 2"? in require_once()
(line 341 of  /Applications/MAMP/htdocs/rltc/includes/module.inc).

The warning looks like a PHP incompatibility. So either fix the code that's been triggering it (and at best provide a patch for it on drupal.org) or change MAMP's PHP version. Probably to something lower as it is now.

The URL not found error looks like as if you misconfigured your .htaccess file. Ensure this file exists and maybe uncomment the following line.

RewriteBase /


Flags - show a flag marker even if user cannot modify it I have been able to set up a flag with Advanced forum to allow users to mark comment in  a thread they started as an accepted answer. It was simple to set up and works well.

However, it seems Flag only alters a comment if the user has permissions to set/unset the flag. I want a tick to appear on a comment which has been flagged which any (even anonymous) users should be able to see. How do I go about doing that?

You could add a new boolean field Answer to comments which has a default value of 0. Next, create a Rule that changes the boolean value of a flagged comment to 1. The rest is theming; use the following code in your comment.tpl.php file:

<?php if ($comment->field_answer['und'][0]['value']): ?>
  <mark>This is the answer</mark>
<?php endif; ?>


Filtering a view by a checkbox field My site has a node type called "Resource". This node type has a field called "Reviewed"; this field is a single on-off checkbox:

I've created a view that lists all of the nodes of node-type "Resource". I'd like to filter that view so it only displays nodes that have the "Reviewed" checkbox checked. However, when I try to add that field to my view, I'm shown the following:

I would expect the "Options" select box to be a checkbox that I could either check or leave empty. Instead, I'm given a select box with "Select all" in it. Whether I select this or not, I'm then presented with an error message saying that there are "No valid values found on filter: Content: Reviewed.":

I've tried the "exposing the master display trick" at http://technology.blue-bag.com/top-tip-drupal-views-no-valid-values-found-filter, but that hasn't worked: there's no "unknown" filter in the master display, so there doesn't appear to be anything to fix.

Any idea as to how I can achieve the result I'm looking for? And what's the deal with the strange UI with the select box rather than a checkbox? Would be good to know if there's some logic to it; if not, I'll post an issue to the appropriate drupal.org issue queue.

this is some sort of a bug / incosistency of how the boolean field is made. if you leave it in default, without any 0 / 1 values, it wont show them in places like this filter.
But : the values are there :) under "Select all" you have 2 rows that just dont have captions. When you pick one of them, you can see that the SQL for your view is changed.
The workaround would be to add some captions to the values in the field defintion.


Login page when using a Zen's sub theme I've created a website based on a Drupal 7 Zen subtheme and now I would like to create a login page for the administrator. When I navigate to http://mysite.com/?q=user, I return to the main page as specified in the page.tpl.php file. I would like to have a manual login page, so I tried following the following tutorial: https://drupal.org/node/350634. My template.php looks like this:

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

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'camuse') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'camuse_preprocess_user_login'
    ),
  );

  return $items;
}

function camuse_preprocess_user_login(&$vars) {
  $vars['intro_text'] = t('This is my awesome login form');
}

And my user-login.tpl.php file like this:

<?php print render($intro_text); ?>

<?php print drupal_render_children($form) ?>

However, when I navigate to http://mywebsite.com/?q=user, I still go to the home page. I don't know what I'm doing wrong here, I've checked the names and everything seems fine. Could anyone help me with this?

You have to change the name of your template file to user--login.tpl.php, place this file in the templates folder of camuse theme and clear all caches.


How to do dependency injection on complex classes like when extending WidgetBase Since the Drupal sniffer whines at you if you call \Drupal::service() in your code, I have been trying to figure out how to use dependency injection on a widget  I’ve been working on. Here’s what I’ve currently arrived at:

<?php

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\xois\SicsService;
use Symfony\Component\DependencyInjection\ContainerInterface;

class XoisSicSelect extends WidgetBase {

  /**
  * SICs service.
  *
  * @var \Drupal\xois\SicsService
  */
  protected $sicsService;

  /**
  * {@inheritdoc}
  */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, SicsService $sicsService) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->sicsService = $sicsService;
  }

  /**
  * {@inheritdoc}
  */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('xois.sics')
    );
  }

}

Pretty much the standard DI pattern, no? Only difference is that WidgetBase takes a whole load of construct parameters already.
Problem is, it doesn’t work. When run, it gives this delightful error:

The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Argument 6 passed to Drupal\xois\Plugin\Field\FieldWidget\XoisSicSelect::__construct() must be an instance of Drupal\xois\SicsService, none given, called in /var/www/docroot/core/lib/Drupal/Core/Field/WidgetPluginManager.php on line 125 and defined in Drupal\xois\Plugin\Field\FieldWidget\XoisSicSelect->__construct() (line 35 of modules/xois/src/Plugin/Field/FieldWidget/XoisSicSelect.php).

Anyone got an idea on how to accomplish this?

You will need to implement ContainerFactoryPluginInterface in order to use dependency injection in your class.

Include use Drupal\Core\Plugin\ContainerFactoryPluginInterface; and implement the interface so it looks like:

class XoisSicSelect extends WidgetBase implements ContainerFactoryPluginInterface {

    ....

}

You will also need to make sure your __construct() and create() methods contain the correct parameters.

If you look at ContainerFactoryPluginInterface.php, you will see the parameters the create() method takes in:

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition);

Thus, your final code should look like:

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\xois\SicsService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;

class XoisSicSelect extends WidgetBase implements ContainerFactoryPluginInterface {
  /**
   * SICs service.
   *
   * @var \Drupal\xois\SicsService
   */
  protected $sicsService;

  /**
   * {@inheritdoc}
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, SicsService $sicsService) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->sicsService = $sicsService;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('xois.sics')
    );
  }
}


What are the functions of the callbacks in the commerce payment method info hook? Can someone explain me the differences, maybe with some examples, between the callbacks in the hook_commerce_payment_method_info()?

The callbacks are these: settings_form, submit_form, submit_form_validate, submit_form_submit, redirect_form, redirect_form_validate, redirect_form_submit.

I'm trying to implement a payment module and I need to know how to use the callback of the above-mentioned hook.

Thanks

You can find Contributed Modules API Documentation in http://drupalcontrib.org/ portal.

Please find link to above hook documentation hook_commerce_payment_method_info .

Callbacks Documentation links below...

CALLBACK_commerce_payment_method_settings_form()
CALLBACK_commerce_payment_method_submit_form()
CALLBACK_commerce_payment_method_submit_form_validate()
CALLBACK_commerce_payment_method_submit_form_submit()
CALLBACK_commerce_payment_method_redirect_form()
CALLBACK_commerce_payment_method_redirect_form_validate()
CALLBACK_commerce_payment_method_redirect_form_submit()

Check out commerce_payment_example module to find out how to write a payment method for more information.