How to implement decoupled user registration with React / jsonapi? I have built a React app that uses JSON:API to pull in data, but now I want to implement user registration.
JSON:API doesn't do user registration because it isn't a CRUD operation.
However, the links above explain that core provides a REST endpoint for handling user registration.
The documentation gives this example:
curl \
  --header "Content-type: application/json" \
  --request POST http://drupal.d8/user/register

But this example seems incomplete-- for example, where is the username?
My website is configured with the Email Registration module and only an email address is required to register, but where do I submit the email address?
EDIT: If you're answering this question, I will accept an answer that uses core's username/email address combo for registration; it doesn't have to be specific to the Email Registration module.  The problem is that I can't find an example of how to register users with JSON:API, and there is no documentation.
Here's the code I tried in React:
UserRegistrationForm.tsx
import * as React from 'react';
import { useForm } from 'react-hook-form';
import { IonButton } from '@ionic/react';
import { baseUrl, basicHeaders } from '../utils/globals';
import handleErrors from '../utils/fetchHandleErrors';

interface InterfaceRegistrationFormInput {
  email: string;
}

const UserRegistrationForm: React.VFC = () => {
  const { register, handleSubmit, errors } = useForm<InterfaceRegistrationFormInput>();

  const onSubmit = (formData: InterfaceRegistrationFormInput) => {
    fetch(`${baseUrl}/user/register`, {
      method: 'POST',
      headers: basicHeaders,
      body: formData,
    })
      .then(handleErrors)
      .catch((error) => Promise.reject(new Error(error)));
  };

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <label htmlFor="email">
          Email address
          <br />
          <input
            name="email"
            type="email"
            ref={register({ required: true })}
          />
        </label>
        <IonButton type="submit">Register</IonButton>
      </form>
    </>
  );
};

To register user using core Rest Module you need 5 steps:
Step 1: Download and enable Rest UI module, this module provides a user interface for administrating Rest Endpoints. Using this module's configuration (admin/config/services/rest) Enable User Registration

Step 2: Then in account setting configuration you should allow user to create account, and if you want user to be added using user name and password you will need to uncheck require email verification else leave it checked.

Step 3: Now you need to allow anonymous user to access user registration (admin/people/permissions/anonymous):

Step 4: Another step to take is to get a xcsrf token from drupal cause you need to use a post method for user creation and post methods are unsafe methods, so drupal protects them using token, to get a XCSRF Token simply call /session/token endpoint.
Step 5: Now final step is to ask for user creation:
Method: POST
Endpoint: user/register?_format=json
Header:
Content-Type: application/json
Accept: application/json
X-CSRF-Token: "XCSRF TOKEN PROVIDED BY DRUPAL"

Body:
{
  "name": [{"value": "USERNAME"}],
  "mail": [{"value": "EMAIL"}],
  "pass":[{"value": "PASSWORD"}]
}

and that's it.
PS:
Remember that if you have not unchecked "require email verification" in account settings form then you should exclude pass from your request body. in this case user needs to navigate to your drupal site for email verification which in case of decoupled scenario it sounds wired. so I highly recommend to uncheck this option in account settings configuration.
Another PS:
If you need to require user to confirm his/her email, then you can use a simple solution, like add a verify code to user (prevent user access to this field using Field Permissions module) then in hook_user_presave you can assign a code to it, send user an email containing this code and finally deactivate user) , finally you will need a custom Rest endpoint so user can fill a form containing email field and code and if code matches the one you sent you can activate user's account.


