Error while trying to install drupal commerce kickstart I am new to drupal and am trying to install drupal commerce kickstart on a digital ocean server. But it fails at install profile step with the following error,

An AJAX HTTP error occurred. HTTP Result Code: 404 Debugging information follows. Path: http:///install.php?profile=commerce_kickstart&welcome=done&locale=en&use_dfp=1&id=1&op=do StatusText: Not Found ResponseText: 404 Not Found 404 Not Found nginx/1.0.15

I dont know what to do.  Please help.
I can install drupal easily with no issues but installing all modules for commerce is a headache so I decided against it.

NOTE:  is my website

Go to your php.ini file. Search and change values for the following:

post_max_size = 500M
upload_max_filesize = 500M
max_execution_time = 2000
max_input_time = 2000
memory_limit = 512M

and save file

In apps config

C:\wamp\apps\phpmyadmin3.3.9/config.inc.php (whatever your server is)

add the below code

     //maximum execution time in seconds (0 for no limit)
     $cfg['ExecTimeLimit'] = 300;

and save the file.

Restart your WAMP Server.

For more details go there.


How can I disable JavaScript in Drupal themes or Drupal itself? How can I disable JavaScript in Drupal themes or globally?

Javascript in and of itself is not the problem. I'd place more energy into ensuring that your Rich Textareas  (body, comments, etc) and permissions are configured properly. This is one area where people can slip in rouge JavaScript which may be run on other visitor's browsers. Use TLS (Https) by default and use modules that aid in security such as Security Review, Secure Pages or Secure Login help secure the login process.

There is also tons of great advice and direction on line:

10 Simple steps to protect your Drupal site
Configuring text formats (aka input formats) for security
Securing file permissions and ownership


Populate $form_state['values'] with defaults from drupal_get_form() I'm looking to resave a form's defaults values. In core the test module uses drupalPost() to test the form so I'm thinking this will be custom code.

This is the function I've come up with.

/**
 * Given a form get the default values from it.
 *
 * @param array $defaults
 *   An empty array used to populate the default values.
 * @param array $form
 *   The form returned from drupal_get_form().
 * @param string $parent_key
 *   The key name of the parent.
 */
function get_defaults_from_form(array &$defaults, array $form, $parent_key = '') {
  foreach (element_children($form) as $key) {
    $values = $form[$key];
    if (isset($values['#value'])) {
      // Grab defaults at this level.
      if (!isset($defaults[$key])) {
        $defaults[$key] = $values['#value'];
      }
      else {
        $defaults[$parent_key . '-' . $key] = $values['#value'];
      }
    }
    elseif (isset($values['#default_value'])) {
      // Grab defaults at this level.
      if (!isset($defaults[$key])) {
        $defaults[$key] = $values['#default_value'];
      }
      else {
        $defaults[$parent_key . '-' . $key] = $values['#default_value'];
      }
    }
    elseif (is_array($values)) {
      // Go deeper if needed.
      get_defaults_from_form($defaults, $values, $key);
    }
  }
}

Use it like this:

$theme_name = 'seven';
// Load the required file for the form functionality.
$router_item = menu_get_item('admin/appearance/settings/' . $theme_name);
if ($router_item ['include_file']) {
  require_once DRUPAL_ROOT . '/' . $router_item ['include_file'];
}
// Get the form for this theme.
$form = drupal_get_form('system_theme_settings', $theme_name);
// Get the defaults.
defaults = array();
get_defaults_from_form($defaults, $form);
print_r($defaults);


Display Node edit under edit tab I would like to know whether the "node edit form" (admin form) can be displayed under the edit tab itself using MENU_LOCAL_TASK?

I suggest hide default edit tab and create a tab set with Quick Tabs module.I mean bypass default drupal menu tab( or hide it completely ) and create your own . this module help you to create a quicktab set that click on each item don't need page getting refresh.

  The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*. You can
  create a block on your site containing multiple tabs with
  corresponding content. Clicking on the tabs makes the corresponding
  content display instantly, using jQuery. With the 6.x-2.x branch, this
  can be done in either ajax or non-ajax mode:

if you choose ajax mode for your Quick Tabs block (and this is chosen on an individual QT basis), only the content of the active tab

  will be loaded on page load and the content of the other tabs will be
  loaded via ajax on tab click (this is good for performance if you are
  loading, for example, several large views)
      in non-ajax mode the tab content is just hidden / shown on tab-click. This latter method is an ideal way to do something like the
  Most Popular / Most Emailed stories tabs you see on many news
  websites, where it is used more as a space-saving device in your
  sidebar. If however, you want a QT block as the main content of your
  entire page, then the chances are that ajax mode will be more
  appropriate.

  Once created, the Quick Tabs blocks show up in your block listing,
  ready to be configured and enabled like other blocks. Multiple Quick
  Tabs blocks can be placed on a single page.

  For theming of the tabs, several styles have been provided for you to
  choose from (in the 7.x-3.x branch this functionality comes in a
  separate submodule, Quicktabs Tabstyles), along with the default
  option of no style, if you prefer to add your own theming instead.


The following module is missing from the file system: (Theme name) In D7, I'm getting many of these warnings:

User warning: The following module is missing from the file system: bootstrap_barrio.
For information about how to fix this, see the documentation page.
   in _drupal_trigger_error_with_delayed_logging()
      (line 1143 of /home/xxxxx/www/www/includes/bootstrap.inc).

User warning: The following module is missing from the file system: XXXXX.
For information about how to fix this, see the documentation page.
   in _drupal_trigger_error_with_delayed_logging()
      (line 1143 of /home/xxxxx/www/www/includes/bootstrap.inc).

The problem is that those 'modules':

Are actually themes in the site.
They are being used and the files are there (under /sites/all/themes/)

I've installed the Missing Module module and it didn't detect those themes as missing.

Why is Drupal confusing modules with themes and how can I remove those messages?

This is probably due to the modules changing locations since they where installed.  One way to fix this is to just edit the system table.  You can do this via Drush like this:

drush sql-cli

> select * from system where name = 'bootstrap_barrio';

Verify that the path column is not correct.

> update system set path='correct path here' where name = 'bootstrap_barrio';

If the path is correct, then it might be a directory rights issue.  E.g. either the module or a parent can't be read by the webserver.


Ckeditor and IMCE not working with Plupload When I use IMCE with CKeditor as a WYSIWYG for my website it works fine:

However when I add the Plupload module which would allow me multiple files selection it breaks!

If this can't be fixed, is there any other alternatives similar to Plupload that I can use with CKeditor?

Use Insert module instead of IMCE

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.


Can't get id/name of view in hook_preprocess_views_view_unformatted In this function I can't get id of view

function THEMENAME_preprocess_views_view_unformatted($vars){
  $view = $vars["view"];
  //does not work
  $id = $view->storage->id();
  //does not work
  $name = $view->name;
}

$id does not  get anything meanwhile if used in hook_preprocess_views_view_fields work properly.  Why it does not work here ?

EDIT: the process is firing and I can see with a debugger that id/name don't get a value meanwhile on other hook above can get the id ... could it be a bug ?

This is the only way I could get view id (not sure why)

function THEMENAME_preprocess_views_view_unformatted($vars){
  $view = $vars["view"];
  //works
  $id = $view->id();
}


Radio button & Option list values migrate successfully with Feeds Importer but disappear in node edit I'm doing a couple data migration projects. I'm using Feeds Importer and for the most part, things are going well.

But when I migrate option list fields, I get this weird thing where the data is migrated OK (I see it when I view the node and I see it in the appropriate table in the database), but when I edit the node, the option list field is empty/not-selected.

On one of the projects, I was using the radio button widget and the work-around ended up being changing the field's widget from that to Select list.

But on my second project, I was already using the Select List widget, and I can't seem to work around the problem. Tried changing it to radio buttons (hey - I'm not picky), but it didn't help.

It's a really sinister problem because it means I migrate the client's data OK, but when they edit one of these nodes, they will essentially delete data because the radio button or select list widget is not displaying the data. Help?

I don't have enough reputation to comment, so I'm posting this as an answer.

I'd suggest that you install and enable the devel module to compare the data structure of the field in question in these three situations:

when the data is input manually
when the data is loaded via feeds
when the data loaded via feeds is later edited

If you haven't used it, with Devel installed, you can get the 'devel' view of the node.


Clean up test payment transaction from drupal commerce site I am trying to find an admin page where I can delete all test payment transactions happened on drupal commerce, but could not find it.Need to no if my following plan will create any referential integrity issue after cleanup.

From orders page clean all test orders.

Manually clean the database tables 'commerce_payment_transaction' and 'commerce_payment_transaction_revision' and then using db API clean payment transaction table using
db_truncate('commerce_payment_transaction');
db_truncate('commerce_payment_transaction_revision');

Clean up all tested customer profiles from admin page for the same using bulk operation.

Clean up test users created with the checkout process.

Truncate orders table to start with order id , using again following code.

db_truncate('commerce_order');
db_truncate('commerce_order_revision');

The short answer is there is no such page. What you're attempting to build with VBO should work well, but currently there is no automatic deletion of payment transactions when orders are deleted. It's questionable whether or not we actually want that to be the default behavior. However, if you're just using VBO driven by custom rules components, you should be able to load any payment transaction referencing the order to be deleted and delete them from within the same rule. Using commerce_order_delete() will not delete payment transactions; for that you'd need commerce_payment_transaction_delete().


How do I add JavaScript? I'm creating a website and I want to display a widget from another website inside a block.

In the widget description, I have this information:

  Paste this code at the top of your website code, with the other JS
  includes. If you are already loading jQuery, please remove it from the
  code below and only load the widgets.js

  Paste the following code where you want your widget to appear on your
  website, note that the widget is 100% width, so you will need to
  contain it.

How do I include this first code inside the header (or footer)?

Your canonical reference for this is here. In short:

Save the CSS or JS to a file. (I normally do this at
docroot/themes/projecttheme_directory/js/)
Define a "library", which can contain both CSS and JS files.
"Attach" the library to a render array in a hook.

You can add these files globally, (see "Attaching to all pages") or to specific pages or blocks, (Attaching a library in a Twig template) There's a good deal of flexibility in how you can add your javascript, so be sure to review all the options listed there.


7 - Attachments are not showing in search results for non admins when using apache solr attachments I am using apache solr search module in my site, and using local Tika extraction for indexing attachments.

When I logged in as admin I can able to search attachments as well as nodes, but if I logged in as other user attachments are not showing up in search results, only nodes are showing.

Do I need to do any settings for this? I have provided Seach permissions for all the users in people tab.

Any help will be appreciated, Thanks.

One dirty hack for this problem is: Disable Apache Solr Access module and than the file search should work fine for other users as well.

But first check if there are permission available for Solr Access, if not than you may try this hack and see if this works.


How can I create an ajax on/off toggle? I am trying to create a simple on/off link using jquery and ajax. Basically what I want to to is add a link to a page that when clicked will insert a row into my database and update the text of the link. Then when clicked again, that record will be deleted from the database.

So far everything works as expected but the problem is that the second time the link is clicked, the record is deleted like it should, but the page refreshes and redirects to the homepage.

I am following the "plus 1 vote widget" example from Pro Drupal Development and am trying to alter the code to suit my needs. Following is my .js file.

$(document).ready(function() {
  $('a.toggle-visibility-links').click(function() {
    var parentDiv  = $(this).parent();
    var toggleSaved = function (data) {
      $(parentDiv).html(data.toggleon);
    }
    $.ajax({
      type: 'POST',
      url: this.href,
      dataType: 'json',
      success: toggleSaved,
      data: 'js=1'
    });
  return false;
  });
});

Here is my "toggle_visibility" module code

/**
 * Implementation of hook_menu().
 */