Drush does not work after I sudo su to another user I have a CentOS 6 server with WHM/cPanel. I installed a global Drush as root using the instructions here (http://docs.drush.org/en/master/install/). Drush works fine for any user I ssh in as. However I typically ssh in as my user and then sudo su to the user I'm working on. When I do that I get these errors. If I ssh in as that user directly drush works fine. How can I make drush work when I su to a different user?

PHP Warning:  proc_open(): Descriptor item must be either an array or a File-Handle in phar:///usr/local/bin/drush/includes/startup.inc on line 366
Content-type: text/html; charset=UTF-8

Warning:  proc_open(): Descriptor item must be either an array or a File-Handle in phar:///usr/local/bin/drush/includes/startup.inc on line 366

PHP Warning:  proc_get_status() expects parameter 1 to be resource, boolean given in phar:///usr/local/bin/drush/includes/startup.inc on line 367

Warning:  proc_get_status() expects parameter 1 to be resource, boolean given in phar:///usr/local/bin/drush/includes/startup.inc on line 367

PHP Warning:  proc_close() expects parameter 1 to be resource, boolean given in phar:///usr/local/bin/drush/includes/startup.inc on line 368

Warning:  proc_close() expects parameter 1 to be resource, boolean given in phar:///usr/local/bin/drush/includes/startup.inc on line 368

EDIT

So I got it to work. If I do
sudo su - newuser
instead of
sudo su newuser it works.

I think it's related to CLI/CGI. PHP runs as CLI when I su with the - and CGI when I su without the -. Can anyone explain the difference the - makes?

Found the answer here:
https://superuser.com/questions/453988/whats-the-difference-between-su-with-and-without-hyphen

  The difference between "-" and "no hyphen" is that the latter keeps
  your existing environment (variables, etc); the former creates a new
  environment (with the settings of the actual user, not your own).


How to create a list of users according their roles? How can I create/see the list of user according their roles?

I'm interested in any answers to do this programmatically, or via any other way/technique I could use for this.

Create a View Page of users with exposed filter as role.


Custom php to handle url based on taxanomy terms Our site uses taxanomy to maintain a blog page. And for now we use views to render the contents. Now we are planning to get rid of views and use templates. What we need is to have custom tpl.php only for request containing vocabulary. So for any request to my site of a pattern path/*,

I need my custom tpl.php to be used only when the path is valid vocabulary.
Let the default flow get executed when the path is not a valid vocabulary.

What would be right way to handle this?

In views use TID converted to Name filter then use TID in url as a parameter and when the url is hit check the tid is valid or not and write behavior accordingly.


Drupal Fields Ajax not working I have added fields to my entity via Field UI and trying to fire an ajax callback but it is not working.

This works

$form['customField'] = array(
        '#type' => 'textfield',
);

$form['customField']['#ajax'] = array(
      'callback' => 'just_test',
      'wrapper' => 'membership_suggestions',
);

But this does not ('field_member_first_name' is added to the entity via Field UI and is a text field)

$form['field_member_first_name']['#ajax'] = array(
    'event' => 'blur',
    'callback' => 'just_test',
    'wrapper' => 'membership_suggestions',
);

Thanks a lot.

Since the fields were attached via Field API, I have to do this way

$form['field_member_last_name'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
    'event' => 'blur',
    'callback' => 'get_suggestion_by_name',
    'wrapper' => 'suggestions_by_name',
    'method' => 'html',
);


How to define custom permissions for organic groups? I would like to define some organic group permissions for a custom entity. The permissions should look like:

  $perms += array(
        "create $type content" => array(
          'title' => t('Create %type_name content', array('%type_name' => $name)),
        ),
        "update own $type content" => array(
          'title' => t('Edit own %type_name content', array('%type_name' => $name)),
        ),
        "update any $type content" => array(
          'title' => t('Edit any %type_name content', array('%type_name' => $name)),
        ),
        "delete own $type content" => array(
          'title' => t('Delete own %type_name content', array('%type_name' => $name)),
        ),
        "delete any $type content" => array(
          'title' => t('Delete any %type_name content', array('%type_name' => $name)),
        ),
      );

How do I do this? I found the function  og_get_permissions() to get all set permission, but how to modify this array?

Or may be it should be another way round? You set a normal drupal permission first with:

function custom_example_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

And then make it eligible on the permission preferences page of OG? But how?

I found the solution here:

/**
 * Implements hook_og_permission().
 */
function custom_permissions_og_permission() {
  $name = "taks";
  return array(
    'update own task content' => array(
      'title' => t('Update own %type_name content', array('%type_name' => $name)),
      'description' => t("Edit own %type_name content.", array('%type_name' => $name)),
      // Determine to which role to limit the permission. For example the
      // "subscribe" can't be assigned only to a non-member, as a member doesn't
      // need it.
      'roles' => array(OG_AUTHENTICATED_ROLE, OG_ADMINISTRATOR_ROLE),
      // Determine to which roles the permissions will be enabled by default.
      'default role' => array(OG_AUTHENTICATED_ROLE, OG_ADMINISTRATOR_ROLE),
    ),
    'update any task content' => array(
      'title' => t('Update any %type_name content', array('%type_name' => $name)),
      'description' => t("Edit any %type_name content.", array('%type_name' => $name)),
      'roles' => array(OG_AUTHENTICATED_ROLE, OG_ADMINISTRATOR_ROLE),
      'default role' => array(OG_ADMINISTRATOR_ROLE),
    ),
    'create new task content' => array(
      'title' => t('Create new %type_name content', array('%type_name' => $name)),
      'description' => t("Create new %type_name content.", array('%type_name' => $name)),
      'roles' => array(OG_AUTHENTICATED_ROLE, OG_ADMINISTRATOR_ROLE),
      'default role' => array(OG_ADMINISTRATOR_ROLE),
    ),
  );
}


How can I show video and images in slideshow with lightbox style? I need to combine pictures and videos to come out in one Slideshow and when they click on an image or video is displayed in a lightbox. (I have only a 1 video)

Currently, video I have them separately and displayed on a lightbox as follows:

And if possible, show a small text in Slideshow with the image/video. As a caption that says if a video or image.

Using Drupal 7.

I achieved this some months ago... you can see an example in here http://www.entretierras.com/en on the left sidebar there is a block (slideshow) called "Our routes in pictures"

What we did:

First of all - New content type:
- Create a new content type. In my case I called it "slideshow sidebar"
- Add image field
- Add video field (see http://drupal.org/project/video_embed_field)
- The idea is the content can have an image or a video, but not both. (I control this by using Conditional fields module) Optional
- Create some nodes

Create an image style

Second - Create a view:
- Create a view. Block presentation. Showing content fields.
- Install Colorbox and Views slidehow modules. Colorbox is used for opening the slide in a lightbox way. Views slideshow is needed to create the slideshow.
- Add the fields you have created above.
- Apply a filter for the "slideshow banner" content type
- Select the format as slideshow and configure it as your requirements
- On every field (in the view) select the formatting as color box and aply the image styles you have created previously.

Hope this could help.


Taxonomy Access Control I'm creating a site which will have multiple 'store' sections, with each store's staff needing to edit their own content, but not anyone else's.

The eventual layout will look something like this.

Store One

Page A
Page B

Store Two

Page C
Page D

This is fine - I figure I should have a vocabulary for 'Stores' and a term for each Store, and then use an access control module to limit page editing based on term.

Now, the complexity: we also need a certain amount of custom information displayed on the front page for each store (think opening hours, location etc). I figure the best place way to achieve this is to have a set of custom fields for each term, and then display them in a view that also lists the pages for the store.

Thus the problem: How do I allow a store to edit their term (and it's custom fields) but not others?

Will gratefully receive to any and all potential solutions.

I have a similar use case on my site.  I ended up making stores a content type for that very reason.  Entity reference is your friend cause you can create page a and b and link em to the store content entity.


How to define multiple blocks in a module? Thanks to this tutorial, I cam up with this block-generating module:

function myblockmodule_block_info(){
    $block['myadblocks'] = array(
        'info' => t('My first ad blcoks'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function myblockmodule_block_view($block_key){
    $block = array();

    if($block_key == 'myadblocks'){ //We only want to define the content of OUR block
        //This is the title of the block.
        $block['subject'] = t('First ad block comes here');

        //Define the block content.
        $block['content'] = 'some fancy script comes here';
    }

    return $block;
}

I am wondering how to extend the module to create 2 blocks instead of one?

Simple as:

function myblockmodule_block_info(){
    $block['myadblocks'] = array(
        'info' => t('My first ad blcoks'),
        'cache' => DRUPAL_NO_CACHE,
    );

    $block['myadblocks2'] = array(
        'info' => t('My second ad blcoks'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function myblockmodule_block_view($block_key){
    $block = array();

    if($block_key == 'myadblocks'){ //We only want to define the content of OUR block
        //This is the title of the block.
        $block['subject'] = t('First ad block comes here');

        //Define the block content.
        $block['content'] = 'some fancy script comes here';
    }
    elseif ($block_key == 'myadblocks2') {
      $block['subject'] = t('Foo');
      $block['content'] = 'var';
    }

    return $block;
}

And clear the caches.


RSS Feed does not validate using Views RSS module Drupal version: 7.14

Views RSS version: 7.x-2.0-rc3

I am trying to validate an RSS feed in feedburner for a drupal blog. When I try to validate de xml file at feedvalidator.org I get this error

line 3, column 0: XML parsing error: <unknown>:3:0: XML or text declaration not at start of entity

The xml file is well written (I compared it against another one which validated) and the error I found is that that xml file generated by Views RSS puts three blank lines at the beginning and therefore I think the file does not validate.

I've looked for answers in the oficial Views RSS module issue track but unsuccessfully. I've also created many feed views using Views RSS module, but all of them provide the same error at feedvalidator.org.

I'd like to correct this through the source code of the module, but I do not know where to start or which file I should edit to correct that mistake, just if only through code I could solve this validation.

In some cases this error will be caused by space in one of your modules. Best way to find the issue is to edit module.inc file in includes folder and add this after the drupal_load function in the module_load_all function:

print $module.'|';

you will probably get a huge list but one that starts on line 3 will be the issue.


Send Notification to users with username and password I have imported a set of user information into drupal website and all the users are active.

Now I need to generate the password for each user and send an email to them to notify them that the account has been created.

I found the code here which shows how to update the password of the user by code.

$account = user_load(array('uid' => $userdata['uid']));
$password = user_password();
$username = $userdata['username'];
$updates = array(
  'pass' => $password,
   'roles' => array(
    <rid> => '<role title>';
 ),
);

user_save($account, $updates);

Now how can I notify the users of their new username and password.

You can notify your user by mail using drupal_mail either at the time of updating your password. You arrange your username/password in some template using HTML & send that by help of the above given function drupal_mail.
I hope this help. Let me know if do..


drupal 7 Views: output a field with views php Drupal 7.22
Views: 7.x-3.7

i have the field "content:path" and i want to output the containing data with php. I use a global php field.

it shows me this:

Available variables

$row->path: Inhalt: Pfad

but the output with print $row->path gives out a number only and not the content path. Then i tried print_r($data) to look for the correct output information. but there i dont found anything about the field: content:path

any solution to get the data of this field to php?

regards

Indeed, views PhP doesn't always get the processed field and only gives you the nid instead. You have to use $data as you tried (by the way, easier is to dpm($data) than print_r).

if it doesn't give you any info on what you're looking for, you can simply obtain your content:path by using drupal_lookup_path :

$path = drupal_lookup_path('alias', 'node/' . $data->nid);


Cannot start session for anonymous user I'm trying to start a session for anonymous users (using Drupal 8.2.2), so I can use the private temp store, but the session does not persist. This is what happens with anon users:

// $session is the Drupal `session` service (Symfony Session component)
$session->start();
var_dump($session->isStarted()); // always FALSE
var_dump($session->getId()); // changes from request to request

With an authenticated user, isStarted() returns TRUE, and the session ID remains the same.

How can I start a session for anonymous users that will enable private temp store?

It's not necessary to use a private temp store for anonymous user if you don't have a lot of data. And for anonymous it's not so easy to implement this.

To store data for anonymous users you can simply use the php $_SESSION variable.

$_SESSION['my_module']['data'] = 'My Data';

Drupal will take care of starting and saving the session.

Edit:

OK, to make this official, you should use the request object. See https://www.drupal.org/node/2380327. But drupal core and contrib code still uses the $_SESSION variable. This should be OK at least for D8.

In both cases you have not to handle the session yourself. Drupal will load the session if there is one present when it begins with the request. And drupal will start a new session and saves it at the end of the request, if there is newly added session data.


Set up *only* module configuration page I have a custom module that has a settings page.  Problem is, something about my hook_menu settings is also putting a link to this page in the main admin menu (along with Dashboard, Content, etc).

How do I keep my settings page without seeing the main menu item?

  // admin config option
  $items['admin/configuration/content/brd_contact'] = array (
     'title' => t('BRD Contact Form'),
     'description' => t('Configuration options for the BRD Contact Form module.'),
     'page callback' => 'drupal_get_form',
     'page arguments' => array ('brd_contact_admin'),
     'access arguments' => array('administer brd_contact'),
     'type' => MENU_NORMAL_ITEM
  );

If you want to remove the link from the admin menu altogether, you just need to change the type to something other than MENU_NORMAL_ITEM. MENU_CALLBACK is the standard for this type of thing:

$items['admin/configuration/content/brd_contact'] = array (
  'title' => t('BRD Contact Form'),
  'description' => t('Configuration options for the BRD Contact Form module.'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array ('brd_contact_admin'),
  'access arguments' => array('administer brd_contact'),
  'type' => MENU_CALLBACK
);

After you clear Drupal's caches the link should be gone from the admin menu.

If instead you want to move the link from the top level of the menu into the sub-menu under 'Configuration', then you just need to change the string 'configuration' to 'config' in your path, to match the other system menu paths:

$items['admin/config/content/brd_contact'] = array (...

You'll need to clear the caches before that'll take effect too.


Login with iframe popup I have popup showing on click on a link on my site which shows a login form in iframe.
i am able to login with popup iframe but when i close that popup, i am not logged in on main site and need to login again.
is there a way so that i only need to login once, either from main site or from iframe?

To maintain the sessions configure htaccess to run site with consistent protocol like www, https, if urls for pages are not with same protocols they login issues comes.


TWIG for loop returning first value only I have an array of 5 objects. I would like to loop throught the 5 objects and display fields from within.

I have a for loop in place that is returning the appropriate fields, but it is displaying the same object 5 times.

{% for key, object in featured_resource_nodes %}

  {% if node.field_featured_resources[0].entity.field_resource_type.value == 'whitepaper' %}

  {% elseif node.field_featured_resources[0].entity.field_resource_type.value == 'Datasheet' %}

  {% elseif node.field_featured_resources[0].entity.field_resource_type.value == 'blog' %}

  {% elseif node.field_featured_resources[0].entity.field_resource_type.value == 'video' %}

  {% elseif node.field_featured_resources[0].entity.field_resource_type.value == 'analystreport' %}

  {% endif %}

  {% if node.field_featured_resources[0].entity.field_resource_type.value == 'video' %}

{{ node.field_featured_resources.entity.title.value }}

  {% else %}

{{ node.field_featured_resources.entity.title.value }}

  {% endif %}

{% endfor %}

But this is what is being returned

How do I loop through the objects and have it display the 5 individual results?

It is displaying the same object 5 times because node.field_featured_resources[0] is referenced 5 times. Use the iterator variable object or use node.field_featured_resources[key] instead.

It also may be better to do this without all of the logic in the template. Off of the top of my head,

In template preprocess for the field (PHP), set the class in Attribute.
In module layer (PHP), add a Field Formatter.

Or if Field Formatter are already available, configure Manage Display to display the fields in the desired format.

In template (Twig), print out the field value in the span directly.

Here's some Twig:

{% for key, object in featured_resource_nodes %}

  {% if object.entity.field_resource_type.value == 'video' %}
    {# @todo: Configure Field Display for On-Demand Webinar instead... #}

      {# @todo: consider object.entity.title instead of .value #}

{{ object.entity.title.value }}

  {% else %}
    {# @todo: Configure Field Display for Resource File instead... #}

      {# @todo: consider object.entity.title instead of .value #}

{{ object.entity.title.value }}

  {% endif %}
{% endfor %}


Is it possible to have a custom filter for exposed criteria? When I've created a view where the filter criteria is:

"Content: Has taxonomy terms (with depth) (exposed)"

It works well, but I'd like to filter the terms. I have some "main term" and a lot of "sub-terms" for each "main term". What I'd like for this view, is to search only through "main term", i.e. propose in the list only "main term", not "sub-terms".

How can I achieve this?

If that may help: the parents of main "main term"s == 0 (in other words, "main term"s have no parents)

Here's the solution that works for me. I've been heavily inspired by this solution which is for Drupal 6, so I've adapted it for Drupal 7 and it works for me:

(Nota: I give two hints in the code : (1) how to make a query that asks for all nodes that have no parent (join on taxonomy_term_hierarchy where parent=0) and (2) how to search form terms using LIKE statement):

/**
 * Implements hook_form_alter().
 */
function bcg_form_alter(&$form, &$form_state, $form_id) {
    if ($form['#form_id']=='views_exposed_form') {
        // override the original completion path which was:
        // 'admin/views/ajax/autocomplete/taxonomy/2'
        $form['term_node_tid_depth']['#autocomplete_path'] = 'admin/bcg/ajax/autocomplete/user';
    }
}

function bcg_menu() {
    $items = array();
    $items['admin/bcg/ajax/autocomplete/user'] = array(
        'page callback' => 'bcg_ajax_autocomplete_user',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

/**
 * bcg_ajax_autocomplete_user makes specific autocompletion
 */
function bcg_ajax_autocomplete_user($ajax_search = '') {
    $result = array();
    $vocabularies = taxonomy_get_vocabularies();
    foreach ($vocabularies as $obj) {
        if ($obj->name == 'MY_OWN_VOCABULARY') {
            $vid=$obj->vid;
            break;
        }
    }
    if (isset($vid)) {
        $results = db_query(
            'SELECT td.name ' .
            'FROM taxonomy_term_data td ' .
            'JOIN taxonomy_term_hierarchy th ' .
            'ON th.tid=td.tid ' .
            'AND th.parent=0 ' .
            'WHERE (' .
                ' td.name LIKE :name ' .
                'OR ' .
                ' td.description LIKE :name ) ' .
            'ORDER BY 1',
            array(
                ':name' => '%'.$string.'%'
            )
        )->fetchAll();
        foreach ($results as $obj) {
            $result[$obj->name] = $obj->name;
        }
    }
    drupal_json_output($result);
}


"The service 'serializer' has a dependency on a non-existent service 'entity.manager'" I have a multidomain site and recently I update from D8 to D9.
In my multidomain site I have 2 websites, sharing core and modules, but with different DB.
One of them after update works correctly but the other one not.
I got this error:

The service "serializer" has a dependency on a non-existent service "entity.manager"

In this last 2 days I search and tried some fixes but no luck.
What I tried:

uninstall contrib modules
disable views
uninstall/delete paragraphs
tried a couple of patches

If I return to D8 everything works good.
My modules list:

Dind't find anything related with theses modules and current error.
Any thouths about this migration error?
Thanks in advance :)

After @leymannx and @Kevin tips I could fix my problem, I will leave step by step what I have done, hope help anyone else :)

Set my sites do Drupal 8 again
Search inside my modules folder if any module use "entity.manager"
Update those modules according module page
Update D8 to D9 with composer
Run update.php (this give couple more errors about compatibility in some modules)
Update those modules

I have a couple of custom modules and custom theme, in those I replace

core: ^8.8

with

core_version_requirement: ^8.8 || ^9

Also have couple more contrib modules with the same problem, so I created a patch for those modules.
After all that could run update.php and everything works as expected.


node_submit fill start/end date field I have the following code:

            $node = new stdClass();
            $node->type = 'enterprise_event';
            node_object_prepare($node);
            $node->title = $event->title;
            $node->venue = $event->venue;

My enterprise_event content type also has a date field which is a (start_date - end_date) field, but using the devel module it shows that the field is called date.
How can I set the date->start_date, date->end_date values?

Is there something like $node->date->start_date?

The db columns for a date field's start and end are value and value2 respectively. The usual method to set them would be:

$node->field_date[$node->language][0]['value'] = $from_date;
$node->field_date[$node->language][0]['value2'] = $to_date;


How can I validate that a date is available before prompting the user to complete the rest of a webform? I have a webform that contains a date field. I need to run some code that checks to make sure the date is not already in use (i.e. that no one else has submitted a webform with that particular date). I already have the webform validation module installed, and I know I could use that (create a custom module with custom validators), but the validations don't run until the form is submitted. Because there's a required file upload, I'd rather be able to allow the user to check if the date is available before doing the upload.

Is this possible? How would I go about it?

You have to use AJAX to check if the date is available.

In your form add a button to check for the date, for example:

  $form['submit-check'] = array(
    '#type' => 'submit',
    '#value' => '('Check date'),
    '#ajax' => array(
      'callback' => 'mymodule_check_date_callback',
      'wrapper' => 'datecheck-result-wrp',
    ),
  );

When user clicks on the button, an AJAX call is made. inside the AJAX callback you can check the date availability and return the result in the callback fucntion (mymodule_check_date_callback() in the above example).

AJAX forms are beyond a simple answer, you'll have to check the documentation. I recoomend the Drupal 7 AJAX Forms documentation, the Example for Developers  module that includes AJAX form examples and the Form API Internal Workflow Illustration


How to set paths where to load administration theme? E.g. administration themes are used only on paths that start with /admin/, what if I want to use administration theme on paths like /user/, /users/* or user/login?

There is a module for that where you can set paths where to load your admin theme https://www.drupal.org/project/admin_theme, but my question is for Drupal 8.

You need a route subscriber, where you search for routes, which have a path you want to load with the admin theme, and add the option:

$route->setOption('_admin_route', TRUE);

More info Altering existing routes and adding new routes based on dynamic ones.

Example

There is an example in core. You can configure the admin theme for the node edit form in UI and this route subscriber is applying this configuration:

namespace Drupal\node\EventSubscriber;

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

/**
 * Sets the _admin_route for specific node-related routes.
 */
class NodeAdminRouteSubscriber extends RouteSubscriberBase {

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Constructs a new NodeAdminRouteSubscriber.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory;
  }

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($this->configFactory->get('node.settings')->get('use_admin_theme')) {
      foreach ($collection->all() as $route) {
        if ($route->hasOption('_node_operation_route')) {
          $route->setOption('_admin_route', TRUE);
        }
      }
    }
  }

}


How to approximate user location on IP&Geoloc maps I'm using the combinaison of this modules :

Address field
Geofield
Ip&Geoloc
Leaflet

I need to approximate the location of user's markers on the map for privacy reason.

For exemple if somebody live at 123 addressstreet 10000 Washington I want the marker on leaflet map to point a random location in the area of this address and not the real geocoded location.

What's the best way to do that ?

So, there's probably several ways to do this and your approach will depend on exactly what your needs are for this app.

If you need to preserve the geofield data accurately in the db, but you just want to change the display, you'd need to write a script to modify the Leaflet JS create.point function. This is complicated because you'll have to consider things like the visual context of what you're mapping (i.e. if there's only one house in an area, then even abstracting the location won't really accomplish what you want). Also, your changes will get wiped if your not careful upgrading modules potentially exposing the addresses your trying to hide (depending on how sensitive your data is, this may expose it as well, because someone might be able to dig through the JS and extract the original coordinates). This is also complicated, because simply randomizing the lat-lon data will produce really wonky map results (here's an alternate approach to randomizing user data. I would think that a good approach would be to choose a distance offset, and then randomly apply it to either the lat or lon value. This will keep your point close to where it should be, but it will be offset on either the X or the Y axis to the point where it shouldn't be on the exact location. You could also take the approach where you mis-match the real locations of the users to other users.

If you don't need to store the Lat-Lon accurately, you could write a custom module to hook into the geofield_compute_location function and apply your offset there. This will keep your addresses intact and then apply a similar function to the lat-lon values returned by whichever service is providing your geocoding. This will give you obscured location data to pull into your view.

There's also probably a way of modifying the geocoding request to only provide city-level accuracy, but this is getting over my head.

Hope this helps.


Single menu link not translating I am working with a site which uses many different languages. When switching languages there is always one main menu item which doesn't translate, but the title on the page it links to does translate (menu title and page title are both the same).

The main menu mostly consists of a number of links to taxonomy terms, but this single troublesome link is to a node.

What is going wrong here?

did you translate the site using any module

go for Content Translation core module: http://drupal.org/documentation/modules/translation


How do I make my site with pre-loaded content and pre-loaded config available to others without creating a distribution? I want to be able to provide a simple way for users to install a Drupal website that contains a certain set of content, contributed modules and custom content types. I also want to keep the process of developing this scenario as simple as possible for the developer.

I know that the standard way to do this would be to create a Distribution such as those that are listed at https://www.drupal.org/project/project_distribution. Another example is the Umami content available in a standard Drupal distribution. However, building a distribution seems to be quite a bit of work and should require a commitment to maintain that distribution if it is listed on the Drupal website. So, my question is whether there is a simpler way to allow users to install a website with some given content without my having to make the effort of building a distribution, since whatever I build will not be listed on the Drupal website.

The thought that there may be an easier way was prompted by my experience with some theme vendors. With some theme vendors, the process of installation involves only creating a database from an included SQL script and then starting the installation wizard and only having to input the database credentials. No other answers need to be answered in the installation wizard. It is almost as easy for the user as installing a distribution, and I am wondering if it may be easier for me as a developer to implement.

When I examine some of these theme installations that use this approach (e.g., News+ lite at https://www.drupal.org/project/newsplus_lite) there is no code in the docroot/profile sub-directory, so this approach cannot be using a standard install profile or distribution because that is where extra content or code would be stored for an install profile or distribution. From my investigations so far about creating Distributions or Installation Profiles, I have not yet read how such an approach would work or be implemented. So, I am asking if anyone knows how such an approach (as utilized in the News+ Lite and other similar installations) works and how I might duplicate it.

One of the support staff at MoreThanThemes was kind enough to provide some direction on how they do this. You can see the result in the structure of their free or paid themes. In short, the steps are pretty simple for what might be termed a cloned installation. The steps are basically the following.

Create a clone of the site that you want to install (https://www.youtube.com/watch?v=9NMRwkTzrCM describes that pretty well)
In the clone, overwrite/replace the /docroot/default/settings.php file with the docroot/default/default.settings.php file
Make a clone of the original database (e.g., using MySQLDump, PhpMyAdmin copy or drush sql-dump) and install it in a new database instance that you will use for the cloned site.

If you also have removed the Umami distribution and the minimal distribution from core, then the installation wizard will automatically bypass the choice for which install profile to use. In that case, the installation wizard only asks for the database information, where you will use the information for the cloned database. That will be all you need, and you will have a installed clone of your original website.

From my testing, it looks like the UUID of both sites are the same, just as if you had cloned the original site. So, the main use case from what I can see for this scenario would be if you wanted to share a copy of your site with other people, including the content (like the theme companies do). The only difference from a regular distribution like Umami or OpenAtrium from the user's standpoint is that they have to load the database file on their own before they do the installation. But from a developer's standpoint, this seems to be a much easier approach to sharing a website with the content and should be adequate for many users who want to test out your site.

I am surprised that this is not more widely documented and perhaps I have missed something here. But in my tests so far, this seems to be all that is needed. Hopefully this will help someone else who may need this simpler approach.


How to use Twitter Bootstrap with panels? I am using D7 to built a new site. I am using Twitter Boostrap to create responsive themeing in my site. But most of my design has to be built with panels, the panels does not work responsive with the twitter bootstrap. I found that adaptive theme can be used with panels to make it responsive, But my requirement is to use twitter bootstrap for responsive themeing.

Is there an chance by which I can make the panels responsive with the twitter bootstrap?

Thanks.


entity reference as attribute, is it possible in commerce v2? User story:
The end-users should be able to pick an image from an image gallery and attach that image to a product before adding it to cart

In Commerce v1 this was possible via line items by defining an entity reference field, along with a couple of other modules e.g. entityreference view widget. A sample, although not 100% finished, can be found in d7demo when you click on the 'add item' button.

I used entity reference since the images are actually nodes with a file field, so that i could also categorise them via term references.

Is the above functionality somehow possible on commerce v2? I cannot find  'line items' as used in v1, but only attributes and variants. However i cannot seem to find the way (configuration or contribs) to achieve the above functionality.

Any pointers to the above issue are very much appreciated.

Since product attributes are entities in CommerceV2, the following module should cover your needs => https://www.drupal.org/project/entity_browser

Some points to consider:

It is still in alpha
It is strongly supported at the moment by the community and especially the Drupal Media Team
It has more than 5K downloads.

There is also a recent presentation available from DrupalCon Dublin 2016 => https://www.youtube.com/watch?v=VXor-HZiYrs

Update:
Following the documentation, you may also need to look into "Product Variations Fields", http://docs.drupalcommerce.org/v2/product/products.html.
This CV2 functionality seems to allow you to expose specific fields to the end-user for e.g. uploading images in order to modify/configure a product.

Good luck!


Enable admin theme in my install profile Is it possible to enable an admin theme in my install profile?

Used this:

// Enable themes
  $enable = array(
    'theme_default' => 'geoslate',
    'admin_theme' => 'adminimal_theme',
  );
  theme_enable($enable);

  foreach ($enable as $var => $theme) {
    if (!is_numeric($var)) {
      variable_set($var, $theme);
    }
  }

Yes, you just need to set the relevant variable (admin_theme), e.g.

variable_set('admin_theme', 'seven');


Button with different value and label / text in Drupal 8, I want my form display such a (submit) button:

<button name="name" type="submit" value="value">Not the value</button>

So basically, the button value (that will be submitted) shall be different than the button text / label (following that solution).

Is that possible with the Form API? If yes, how?

I think this might be a duplicate of a question I posted a few weeks ago for Drupal 8.

Original question: https://drupal.stackexchange.com/a/226494/57

Some more write up: http://kevinquillen.com/drupal/2017/01/28/adding-twig-template-suggestions-for-form-elements

Basically I wanted to target just one submit, hence that technique. Simply changing the #type to button is not enough in the Form API to get that result you're asking for.


Selling user accounts with Ubercart module A question regarding the registration process.
The project I am currently working on has a 1 step registration form (Drupal default). Upon completion of the form an account is created and the new user is e-mailed with an activation e-mail. At this point they are taken to the payment (ubercart) page to purchase the applicable role for the account.

Issue is, I need the registration form to only be shown either after the account has been paid for OR not to actually create the user until payment has come through.

Is this possible, and if so could you please point me in the right direction?

Thanks!


When does the core search module become worth using? I mean, is there any approximate number of nodes or just website pages (or any other measures of website size) when the out of the box Drupal search module is still worth using? I understand that much depends on webserver, but there should be some general guidelines. E.g., should I use the core search module if I have a Drupal website with 5K nodes?

It really depends on your situation.

You should use Drupal search core module only when you don't have any performance issues (as it's using database backend), your site is not so complex (in terms of search functionality) or you're not advanced user and you are not looking to make make your site more complex than already is.

Please note that high traffic sites running search queries against the database can affect overall performance especially when the database becomes the bottleneck. Secondly Drupal core search doesn't scale much.

Therefore using Search module from Drupal core it's not adequate when you have thousands of nodes on site. In this case you should use either Search API (with solr backend) or Apache Solr Search modules. Using Apache Solr provides advanced and accelerated search platform which features faceted search (Facet API), searching multiple sites, real-time indexing, dynamic clustering, NoSQL features, indexing attachments and many more. It's a great way to have fast access to big data on a budget. Basically Solr solutions are designed for searching the same way as Search API is designed to replace the core "Search" module.

It's also worth to mention about Elasticsearch as alternative for Solr, but it's topic for another discussion. The decision to choose whether Elasticsearch or Solr really depends on the project requirements and the decision needs to be made by experienced Drupal developer or solution architect.

In overall, Databases and Solr have complementary strengths and weaknesses, so you've to investigate these further depending on your project. However core search has a very limited functionality.

Please find the following chart which shows Drupal core's search performance vs. Solr based on its execution time.

  The results are pretty clear: Drupal core's search takes longer as you put more words in the query. This may seem fair enough, as it makes the searching more complex. But when using Solr you can't barely see any difference at all. It doesn't really matter if you search for 1 or 6 keywords. The response time for a page is almost the same.

  DISCLAIMER: This is not a valid test, and the result is only used here to give a glimpse of what the difference might look like. The results will most likely look different on your environment. You can see the shell scripts I used to perform the test in the document folder I pointed out earlier. All tests were performed on a system where content was using cache.

Please find the following table which is comparison Solr v.s. Relational Database:

See also:

Search API vs Apache Solr Search Integration in Drupal 7?
What are the advantages of using Apache Solr over the core search module?
Solr or database? at stackoverflow SE
Search API documentation at Drupal.org
Why use Solr? at Solr Wiki
Solr's features at Solr
Enlightening - The Dark Art of Solr Search with Drupal at annertech


Is there some way to compress CSS and Javascript only for certain users? When I check the source of my web pages I am appalled at the amount of Javascript links in the page, but I have disabled the CSS and JS compression as I am often in development mode.

Is there some way to disable the compression for admins and developers and enable it only for viewers?

You're looking for AdvAgg. If the user has the correct permissons you can add ?advagg=-1 to the URL and all CSS/JS files are un-aggregated for that page request. You can also set a cookie on the admin/config/development/performance/advagg/operations page so you no longer need to add that to every URL.


How to create custom menus with different path I want to create custom menus.

I created dashboard named menu,
now i want to provide links under dashboard menu,

i created one link named myprofile.

and it is asking for path. i want to link it with user edit page who is logged in.

I have no idea regarding this.

Does anybody have idea regarding this.

Thanks

If you want to give user view page then this :

1) You need to give path as user. That will take you to the currently logged-in user account.

Or if you want go to view edit page:

2) You can use menu token module to give path as user edit page.You can use the token replacements to get to the user edit page.Hope this helps you.

3) You can use user/[current-user:uid]/edit once you have the menu_token module installed.But i dont know why its not working.

You can try installing me aliases module and give path as user/me/edit. This will give option for editing user account.Hope this resolves your current issue.


Function in views tpl How can I add a function  in my custom views .tpl page or where can I write my function and call that function in my views .tpl ?

You can write the function in any php file that gets loaded.  PHP is not sequential in loading/processing files, it will load them first then process.


How can I filter content with conditional taxonomy terms? I have created a vocab (called like apple) that contains;
iOS: iPhone, iPad, iPod
Mac OSX: Mac pro, Macbook air, iMac...

Now I need/want to create a page/view; when my customer select 'iOS' from first drop-down, they can select iPhone, iPad etc. from second drop-down. And my page will be loaded with chosen values.

İt will like a multi-conditional boxes.

How can I do that, could you help me please?

Regards.

You can use https://www.drupal.org/project/shs in combination with views.

From the project page:

Views (exposed filter)

add a new filter using the field set-up as "Simple hierarchical select" or
use "Content: Has taxonomy terms (with depth; Simple hierarchical select)"
as a new filter
use "Simple hierarchical select" as selection type
select "Expose this filter to visitors, to allow them to change it"
enjoy ;)


Double values (products) in Commerce cart form I use Drupal Commerce version 8.x-2.15. I have a multilingual Drupal site with multiple languages based on domain.

mystic.com -> EN language
mystic.eu -> NL language

etc

I added relationships:

(order_items: Order item) Product variation
(Product variation) Product

To get the image_field available to show a thumbnail in my cart form. This works fine.

After I added those relationships and I add one product to my shopping cart and I see now the number of times that I translated my product back in the shopping cart, like:
My product
My product
My product
My product

(so above product is translated into 4 languages).

I've fixed this by adding a filter to the view:

Product: Translation language Is one of Content language selected for page

It looks like this is working but I see now 2 values (see screenshot)

It doubled the added product. But the price and quantity shows 1.

In the commerce_cart _form view under Advanced, edit the Query Settings, and set it to DISTINCT.


Links converting to plain text I've got a function that should generate a link as such Set Password, which does happen, but it is generating as plain text.

My guess is that this is due to my use of the t() and l() functions in the manner I'm using them.

Here's my code:

  global $user;
  $account = new stdClass();
  $account->uid = $user->uid;
  $account->login = $user->login;
  $account->pass = $user->pass;
  $link = l('Set Password', user_pass_reset_url($account));
  $token = t(token_replace(variable_get('listing_edit_free_activated_page', 'Your free content has been activated. Thanks! @link')), array('@link' => $link));

As you can tell, I'm attempting to generate a one-time user login link with the text, "Set Password". The token_replace() isn't really relevant to this problem.

Am I completely without options here? I want to use both t() and l() here - there's not really an easy way to not use both that I can see.

How do I use both while still maintaining the structure of $link as a link?

The t function's first argument is a string, and the second is a keyed array of arguments (search => replace).

The string your passing in is:

token_replace(variable_get('listing_edit_free_activated_page', 'Your free content has been activated. Thanks!'))

And the replacement your searching for it @link.

As the string @link does not appear in the string your passing in no replacements are made.

Here is an example where a replacement will be made:

$text = t("@name's blog", array('@name' => format_username($account)));


Hook for removing product from cart I am removing products from cart programmatically using such a code:

commerce_line_item_delete($line_item_id)

The problem is, I cannot find any hook, that would be invoked after removing product from cart.
I have tried hook_commerce_cart_product_remove, but this hook is not called when removing product with commerce_line_item_delete function.

How can I remove product from cart programatically, so I can use hook after it happen?

If you want to remove product programatically, and still allow other modules to interact with this event, you should invoke hooks explicitly just after deletion using module_invoke_all:

module_invoke_all('commerce_cart_product_remove', $order, $product, $quantity, $line_item);

That way you have a choice - you can call it and emulate regular deletion, or you can omit it, and prevent any marketing interactions etc that your user did not trigger.

Alternatively, because line items are entities, you should be able to hook into their deletion with generic hook_entity_delete, without any modifications to the way you invoke deletion.


Does drupal_http_request ever cache results? Does drupal_http_request ever cache results?

I am making a request that looks something like:

$url = "http://www.example.com/some/rest/service?" . drupal_http_build_query(array(
    "id" => 1234,
));

$options = array(
    "headers" => array(
        "Pragma" => "no-cache",
        "Cache-Control" => "no-cache",
    ),
);

$response = drupal_http_request($url, $options);

The problem is that I am getting back some cached results.  I am not looking for ways to cachebust this request; I am trying to rule out Drupal caching this internally so I can work with the far end to see why their Varnish is being weird.

No, drupal_http_request() is not doing any kind of caching. If the results are cached then it's either the server or some intermediary system, e.g. a proxy.


How to alter the query that selects node in the admin/content page i need to alter the list of nodes displayed in the admin/content page (the basic administrative page for content) depending of the role of the user. For example if the user has a role, i want him to display only pages with content type = article.

I thought i could modify the query using hook_query_alter

function provintegra_query_alter(QueryAlterableInterface $query){
    fb($query);
}

but i was wondering on how to add the condition i need and how to find the correct query to modify. Of course other solutions arre accepted, but i can't use views because i need to have a page that it's exactly like the one that is displayed normally (with the same filters and links for editing). I need to restrict visualization to certain content types (articles for example but also user defined content types) and if possible to content created by the user

I had this issue in Drupal 6 just now, on the "/admin/content/node" overview page.  I wanted to hide certain content types -- and you can't do that with views per se because the admin page is a form, where you can easily bulk update.  Sorry that I'm not putting a D7 answer -- this may not be exactly what you are looking for, but it works for me in 6, and maybe others will find it helpful:

/**
 * hide child content types from /admin/content/node overview
 */
function [your module]_db_rewrite_sql($query, $primary_table, $primary_field, $args){
    if(arg(0)=='admin'&&arg(1)=='content'&&arg(2)=='node'){ // /admin/content/node page
        if($primary_table=='n' && $primary_field == 'nid'){
            if(!user_access("[your access callback for viewing this type]")){
                  $return['where'] = 'type != "[type to hide machine name]"'; // or you could use type == type_name
                  return $return;
            }
        }
    }
}

again.. that's D6, so I'm sorry but hopefully that will get you started


How do I get emails about core update? I'm not talking about updates within your site, I'm talking about waking up in the morning, checking your email and seeing an email sent to you from Drupal.org that new core version is out.

7.58 critical update just came out and I found out about it from a buddy.

I clicked follow at https://www.drupal.org/project/drupal but I get no email notification about any core versions coming out. I get only notifications for module issues that I'm subscribed to, I expected the same when clicking Follow in the modules page.

Log in on your drupal.org account (or create one)
Go to My Account > Edit > My Newsletters (https://www.drupal.org/user/[uid]/edit/newsletter where [uid] is your user ID)
Check "Security announcements" and click "Save"


How to add html tags to account setting emails? I am working on a project where I need to add some custom headers to the email which we send to the user on registration. Is there a module which support this functionality?

Have a look at Mail Headers project.
As says doc, it allows you to control and modify any (almost any) mail header.


Drupal module updates failing through administrative interface after update to 7.50 So, I just updated my site to Drupal 7.50, and in addition to being informed of a host of modules that weren't properly uninstalled, it seems that I can no longer update modules through the administrative interface. I have a long list of module updates and it will be annoying to do all of them manually.

So is there some setting that changed? Or how can I get back to being able to update modules through the admin UI. I've tried a few at a time, as well as one at a time. I get the following warning after trying to update

The file could not be created.
https://ftp.drupal.org/files/projects/google_analytics-7.x-2.3.tar.gz could not be saved to temporary://update-cache-d103ec38/google_analytics-7.x-2.3.tar.gz.
The file could not be created.
https://ftp.drupal.org/files/projects/webform-7.x-4.14.tar.gz could not be saved to temporary://update-cache-d103ec38/webform-7.x-4.14.tar.gz.
Downloading updates failed:

Failed to download google_analytics from https://ftp.drupal.org/files/projects/google_analytics-7.x-2.3.tar.gz
Failed to download webform from https://ftp.drupal.org/files/projects/webform-7.x-4.14.tar.gz

This is most likely a problem with your file permissions. A quick test on simplytest.me showed that module installation is not broken in 7.50.

I would try to check the file_temporary_path variable under:

"Administrator -> Configuration -> Media -> File System"

And see that the web server can write to the configured directory.

If my assumption is correct, then also all other file uploads will fail, so it might be a good idea to test uploading an image to an article, too.


Local Drupal installation can't copy files to another computer on network I want to use file_copy to copy a file from Drupal public directory to a shared folder of another

computer on the same network.
I can access the shared folder by Finder (Drupal is installed on

MAMP) but coping files in that directory gives me the same error:

  The specified file public://file.pdf
  could not be copied, because the destination directory is not properly configured. This may be
  caused by a problem with file or directory permissions. More information is available in the system log.

The shared folder is totally writable.
I tryed putting an alias on httpd.conf but no luck
Could it be an apache permission problem?
Or can I solve the problem within Drupal?

Thanks a lot

Go to the MAMP console under "General" tab, go to the setting for "Run Apache/MySQL server as user".

It should be setting to www (Apache) / mysql (MySQL).
So you need to change it to username (Apache) / username (MySQL).

Save and restart the servers

Refresh the browser, then change it back to www (Apache) / mysql (MySQL), save and restart, and everything should be working


How to override a view template in Bootstrap sub-theme I'm using a Bootstrap sub-theme and am using the templates directory to override the templates for specific pages and is working ok.

I'm looking at this page in order to override the template file for a specific view, have added the file with my view name inside the template folder but its not working. Neither I can find the Bootstrap original views-view-unformatted.tpl.php in the bootstrap folder.

Can anyone point me in the right direction?

This is how I template my views in bootstrap sub-themes with or without the bootstrap views module b/c sometimes you need to change those as well :)

First - In my sub-theme's for Bootstrap I make a folder called 'views' in the 'templates' folder (this is for sanity and structure, I think it works without the folder but don't quote me on that). There's only one view template in the bootstrap theme, for a responsive table so you can template anything however you want using the normal views templates.

You can also use the bootstrap views module mentioned in the other answer but you may still want to template those again in your subtheme so you will need the above folder '/templates/views' and now the  documentation page you mention has some of the templates but views comes with a way to accomplish this without that page in the UI.

Loose instructions for views templates.

open a view in the admin view UI screen
look on the left hand column for advanced, expand if needed.
look to the very bottom of that column and you will see Theme: Information
click that link, pop up appears
this is your views theming information, you will see that the current template being used is in bold.
I usually go find that template beg used, copy that into my subtheme's '/templates/views' folder and choose from the list in the popup what I need to name the file, like for a view named "repair" I wouldn't want to use views-view.tpl.php and overwrite all the views display output, I would want to use views-view--repair.tpl.php so I name my file that and change something subtle.
then I go hit the rescan templates files button in the popup and my new template will be in bold.
I save the view and go make sure I did something productive.
don't forget to clear cache if you aren't seeing what you want to see, it usually pops up after that, if not double check your naming of the file.

Hope that helps, views templates rock and I use them a pretty good bit just let me know if that doesn't work.


How to create Newsletter in drupal? I want to create a newsletter in drupal. What i want is the ability to subscribe the users that are not registered to the site. I can use the third party or any contrib modules available . Any help ..?

Check out Simplenews module.

Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and authenticated users can opt-in to different mailing lists. HTML email can be sent by adding Mime Mail module.


Programmatically set class on extended field type Earlier I created an extended version of the Node class. I called it AbleNode and it extended BaseNode. In order to set all nodes to this node type I added this to my custom .module file

function ablecore_entity_type_build(&$entity_types){
    if(isset($entity_types['node'])){
        $entity_types['node']->setClass('Drupal\ablecore\Plugin\Node\AbleNode');
    }
}

This works fine but I'm not sure how to do this with an extended field type. Here is the code for my field class that is extending the BaseFileFieldItemList class

<?php
namespace Drupal\ablecore\Plugin\Field\FieldType\FileFieldItemList;
/**
 * @file AbleNode.php
 */
use Drupal\file\Plugin\Field\FieldType\FileFieldItemList as BaseFileFieldItemList;

class AbleFileFieldItemList extends BaseFileFieldItemList {
    public function style($image_style) {
        $image_style = \Drupal\image\Entity\ImageStyle::load($image_style);
        if (!empty($image_style)) {
            return $image_style->buildUrl($this->getEntity()->getFileuri());
        } else {
            return false;
        }
    }
}

I see how I was able to turn all nodes into AbleNodes, but I'm not sure how to make all FileFieldItemLists into AbleFileFieldItemLists. Is there a hook I can use to setClass on the field whenever I encounter it? Keep in mind that I'm not trying to create a brand new field, I just want to give more functionality to existing field types.

This is untested, but I'm pretty sure you just need to change the list class for the field types using hook_field_info_alter():

function ablecore_field_info_alter(&$info) {
  foreach ($info as &$field) {
    if ($field['list_class'] == '\Drupal\file\Plugin\Field\FieldType\FileFieldItemList') {
      $field['list_class'] = '\Drupal\ablecore\Plugin\Field\FieldType\AbleFileFieldItemList';
    }
  }
}


how to put markup around indiviual radio buttons Is it possible to set the markup (#prefix and #suffix) around individual radio buttons? I know that I can add these fields to the radio button group, but that would mean that I would be wrapping the entire group, which is not what I want to do.

According to the Forms API matrix you can.  See https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#radio  Have you tried some code to see if it does what you are looking for?

You can set '#options' for the radios to be a variable:

$rads = array(
  0 => '' . t('Yes') . '',
  1 => '' . t('No') . '', );

$form['fldset8']['exp_radios'] = array(
 '#type' => 'radios',
 '#options' => $rads, );


How to solve the huge HTTPRL error that fills down all of Cron \ Status report? Background

For some time now, and only in some occasions, when I run CRON (Status report), I see a huge error (About 170 rows) at the HTTPRL section (related to the HTTP Parallel Request & Threading Library module). It happens randomly - Sometimes it happens and sometimes it doesn't. When the error does not appear, the HHTPRL "section" in status report is all green. Here is a screenprint of it:

What I already tried

I've tried to play a bit with the HTTPRL preferences, but nothing really helped... For example, tried to change at "IP Address to send all self server requests to": from -1 to 1. Also tried to uncheck "Enable background callbacks", But IIRC nothings has changed.

The only changes I saw (When the error was apparent) were when I unchecked "Enable background callbacks", or otherwise, when I check-marked "Use httprl to handle drupal_http_request" --- When I ran Cron afterwards the error's text went from about 170 rows to 90 rows. But this data doesn't help me to understand Why the error was there on the first place and even worse - Why it appears randomly?

Bottom line

Is this a known problem? You might have an idea why this happens or a tip how to try to solve it?

The solution (or at least work around?) could be what is described in Comment # 8 of Issue # 2450725 related to the HTTP Parallel Request & Threading Library module:

change "'timeout' => 7," to "'timeout' => 1,"
This timeout is used in lock_acquire() that probably locks Drupal for 7 seconds, but in httprl config httprp waits only 5 seconds for a response.

Comment # 17 in that issue also contains a corresponding patch, which looks like so:
diff --git a/httprl.install b/httprl.install
index d7e2963..e2d4f04 100644
--- a/httprl.install
+++ b/httprl.install
@@ -177,7 +177,7 @@ function httprl_install_http_test($mode, $blocking = FALSE) {
       // Setup options array.
       'options' => array(
         'blocking' => $blocking,
-        'timeout' => 7,
+        'timeout' => 1,
         'max_redirects' => 0,
         'headers' => $headers,
       ),


Insert several lines in field collection programmatically I have a problem with field collection and entity reference fields. I have a field collection called 'field_co_intervenant' and i want to add several entities in this field collection and after saved my node. But i got an error with the index i think, because when the node is saved, there is just one reference entity in my field collection. You can see the code here :

$intervenant is the array of my 'nid'.

if(!empty($intervenant)) {
    //Create entity
    $fieldcollection = entity_create('field_collection_item', array('field_name' => 'field__doc_fc_intervenant_tab'));
    //Attach entity
    $fieldcollection->setHostEntity('node', $node);
    //Fill field
    $i = 0;
    foreach ($intervenant as $val) {
        if($val != null) {
            $fieldcollection->field_fc_intervenant_tab[LANGUAGE_NONE][$i]['target_id'] = $val;
            $i++;
        }
    }

    //Save entity
    $fieldcollection->save();
}

How can i save all my values in the field collection and not just one ?

Thanks

First be sure that that field in your field collection field setting accept multi value then try save your item with

  $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
    'revision_id' => $field_collection_item->revision_id,);

and finally be something like

if(!empty($intervenant)) {

    // you should have $node here
      $field_collection_item = NULL;
      $field_collection_item = entity_create('field_collection_item', array('field_name' => ''field__doc_fc_intervenant_tab '));
      $field_collection_item->setHostEntity('node', $node);
      $field_collection_item->save(TRUE);
          foreach ($intervenant as $val) {
             if($val != null) {
      $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
        'revision_id' => $field_collection_item->revision_id,);
}
}
    $fieldcollection->save();
}


Custom authentication provider returns 403 for _access: 'TRUE' The Jenny module implements an API and needs to authenticate based on this header...

Authorization: Jenny 8675309

Here is my API route...

jenny.api.get:
  path: '/api/jenny'
  defaults:
    _controller: '\Drupal\jenny\Controller\ApiController::get'
  methods: [GET]
  requirements:
    _access: 'TRUE'

The API returns data for any type of user, but for some roles additional data is included.

Here is my implementation for AuthenticationProviderInterface...

public function applies(Request $request) {
  if ($header = $request->headers->get('Authorization')) {
    if(strpos($header, 'Jenny ') !== FALSE) {
      \Drupal::logger('jenny')->info('this applies');
      return TRUE;
    }
  }
  return FALSE;
}

public function authenticate(Request $request) {
  \Drupal::logger('jenny')->info('authenticate');
  return $this->entityTypeManager->getStorage('user')->load(1);
}

This example code authenticates the admin user whenever there is an Authorization: Jenny header. Obviously the real code implements the logic to authenticate the proper user.

Here's what shows up in the log...

uid  type            message
0    jenny           this applies
0    jenny           this applies
0    jenny           authenticate
1    jenny           this applies
1    jenny           this applies
1    jenny           this applies
1    accesss denied  /api/jenny

It shows the uid changing, so it suggests that my authentication provider is doing it's part, but for some reason it's still coming back 403 access denied even though the route is _access: 'TRUE'. A request for /api/jenny without an Authorization: Jenny header returns the expected data.

This makes no sense to me. Could someone please point out what I'm doing wrong or why this isn't working? Thanks.

Upon further review, this is happening on all routes if there is an Authorization: Jenny header, even though the authentication provider is returning the admin user.

Routes need to specify the authentication providers they want to support.

By default, that's session, so authenticating with something else is not allowed.

You do this by specifying _auth: ['your_authentication_provider'] within the options: key of your route.


In hook_boot jQuery is undefined I am doing some processing in hook_boot since I need that code to run on every page, irrespective of whether or not they are cached.

As a result, jQuery is undefined when I add inline JavaScript to the page.

function hook_boot() {
  drupal_add_js("jQuery('document').ready(function() { //do });");
}

The idea is that we will potentially load a lightbox on every page after processing in hook_boot.

The only way I can see round this is using variable_set and then retrieving that in another hook (e.g hook_node_*). However, that might not be sufficient since we need it to run on every page.

How would you get round this?

If you add the JavaScript in hook_init, then it will be there the next time the page is served from the cache.

And if the page is served from the cache, then calling drupal_add_js in hook_boot will not add JavaScript to the page, because the page is not assembled from calling the page callback, but is served from the cache.

Use hook_init instead of hook_boot.


Setting the permission for editing block content with a specific role I have installed the modules below, but still can not set the permission for editing a block body with an specific role. Does someone know how to solve this issue?

Thanks

Block Access

Block Content Per Role

Both of those modules look more like they are meant to simply display different blocks/content depending on user role.  You may be better off utilising Nodes In Block.   Create a content type, or use one of your existing content types and create a node that has the required block content.  Lastly, allow certain roles permissions to edit that particular node.  That will in turn update the block content!


How to fix migrate query() that's breaking my migration? So I have a Drupal 2 Drupal (d2d) migration configured as follows:

class RanchoAboutNodeMigration extends RanchoNodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    ...

    // This is an entity reference field
    $this->addFieldMapping('field_attached_images', 'iid')
         ->separator(',')
         ->sourceMigration('Image');
    ...
  }

  protected function query() {
    // Get the default query
    $query = parent::query();
    $query->leftJoin('image_attach','ia','n.nid = ia.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT ia.iid)', 'iid');
    $query->addField('ia', 'iid', 'iid');
    $query->addField('ia', 'nid', 'inid');

    return $query;
  }
}

The query causes two problems:

I can only import items one at a time through drush mi or the UI
Most important: I'll eventually run into a PDOexception for duplicate rows and then the error "Could not save to map table due to NULL value for key field nid" with migrate attempting to move totally empty rows.

Both items can be addressed by commenting out the line with $query->addExpression(), but then I miss some desired images. When the migration is actually working, everything migrates correctly, including the referenced image(s).

Any thoughts on what's causing this bizarre behavior when things go wrong and how to address it?

Only thing I can think is to create a local query in prepareRow(), but I don't think I've seen anyone else do that before.

Adding a query to prepareRow() is the way to go:

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    $query = Database::getConnection('default', 'd6source')
           ->select('image_attach', 'ia')
           ->fields('ia')
           ->condition('nid',$row->nid);
    $query->addExpression('GROUP_CONCAT(DISTINCT ia.iid)', 'iid');
    $query->groupBy('ia.nid');
    $result = $query->execute();
    foreach ($result as $r) {
      $iid[] = $r->iid;
    }
    $row->iid = implode (",", $iid);
  }

This has the huge added benefit of not messing up the source row count.


Migration configuration I'm setting up a migration from an URL with JSON on it.

Got the first level values without any issues. Currently I'm stuck at nested arrays which resemble something like this:

{   "content": [
    {
      "id": 148,
      "hardwares": [
        {
          "hwId": 16,
          "products": [
            {
              "pid": 2097,
              "productName": "ProductName1",
            },
            {
              "pid": 2100,
              "productName": "ProductName2",
            },
            {
              "pid": 2103,
              "productName": "ProductName3",
            },
            {
              "pid": 2094,
              "productName": "ProductName4",
            }
          ]
        }
      ]
    },
   ],
}

I have a custom content entity with a text field called Product Names, the field is a multi-value field. I've been trying to get the productName values and populate the field. Basically this JSON here would create one entity, and then get the value by this hierarchy:

hardwares->products->productName

I can't seem to grasp the usage of the sub_process plugin and I would really appreciate any hints or any working examples.

What I did:

I defined a field entry in the source:

  name: hardwares
  label: 'Hardwares'
  selector: hardwares

In my process:

_products:
    plugin: sub_process
    source: hardwares
    process:
      products:
        plugin: sub_process
        source: products
        process:
          productName: productName
field_products:
    plugin: flatten
    source: '@_products'
_hwIds:
    plugin: sub_process
    source: hardwares
    process:
      hwId: hwId
field_hardware_ids:
    plugin: flatten
    source: '@_hwIds'

In order to get to the 2nd level of my data array, I needed to nest the sub_process plugin. I flatten the result afterwards in order to get a numerically indexed array which resembles the multiple value field structure.


Failed to import Bootstrap Paragraph sub module configuration I tried to implement the Hero with Xeno Hero in the Bootstrap Paragraphs in Drupal 8.  I encountered an error when I tried to import the config of the sub module.  I am not sure if I do it the right way but I ended up getting this error.

  The configuration cannot be imported because it failed validation for the following reasons:
  Configuration paragraphs.paragraphs_type.paragraph.xeno_hero.default depends on configuration (field.field.paragraph.xeno_hero.xeno_content, field.field.paragraph.xeno_hero.xeno_invert, field.field.paragraph.xeno_hero.xeno_offset, field.field.paragraph.xeno_hero.xeno_overlay, field.field.paragraph.xeno_hero.xeno_parallax, paragraphs.paragraphs_type.xeno_hero) that will not exist after import.

What I did is importing a single item, but I don't know which configuration type to go for, so I tried Entity Form Display and Entity View Display as well as Fields.

Could anyone just point me to the right direction or show me hints that I could follow to get this right?

To use that module, you should upload it to the site, usually in the /modules/custom/ folder since it is not an official Drupal.org module, and then enable it.  The configuration should get installed when you enable it.  You should not have to do that manually.

After the module is enabled, you need to edit the Paragraph reference fields that you want to make this bundle available in.

Hope that helps.


Is it possible to join dynamic tables (subqueries) using db_select()? I've got a complex query I'm trying to convert to db_select().

SELECT c.cid, c.pid, c.thread, count.replies, SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1)) as torder
FROM comment c
JOIN(
    SELECT count(*) as replies, SUBSTRING_INDEX(LEFT(thread, LENGTH(thread) -1 ), '.', 1) as torder
    FROM comment
    WHERE nid = 1
    GROUP BY torder
) as count
ON SUBSTRING_INDEX(LEFT(c.thread, LENGTH(c.thread) -1 ), '.', 1) = count.torder
WHERE c.nid = 1 ORDER BY count.replies DESC, torder ASC;

I'm not sure how join through a select statement, if it is possible, or if there is another alternative.

I don't need to return anything from the join (count.replies is only there for show) so maybe there is another option other than join.

I'm trying to select order by the top-level comment with the highest number of replies and it's children.

The result prints this for my test data:

+-----+-----+-----------------+---------+----------------+
| cid | pid | thread          | replies | torder         |
+-----+-----+-----------------+---------+----------------+
| 262 |   0 | 03/             |      11 | 03             |
| 269 | 262 | 03.00/          |      11 | 03.00          |
| 272 | 269 | 03.00.00/       |      11 | 03.00.00       |
| 270 | 262 | 03.01/          |      11 | 03.01          |
| 273 | 270 | 03.01.00/       |      11 | 03.01.00       |
| 275 | 273 | 03.01.00.00/    |      11 | 03.01.00.00    |
| 276 | 275 | 03.01.00.00.00/ |      11 | 03.01.00.00.00 |
| 280 | 275 | 03.01.00.00.01/ |      11 | 03.01.00.00.01 |
| 277 | 270 | 03.01.01/       |      11 | 03.01.01       |
| 278 | 270 | 03.01.02/       |      11 | 03.01.02       |
| 271 | 262 | 03.02/          |      11 | 03.02          |
| 264 |   0 | 04/             |       3 | 04             |
| 281 | 264 | 04.00/          |       3 | 04.00          |
| 282 | 264 | 04.01/          |       3 | 04.01          |
| 260 |   0 | 01/             |       2 | 01             |
| 279 | 260 | 01.00/          |       2 | 01.00          |
| 261 |   0 | 02/             |       2 | 02             |
| 274 | 261 | 02.00/          |       2 | 02.00          |
| 283 |   0 | 05/             |       1 | 05             |
+-----+-----+-----------------+---------+----------------+

The 'replies' number includes the top level comment which is OK because I'm only using this for ordering and includes all of the comments in a thread for each comment which is by design because I want to group all of the comments first by how many comments are in their group.

The SELECT in the join returns the number of replies for each top level comment:

+---------+----------+
| replies | torder   |
+---------+----------+
|       2 | 01       |
|       2 | 02       |
|      11 | 03       |
|       3 | 04       |
|       1 | 05       |
+---------+----------+

I can't to this using db_query because I'm trying to overwrite the query in comment_get_thread() using hook_query_TAG_alter().

I've tried using $query->join() but don't see where it is possible to put in an argument.

EDIT:

Thanks so much for your answers. Here is the db_select translation of the sql query above if anyone is having trouble with this in the future:

$subquery = db_select('comment', 'c')
  ->fields('c', array('thread'))
  ->condition('c.nid', '1134');
$subquery->addExpression('COUNT(*)', 'replies');
$subquery->addExpression('SUBSTRING_INDEX(LEFT(c.thread, LENGTH(c.thread) -1 ), \'.\', 1)', 'toporder');
$subquery->groupBy('toporder');
$query = db_select('comment', 'c')
  ->fields('c', array('cid', 'pid'))
  ->condition('c.nid', '1134');
$query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
$query->addJoin('', $subquery, 'count', 'SUBSTRING_INDEX(LEFT(c.thread, LENGTH(c.thread) -1 ), \'.\', 1) = count.toporder ');
$query->orderBy('count.replies', 'DESC');
$query->orderBy('torder', 'ASC');
$results = $query->execute()->fetchAll();

Both db_select and addJoin documentation says clearly that the table

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

So,

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


How to override the H1 element from module? I am trying to override the h1 element on a node view for a content type. I do not want to change the meta tags or anything else. Any tips how I could achieve this?

I have been trying something like this, but it has no effect

function xxx_preprocess_node(&$vars) {
    dpm($vars);
    if ($vars["type"] == 'mycontenttype') {
        $custom_title = $vars["title"] . " TESTING";
        $vars['title'] = $custom_title;
        dpm($vars);
    }
}

This is the sample code that will overwrite the title page of Drupal, you have to locate within the template.php file of the active theme Drupal website.

function YOUR_THEME_NAME_preprocess_page(&$vars) {
  $node = menu_get_object();
  if (isset($node->nid) && $node->type == 'your-content-type-name') {
    $custom_title= "My custom title on node: ". $node->title;
    $vars['title'] = $custom_title;
  }
}


How to force users to register with only email address? I need force users to register on my site with just email only. I cannot use the Email Registration module. With this module, a username is generated and assigned based on the user name part of the email address. Subsequent users who have the same name (email prefix) are numbered sequentially. For example, "johndoe@exampleA.com" would be assigned username "johndoe", "johndoe@exampleB.com" would be assigned "johndoe001" and so forth..

The use case is that I have a number of subdomains that I am using Bakery on and need to ensure that there aren't any conflicting slave site accounts. The Email registration module will just create a tokenized username with appended unique IDs, creating conflicting accounts.

I figure by forcing email addresses, I can bypass most of this as an issue. How can I completely eliminate the username field and just use email field?

Use hook_form_alter to hide the username field

/**
 * Implementation of hook_form_alter.
 */
function mymodule_form_alter(&$form, &$form_state, $form_id){
  if($form['#form_id'] === 'user_register_form'){
    unset($form['account']['name']);
  }
}

Then you can use hook_user_presave to set the username using the convention you want (the md5 hash of the email is a good candidate):

/**
 * Implementation of hook_user_presave.
 */
function mymodule_user_presave(&$edit, $account, $category){
  $edit['name'] = md5($edit['mail']);
}


Users field manually delete from database cache problem i manually remove  a column of field_data_field_about in database belongs to some users. and this field is user field. And after in admin panel i edit this user which i delete this user column from database. But this user about value is shown there. Then i Clear All Caches then i come back to edit this user the about value is gone.

How can i disable cache for users fields?

I'm really not sure why you'd want to remove a column from a field table but just looking at your problem as is, a way by which you can disable caching of field values in the cache_field bin is by letting Drupal know that you don't want values for the field instances attached to a given entity type to be cached at all.

You can do this by implementing hook_entity_info_alter() from a custom module and setting the field cache key for the user entity as shown below:

function mymod_entity_info_alter(&$info) {
  $info['user']['field cache'] = FALSE;
}

You might find the documentation of hook_entity_info here useful. You might also want to lookup the definition of field_attach_load() from here.


Embedded images not shown in Google Chrome I just realized that my embedded images, from an external source, aren't shown up in Google Chrome, but they are working fine in Safari and Firefox.
I cannot even click the link I generated with the tag, as it's not clickable.

Maybe someone has an idea on why this is happening.

<a href="content/httpwwwgooglede#content-top" title="Hier geht's zur Homepage von http://www.google.de"

This was generated through the Display Suite Module, within a view:

<?php $text = ltrim($object->field_link['0']['url'],'http://')?>
<?php $orig = drupal_lookup_path(source,$object->path); ?>
<a href="<?php print $orig; ?>" class="homepages_klein" title="Hier geht's zur Homepage von <?php print $object->title; ?>">
<img width="202" height="152" title="<?php print $title; ?>" alt="Hier gehts zur Homepage von" <?php print $object->title; ?> src="http://www.kwengo.de/external/shots/get.thumbshots.ru/%3Furl=<?php print $text;?>%26size=m%26v=1%26lang=en%26" />

Is that an exact copy-and-paste?  It isn't valid HTML.  Try

I think I fixed everything...

Whenever you have browser differences, run your page through http://validator.w3.org/ and fix the errors first.


Pathologic breaks my external links My basic page is using a wysiwyg editor (ckeditor) which is filtered by pathologic to generate links that uses my pathauto aliases. This is great. My problem is with external links. Somehow, pathologic detect those links as a broken internal link and replaces the external domain with its local domain...

ex: my site is on domain.com and on a page's wysiwyg field I am putting an external link to anotherdomainwehost.com/about/us.

This is changed by pathologic to "domain.com/about/us" which is completely wrong!

How can I fix this? Somehow pathologic thinks that anotherdomainwehost.com is the same web site as domain.com. I don't know why and can't find where are those configured.

I found no where in my installation a way to edit the pathologic settings. I went to the Pathologic page but can't find the provided link. I have no "Pathologic" option in the Content Authoring menu...

I am willing to hack the damn thing, whether it is in the code or in the db if someone tells me where to look!

Pathologic settings are on the text format.  So you'd go here: admin/config/content/formats and click "configure" next to the format you want to tweak.  If it's a format that has Pathologic selected for it, then you will see a "Correct URLs with Pathologic" vertical tab down near the bottom of the page.  The settings are in there.

It sounds like you have anotherdomainwehost.com in the list of "all base paths for this site".


Reassign $view_mode using entity field passed to hook_entity_view_mode_alter() I'm using baseFieldDefinitions to create my custom entity form.
With gracious help here, I've been able to successfully generate a radio button on the form which lets the user select what view mode to use for the display.

Goal:
Get the selected value from the radio button on the form and use it to reset the view mode for the display.

Problem:
Other than my general confusion, I believe I have a cache issue when invoking the hook to alter the view mode.  I'd like to think I was finally able to overcome the array value to single value assignment problems.

I added this code into MY-MODULE.module:

/**  * Implements hook_entity_view_mode_alter().  */
function nfl_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
    // Change the view mode to the value selected via radio button on the form.

    if ($entity->getEntityTypeId() == 'nfl_fact'  ) {  /*<-- restrict to custom entity */

        $change_to_view_mode = $entity->change_view->value;  /*<-- get the lowercase value -- not Initial Cap Label  */

        drupal_set_message(sprintf('
 change_to_view_mode %s
', print_r($change_to_view_mode, TRUE)));
        drupal_set_message(sprintf('
 view_mode before %s
', print_r($view_mode, TRUE)));

        //  $view_mode = $change_to_view_mode;  /*<--- reassign view mode here -didn't work*/
        $entity->view_mode[LANGUAGE_NONE][0]['value'] = $val[0]->change_to_view_mode;  /* <-- reassign */
        $entity->save();

        drupal_set_message(sprintf('
 view_mode after reassignment %s
', print_r($view_mode, TRUE)));
    }
}

I added some drupal_set_message entries to reassure myself that I was getting the variable values changed.

 change_to_view_mode standard

 view_mode before full

 view_mode after reassignment standard

Cache cleared.

When I click on my link from the viewlist builder, I don't get the display.  I get White Screen of Death with the error in the PHP log:

(first few lines)

[29-Sep-2018 02:15:53 UTC] TypeError: Argument 1 passed to Drupal\Core\Form\OptGroup::flattenOptions() must be of the type array, null given,
    called in C:\wamp\www\drupal8\web\core\modules\options\src\Plugin\Field\FieldFormatter\OptionsDefaultFormatter.php on line 40
    in C:\wamp\www\drupal8\web\core\lib\Drupal\Core\Form\OptGroup.php on line 23
#0 C:\wamp\www\drupal8\web\core\modules\options\src\Plugin\Field\FieldFormatter\OptionsDefaultFormatter.php(40): Drupal\Core\Form\OptGroup::flattenOptions(NULL)
#1 C:\wamp\www\drupal8\web\core\lib\Drupal\Core\Field\FormatterBase.php(80): Drupal\options\Plugin\Field\FieldFormatter\OptionsDefaultFormatter->v

I'm confused.
Also am open to guidance on how to better format this question if it looks too goofy ;)

I'm not sure exactly what's going on here, but looking at the documentation for hook_view_mode_alter, it looks like you're not resetting the view mode properly. It looks like you need to set it like:

/**
 * Implements hook_entity_view_mode_alter().
 */
function nfl_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  // Change the view mode to the value selected via radio button on the form.
  if ($entity->getEntityTypeId() == 'nfl_fact' ) {
    $view_mode = $entity->change_view->value;
  }
}


Render the User creation form on another page I have a Views page and I want to insert the user creation form as found in /admin/people/create into the Views page header. I know people frown upon the PHP filter, but I just need to output the user registration form, which is at most 2 lines of php code vs having to make a module just for that. Unless there is a better way?

I know drupal_get_form() has been replaced from the form builder in Drupal 8, and the Drupal 8 equivalent of drupal_get_form() is, for example, $form = \Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class);.

But how do I get the form name or ID? How do I put it in that example? Do I just inspect the form and grab the form ID?

I tried the following code, but I nothing gets returned. What could I be missing?

$form = \Drupal::formBuilder()->getForm(Drupal\user\Form\user_register_form::class);
drupal_render($form);

You could use the Form Block module and place it before/above your view.

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

  Do I just inspect element the form and grab the form id again and
  replace it with the UserLoginForm section?

You just need the ID user-register-form which means your form ID is user_register_form

I see now that you're talking about the admin form, I believe you just have to modify the formblock.module file and comment out or remove this part

 // Don't display the form to logged in users or if registration is disabled
  if (!$user->uid && variable_get('user_register', 1)) {
    $block['content']['form'] = drupal_get_form('user_register_form');
    $block['subject'] = t('Create new account');
    return $block;
  }

So try:

$parameter = 'new';
$form = \Drupal::formBuilder()->getForm('user_register_form', $parameter);


Extending EntityFieldQuery. Which variables should I define? I have been playing around with extending EntityFieldQuery, and I was wondering which variables I should define on the class. I am also a beginner in OOP so this is an experiment.

class nodematcher extends EntityFieldQuery
 {
  private $pathtomatch = NULL;
  private $nodestocheck = array();
  private $matchingnode = NULL;
  private $query = NULL;
  private $results = NULL;
  public $nodes = NULL;
  public $path = NULL;
  public $json = NULL;
  public function __construct()
   {
    $this->query = New entityFieldQuery;
    $this->query->entityCondition('entity_type', 'node')->fieldCondition('geoslate_slate_entry_path', 'value', '', '<>');
    $this->results = $this->query->execute();
    foreach($this->results['node'] as $result)
     {
      $this->nodestocheck[] = $result->nid;
     }
    $this->nodes = entity_load('node', $this->nodestocheck);
    return $this->nodes;
   }
  public function lookupfullpath($path)
   {
    foreach($this->nodes as $key => $value)
     {
      $wrapper = entity_metadata_wrapper('node', $value);
      $entry_path = $wrapper->geoslate_slate_entry_path->value();
      if(reset($entry_path) == $path)
       {
        $this->matchingnode[] = $wrapper->nid->value();
       }
     }
    $loadedentities = entity_load('node', $this->matchingnode);
    //$this->json = drupal_json_encode($loadedentities);
    return $loadedentities;
   }
 }

class nodematcher extends EntityFieldQuery {
  public function __construct() {
    $this->query = New entityFieldQuery;

This doesn't make any sense. You are either subclassing EntityFieldQuery or you are using a delegate pattern. Doing both makes little sense. What you wanted here is perhaps parent::__construct and wherever you used $this->query just use $this.


how to `absolute` position an image over another image? I want to position an image over to appear over another image at a fix position, even if that other image changes its location due to resizing of the browser window. My URL: http://spabc.com/drupal/ and I want to have the orange arrow over the "Offers & Packages" tile on fix position, on the top left corner. How can I achieve this?

Well, there's a couple of things going on, and I don't want to approach re-designing how you've implemented your DOM for this page. Looking at your HTML in question:

which renders this:

You've wrapped your two inline IMG elements within an inline A element. Inline
elements are not meant to moved around in block-like fashion. One approach is
to redefine your anchors here as blocks. We'll also need to define a height
and width for the parent element, as the redefining of imgs to blocks,
absolutely positioned, will remove the parent elments ability to calculate
height and width. Position: absolute removes the object from the page's flow.
(I presume height 200px and width of 220px is accurate, if not, correct to
taste.)

Here's the key aspect: the parent DOM item must be "position: relative" which
you must explicitly declare. THEN the child elements may be positioned
absolutely, within where ever the parent element falls on the page.  The parent
div will move as it needs to on the page, moving the absolutely positioned
child imgs within it.  Otherwise, your css will traverse the DOM backwards to the
first position:relative element. Not finding one, it uses the HTML element for
positioning. The other thing to consider is that img is an inline element, not
a block element. So you must redefine it as a block.  Finally, notice the
z-index forcing the graphic callout to overlay the featured graphic.

This refactored code shows what you're looking for:

Which renders this:

Of course I wouldn't do this with in-line styles, I'm just being lazy to get my thoughts up quickly. Finally, I wouldn't use a table for that display element, I'd use an unordered list. But that's for a different discussion.