function toggle_visibility_menu() {
  $items = array();
  $items['toggle-visibility'] = array(
    'page callback' => 'toggle_visibility_toggle',
    'access arguments' => array('toggle profile'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/*
 * page callback
 */
function toggle_visibility_toggle() {
  global $user;
  $toggle_sql = "SELECT * FROM {toggle_visibility} WHERE uid = %d";
  $toggle_result = db_query($toggle_sql, $user->uid);
  $num = mysql_num_rows($toggle_result);

  if (!$num) {
    db_query('INSERT INTO {toggle_visibility} (uid, visible) VALUES (%d, %d)', $user->uid, 1);
  } else {
    db_query('DELETE FROM {toggle_visibility} WHERE uid = %d', $user->uid);
  }

  if (!empty($_POST['js'])) {
    drupal_json(array(
        'toggleon' => 'Toggle My Profile On'
        )
    );
    exit();
  }

  //UPDATE THIS TO RETURN TO THE SAME PAGE
  $path = drupal_get_path_alias('node');
  drupal_goto($path);
}

/**
 * Implementation of hook_theme().
 */
function toggle_visibility_theme() {
  return array(
    'toggle_visibility_link' => array(
      'arguments' => array(),
    ),
  );
}

/**
 * Return a message for no results
 */
function theme_toggle_visibility_link() {
  drupal_add_js(drupal_get_path('module', 'toggle_visibility') . '/toggle_visibility.js');
  global $user;
  $toggle_sql = "SELECT * FROM {toggle_visibility} WHERE uid = %d";
  $toggle_result = db_query($toggle_sql, $user->uid);
  $num = mysql_num_rows($toggle_result);

  if ( $num == 0 ) {
    $link = 'Toggle My Profile Off';
  } else {
    $link = 'Toggle My Profile On';
  }
  return $link;
}

Not sure what I'm missing.

Thanks!

In the javascript you should format the data as an object:

data: 'js=1'

replaced with

data: {js: 1}

The problem with the redirect is most likely an JS error caused by the returning value of the ajax callback. To be able to spot it you can hardcode the url in development and change the link simple be xx, that would prevent a new page from loading in case of JS errors and would give you the possibility to read the error log from tools like firebug. Another options would be to insert breakpoints in your JS code, which can be a bit more tricky.


Cloning Node with Webform and Conditional Confirmation Message I currently have an "Event" content type with a webform attached to each event. The webforms use the conditional confirmation message module to display different confirmation messages depending on the input to the form. I'm using the node clone module to duplicate events and everything works well expect that the conditional confirmation messages are not being duplicated. What should I do so that every part of the event node (including the conditional confirmation messages) is duplicated?

The node clone module gives you the tools to make this happen. You can have a custom module make use of hook_node_clone_alter then use the Webform Conditional Confirmation module's functions to load & copy the original messages, store them temporarily, then save them upon saving the newly cloned node.

Something like this...

function MYMODULE_clone_node_alter(&$node, $context) {
  $messages = webform_conditional_confirmation_message_load($node->clone_from_original_nid);
  foreach($messages as $msg_id => $message) {
    //@TODO: Store in some temporary spot until cloned node is saved
  }
}

function MYMODULE_node_update($node) {
  //@TODO: Retrieve messages from temp location and place into $messages
  foreach($messages as $msg_id => $message) {
    $message->nid = $node->nid;
    webform_conditional_confirmation_message_save($message);
  }
}


Comparing node creation and modification dates in twig I want to compare a node's creation date and modified date in Twig, and it drives me bonkers. I've looked at various examples and snippets as part of this, this, this or this external source.

Using Drupal 8, Bootstrap 3, Bootstrap Layouts, Display Suite, and a custom  sub-theme, I have a twig template customising what is going to be displayed and how. This custom template is a copy of the default bootstrap layouts 1 column template.

Within the template, I can access and print the dates using this:

{{ main.content.node_changed_date }}
{{ main.content.node_post_date }}

and all is well.

However, I want to compare the dates in my template like so:

{% if main.content.node_post_date|date('Y-m-d') > main.content.node_changed_date|date('Y-m-d') %}
    {{ main.content.node_post_date }}
{% endif %}

But this barks at me with the following error:

The website encountered an unexpected error. Please try again later.
TypeError: DateTime::__construct() expects parameter 1 to be string, array given in DateTime->__construct() (line 455 of /home/michel/devel/vendor/twig/twig/lib/Twig/Extension/Core.php).

DateTime->__construct(Array, Object) (Line: 455)
twig_date_converter(Object, Array, Object) (Line: 380)
twig_date_format_filter(Object, Array, 'Y-m-d') (Line: 77)

Yes, I use Composer to manage my installation.

What am I doing wrong?

Pulling my hairs

Michel

You can't compare render arrays. To compare fields better use raw values stored in the node:

{% if node.getCreatedTime > node.getChangedTime %}
    ...
{% endif %}

(The comparison doesn't make much sense, probably you want to swap both dates)

The node object is available in node and page templates. In other templates you might find it in a deeper level. If not and the node is displayed as main content you can add it in preprocess:

  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
  }


Conditionally display a field On my "teaser" view mode I want to display my Image field but if the Image field is empty I want to display my Title field instead.

I have tried using hook_preprocess_node but it appears that this is not called when rendering the node in the "teaser" display mode when using Display Suite.

Another thought I had was to create a custom DsField plugin... but in that case I do not have the context of the other fields (unless I do?) so I cannot say "if img is empty display title, else display img" Using the suggestion below I came up with:

class ImageElseTitle extends DsFieldBase {

  public function build() {
    /** @var /Drupal/node/Entity/node $node */
    $node = $this->entity();

    if ($node->get('field_event_image')->isEmpty()) {
      return $node->get('title')->view('teaser');
    }
    else {
      return $node->get('field_event_image')->view('teaser');
    }
  }

}

But in this case the settings for the title field are not obeyed. For example, it is wrapped in a span instead of an h2 as specified in the display settings. Similarly it is not a link even though "link" is checked in the display settings...

I tried adding a preprocess to the title field that checks if the image field is empty, but I think the preprocess function is too late to say "the image field is not empty, so never mind, dont display the title"

Thoughts?

-- Continued --

I also tried this, but the fields are not hidden as I'd expect them to be:

function mymodule_ds_pre_render_alter(&$layout_render_array, $context, &$vars) {
  if ($context['entity_type'] == 'node' && $context['bundle'] == 'event' && $context['view_mode'] == 'teaser') {
    if ($context['entity']->get('field_event_image')->isEmpty()) {
      $layout_render_array['field_event_image']['#access'] == FALSE;
    }
    else {
      $layout_render_array['node_title']['#access'] = FALSE;
      $layout_render_array['title']['#access'] = FALSE;
    }
  }
}

I've done this a couple ways.

First, you can you hook_ds_pre_render_alter (I can't find a better link to ds.api.php!) like hook_preprocess_node and just hide your title field if the image field is set. If you're using this option be sure to dig into the layout render array to the correct spot. For example if you have the ds node_title field within the ds_content region, hide it like

$layout_render_array['ds_content']['node_title']['#access'] = FALSE;

of if you have the same field within a title_wrapper field group, hide it like

$layout_render_array['ds_content']['group_title_wrapper']['node_title']['#access'] = FALSE;

Or you can create a custom ds field (yes, you have access to the whole entity). I usually enable the hidden region at /admin/structure/ds/settings, then I add both my title field and image field to the hidden region on my view mode and then just render whichever one I need in my ds field's build() method via the field's view method, in this case it would be like

$this->entity()->field_MY_IMAGE_FIELD->view('teaser');

or

$this->entity()->title->view('teaser');

Instead of passing a view mode's name, you can pass a display configuration array straight to the field's view method.


Drupal Doesnt Load after Installing Theme I had installed Omega Theme in drupal. I enable and set it as a default theme.I also disable it's former default theme "Bartik". Now I didnt see changes taking place in my Drupal site. Because of impatience I exit the browser and  loads drupal again but it doesnt work like before. I cannot access drupal anymore and shows only white page just like the image below.

What shall I do to fix it?

Start by re-downloading the theme to eliminate file corruption as a possible cause. Can't say how to fix the site without knowing what's happening- If copying the files doesn't work, enable error reporting and troubleshoot from there.


After moving a module to another folder , i cannot clear reminiscent module paths I have moved the contrib module pagerer from

  /sites/my_site/modules

to

  /modules/contrib

It breaks the site as some files are unaccessible

  /platforms/drupal8-development/sites/recherche-dev.univ-amu.fr/modules/pagerer/src/Entity/PagererPreset.php):
  failed to open stream: No such file or directory in require()

i guess i would need to perform a registry rebuild but i don't know how.

drush rr outputs

  The drush command 'rr' could not be found

i have ended up putting in local.settings.php

   /**
 * Class Loader.
 *
 * If the APC extension is detected, the Symfony APC class loader is used for
 * performance reasons. Detection can be prevented by setting
 * class_loader_auto_detect to false, as in the example below.
 */
$settings['class_loader_auto_detect'] = FALSE;


Moving site to another domain, install appears I move the website to another domain on the same server, by copying all files to the other domain's folder.
When I visit the new domain the install.php appears. Trying to navigate to another page like /user/login redirects to the installer as well.

I don't think I need to change database settings because it's on the same server.

Any ideas why?

When install appears on a site that you expect to be fully installed, the problem is usually with the file settings.php (in the sites/default/ directory).

It may be missing in action, not visible to the web server user, or unable to establish the credentials to connect to the site's database.


Creating a one-time password, and send the email We need to create a system where the user enters only an email address. For a specific domain user receives an email with a generated password, and for all other domain receives a notification email to contact support. Password used to access a protected area of the site that is not available to the public. Also, the password can be used only once, ie. each time a user enters an email address, get a new password.

Any ideas how to make this system to Drupal 7?

Login One Time comes closest to your requirements. From its project page:

Login one time provides the ability to email one-time login links to users.
Features
Rules:

[user:login-one-time] token on user events.

[comment:login-one-time] token for node author on comment event.

User profile - "Send login one time link" button.

VBO - Create a view and send login links to the view. Checkout View
Reference for ideas on how to embed views.

Block - Select a user and send the link. You can use this block in
nodes as a CCK field using Block Reference.

PHP - Print a button in a template or directly send the emails using
the functions described in the README.


Create Relationship In Views I have three content types that have a text field called PID.  How do I tell views there is a relationship between these content types?

Here are two ways to set up a relationship, depending upon how it is to be applied to content.

It is not clear how you are suing the PID field, so I will ignore it.  You could create a field with a name like 'relate' and you could enter a term there that identifies a name for a relationship that various content types would share.  You would then set up a View to filter for that field with the specific term you want and Views will retrieve all the content that shares that term.  Further filtering could narrow the selection further if you desire.
You could use a module such as Relation to define a type of relationship and link pairs of content eg. a 'friends' relationship could be used to link two users in a specific type of relationship.


How to use the Match Redirect module I'm trying to use the Match redirect module and follow the basic description I've tried the following:

/my-path-1/my-path-2/*

to

/my-path-2/*

OR

/ma-path-2/

And it doesn't work. I do have pages like:

www.example.com/ma-path-2/page-title

that works fine as expected, but when I visit

www.example.com/my-path-1/my-path-2/page-title

I was expecting to be redirected to:

www.example.com/my-path-2/page-title

Which did not happen. Why? What am I missing here?

Thanks in advance

From reading the module description, I get the impression that the Match redirect module module only replaces wildcards and cannot remove them.

I suggest you try redirect module with pathauto. After you change the path in pathauto, remember to use the BULK UPDATE tab to update the urls. Redirect will automatically do it's thing.


Weird redirect on taxonomy term edit page When I try to edit taxonomy terms, or delete them, and I click on edit/delete,  it redirects me to that term page instead.

I also have Devel module installed, and when I choose that option in the drop-down menu, it works.

I have tried almost everything.

URLs are OK; if I inspect the edit/delete buttons, the URL is the expected one. When it redirects me, that URL remains in the browser.
I thought it was a Drupal core issue. At the time I was using Drupal 8.5.3, but I am still having the problem after updating to Drupal 8.5.5.
I have removed all my custom modules/theme files (to check if it were my fault).
I changed the administrative theme from the Seven theme to the Bartik theme.
I cleared the cache and ran update.php several times.

The problem still remains, and I'm still not sure if it's an issue I have somehow caused, or it's a Drupal core issue.

Did anyone have a similar problem, or know what would be the problem?

Did you try to edit Taxonomy Term view /admin/structure/views/view/taxonomy_term I'm having issues with editing / deleting / translating taxonomy terms because I've edited taxonomy_term view. Disable taxonomy_term view and edit/delete should work.


Migrating only articles with a specific taxonomy term In the source D7, i have a content type 'article' containing a reference to a 'category' taxonomy vocabulary term.

In the target D8, I have a content type 'article' as well, but i only want to import those nodes whose 'category' reference does not equal 'interview' ('interview' is one of its terms).

Also, in the target D8, i have a content type 'interview' to which i want to import all D7's 'article' nodes whose 'category' reference equals 'interview'.

Any ideas how to condition this?

Besides setting up a process plugin for the migrate import mapping (via code) as suggested by Berdir in the comments, another option is to setup a views data export on the legacy site to output only the select articles or "interviews".

This approach also allows non-database admins or developers to easily audit the content being migrated (because you can setup an alternative view display as a webpage, or excel spreadsheet, for use as a checklist).

To setup a view in JSON format:

install the Views Data Export module
install one of the add-on modules for JSON, such as Services Views or Views Data Source.

Refer to this StackOverflow answer/post about setting up a JSON view display mode.


Can I remove the "Item successfully added to your cart" popup? Can I removed the Item successfully added to your cart popup in Drupal Commerce?

Goto: /admin/config/workflow/rules
and disable 'Display an Add to Cart message' Rule.

Thank You.


What should I enter as server URL? I have a Drupal site on Amazon server. On the amazon server, I have created an Elasticsearch server. I want to connect my Drupal instance with that server so I can use the search server for performing the search operation on the site.

I added and configured the Elasticsearch connector module which, in order to connect to the search server, needs I create a cluster which would help in connecting both the instances.

While adding a cluster to the Drupal instance, it asks me about the server URL. I am not sure on what I should write as server URL. What should I add in that form field?

Just enter the Endpoint of your AWS Elastic-search Cluster.

Use port : "80".

the Complete url will be something like:

XXX-XXX-XXX-XXXXXX.ap-southeast-1.es.amazonaws.com:80

First check are you able to access the Elastic-search , Try to telnet on the server:

telnet XXX-XXX-XXX-XXXXXX.ap-southeast-1.es.amazonaws.com 80

If it's not accessible make it available for your IP by changing the access policy .


Routing path with Entity Reference field I'm working on a custom module (my_module) which provides some functionality to a specific paragraph type (my_paragraph) created from the  user interface. In my routing file, I have the following route definition.

my_module_controller_action:
  path: '/node/{node}/my_paragraph/{paragraph}'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::action'
    _title: 'page title'
  requirements:
    _permission: 'access content'

Now I add a new entity reference field (field_paragraph) to the Basic page content type. Using this field I can add my_paragraph along with other paragraph types.

With this set up, I create a basic page, add a piece of my_paragraph, and saved it (/node/123). I can see my custom controller is not called (because now the path is /node/123), but if I go to /node/123/my_paragraph/1, my custom controller is getting called there and I get the output I want.

What should I do so that my custom controller can be used on /node/123 page?
If I add /about as path alias of /node/123, how do I achieve the same outcome?

I'm actually refactoring an old custom module I wrote and trying to move away from the hooks approach if possible. One of the main motivations for me by refactoring is I can use one or more services (together with dependency injections) to separate all the possible logics here.

The problem here is that controllers are specifically intended to return a result based on a given path. The result you want isn't dependent on a path, but rather on an operation performed on an entity.

What you'll want to use instead is one of the entity API hooks, found here: Entity CRUD, editing and view hooks

To respond to your entity being created, I recommend using:
hook_ENTITY_TYPE_insert()

function my_module_node_insert($node) {
  // Get ids for all Paragraph references stored in your field.
  $paragraph_ids = $node->get('field_paragraph')->getValue();
  // Get Paragraph storage handler.
  $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
  // Load Paragraphs from their IDs.
  $paragraphs = $paragraph_storage->loadMultiple( array_column($paragraph_ids, 'target_id') );

  // Iterate through your loaded Paragraph instances...
  foreach($paragraphs as $paragraph) {
    // Do your stuff to the paragraph.
  }
}

Similarly, if you need to update field_paragraph when you update your node, implement hook_ENTITY_TYPE_update().


Can I rewrite a view's query SQL directly? Can I modify the SQL generated by the Views Query Builder? Views doesn't support subquery out of the box, so I'm just wondering if I can add the final line to my query manually?

Background info:
The query I'm trying to perform looks a little like this:

select full_name, email, users.uid
from
cloudsponge
inner join
`users` on users.uid = cloudsponge.importer_uid
where cloudsponge.email not in (select mail from users)

It's worth pointing out that all tables have millions of rows so performance is also important (I haven't checked this query on a large dataset yet).

try hook_query_alter. Views queries should pass though this hook allowing you to alter them. https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_query_alter/7


Drupal SEO module - Error on the setup wizrad and on dblog I am using all Drupal SEO module , and all recommended module with it.
I do not see any states on the Drupal SEO module reports.

When I am trying to run the setup on admin->config->search->seo tools-> "+Setup wizard", I get the following error:

  Strict warning: Only variables should be passed by reference in
  seotools_admin_setup() (line 16 of
  xx/MYusername/public_html/sites/all/modules/seotools/seotools.setup.inc).

In addition, in the dblog, I get many errors after trying to use Drupal SEO:

  TYPE    google analytics reports
  DATE    Wednesday, March 26, 2014 - 18:07
  USER    Admin   Admin-family
  LOCATION    http://www.MySite.com/admin/reports/intel/content?return_type=json&refresh=1
  REFERRER    http://www.MySite.com/admin/reports/intel/content
  MESSAGE Code: 401 - Error: Unauthorized - Message: GDatarequiredAuthorizationLogin Required
  SEVERITY    error

Drupal SEO looks like amazing module. Can you help me make it work?
how can I solve this issues the problem?

Hopefully this helps the next user.

I was having this issue and stepping through your code I noticed it sends a time stamp. Our server time was off by 12 minutes. Once I corrected it everything worked.


db_select with mysql reserved word in the statement This seems to be fairly easy question, but I could not find simple answer to it.

Using db_select when database column happens to be a reserved mysql word (when in this case) results in an error.

Table:

+-----------------------------------+------------+--------+
|               sort_id             |    when    |  user  |
+-----------------------------------+------------+--------+
| 1                                 | 1448270950 |    123 |
| 3                                 | 1448270955 |     12 |
| 50                                | 1448270959 |     45 |
+-----------------------------------+------------+--------+

Standard drupal7 select using db_select:

$query = db_select('my_table', 'd')
    ->fields('d', array('sort_id', 'when', 'user'))
    ->condition('user', $uid)
    ->execute();

BUT column named when is the problem here.

I know I can write the query using plain SQL:

db_query("SELECT sort_id, user, `when` FROM {naughty_table} WHERE user = :user", array(":user" => $user_id));

But there should be a way to solve this using regular db_select?

IMPORTANT:

I have tried to use backticks like this:

$query = db_select('my_table', 'd')
    ->fields('d', array('sort_id', '`when`', 'user'))
    ->condition('user', '123')
    ->condition('`when`', '1448270950')
    ->execute();

But backticking like this does not seem to work whatsoever.

You can use where() instead:

$query = db_select('my_table', 'd')
  ->fields('d', array('sort_id', '`when`', 'user'))
  ->condition('user', '123')
  ->where('`when` = :timestamp', array(':timestamp' => 1448160590))
  ->execute();

Produces:

SELECT d.sort_id AS sort_id, d.when AS when, d.user AS user
FROM
{my_table} d
WHERE  (user = :db_condition_placeholder_0) AND (`when` = :timestamp)


How to change logo dynamically? How can i change the logo on a site, dynamically, with a URL field which doesn't point to an actual image but to a rendering of an image.
Is this possible?
I've tried this:

$thisimage = $logo_img_url. "&file=" . $_SESSION[ 'logo_img' ] . "&width=300&height=80";
variable_set( 'logo', $thisimage );

but it's not working.

Any help would be appreciated.
Thanks

This should echo the path to the theme logo, which you could wrap in an  tag:

<?php echo theme_get_setting('logo_path'); ?>

If you want to re-size, crop, or modify the image you should do that in an image style. Once you have made an image style in Configuration > Media > Image Styles, you can echo the logo with that style like so:

<?php echo image_style_url('my_style_name', theme_get_setting('logo_path')); ?>


What arguments can I use when defining a service? Looking at system.services.yaml, I noticed that some of the services arguments are strings starting with @. They seem to contain a reference to another defined service.

system.manager:
class: Drupal\system\SystemManager
arguments: ['@module_handler', '@database', '@entity.manager']

Are those @-arguments only references to other services? Are there any other type of arguments I can use when defining a new service?

Yes, the @ arguments are references to services. From Symfony's Introduction to Parameters:

  You can of course also reference services, which looks a bit different in each format. You can configure the behavior if the referenced service does not exist. By default, an exception is thrown when a non-existent service is referenced.

  Yaml

  Start the string with @ or @? to reference a service in Yaml.

  @mailer references the mailer service. If the service does not exists, an exception will be thrown;
  @?mailer references the mailer service. If the service does not exists, it will be ignored;

You can also use %-wrapped parameters which are slightly different; they can be used to refer parameters or get access to special SYMFONY__ prefixed server environment vars. (See How to Set External Parameters in the Service Container.)


Node Reference Argument In loadByProperties() while Creating API I have a custom module which generates an API, I want the API to filter content based on a node reference field. How do I pass the field field_author(Entity Reference from another content type) field as an argument to loadByProperties?

public function get() {

$entities = \Drupal::entityTypeManager()->getStorage('node')-
>loadByProperties(['field_author' => 'Holmes']);

}

Thanks to 4k4

I modified my code to

    $entities = \Drupal::entityTypeManager()->getStorage('node')-
    >loadByProperties(['field_author' => '469']);

Where 469 is the nid of my Referenced Node


Allow user to use entity reference to nodes they own? I have a Doodad content type that has a couple of Entity Reference fields, for example, parentDoodad. Those fields point to other Doodad nodes. When I'm logged in as an Admin, I'm able to use the auto-complete field to set any doodad in the parentDoodad field.

However, if I switch to a different user and create Doodad1 and Doodad 2 (so that I have multiple nodes owned by this user), when I try to use the entity reference field, it won't show me any of my other Doodads.

If I give my non-admin-user the "Bypass content access control" permission, then I'm able to see and choose those other Doodads in the parentDoodad field.

I want users to be able to choose any of their own Doodad nodes. Is it just a matter of configuring certain permissions? How do I let UserA be able to choose from UserA's nodes in that entity reference field?

You can do it this way.

Create a view to list the nodes of particular type.

1a. Add a contextual filter of Content: Author Uid and provide default values as USER ID from logged in user

1b. Add a Entity Reference display to the view.
Now go to the Entity Reference field you have created in your content type and edit it.

2a. Under Entity selection select the Mode to Views: Filter by an entity reference view then you will get the view you have created above and select it.

2b. Save the changes.

This way the user will see only the node they created in the reference field. Read More

There is a second way also, you can implement hook_query_entityreference_alter() and alter the query. Read More


How to ignore specific Drupal release in update notifications? I'm using Drupal 7.28 and getting this message:

  There is a security update available for your version of Drupal. To ensure the security of your server, you should update immediately! See the available updates page for more information and to install your missing updates.

Sadly, there is a critical bug in 7.29 that makes this particular release totally not workable for me. No way I'm installing it, it's that simple. I'll either apply some of 7.29 patches manually, or wait for 7.30. Thus, I don't want to be bothered with release I know I will not install. How can I make my Drupal ignore it? I do want to be notified when 7.30 is ready, so simply turning off all messages about updates is not an answer I'm looking for.

Note: this is definitely not recommended. Hiding security updates is bad for all the obvious reasons (it's clear you know that, but for the sake of others who see this...).

As a technical exercise, I can't see why something like this wouldn't work (un-tested):

function MYMODULE_update_projects_alter(&$projects) {
  $projects['system']['info']['version'] = '7.29';
}

That should basically trick Drupal into thinking core is already at 7.29, so you shouldn't get any warnings. Plus you should also receive update notices for 7.30.


how to provide security to user Profile? I want to provide security to user profile, so that purpose am adding two check boxes

Account Settings

List item Make my profile only visible to members of my website members only.
Make my profile private

above two options are check box but how can i apply the functionality to this check boxes otherwise

please suggest me to any module are available

Using profile2 module you can create private profile. This module provides the following items :

  With profile2 user account settings and user profiles are conceptually different things, e.g. with the "Profile pages" module enabled users get two separate menu links "My account" and "My profile".
  Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)
  Profile2 supports private profile fields, which are only shown to the user owning the profile and to administrators.


What is a placeholder? Drupal uses the concept of a placeholder quite a lot during form creation and theming, and also has a Placeholder Strategy in its the response event of its Render Pipeline.

What wasn't explained is what is a Placeholder?

In the render pipeline placeholdering is used together with lazy building, see this example from the status messages:

\Drupal\Core\Render\Element\StatusMessages

  /**
   * #pre_render callback to generate a placeholder.
   *
   * @param array $element
   *   A renderable array.
   *
   * @return array
   *   The updated renderable array containing the placeholder.
   */
  public static function generatePlaceholder(array $element) {
    $element = [
      '#lazy_builder' => [get_class() . '::renderMessages', [$element['#display']]],
      '#create_placeholder' => TRUE,
    ];

    // Directly create a placeholder as we need this to be placeholdered
    // regardless if this is a POST or GET request.
    // @todo remove this when https://www.drupal.org/node/2367555 lands.
    return \Drupal::service('render_placeholder_generator')->createPlaceholder($element);
  }

Then, before caching, the renderer puts instead of the content a static placeholder, which will be, on delivery, replaced with the actual content from the lazy builder.

The placeholdering is done here right away, see the last comment in the code. Which is good for demonstration purpose. If you run this code the result will look like this:

<drupal-render-placeholder callback="Drupal\Core\Render\Element\StatusMessages::renderMessages" arguments="..." token="..."></drupal-render-placeholder>

By the way, the content of the placeholder tag in the markup is not important, it only has to be unique to be replaceable. The details are for debugging purpose only. The response event subscriber uses the information attached to ['#attached']['placeholders'].

A placeholder strategy is for example BigPipe, which uses another strategy to deliver the placeholder content after page load.


Check if a view is enabled or disabled How can I check from a custom module if a specific view is enabled or disabled?

I did it with module_invoke().

$block = module_invoke('views','block_view','-exp-machinenameoftheview-page');
if (!empty($block)) {
  // The view is enabled.
}
else{
  // The view is disabled.
}


How to create one node tpl files for multiple content types? In my site I have 10-15 content types that have the exact same node template layout. Like node--productone.tpl.php, node--producttwo.tpl.php etc...

How can i create one node tpl files for that similar type of content types?

Yes you can. Here is the example:

function YOURTHEMENAME_preprocess_node(&$variables) {
  if ($variables['node']) {
    $node = $variables['node'];
    switch ( $node->type ) {
      case 'type1':  // Replace with your actual content types
      case 'type2':
      case 'type3':
      // looks for node--common.tpl.php in your theme directory
      $variables['theme_hook_suggestion'] = 'node__common';
      break;
    }
  }
}


How do I access the values of my results from a view I have a preprocess function that I would like to run against a view, but I can not seem to be able to access the actual results. I have a custom entity called entity1 with two fields, field1 and field2. This function runs, but the value of $value is never set

function template_preprocess_views_view_hook(&$variables) {
  // View options set by user.

  foreach ($variables['view']->result as $id => $result) {
    //Things I've tried:
    $value1 = $result->field_field_field1;
    $value2 = $result->field_field_field1[0]['raw']['value'];
    $value3 = $result->entity1_field_field1;
    $value4 = $result->field1;
    //and many other things
  }
}

The foreach loop does in fact cycle through for the correct number of results.

You need the method getValue() from each field to get the field data from row:

$view = $variables['view'];
$values = [];
foreach ($view->result as $row_id => $row) {
  foreach ($view->field as $field_id => $field ) {
    $values[$row_id][$field_id] = $field->getValue($row);
  }
}

If you want the rendered field use $field->render($row)


How do I render the comment form? I have attached a comment type to a content type via a field.  Right now all I can see is a link called Add new comment. How do get the comment form to render on the node and not show the link?

If I've assumed your question correctly, you want to show the comment form when displaying the node content page. You can do this by enabling a setting "Show reply form on the same page as comments" in Comment field. Check screenshot below:

Edit Comment field

Enable "Show reply form on the same page as comments" setting checkbox and click on "Save Settings".


How to reset a site to its profile installation? D7 I installed the Commerce Kickstart distribution and I've made some modification. Now I'd like to reset the site to remove all my modification and get the site restored.

Do I need a module to do this? Maybe this one: http://drupal.org/project/drupal_reset

Yep. You can also check out Demo as it is very very much helpful during testing and playing around in local development. You can create a snapshot of a clean website with your settings and then do whatever you want; if necessary with a click you can roll back to the initial settings without reinstalling the whole site.

Keep in mind though that you can use and setup Demo only before you start playing around - it will save the current site in a snapshot.


How do I add a custom region? How do I add a custom region in the bootstrap theme using Drupal 8?
I have installed a Bootstrap theme and now I want to add a custom region before the Header region.  What should I add in the theme .info file? How do I render it in the page template?

In your sub-theme's .info.yml file add the new region alongside the existing ones, e.g.

regions:
  header: Header
  content: Content
  sidebar_first: 'Sidebar first'
  footer: Footer
  custom_region: 'Custom region'

Then in your page.html.twig file render it like so:

{{ page.custom_region }}

Visit the Block layout admin page and assign some blocks to the region so it displays on the page.


How to delete sites showing up in backend of Aquia Dev Desktop Deleted sites still showing up with Aquia Dev Desktop even if I already deleted files and databases.

Any way to clear these?

Found the solution, at the bottom left of the window there is a + and - sign, they look like sorting icons,but actually they are to delete. Clicking on minus does it.


In Views 2, display only one value and leave blank all other values I have a view that displays all nodes of a content type but I'm trying to display 1 value of a multi-value field and keep the rest of the values of the same field as blank. For example:

One field has 2 values: Yes and No. I'd like to display both nodes in my block in a table but for the column with the Yes/No field, I'd like to show "Yes" but leave blank if value is "No". Can this be done? Thanks

Have a look at the Views PHP module. This allows you to check any field of the view with an if-statement (or wgatever you like). Not really a very nice solution, but simple.


What is the fastest way to get node title from nid? Say I have an nid (or a lot of them). Would it be faster to load the node to access get the title, or do the very simple db_query required to get the node title?

You said fastest.

If you can compromise two things, this should be the fastest one. Now, note that you have to compromise:

If you are only trying to get the node title, and if you are sure that there are no other hook_node_load implementations (basically module handlers that would alter the node load at the time they are loaded), you can skip using the node_load() or node_load_multiple() functions and go for this solution.
When loading a node from the database, it's advised that you use a query tag to make sure that the user has access to those nodes. If you don't use any node access modules, you can go down for this solution.

With both above points in mind you can uses something like this:

function MYMODULE_node_get_title_fast(array $nids) {
  $titles = &drupal_static(__FUNCTION__, array());
  $return = array();
  $unavailable = array();
  foreach ($nids as $nid) {
    // Lookup static cache of self.
    if (array_key_exists($nid, $titles)) {
      $return[$nid] = $titles[$nid];
    }
    else { // Set NULL, so unavailable nodes will have NULL as their return value.
      $unavailable[$nid] = NULL;
    }
  }

  if ($unavailable) {
    $results = db_query("SELECT nid, title FROM {node} WHERE nid IN (:nids)", array(':nids' => array_keys($unavailable)))->fetchAllKeyed(0, 1);
    if ($results) {
      $return = $results + $unavailable;
      $titles = $return + $titles;
    }
  }

  return $return;
}

You can pass an array of node IDs, and the above function will return their titles without the overhead of node_load, field_attach, or entity_load overheads. It also skips node access checks, so do not use this in sites that you want any sort of access restrictions.

Usage example:

 $titles = MYMODULE_node_get_title_fast(array(256, 258, 54898));

You would return an array, with all given array values as keys, and the title as their value. NULL if the node is unavailable.


How to show categories and regarded node in drupal 7 I have a site in Drupal 7. I am using brands(taxonomy term) and product(node).
For example I have 4 brand -- brand1 brand2 etc.. I need to show all 4 brands and regarding node .. When I click on brand 1 . then brand1 related node need to show..

I need something like this structure..
 display all terms on left and right all regarding products.

Create taxonomy(first add vocabulary and then add terms) by going to
the below path:

  admin/structure/taxonomy

Configure your content type to add a field of type 'term reference':

  admin/structure/types/manage/article/fields

Add content and select your brand field.
Create a view by doing the following configurations shown in
attached image.


Add '?' and '=' characters to query string I'm trying to pass '?' and '=' symbols to a page using routing.yml

company.calc:
  path: '/form?company={nid}'
  defaults:
    _controller: FrameworkBundle:Redirect:redirect
    _title: 'Calc'
 requirements:
   _permission: 'access content'

but the symbols are transcoded to HTML-entities. It looks like form%3Fcompany%3D%3Fcompany%3D18141 and leads to page 404.

Any ideas how to pass the string like

/form?company=1234

? This string is necessary to prepopulate the form's field.

Find the same question here but no reply, no solution :(.

You declare query parameters in drupal routes in a mymodule.routing.yml file like this:

mymodule.mailcommitter:
  path: '/mailcheck/{uid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ProfilController::checkMailCommit'
    _title: 'commit mail'
  options:
      query:
        token: ""
  requirements:
    _permission: 'access content'

Then, you build an url by route like so

'url' => Url::fromRoute('mymodule.mailcommitter', ['uid' => 1], ['query' => ['token' => 'hello']])

Also check this doc: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes


Store entity with entity reference field? I want to create an ECK programmatically, I can create it but the issue is with the entity reference fields that being empty

The interesting issue is that when I try to edit the created entity, just some fields are accessible none of entity references.

The more interesting issue is when I try to see the list of that entity page is broken and show this error to me.

  Error: Call to a member function label() on null in Drupal\eck\Controller\EckEntityListBuilder->buildRow() (line 43 of modules\contrib\eck\src\Controller\EckEntityListBuilder.php).

I tried these codes:

  // Define entity type and bundle.
  $entity_type = "attendees";
  $bundle = "attendees";

  // Get definition of target entity type.
  $entity_definition = \Drupal::service('entity.manager')->getDefinition($entity_type);
  // Load up an array for creation.
  var_dump($entity_definition);
//  die();
  $entity_data = [
    'title' => 'this is test new',
//    'field_address' => $studentRecord['field_address'],
    'field_student_account' => 10,
    'field_students' => 48,
    'field_enrollment' => 270,
    'field_status' => 'Active',
//    'field_description' => "tsetestsetstes",
     // Use entity definition to set the appropriate property for the bundle.
    $entity_definition->getKeys()['bundle'] => $bundle,
  ];
  $new_entity = \Drupal::service('entity.manager')->getStorage($entity_type)->create($entity_data);
  $new_entity->save();
  var_dump($new_entity->id());
  die();

here are the valid values for another that created from the front end.

#values: array:12 [▼
    "id" => array:1 [▼
      "x-default" => "15"
    ]
    "type" => array:1 [▼
      "x-default" => "attendance"
    ]
    "uuid" => array:1 [▼
      "x-default" => "9a1fd3ec-3d7d-4926-a1d2-fcafc8fce3c2"
    ]
    "langcode" => array:1 [▼
      "x-default" => "en"
    ]
    "title" => array:1 [▼
      "x-default" => "group lesson"
    ]
    "created" => array:1 [▼
      "x-default" => "1561802666"
    ]
    "changed" => array:1 [▼
      "x-default" => "1561802705"
    ]
    "default_langcode" => array:1 [▼
      "x-default" => "1"
    ]
    "field_enrollment" => array:1 [▼
      "x-default" => array:1 [▼
        0 => array:1 [▼
          "target_id" => "271"
        ]
      ]
    ]
    "field_status" => array:1 [▼
      "x-default" => array:1 [▼
        0 => array:1 [▼
          "value" => "Inactive"
        ]
      ]
    ]
    "field_students" => array:1 [▼
      "x-default" => array:1 [▼
        0 => array:1 [▼
          "target_id" => "69"
        ]
      ]
    ]
    "field_student_account" => array:1 [▼
      "x-default" => array:1 [▼
        0 => array:1 [▼
          "target_id" => "27"
        ]
      ]
    ]
  ]

And this is the data that comes with programmatically creation.

EckEntity {#1106 ▼
  #values: array:8 [▼
    "id" => array:1 [▼
      "x-default" => "16"
    ]
    "type" => array:1 [▼
      "x-default" => "attendees"
    ]
    "uuid" => array:1 [▼
      "x-default" => "1048d24d-ffc7-4243-81c1-b26b5e9e9ecb"
    ]
    "langcode" => array:1 [▼
      "x-default" => "en"
    ]
    "title" => array:1 [▼
      "x-default" => "this is test new"
    ]
    "created" => array:1 [▼
      "x-default" => "1561806843"
    ]
    "changed" => array:1 [▼
      "x-default" => "1561806843"
    ]
    "default_langcode" => array:1 [▼
      "x-default" => "1"
    ]
  ]

this is my fields map

And this is the form display setting

You should try this for entity reference fields:
Single value:

$entity_data = [
'field_student_account' => ['target_id' => 10],
];

Multiple values:

$entity_data = [
'field_student_account' => [
    ['target_id' => 10],
    ['target_id' => 11],
  ],
];

Hope that works :)


Change in core module security risk As interim solution to an issue in JavaScript, I changed the User module code, to disallow single quotation mark. I changed the following line.

if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {

After my edit, it becomes as follows.

if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.-]/i', $name)) {

One of our senior Drupal developers said that this is not an acceptable solution because it could open up the site to serious security risks and it could potentially lead to a security flaw around form injection.

I do not understand why that could happen. Can anyone explain me why?

PS. I understand that this will get overwritten on Drupal update. This was to temporarily prevent serious bug that is blocking the whole page from functioning.

So it turns out the regexp is not for avoiding apostrophes but to allow them, you can track down the origin to this issue to 6 years ago: https://drupal.org/node/266488

  I've added apostrophe support(+test) and a small change in check_plain() as proposed in http://drupal.org/node/165226 in the new version of the patch.

So it would be not due a security flaw but to have names with apostrophes correctly handled as you can see in the issue above:

  One of my friends is fortunate, or unfortunate, enough to have an apostrophe in his last name. Many first and last names have this, for example: O’Reilly.

  The crazy thing is: Drupal completely ignores this, and O'Reilly becomes OReily

The reason why this is crashing your site is hard to foresee, I stand that you might be fixing the symptoms here and not the cause by changing the regexp. Check the username databse you've got for strange chars.

If you want to have a way to modify this validation pattern, you can check this module Custom username validation.


How do I override headers displayed in permissions tables? I'm using Organic Groups on my (D7) site. I've set it up so that group managers can create new roles and change permissions in their groups. I've overridden some of the permissions using hook_og_permission_alter() to limit what they can actually change, and this seems to work well.

The problem I'm having is I want to alter/remove the section headers (ex. Organic Groups, Organic groups UI) that are set up by the different OG modules in this permissions table (I currently have three modules generating their own heading), and I can't find a way to do this. I can't find a hook that does what I want, and I've tried making sure none of the permissions are associated with the headings, but that didn't remove them. I guess I could edit the modules generating these headings and change their names to what I want the headings to display, but that really doesn't feel like the right approach here (and I'd rather remove the headings altogether anyways).

Does anyone know how I can approach this?

Implement hook_page_alter() and

function mymodule_page_alter(&$page) {
  if (current_path() == 'admin/people/permissions') {
    foreach ($page['content']['system_main']['permission'] as $index => $permission) {
      if ($permission['#markup'] == 'Organic Groups') {
        $page['content']['system_main']['permission'][$index]['#markup'] = 'Foobar';
      }
    }
  }
}


Drupal Distribution best practices I have a site with drupal commons distribution. I updated the existing content type to add some fields which made the feature in overriden state. Now, I am not sure the best practice to follow. Should I update the feature in profiles/commons/modules/... or is there another way to update the existing content type without changing the default code? Should I move all profile modules under sites/all/modules/...?
Please help me to follow the best practices.
Thank you.

Once your features are overridden, then the configuration is moved from the files to the database (i.e. Drupal no longer looks for the configuration supplied by the feature module and uses your configuration in the DB). This means you can update the files without overriding your changes/additions (Just don't hit the revert button in the Features admin UI). That being said, if you changed/updated a content type, you will no longer be able to take advantage of any changes/updates that were made to the commons distro supplied content type. This is the same for views, contexts, rules, etc.  Some devs will use the Features Override module to allow them to store their site specific overrides in a feature.  This allows you to store your overrides in files and still leverage any changes/additions from the distro.


Customising Views Serializer JSON Output I have created a Views Rest Export that looks like this:

{
   "id":"10",
   "title":"Plot 10",
},
{
   "id":"20",
   "title":"Plot 20",
}

But I would like to wrap some extra bits around it like this:

{
   "mapwidth":"690",
   "mapheight":"982",
   "levels":[
      {
         "id":"uk",
         "title":"United Kingdom",
         "locations":[
            {
               "id":"10",
               "title":"Plot 10",
            },
            {
               "id":"20",
               "title":"Plot 20",
            }
         ]
      }
   ]
}

I have created a php file with this in it, which seems to work:

{
    "mapwidth":"690",
    "mapheight":"982",
    "levels":[
        {
            "id":"uk",
            "title":"United Kingdom",
            "locations":
            <?php $locations = file_get_contents('/api/plots?_format=json');
            echo $locations; ?>
        }
    ]
}

But I was wondering what the better way of doing this would be.

Thanks in advance.

You can create a module and extend ContentEntityNormalizer to provide a custom structure.

Example:

<?php

declare(strict_types = 1);

namespace Drupal\mymodule\Normalizer;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Drupal\image\Entity\ImageStyle;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\node\NodeInterface;

/**
 * Converts the Drupal entity object structures to a normalized array.
 */
class NodeEntityNormalizer extends ContentEntityNormalizer {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = [
    'Drupal\node\NodeInterface',
  ];

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function normalize($entity, $format = NULL, array $context = []) {
    $type = $entity->getType();

    $methods = [
      'library' => 'normalizeLibrary',
      'collection' => 'normalizeCollection',
    ];

    if (isset($methods[$type])) {
      return $this->{$methods[$type]}($entity, $format, $context);
    }

    return parent::normalize($entity, $format, $context);
  }

  /**
   * Normalize a library content type.
   */
  protected function normalizeLibrary($entity) {
    $attributes['id']       = $entity->id();
    $attributes['featured'] = !empty($entity->get('field_is_coming_soon')->value);
    $attributes['external'] = !empty($entity->get('field_is_stub')->value) && !empty($entity->get('field_website_link')[0]);
    $attributes['name']     = $entity->label();
    $attributes['subTitle'] = !empty($entity->get('field_subtitle')->value) ? $entity->get('field_subtitle')->value : '';

    return $attributes;
  }

  /**
   * Normalize a collection content type.
   *
   * @param \Drupal\node\NodeInterface $entity
   *   The node entity.
   *
   * @return array
   *   The item attributes.
   */
  protected function normalizeCollection(NodeInterface $entity) : array {
    $attributes = [];
    $attributes['id'] = $entity->id();
    $attributes['title'] = $entity->label();
    $attributes['subtitle'] = $entity->get('field_subtitle')->value;
    $attributes['summary'] = $entity->get('field_summary')->value;
    $attributes['card_type'] = $entity->get('field_directory_view')->value;
    $attributes['list_image'] = NULL;
    $attributes['card_image'] = NULL;
    $attributes['url'] = Url::fromRoute('entity.node.canonical', ['node' => $attributes['id']])->toString();

    $media = $entity->get('field_featured_image')->getValue();

    if (!empty($media)) {
      $item = $this->entityTypeManager->getStorage('media')->load($media[0]['target_id']);
      $image = $item->get('image')->getValue();

      $attributes['list_image'] = [
        'src' => ImageStyle::load('collection_listing')
          ->buildUrl($item->image->entity->getFileUri()),
        'alt' => $image[0]['alt'],
      ];

      switch ($attributes['card_type']) {
        case 'wide':
          $attributes['card_image'] = [
            'src' => ImageStyle::load('collection_listing_wide')
              ->buildUrl($item->image->entity->getFileUri()),
            'alt' => $image[0]['alt'],
          ];
          break;

        case 'tall':
          $attributes['card_image'] = [
            'src' => ImageStyle::load('collection_listing_tall')
              ->buildUrl($item->image->entity->getFileUri()),
            'alt' => $image[0]['alt'],
          ];
          break;

        case 'standard':
          $attributes['card_image'] = $attributes['list_image'];
          break;

        default:
          break;
      }
    }

    return $attributes;
  }

}

This code only applies to Node entities, and only for two content types (you will want to specify them, since this will override anything matching the $supportedInterfaceOrClass property.

You will need to add it to your custom modules services.yml file:

services:
  mymodule.node_entity:
    class: Drupal\mymodule\Normalizer\NodeEntityNormalizer
    arguments: ['@entity_type.manager']
    tags:
      - { name: normalizer, priority: 8 }

The View will now use this normalizer if the conditions match and you can structure the output however you like. This gives you the power say, to reach into entity references and pull in values or do conditional things (like the custom image size I am passing in normalizeCollection depending on a field value).

Note that my example is custom and does not do things like check field level access for the user, since we do not have any restricted fields.


Views: Rewrite Results Broken? I've just installed the Views Slideshow Module and gone threw some tutorials to see how it is installed and how it works. Everything works just fine except that Rewrite Result don't work. No Textbox for editing is showing up when I check Rewrite the output of this field. I've tried both in Firefox and Chrome to see if there was some JavaScript thingy but it wasn't. Anyone else is having this very annoying problem?

Checked status report and found no errors. Cleared all cache too.

Also tried with some old Views that I've created and it don't work on those either now. I've tried to disable Views Slideshow but no change. So this might be some other issue that occurred before I installed Views Slideshow.

Using D7, Views 3 and Views Slideshow 3.1

EDIT: It turns out that it's all settings that can be done from checkboxes are disabled somehow. I've even re-installed the Views Module but no luck. Don't know what's causing this behavior.

This is a problem that raises it head in some or other form quite regularly. The answer is to change the jQuery version. Use jQuery Update. Set it to 1.7 or 1.8 for admin pages.


Default Price for Commerce Product As it is not possible to set a default price to products I was trying to achieve that by using rules. I'm checking "Before saving a commerce product" Event. Condition is "Data value is empty" and my Action would be "Set a data value", but all I get is an error because price isn't set. Anyone know why this is happening?As this is the first time I use rules, maybe I've done something wrong.

/**
 * Implements hook_field_widget_form_alter()
 */
function HOOK_field_widget_form_alter(&$element, &$form_state, $context) {
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'commerce_price') {
      if (empty($element['amount']['#default_value'])) {
        $element['amount']['#default_value'] = 0;
      }
    }
  }
}


bandcamp embed field I'm running D8.
I need to have a field to embed a bandcamp player in. I'm using media module but there doesn't seem to be a way to embed platforms not officially supported by fx media video, media audio etc.
I'm not a php-coder, just html / css.

Any ideas?

If bandcamp offers a method of embedding their players into other websites, you can open a request in the issue queue for the URL To Video Filter module (which I'm the developer of), with a link to their embed method, and I'll try to integrate it for you.


Sending email notifications to all editors the content's editorial section on content state change I am using Using Workbench for content moderation and Workbench Access for access control.

Is it possible to use the rules integration to send an email to all of those users who are in a content node's editorial access control?

The screenshot shows what I've currently got, which is sending the notification to one particular email address on state change to Needs review.

I don't know what the "editorial access control" is but if you don't find any easier solution you can always write your own rules action for generating the list of people you need. In my case I am sending a message to the reviewers that are provided in one of the fields of the content. It should be easily adaptable to any other porpoise.

/**
 * Implements hook_rules_action_info().
 */
function mymodule_workflow_rules_action_info() {
  $items = array();
  $items['mymodule_workflow_reviewers'] = array(
    'label' => t('Get reviewers'),
    'group' => t('Windbench'),
    'parameter' => array(
        'node' => array('type' => 'node', 'label' => t('Node')),

    ),
    'provides' => array(
      'reviewers' => array('type' => 'list<user>', 'label' => t('List of reviewers')),
    ),
  );
  return $items;
}
function mymodule_workflow_reviewers($node){
  $reviewers = array();
  foreach($node->field_workflow_reviewers['und'] as $reviewer){
    $reviewers[] = user_load($reviewer['uid'],true);
  }
  return array('reviewers' => $reviewers);
}

And then use that action in your rules


Why do I get a syntax error on this query? I need some help with this query:

$result = db_query("SELECT
  UNIX_TIMESTAMP(FROM_UNIXTIME(s.timestamp, '%Y%m%d')) AS date,
  s.nid, COUNT(*) AS all_count,
  COUNT(DISTINCT s.ip_address) AS unique_count
FROM {simpleads_impressions} s
WHERE FROM_UNIXTIME(s.timestamp, '%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE() - INTERVAL 1 SECOND
GROUP BY date, s.nid");

The main issue is the WHERE clause, and the count/group issue.

$query = \Drupal::database()
    ->select('simpleads_impressions', 's')
    ->fields('s', array('nid'));
$query->addExpression("UNIX_TIMESTAMP(FROM_UNIXTIME(timestamp, '%Y%m%d'))", 'date');
$query->addExpression('COUNT(*)', 'all_count');
$query->addExpression('COUNT(DISTINCT ip_address', 'unique_count');
$query->where("FROM_UNIXTIME(timestamp, '%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE() - INTERVAL 1 SECOND");
$query->groupBy('date');
$query->groupBy('nid');
$result = $query->execute()->fetchObject();

This is the error message I get:

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AS unique_count FROM simpleads_impressions s WHERE (FROM_UNIXTIME(timestamp, '' at line 1: SELECT s.nid AS nid, FROM_UNIXTIME(timestamp, '%Y-%m-%d') AS utime, DATE_SUB(CURDATE(), INTERVAL 1 DAY) AS startdate, DATE_SUB(CURDATE(), INTERVAL 1 SECOND) AS enddate, UNIX_TIMESTAMP(FROM_UNIXTIME(timestamp, '%Y%m%d')) AS testdate, COUNT(*) AS all_count, COUNT(DISTINCT ip_address AS unique_count FROM {simpleads_impressions} s WHERE (FROM_UNIXTIME(timestamp, '%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE() - INTERVAL 1 SECOND) GROUP BY date, nid; Array ( ) in simpleads_cron() (line 23 of D:\www\nla-refactor\modules\custom\simpleads\simpleads.module).

What code should I use to fix the error?

I changed the code to the following one, and I don't get the error anymore.

$query = \Drupal::database()
    ->select('simpleads_impressions', 's')
    ->fields('s', array('nid'));
$query->addExpression("FROM_UNIXTIME(timestamp, '%Y-%m-%d')", 'utime');
$query->addExpression("UNIX_TIMESTAMP(FROM_UNIXTIME(timestamp, '%Y%m%d'))", 'date');
$query->addExpression('COUNT(*)', 'all_count');
$query->addExpression('COUNT(DISTINCT ip_address)', 'unique_count');
$query->where("FROM_UNIXTIME(timestamp, '%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE() - INTERVAL 1 SECOND");
$query->groupBy('date');
$query->groupBy('nid');
$query->groupBy('timestamp');
$result = $query->execute()->fetchObject();


Controlling file paths in multi domain setup A site responds to internal.example.com, and external.example.com.

Content editors all use internal. When Drupal generates the cached output, all images are now absolute URLs pointing to an internal domain, making them fail.

How would you handle this?

I use the sledgehammer approach and search/replace from template_process_html:

function foo_process_html (&$variables)
{
  $variables["page"] = str_replace("http://internal.example.com/", "/", $variables["page"]);
}

You can also get fancy and use preg_replace if you need better control.  I typically end up needing this when I move a site from our staging server, which is a subdomain off of ours, onto a client's own domain.

If I were in your shoes, I would think about having an internal theme and an external theme, combined with one of the choose-a-theme-based-on-domain-name solutions.  Then you can add preprocess/process as needed to just the external theme.


Drush tries to export config for modules I deleted months ago I'm using Drush 9.3 and when I export config it wants to create config files for modules that have been gone for months.  One of those is plupload which is nice because it's easy to search the code base to see if I have anything that references plupload whatsoever.  I do not.  Yet when I run "Drush cex" it exports plupload.settings as well as settings for several other modules that are LONG GONE.  When I try to "Drush cim" on the staging server the import fails complaining that these modules do not exist.  I'm sure these modules are in fact referenced in the drupal database but I cannot figure out anywhere in the GUI to remove them, no option to uninstall Plupload from the uninstall page.  If I do install plupload using composer it appears as a module that can be enabled under the modules page, but still no option to uninstall or remove from the Drupal database.  What am I missing?  Why does Drupal think I still have these modules?

Thank you!!!

When you removed the modules I would guess you didn't uninstall them first. The simplest approach is probably going to be to put the code back by whatever means you originally installed them, in the same location, then uninstall them via the admin panel or drush before removing the code again. That way the core code will fire that deletes the config.

It is possible that a module may break the uninstall process, in which case this is a trickier problem but best to go down the simplest route first.


Is there something like a private FAQ/ask-the-expert? I've been looking for a module that allows something like ask the expert with these conditions:

A registered user U uses a form to submit the question. Anonymous users do not have access to this section.
The expert E is notified of the new question by email.
When E answers the question, U is notified by email.
U can only see the questions asked by himself/herself (with their respective answers). No regular user can see the questions asked by other user, or the answers given to other users.
An administrator A can see all the questions and answers at all times.

The modules faq and faq_ask seem like an option, but I can't use the traditional FAQ format, since that format allows all users to see all questions. The module question is not available for Drupal 7.

Is there anything like what I'm describing? If not, is there any way of modifying, for example, the faq module, so permissions will work the way I want?

Thanks in advance!

The question_answer module is probably what you want. I used to make a private Q/A for registered users on a site. All the "workflow" you talk about can be done via either the workflow module, drupal actions or the Maestro module ... I'd give Maestro a shot only because I haven't used it.


Getting total vote results for several nodes in a view (Drupal 7, Views 3) This is the problem: I have a Drupal 7, Views 3 site with a certain node type with a Fivestar field on it. I want to get total scores not for one node, but for all the nodes in a view.

For example, let's say our nodes are "restaurants". A person can write a review for this restaurant and give it a score.

Okay, now imagine some of these restaurants are thai restaurants. Now imagine I want the average score for all the thai restaurants in a view. Be careful about this, I don't want the average for one of the restaurants, but for ALL the restaurants in a given category. That's clearly a work for views, but how? How do I do that?

Thanks in advance.

Create a view:

Use Agregation.
Use fields.

Add fields in this order remove everything else:

Taxonomy or (Category) as you call it. (Aggregation settings = Group results).
field_rating (or your five star field). (Aggregation settings = Average).

Filters.

Published (YES).
Content type = (restaurants).

What you need to do in resume, is to call all the nodes of type "restaurants" group the results the taxonomy field by Aggregation and AVERAGE all the ratings.


Blocks and CSS Grid Systems How do I achieve the following in Drupal:

[MY BLOCK HERE]

[MY BLOCK HERE]

[MY BLOCK HERE]

I can use the "Block Class" module to assign the grid system classes to the block, however this does not allow me reuse blocks in another layout (changing the grid system classes).

Im also limited to where I can put these blocks. At the moment i have a specific region setup that is wrapped in the "row" class. This prevents me for having a few different rows and from placing the blocks anywhere...

[MY BLOCK HERE]

[MY BLOCK HERE]

[MY BLOCK HERE]

[MY BLOCK HERE]

[MY BLOCK HERE]

[MY BLOCK HERE]

Basically I need to:

Add grid system classes to blocks
Reuse blocks in a different grid system class configuration
Freedom to define rows of blocks and assign them to any region, not just one that is wrapped in a single "row" class.

Any help would be much appreciated, at the moment I have to style each individual block to work responsively and I know that there must be a better way of doing this.

Thanks

We primarily build our sites using Bootstrap with this same technique, so here are 3 modules that will make your life a lot easier.

Block Class - add classes to blocks.

Block Group and/or Region Class - group blocks together in faux regions, add classes to regions.

Blocker - places blocks on specific pages in different regions, alternative to using the core block placement system. Really useful for site building and putting blocks on basic pages.


Making sticky results in Search API Solr We want to be able to promote some nodes on the search results.
I thought about using the "Sticky" option, so if a node is sticky, it should be on top of the results.

I've tried using the "Boost" option in the index field settings but it doesn't work.

Is there any way of achieving that?

(Using Drupal 7, Apache Solr 4.6.1 and Search API)

Could you perhaps?:

Put a boolean field on your content (or make use of the 'promote to front page' field)
Make a view to arrange your search results
Group by that boolean (or 'promoted')

I don't know if 'promoted' is indexed by default, you might need to set that.


How to have a language switcher that allows you to select the country and then the langauge within the country? We are looking to have a menu at the top right that allows users to select the country they want to view and then once the country is selected, we want them to pick a language that they can view the site in. How is it possible and what are the recommended modules?

Example:

Check Language Switcher module or Language Switcher Dropdown module.

But as of now there is no contrib module that does exactly as you wanted.


Pressflow + CDN, node access counter not updating I am using Pressflow (Boost+Varnish) with "boost ajax stat block" enabled for stats, things were working ok and node counter was getting updated. Few days ago I started using full-site acceleration via CDN and the node access counter (page reads) is no longer updating ?

In theory boost ajax stat should work with caching, why is it not in this case ?

Website : http://www.megaleecher.net/

Finally found a working solution.

Module - http://drupal.org/project/jstats gets the job done, make sure to copy the jstats.php file into root.

Thanks


Creating a page to display several content types I have a website to build that requires several quite long pages, each containing several sections with quite different content in each.

A content type for each page isn't going to work as some sections would need to contain several entries, to be displayed as a slider.

So, I think, I need to create each section as a different content type and my problem becomes displaying several of these on the same page?

How can I display several content types on the same page?

Or maybe I could create a category for each page and add the types to those?

The Views module might help you for this purpose. It is highly configurable, and it allows you to display several items on a single page. Other modules can add functionality, like the Views Slideshow module.

Learning how to use Views takes some time, but there are many Views tutorials available in the web. A possible starting point might be this one:

https://dev.acquia.com/blog/a-totally-beginner-tutorial-to-views-for-drupal-7/22/01/2016/9576


Getting a formatted address component in another field's template I need to pull the administrative area component from an Address field and place the full text of it it in the template of another field on the content type. I've managed to accomplish this with the following code.

In preprocess:

function MYTHEME_preprocess_page_title(&$variables) {
$node = \Drupal::request()->attributes->get('node');
  $variables['content_type'] = $node->bundle();
  if ($node->bundle() == 'location') {
    $variables['address_state'] = $node->get('field_address')->getValue()[0]['administrative_area'];
  }
}

And in the twig template:

{% if content_type == 'location' %}
  <h1{{ title_attributes }}>{% spaceless %}{{ title }}{% endspaceless %}{% spaceless %},{% endspaceless %} {{ address_state }}</h1>
{% endif %}

This will produce, for example "Boston, MA". But what I want is "Boston, Massachusetts", using the full name of the administrative area rather than the code. According to Drupal Commerce Address docs, you can get the full name in a twig template using {{ administrative_area.name }}. But I couldn't get that to work. How can I render the full administrative area name in the template?

How I understand the linked doc you need to configure the plain address formatter in a view mode to use address-plain.html.twig. Then you can output the node field as formatted in this twig:

   if ($node->bundle() == 'location') {
     $variables['address_state'] = $node->get('field_address')->view('custom_view_mode');
   }


Is possible to have mutiple email for a user? Is possible by default in Drupal 7 to have more than one email associate for a user ?

In the Users table, 'mail' - the field for email addresses, is unique, as it's tied to other criteria to control account management, login, logout, etc.

So depending on what you are trying to accomplish, I dont think you could have more than one email control one account without some custom database changes.

However if you simply want to link an account to multiple email addresses, perhaps this is as simple as an 'email address' field for the profile. Adding unlimited to that field for the form would invoke the 'add another' and the user could simply have as many as they needed.

If you wanted that person to be able to login with any of those email addresses, then a quick module could link the fields together so that the email addressed used had a primary account referenced by it, and, then would proceed with login.

Or, I could be way off - what are you ultimately trying to accomplish?


How to Table sorter in node page? I have a table in node page. i have requirement to make it sort-able on click.

can anyone help?

I used something like this in one of my installations:

// create a table of nodes of a specific content type
function MYMODULE_create_table($node_type) {
  // setup headers
  $headers = array(
     array('data' => 'Nid'),
     array('data' => 'Title', 'field' => 'title'),
     array('data' => 'Status')
  );
  // build query
  $query = db_select('node', 'n')->extend('PagerDefault');
  $query->limit(30);
  $query->fields('n', array('nid', 'title', 'status'));
  $query->condition('n.type', $node_type, '=');
  // make it sortable
  $query = $query->extend('TableSort')->orderByHeader($headers);
  // execute query
  $result = $query->execute();
  $rows = array();
  foreach($result as $node) {
    $rows[] = array(
       $node->nid,
       $node->title,
       $node->status
    );
  }
  // add a pager if needed
  if(count($rows) && ($pager = theme('pager'))) {
    $rows[] = array(
      array(
    'data' => $pager,
    'colspan' => 3,
  )
    );
  }
  // return html for table
  return theme('table',
            array(
                'header' => $headers,
                'rows'=>$rows,
                'empty' => 'No products found...',
            )
    );
}

The above perhaps work just as is, but it might give you some clue on how this can be done.

TableSort


multiple values of several fields grouped together I am using drupal 7 as a backend, in which I have a content type called conferences, and each conference has several events. I do not want to create another content type for events and would want to add them to the same content type as each event has only two fields the date and the venue. How can I achieve this using UI as CMS ? and then later be able to make API's to send the same. Please suggest modules to achieve the same

You should look at field_collection module. It allows you to create a field, and add fields to that field (behind the scenes it's using entities).

A typical use case, is if you want user to enter multiple sets of data, like fx

name
image
url

To achieve this, you would create a field_collection field on the node or what you want this on and set the cardinality to the limit. Then on the field collection you would add the name, image and url fields. It's also possible to configure some fields to be required and other to be optional.


Getting latest entity data from the database The problem: I open a drush php:cli shell and run the following:
>>> \Drupal::entityTypeManager()->getStorage('paragraph')->load(477)->get('field_end_time')->getValue()[0]['value'];
=> "05:01"

I then change the value in the database to 05:02 via the admin panel (content section).
But if I run the same command again in the shell, I still get 05:01.
If I close the shell and open a new one I get 05:02. How do I demand the latest data without terminating the process and starting over? This seems like it must be a basic thing but I've searched far and wide and tried clearing caches and etc. but no dice.
This is affecting me because I have a PHP process that is started by cron that handles a Websocket connections and the same thing is happening there—it's getting stale data from the database.
Thanks for the help.

You can clear the cached entity in memory to get the latest field values:
\Drupal::entityTypeManager()->getStorage('paragraph')->resetCache([477]);

See Referenced entities show old value when changing properties


Creating ajax modal from event Here's the deal. I want to create a modal popup when an add to cart event is triggered.

I've got the event working just fine but can't seem to get the ajax to work properly. What I'm working off of was using the magnific popup library and was creating the popup using \Drupal::messenger()->addMessage($content, NULL); where content was a render array and the theme has

{{ attach_library('commerce_add_to_cart_confirmation/confirmation_overlay_css') }}
{{ attach_library('commerce_add_to_cart_confirmation/magnific_modal') }}

right at the top.

I thought this was very weird and funky. After some searching I found that you could create an ajax response like :

  $content = "Something to show in the modal";
  $title = "Hi, I'm a Modal";
  $response = new AjaxResponse();
  $response->addCommand(new OpenModalDialogCommand($title, $content, ['width' => '700']));
  return $response;

So I started doing this instead but it wouldn't work. I was told that nothing was handling that return since this function was just called because of an event. That made sense.

I then found this which seemed to be doing nearly the same as me.
I modified my code to use the same method.
No dialog box. :( I used xdebug and saw that there was no ajax response coming from the kernel::response and thus my function kept returning no response.

I then thought that it could be that ajax isn't loaded. I used the chrome network dev tool and found no ajax.dialog there. I tried adding this to my .module file :

function commerce_add_to_cart_confirmation_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'core/drupal.dialog.ajax';
}

Then I saw ajax.dialog in the network but still no popup on my site.
The module linked above uses a hook to some commerce form (I can't tell which because the name is so cluttered) and wonder if that makes a difference.

How can I create a modal popup from a CartEvents::CART_ENTITY_ADD event subscriber? Am I missing something to do with the libraries or something wrong with my php?

How can I create a modal popup from a CartEvents::CART_ENTITY_ADD
  event subscriber? Am I missing something to do with the libraries or
  something wrong with my php?

You can't return a response from any event, this is only possible from specific kernel events by setting the response in the event. But the example you have linked should work in your case. It splits the task into two event subscribers:

  public static function getSubscribedEvents() {
    return [
      CartEvents::CART_ENTITY_ADD => 'onAddToCart',
      KernelEvents::RESPONSE => 'onResponse',
    ];
  }

which are in the same service class, so the second event can use the variable the first one has set:

  public function onAddToCart(CartEntityAddEvent $event) {
    $this->purchasedEntity = $event->getEntity();
  }

  public function onResponse(FilterResponseEvent $event) {
    $response = $event->getResponse();

    // We only care if this happened after an entity was added to the cart.
    if (!$this->purchasedEntity) {
      return;

    ...

    $event->setResponse($response);
  }


Error uploading file. An unrecoverable error occurred I've been troubleshooting a form in Drupal 7 that has two file upload fields.

If you upload a file with one field, then the other, the second upload will usually give an error. This occurs regardless of the order that the files are uploaded. The error does not occur if the files are both added to the "Choose File" fields and the whole page is submitted at once with the save button. The error also does not occur if JavaScript is disabled in the browser, and the individual upload buttons are used.

The easiest workaround I can imagine would be to disable javascript for the form controls on the specific /node/add page, but I do not know how to do this, and I have been unable to find people with a similar need.

The server is PHP/Apache2, with mod_security disabled and with the PHP post size limit and uploaded file size limit set to high limits as per the screenshot. File uploads work normally, leading me to rule out permissions as a culprit.

The watchdog logs and server error_log have no messages of interest, unfortunately.

If anyone has any advice to disable javascript for a page, or to resolve this error, please let me know. Thanks!

This error is for this line in file.module
241 --if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {

You should revise your URL


How to sort order of menus? I am using the sitemap module and have enabled 3 menus to display. However, I dont like the order the menus are being displayed in. Is there a way to change this?

You can use this patch http://drupal.org/node/1529708#comment-6633022
If you need something more specific you can use hook_site_map() to add things to your sitemap and take a look at the _site_map_menus() function.


Define fields created through the UI as non-revisionable on a revisionable entity Let's say, I have a revisionable entity. Whether base fields should be revisionable or not can be set in the code. So far, so good.
But how about those fields that get added through the user interface? Is there a way to set all the fields as either revisionable or non-revisionable? Or is there a way to set this for each field individually in the UI?

By default, all the entity fields created from the user interface are set as revisionable, and the user interface doesn't allow to set a field as not revisionable. That information is added from field_entity_field_storage_info(), which contains the following code.
$ids = \Drupal::entityQuery('field_storage_config')
  ->condition('id', $entity_type->id() . '.', 'STARTS_WITH')
  ->execute();

// Fetch all fields and key them by field name.
$field_storages = FieldStorageConfig::loadMultiple($ids);
$result = [];
foreach ($field_storages as $field_storage) {
  $result[$field_storage->getName()] = $field_storage;
}
return $result;

FieldStorageConfig::isRevisionable() always returns TRUE.
public function isRevisionable() {
  // All configurable fields are revisionable.
  return TRUE;
}

To make a configurable field not revisionable, a module should implement hook_entity_field_storage_info_alter() and alter the $field_storage values returned from field_entity_field_storage_info().
  function mymodule_entity_field_storage_info_alter(&$fields, $entity_type) {
    $ids = \Drupal::entityQuery('field_storage_config')->condition('id', $entity_type->id() . '.', 'STARTS_WITH')
      ->execute();

    // Fetch all fields and key them by field name.
    $field_storages = FieldStorageConfig::loadMultiple($ids);
    $result = [];
    foreach ($field_storages as $field_storage) {
      $result[$field_storage->getName()] = // Replace $field_storage with an object implementing FieldStorageDefinitionInterface and returning the value you want with isRevisionable().
    }
    return $result;
  }