Alter edit link behaviour in a view I am trying to change the URL of the node edit link for a specific view.
This is what I have done and it (almost) works:

created a file mymodule/views/mymodule.views.inc with the following code:

/**
 * Implements hook_views_data_alter().
 */
function kd_ari_views_data_alter(&$data) {
  module_load_include('inc', 'mymodule', 'views/views_handler_field_article_link_edit');
  $data['views_entity_node']['edit_node']['field']['handler'] = 'views_handler_field_article_link_edit';
}

created a second file mymodule/views/views_handler_field_article_link_edit.inc with the following code:

class views_handler_field_article_link_edit extends views_handler_field_node_link {

 function render_link($node, $values) {
   if (!node_access('update', $node)) {
     return;
   }
   $this->options['alter']['make_link'] = TRUE;
   $this->options['alter']['path'] = 'admin/mymodule/' . $node->nid;
   $text = !empty($this->options['text']) ? $this->options['text'] : t('edit');
   return $text;
 }
}

The problem is that the view displays the edit link only one time after I clear all caches... afterwards the display link is gone. Any tips would be highly appreciated.

Add Nid as field,
Set Label to Operation (or anything you want ),
 in Rewrite results section

check Override the output of this field with custom text  and
enter Edit text.
check Output this field as a custom link and in the input box
enter  admin/mymodule/[nid] .

save the field and enjoy the power of views rewriting.


How to show price range I got Drupal 8 / Commerce 2 installation, and trying to create product category pages, showing product image, title and price range (min & max price)

I've created product category page with Views. Category is defined as Taxonomy reference field in product.
Views has "Contextual filter", where category name is taken from url e.g. /product/[category].

Product catalog page works fine, showing fields defined in (custom) Summary view mode. It shows title and the first product variation image and price.

Only thing missing is the price range info

I've tried to do some experiments by

overwriting commerce-product.html.twig in custom theme
writing hook__preprocess_commerce_product in custom module

..but with no luck. Debugging is hard because, for some reason kint() / dpm() calls fail or just take tooo long and give execution time out...

So the question is: how and where to check product variations lowest & highest prices plus pass them to product template?

Any hints or ideas are greatly appreciated.

EDIT:

I got it done by adding the following preprocess  hook to my custom module

function CUSTOMMODULE_preprocess_commerce_product(&$variables) {

  $product = $variables['elements']['#commerce_product'];

  foreach( $product->variations as $variation) {
    $prices[] = $variation->entity->getPrice()->getNumber();
  }

  $min_price = min($prices);
  $max_price = max($prices);

  if ($min_price != $max_price) {
    $variables['min_price'] = $min_price;
    $variables['max_price'] = $max_price;
  }

  $variables['currency'] = $variation->entity->getPrice()->getCurrencyCode();
}

... And then in commerce-product--teaser.html.twig

{% if min_price is defined and max_price is defined %}
  {{ min_price |number_format(2, '.', ',') }} -
  {{ max_price |number_format(2, '.', ',') }} {{ currency }}
{% else %}
  {{ product.price }}
{% endif %}

I don't think the min max would be readily available in the template and you'll have to add it in.

You could use hook_preprocess_commerce_product($variables) and within $variables it will contain the product entity and also all of its variations. You would just need to loop through the variations to work out the min and max price and then add the new value into $variables e.g.

$variables['min_max_price'] = $myvalue;

Then in your template commerce-product.html.twig do:

{{ min_max_price }}

and that should come out with your $myvalue value


Add a link field to block form I've created a module with a custom block that extends BlockBase. To the block form I added multiple textfields and select boxes, by simply specifying the formatter in the '#type' configuration.

My next step is to add a button that links to internal/external content and I've tried adding different types, such as 'link' but without any luck.

I found LinkFormatter, but I can't figure out how to use it properly with block forms.

What has to be added to the blockForm method in order to create a link field (just like the link field that's selectable within a custom block type):

My current code:

public function blockForm($form, FormStateInterface $form_state) {
  //...
  $form['link'] = [
    '#type' => 'link',
    '#title' => $this->t('Link title'),
    '#url' => 'Hmm?',
    '#options' => ['external' => TRUE]
  ];

  return $form;
}

You want to change '#type' => 'link' to '#type' => 'url'

public function blockForm($form, FormStateInterface $form_state) {
  //...
  $form['link'] = [
    '#type' => 'url',
    '#title' => $this->t('Link title'),
    '#options' => ['external' => TRUE]
  ];

  return $form;
}


How can I programmatically create a node? How can I programmatically create nodes with date and image fields?
I know I can do it in Drupal 7 with the following code.
global $user;

$node = new stdClass();
$node->title = "YOUR TITLE";
$node->type = "YOUR_NODE_TYPE";
node_object_prepare($node);
$node->language = LANGUAGE_NONE;
$node->uid = $user->uid;
$node->status = 1; //(1 or 0): published or not
$node->promote = 0; //(1 or 0): promoted to front page

$existing_filepath = "/home/nzcodarnoc/sites/default/files/imported/picture.jpg";
$new_filepath = "public://picture.jpg";
$drupal_file = file_save_data(file_get_contents($existing_filepath), $new_filepath);
$drupal_file->alt = $node->title;
$drupal_file->title = $node->title;
$node->field_my_file[$node->language][0] = get_object_vars($drupal_file);
$node->birth_date[LANGUAGE_NONE][0]['value'] = time();
$node = node_submit($node);
node_save($node);

What is the equivalent code for Drupal 8?

The following code will help you to save an image in a new node.
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
    'alt' => 'Hello world',
    'title' => 'Goodbye world'
  ],
]);
$node->save();


Add new field to node form on validate I am performing a hook_node_validate() and would like to add a new field (e.g. a textfield) during the processing of this function.  Is this possible?  If so could someone let me know how to do it.  I am tried to following so far w/ no luck:

function hook_node_validate($node, $form, &$form_state) {
    $form['content_type_node_form'] = array(
        '#title'    => t('Phone'),
        '#type'     => 'textfield',
        '#required' => TRUE,
    );
    form_set_error('time', t('Stop submission to add new field'));
}

Thanks,
Derek

I'm guessing what you actually want (from a user story perspective) is if a certain condition is met another, otherwise hidden, field is shown. As @geoff points out that field would need to exist on the content type.

I believe the correct way to do this within the Form API is with the #states parameter in order to conditionally show/hide the phone field.
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states


What's the purpose of the type "block_settings" in schema.yml files? In the block_example module, from the Drupal 8 Examples for Developers,
what purpose does the file block_example.schema.yml serve?

I'm familiar with using schema.yml files to set configuration and access it like so:

$config = \Drupal::config('system.maintenance');

However, it appears that the "block_settings" type is different.

That's basically config schema inheritance, like you have class inheritance in PHP.

Any type that you define can be used as by by someone else. And it is what you want to do when you extend the class (usually a plugin) for which it is defined.

block_settings itself is a type that extends from mapping and defines a few common keys, it is defined in core.data_types.schema.yml

block_settings:
  type: mapping
  label: 'Block settings'
  mapping:
    id:
      type: string
      label: 'ID'
    ...

(Multiple keys in there shouldn't exit and are for example block_content specific, but that's a bit complicated to fix now).

And if you'd provide a block plugin that would extend from example_configurable_text, then you can define it like this:

block.settings.my_block:
  type: block.settings.example_configurable_text
  mapping:
    another_thing:
      type: text
      label: 'Another thing'

And you automatically get everything it defines, and what it itself inherits from block_settings.


how to create node for ecommerce display page? I am new to drupal ecommerce.

I created one product type as service for that I have to create a service  display content type using node, how can I create this node ? and how to enable that node ?

Thanks,

Vinudha

There is a module Auto Product Display

This module will do automatically create product display for you.

  This module is created in order to solve that problem. This module can
  simplify the Product Display creation process by providing option the
  create it at the same time with Product creation.

  Features

  Provide the Product Display creation form along with the Product
  creation form. User can fill that form to create Product Display at
  the same time with Product creation.
  That form, which used to create Product Display, will be the same as
  the form when user try to create Product Display manually. So, If
  you have additional fields in your Product Display node type, those
  fields will also appear in the form.
  If the product is referenced by only one Product Display, the
  Product Display content is displayed directly to the form, so it
  will be automatically updated when you save the product.
  If the product is referenced by more than one Product Display, the
  referencing Product Displays will be displayed in list, so you can
  also update the Product Display by clicking the link from that list
  first.

If you want to create manually, this will guide you

"Product Display" is the default content type that Commerce Kickstart 1.x creates and it has a product reference field. Technically, any entity that has a product reference field could be considered a product display. Nodes are the obvious product display entity type, and they're privileged because they're the default and standard entity type to use for the front-end display of content. But you could use taxonomy vocabularies, or even users as product displays.

Taken reference from here

Basically you need to add product reference field field for your node.


Need help finding source of CSS in Drupal code I've added the share42 module, customized, downloaded it an installed it. It used to work fine. And it still works fine on my local development environment. But its not working on my production environment.

The steps to configure this module, are:

install the share42 module
customize the buttons: http://share42.com/
download and install the image and js script you created in step 2 in the all/libraries folder
put some code in the node.tpl.php file

I did all this, and like I said it looks fine on my development environment. However, when i push it to production it's all messed up and doesn't look right. I cleared caches and ran cron multiple times. I deleted my browser cache. Nothing.

So I did an inspect element on the  that's outputting the share42 buttons on the production server. It's showing some inline styling that I didn't add. So I clicked the linked word 'inline' and it shows me the code for the entire page (just a random node). I don't see the inline styling anywhere on the page referenced in inspect element! It just shows the .js file I'm bringing in via . I've looked at that code though and copied and pasted the contents of my local .js file with the one on the production server and they are identical.

Note: I also deleted and replaced the entire /sites folder on the production server, and the bad styling is still there.

So now I'm a bit exasperated. Not sure what else to try to find out where the incorrect styling is coming from. Anyone have any other suggestions for places to look?

This sounds like a file permission problem on your production server for the library you added to your all/libraries folder. I.e. that some read access to those files in that folder is not granted.

Another reason MIGHT be that your library folder name (within all/libraries) is NOT named share42 (case sensitive, so Share42 would NOT be ok). Variation of that could be that "share42.js" and/or "icons.png" cannot be found in that folder (eg beause it got renamed to something else).


How to render a page with arrays and text I'm writing a module, which gets called from a MENU_LOCAL_TASK hook.

function load_statistics(){
    $page = display_yes_no(10,40);
    return $page;
}

the $page is an array used for rendering with Charts API, the problem is that if I do

$page .= 'hello';

for example, it's displaying "Arrayhello" instead of the graph and hello. How can I render the page the in drupal, to display both text, both charts?

You can do

$page['text'] = array('#markup' => 'hello');

Or

$page = render($page) . 'hello';


What is the proper file structure of a module that only contains sub-modules? I have put together a module package that has 3 sub-modules. They must be contained in a single folder to be distributed and used by other devs. Are there drupal best practices for how a module's files structure should be if it contains just multiple modules?

e.g.

name_of_module/modules/module1/module1.info
name_of_module/modules/module2/module2.info
name_of_module/modules/module3/module3.info

or

name_of_module/module1/module1.info
name_of_module/module2/module2.info
name_of_module/module3/module3.info

or?

For what i've seen, putting sub modules in a modules folder like your first example is most common best practice.


Find Out Which Template To Edit/Create I've got a Drupal 7 site with a default theme (Nuboot_Radix). How do I find out which template files (.tpl.php) are being used on each page. For example, I have the following page:

How do I find out which file to change in order to change how the datasets are displayed here (in this case Age by Economic activity 2011, 2011 UK Borders, Ethnic group 2011).

I understand that I need to make these changes in a subtheme, which I have already created. But I don't know what to call the tpl.php files, what the put in them, what variables I can use, etc. If I could find out where the html was being created for that section then I can figure out the rest myself.

I have been advised in another drupal post to not use Theme Developer since it is no longer supported.

tpl.php files are called templates in the Drupal system. They render the HTML that you see on any given page, may it be a block/view/panel or anything.

Theme Developer is a popular module used to pinpoint the template file that's in play. I suggest you try it to better understand how template system works.
To understand more on customizing templates and naming conventions read through this guide on working with template suggestions.

If its a view you want to modify- Use views GUI to the maximum extent(changing the sort order, re-arranging fields etc.). Still not getting what you want ? Override view templates for maximum control.

(Helpful Articles on overriding view templates)

http://www.wdtutorials.com/drupal/views/how-to-create-custom-template-view-drupal-tutorial-article

https://www.interworks.com/blog/carmstrong/2013/02/27/quick-tutorial-overriding-drupal-views-using-templates


Finding all nodes not referenced by a menu entry or another node In the course of creating the content for a site, we've ended up with orphaned content nodes that are not linked to from anywhere. I'd like to find and examine these. Surprisingly, I can't find a module for this.

Tiny hypothetical example: I'm building a brochureware site. Someone wrote a "Contact" page, someone else wrote an "About Us", and someone else wrote "Directions". The person writing "Directions" forgot to put it in a menu link or add a link from "About Us" to "Directions". So "Directions" is orphaned: there are no links to it. I'd like to find all such nodes so I can figure out what to do with them.

I needed this for a clients request, so i decided to try and do it without any additional modules, and push my MySQL a bit. This is what i ended up with.

For clarity, this will only provide a list of NID's that DO NOT have an associated menu item.

I've also added a WHERE clause to limit content types, as some content types will naturally be excluded because of the way they was architected.

SELECT n.nid, n.type, n.title, n.status
FROM node AS n
WHERE (n.type = 'article' OR n.type = 'page')
AND n.nid NOT IN (
  SELECT REPLACE(link_path, "node/", "") AS nid
  FROM menu_links
  WHERE SUBSTRING(link_path, 6, LENGTH(link_path)) REGEXP "^[0-9]+$"
);


Set value on a new term based on a vocabulary custom field I want to set the value of a field of a term based on a custom field set on the vocabulary. Basically if the vocabulary promote_to_index field is checked I want to the field_index_page of the term checked.

I understand I have to write a hook like but I don't understand how to get the value of the vocabulary custom field

function polaris_drupal_taxonomy_form_alter(&$form, FormStateInterface &$form_state, $form_id) {

  switch ($form_id) {

    case 'taxonomy_term_category_form':
    case 'taxonomy_term_article_type_form':
    case 'taxonomy_term_main_purpose_form':
    case 'taxonomy_term_tags_form':
    case 'taxonomy_term_content_partnership_form':
    case 'taxonomy_term_traffic_source_form':
    case 'taxonomy_term_client_form':
      $form['field_index_page']['widget']['value']['#default_value'] = true;
  }
}

You can add an extra validation step to those forms that checks and changes the value accordingly like so.

function polaris_drupal_taxonomy_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_term_category_form':
    case 'taxonomy_term_article_type_form':
    case 'taxonomy_term_main_purpose_form':
    case 'taxonomy_term_tags_form':
    case 'taxonomy_term_content_partnership_form':
    case 'taxonomy_term_traffic_source_form':
    case 'taxonomy_term_client_form':
      $form['#validate'][] = '_polaris_drupal_add_field_index_page';
  }
}

function _polaris_drupal_add_field_index_page(&$form, FormStateInterface $form_state) {
  $promote_to_index = $form_state->getValue('promote_to_index');
  if ($promote_to_index['value']) {
    $form_state->setValue('field_index_page', [ 'value' => TRUE ]);
  }
  else {
    $form_state->setValue('field_index_page', [ 'value' => FALSE ]);
  }
}

This will check the field promote_to_index of the form and set the field field_index_page before executing the submit handlers of the form.


Add new user via Commerce or Add User account I am working with a community site where new members should be able become members by purchasing an annual membership using commerce_license. I see 2 ways forward:

Members add an account application via the page .../?q=user/register and the user fills in all required fields. Via rules the appropriate membership is added, the user is redirected to the checkout, and when payment is complete the role is applied.
User buys the appropriate membership product, and when paid in full receives the correct role.

I have tested both these but cannot seem to get the second option working since I don't have a way to expose the custom fields added to the users, and let the user fill in those when applying for membership.

The first option seems more promising but there the user is not permitted access to the checkout page when redirected ( although I can see that the basket is created with the matching product in it).

Any pointers on how to move forward is much appreciated. I will not require an approval step, except that the membership fee must be paid in full to get access.

BR
/bo

You can add all necessary profile fields to user register form, and disallow checkout to anonymous users. This way every time new user proceeds to checkout' they are redirected to register form where they fill in the info and then proceed with checkout as usual.

A good helper module for this is Commerce Checkout Redirect

  This module redirects anonymous users to a page where they can login or create a new account when they try to checkout.


Problem installing Knowledge base module I installed Drupal using the Bitnami stack.
I'm trying to install the knowledge base module from https://www.drupal.org/project/kb .  I have installed and enabled the modules upon which it is dependent but when I try to enable the knowledge base module itself I get the error

Unable to install KnowledgeBase due to unmet dependencies: core.entity_form_display.node.kb_content.default (field.field.node.kb_content.body)

Obviously I am still missing a dependency and it's telling me what it is but what is but how do I fulfill the requirement?

Further, I can see the core.entity_form_display.node.kb_content.default yml file in C:\Bitnami\drupal-8.7.2-1\apps\drupal\htdocs\modules\kb\config\install when I use file explorer.

Is the yml file in the wrong place?  Or do I need to do something with it so the knowledgebase install knows about it?

Can someone tell me what I need to do?  Please excuse if it's obvious I am a newbie to Drupal.

Thanks for any help, Roscoe

The install yml is not in the wrong place.  This is a new module with 1 install currently in beta state so you might face a few problems with it if not all bugs are not ironed out but perhaps this is not the case.

The error message is not that helpful I must admit. If you want to see what dependencies you are missing you go into the .info.yml file and can also be seen online here and here is the relevant section

...
dependencies:
  - drupal:field
  - drupal:file
  - drupal:text
  - drupal:node
  - drupal:group
  - drupal:gnode
  - drupal:views
  - drupal:views_jump_menu
  - drupal:eva

for field, file, text, node, views are part of core (nothing to do)

but you have to download
https://www.drupal.org/project/group (for group and gnode)
https://www.drupal.org/project/views_jump_menu
https://www.drupal.org/project/eva

before you are able to install this module

I suggest that you start looking into installing things using composer that takes care of the dependencies for you so if you did

composer require drupal/kb

all the dependencies would also be installed for you

More info about composer based drupal installations can be found here and here and perhaps other places but those are good starting points


Google+ in ShareThis module How can I add the Google+ option in the ShareThis module? They posted a blogpost on the 6th of July where they stated the Google+ and Facebook options are added to the module. But when I download the module, there is no such thing as a Google+ button...

However they say it's easy to implement, I didn't find any way how to do this. So if anyone would like to help me out here, it would be much appreciated!

Now you can use ShareThis with both Google+ and Facebook Like.
Go to Menu>Configuration>Web Services>ShareThis

Go to Choose services to pick Google Plus One or Facebook

or

Go to Extra services to pick Google Plus One or Facebook Like

You can also see details how to set this up directly in the html code here.


What is the best way to update Drupal periodically using a cron job? Previously I periodically updated Drupal sites by using a cron-job with a "drush up -y" script running every Wednesday 15,16,17,18,19,20,21,22 hours UTC. which is when "Security releases happen" according to https://www.drupal.org/node/1173280

Lately I noticed that when security issues are really urgent, the update can take place just any time during the week. I now let the update cron take place every hour every day. I am aware this is not an ideal solution. What is the better solution to update Drupal with a cron script say within the hour of any release?

How can we automate our updates when these exceptions take place?

Updates are not automatic. The update manager module will tell you (in the admin) when critical updates or updates are available for core or contributed modules. But nothing will automatically update it all for you. You can also have the system email you when updates are found, too - per site. This is also helpful for staying informed.

You could theoretically "auto update" with a CI/build workflow that builds X times per day, but there is more inherent risk there of breaking the site unless you are strict about versions of contrib, and specify drupal/core as ~8.0 and minimum stability stable. Though, that is not bulletproof. In the last update from 8.4 to 8.5, I had to patch over a contrib module due to a change introduced in core. That contrib module still has not updated to comply with the change. If I had this sort of workflow, core would have updated and broke the site. That isn't so much the fault of core, but the contrib module(s) not keeping pace with the changelog or the sometimes unfortunate BC breaks.

While auto update sounds like a good idea, its usually not worth the mentioned risk. I prefer to clone locally and run through the application to see if anything has changed, moved, or flat out broke instead of have it hit production immediately. I think most would agree.

With this latest PSA, everyone was given a weeks notice that it was coming so people could prepare and plan their release window around it. So there should have been plenty of time to stay informed, and most hosting companies (i.e.: ones who promote Drupal) should have notified their customers.

Wednesday is when the Security Team makes public any security issue on covered third-party modules.


Create a page filter with the last article of each category My articles are grouped in 6 categories (created by taxonomy)

I need to output a view page that contains 6 sections each one displays in a block or div the latest article of the category it belongs.

I have a solution how to do that by creating 6 views for each category filtered desc and displaying the last article and a 7th view to hold all the 6 view blocks. The only thing I don't like it about this is if the editor enters a new category I need to manually update the view.

Is there a way to display the 6 cell grid with the categories as I mentioned before?

Yeah that's possible.

Add a new taxonomy view
Add a relationship: Representative node.
There configure to sort by node created DESC.

That's it


Getting author_picture component values in twig I'm making a theme where the author picture needs to be in one div, but some other fields from the user profile need to be in another.

The fields are all available in the author_picture variable - but I'm a little unclear in Twig how to split it apart into it's relevant pieces.

The author's pic appears to be called user_picture, and the fields are called field_bio and field_title.

I've tried different variations like

{{ author_picture.field_bio.value }} or {{ author.picture.user_picture.value }} etc - but to no avail.  What am I missing?

No Sssweat has right. When you want to display an entity field based on the "Manage Display" settings, you should go just {{ content.my_field }}.
If you "kint" content (var dump it) you can see that each content field element has also "theme" key/property, which tells twig how to render that field.


Apache Solr Indexing data of custom Table I am using Apache Solr in a Drupal 6.22 website. The version of Solr is 3.6.2 and using apachesolr-6.x-1.8 module with it. Solr indexed all the node based contents well. But I want to have a custom table indexed. This table shows some promotional data to the website and has ~531,067 data. The schema is below,

+-------------+--------------+------+-----+-------------------+----------------+
| Field       | Type         | Null | Key | Default           | Extra          |
+-------------+--------------+------+-----+-------------------+----------------+
| topic_id    | int(11)      | NO   | PRI | NULL              | auto_increment |
| subject_id  | int(11)      | NO   | MUL | NULL              |                |
| title       | varchar(255) | NO   |     | NULL              |                |
| created     | timestamp    | NO   |     | CURRENT_TIMESTAMP |                |
| reply_count | int(11)      | NO   |     | NULL              |                |
| view_count  | int(11)      | NO   |     | NULL              |                |
+-------------+--------------+------+-----+-------------------+----------------+

How can I index that table in Solr and how can I add the schemas to schema.xml in Solr?
As I have seen the HOOKS in Exposed Solr Hooks (6.x-1.x) for developers, and it seems that using hook_apachesolr_update_index(&$document, $node) will do the trick but I want to be sure on this.

Please provide me some idea on this. Thanks in advance.

I believe this issue has the information your looking for you have to modify the ApacheSolr schema file to include your custom fields. And tell Solr with an update hook where your data is .... importing that much data could be difficult.

An even better resource may be this blog post from Acquia: Using Apache Solr to Index Custom Data.

Sorry, I wont be able to code up any examples. I dont have Solr installed now, and dont have that much free time.

Both these example links are for D6.


How to create webform according to user rules I wanted to create a "Contact Us" webform, which should have following fields-

Name
Email Address
Contact No
Message

For an anonymous user, all of these fields should display.However for logged in user, field 1, 2 and 3 should not be displayed.

I don't see any option in webform to set a filed in such a way, so that only anonymous user can see it.

I tried to create two webform and assigned different-2 submission access but unknowingly now the website is having two menu items.

you need to try this coding

function _form_edit_module_form_alter(&$form, &$form_state, $form_id) {
 if($form_id =='webform_form_id') {
  //check login user enter in site
  global $user;
  if ($user->uid) {
     $form['component_name']['#attributes']['disabled'] = true;
  }
 }
}

and also you need check  Webform Conditional module


Manage Form Display - not saving configuration i'm working on a pretty big User/register site. Today i created some more fields.
Now i want to order them properly with the "manage form display" settings like i used to but it is not working.
Everytime i press save the page is reloaded but no changes are made. Yesterday evening everything worked fine.

Is there a maximum of fields you can use?
Or does anyone has an idea what could be the problem here?

I'm really clueless because 12 hours ago it worked just fine for me...

with best regards

How many fields are we talking? Is it hundreds?

I don't believe there is a maximum within Drupal but your server might have a limit. Within the php.ini config file on your web server you should see "max_input_vars"

You could try increasing that and restarting your apache/nginx server to see if that resolves the issue


How do I convert the result fro views_get_view_result() to an array? I am getting an object from views_get_view_result().

Array
(
 [0] => Drupal\views\ResultRow Object
    (
        [_entity] => Drupal\node\Entity\Node Object
            (
                [in_preview] =>
                [values:protected] => Array
                    (
                        [vid] => Array
                            (
                                [x-default] => 9
                            )

                        [langcode] => Array
                            (
                                [x-default] => en
                            )

                        [revision_uid] => Array
                            (
                                [x-default] => 1
                            )

                        [revision_timestamp] => Array
                            (
                                [x-default] => 1508904645
                            )

                        [revision_log] => Array
                            (
                                [x-default] =>
                            )

How do I convert it to an array? My objective is to get the content types fields values. In an entity object there is toArray() to achieve this, but it doesn't work for what views_get_view_result() returns.

This is the entity you are looking for:

$node = $row->_entity;

And the field values:

$values = $node->toArray();

These are all of the values from the node, however if you want the results from the fields configured in the Views UI, see Get result view with formatter programmattically


Sort by content types in a view I have 12 content types and a view that shows the title and description of each piece of content.

I want to sort the results of the view as follows:
First, node types 1, 4, 5 and 9.
Then, node types  2, 6, 10  and 12.
And finally, node types 3,7,8 and 11.

Is it possible to sort the results of this way?

Thanks.

Tried several things, but the one bulletproof solution that I could come up with is to use Views Attachments

add a page display, filter by node type 1.
add an attachment display, filter by node type 4, attach to the page display, after its content.

Repeat 2 for each of the remaining node types in the desired order.

It will be a big view, but should do the trick.

Edit: that is the best solution I came up with, without an extra module.


which one has better performance to load views When I want to print my views block result(or views) in my tpl files,I have several ways,

views_embed_view

views_get_view

module_invoke for block ( I means something like $block = module_invoke('views', 'block', 'view', 'map-block_1'); )

which one is better and has better performance?

views_embed_view is just a wrapper for views_get_view:

function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}

So how would you set dynamic arguments on views_embed_view? With views_get_view you can at least do this:

  $view = views_get_view($view_name);
  if (!$view || !$view->access($display_id)) {
    return;
  }
  $view->set_display($display_id);
  $view->set_arguments($variables);
  $view->pre_execute();
  $view->execute();
  return $view->render();

module_invoke for block is too roundabout and limited for my liking. Why limit yourself to a block when you can choose from any display available?

views_block_view contains this snippet:

if ($view = views_get_view($name)) {

So it also uses Views_get_view.

Performance-wise I reckon the differences are negligible.

So, IMO, views_get_view wins.


How to filter views output base on custom field I've created a view listing a content type named foo, it has a custom field 'start_date' which can be left blank.

When a node's start_date field is left blank, it should always show in the listing. When it's populated, and the date is less than the current date - then the node should also be listed.

I've tried to use hook_views_query_alter to do this, but it didn't do what I wanted as it's for changing the query itself.

Which hook should I use?

You can use the Views UI to accomplish this.

Add two date filters: one of them should filter date fields for "is empty" and the other should filter date fields for "is less than" and choose "Enter relative date" and type "now".

Then create an "OR" group and drag the two date filters to it. It should look like this:


how to connect to database for form submission I have website and on its home page there is form in which user enter his own label .As user enters label if the user with same label exists in database it through message that "This Label already exists.Use other Label OR Login". If the user is new it will be directed to other site i.e site "example.com".

The problem is I am getting the same message that "This Label is already exist.Use other Label OR Login" even I enter a new label.

Here is the code for this scenario.

function homepage_userlogin_form($form_state){
// drupal_set_title('Add New Person');
$form = array();

$form['name'] = array(
'#title' => '',
'#type' => 'textfield',
'#size' => '30',
'#placeholder' => "enter desired label",
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Start',
"#submit"=>array('form_submit')
);

//$form['#attributes'] = array('id' => 'user-registration001');
return $form;
}

function homepage_userlogin_form_validate($form, &$form_state) {

$name = $form_state['values']['name'];
global $users;
$error=FALSE;

if (empty($name)) {
form_set_error("erorr",t("Please enter your Label."));
$error=TRUE;
}
//if(strlen($name)<6){
// form_set_error("Please Enter atleast 6 character Label.");
// }

if(!$error){

$result = db_select('users', 'u')
->fields('u',array('uid'))
->condition('name', $name,'=')
->execute()->fetchAssoc();

if($result['uid']>0){
form_set_error("erorr1",t("This Label is already exist.Use other Label OR Login"));
}

else{
global $users;
$user->name=$name;

}
}
}

function homepage_userlogin_form_submit($form, &$form_state) {
drupal_goto("http://example.com");

}

I think there is problem with the condition in the query. Try changing it

$result = db_select('users', 'u')

->fields('u',array('uid'))

->condition('u.name', $name,'=')

->execute()

->fetchField();

You better use Webform Module to create a form without any issues!!

  Webform is the module for making surveys in Drupal. After a
  submission, users may be sent an e-mail "receipt" as well as sending a
  notification to administrators. Results can be exported into Excel or
  other spreadsheet applications. Webform also provides some basic
  statistical review and has and extensive API for expanding its
  features.


How do I programmatically change settings to simplify sharing of config changes? I'm thinking specifically here of layout changes, such as:

moving a block around, or
when a new block is created and needs to be positioned, and shown or hidden on specific pages.

Currently, when somebody makes layout changes using the admin menus, we all have to go through the same process by hand. My issue with this is that it's time-consuming and error prone.

In an ideal world, I would love to have a system that is able to transfer someone's updated config changes to my local site.

Is this possible?

At the risk of opening up a whole ugly can of worms on Drupal's current lack of config management, I am just going to point towards the D8 Configuration Management Initiative as the over-arching response to this.

To answer your more specific question about block/layout management, there are a few attempts at addressing this using Features/Features Extra:

Layout with Context or Panels or Display Suite

Better blocks with Boxes or Bean or Bricks


Overwrite menu.twig only for specific node types I've worked with twig and have overriden most of elements in my application. However, I it is not clear to me how I can overwrite the menu template for specific node-types. The suggestions I get from the theming debug are too general and not node  specific.
Any ideas on how to register a twig template for menu for specific node types?

Menus do things a little differently then, so you have an option or two...

/**
 * Implementation of hook_theme_suggestions_alter().
 */
function mymodule_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if ($hook == 'menu' && ($node = \Drupal::routeMatch()->getParameter('node'))) {
    $content_type = $node->bundle();
    $suggestions[] = 'menu__node_type__%';
    $suggestions[] = 'menu__node_type__'.$content_type;
  }
}

This will give you give you the following suggestion in this order:

menu--MENU-NAME.html.twig
menu--node-type--page.html.twig
menu--node-type--%.html.twig
menu.html.twig

With this the menu--MENU-NAME template still takes preference over the node type, so we need a trick to add suggestions after.

/**
 * Implementation of hook_theme_suggestions_HOOK_alter().
 */
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  $key = array_search('menu__'.$variables['menu_name'], $suggestions);
  if ($key !== FALSE && ($node = \Drupal::routeMatch()->getParameter('node'))) {
    $content_type = $node->bundle();
    array_splice($suggestions, ++$key, 0, array('menu__node_type__%', 'menu__node_type__'.$content_type));
  }
}

menu--node-type--page.html.twig
menu--node-type--%.html.twig
menu--main.html.twig
menu.html.twig

Targeting your placement within the array of suggestions can be helpful, but it can be over kill, so you may just want to keep it simple and place your new suggestion at the end of the list and have the highest override

/**
 * Implementation of hook_theme_suggestions_HOOK_alter().
 */
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'menu__node_type__%';
    $suggestions[] = 'menu__node_type__'.$content_type;
  }
}

You can even throw $variables['menu_name'] into the mix with:

$suggestions[] = 'menu__'.$variables['menu_name'].'__node_type__%';
$suggestions[] = 'menu__'.$variables['menu_name'].'__node_type__'.$content_type;


How to restore private file structure after major version update? After a Drupal 6 to 7 update we are unable to use private image download, symptom is we cannot access private files via system/files, while public files can be loaded.

Trying to download private file results in a 404 -- Not found error, sent from the web-server directly, not drupal. After some changes to the configuration this results instead in a Drupal Error page. The server log says

File does not exist: /home/licebase/drupal/system/files/genefinding_diagram_1_2.png, referer: https://myhost/node/761470/edit?render=overlay

The system file exists and has the correct permissions.

Centos 6 on virtualization host, PHP 5.3.3, Postgres 8.4 on dedicated DB server, Apache 2.2.15 (centos) + a lot of active modules + fields+cck

Edit: We have a workaround, I hope this question can serve as a good practice guide of good to debug complex software like Drupal showing unexplainable errors or WSOD. Wish we had followed our own advice to not waste time on our futile attempts time.

tl;dr It was the core module Database logging 7.42    Logs and records system events to the database. which is interfering with private files in our specific setting. We disabled most modules including core, and brought them back one-by one. Database logging is reproducibly inducing the error on activation.

Don't panic and make a debugging plan, listing options of what could be checked, and then stick to it until everything has been checked. If out of options, try to shake things up
Compare your system to a vanilla system and note down what is does differently
Modules might interfere with each other in unexpected ways or with your specific configuration. That doesn't mean there is a bug in any of those modules. Boil down your system to the least complex configuration possible, remove any unneeded entry in your configuration file, disable any module that can be disabled including core modules, suspect everyone.
Check if error still present, if not re-enable all modules one-by-one, and note down which configuration change causes the error. Otherwise, start debugging going to 1.

Cheers


Views - group/aggregate by field with multiple content types I currently have a block view that I am using as an index. I have 2 content types that I am displaying in this block, and these are grouped together by their type, as an unformatted list of fields. The types are not displaying the same field.

The second content type needs to be grouped further, as they represent items relating to the same thing which will be displayed together on the page.

I am struggling to perform the second grouping. I have tried the unformatted list settings and adding in a second group, but that removes the items for the first group. I have also tried playing with aggregation and the query distinct settings, but that doesn't seem to do anything. I have also tried the Views Distinct module, also with no success.

Edit: It's the value of the field that's duplicated.

What I've got:

*Group1
    -Title1
    -Title2
*Group2
    -FieldValue1
    -FieldValue1
    -FieldValue1
    -FieldValue2
    -FieldValue2

What I would like:

*Group1
    -Title1
    -Title2
*Group2
    -FieldValue1
    -FieldValue2

Is this possible, and if so, how would I go about doing it?

Thanks

I would suggest using the default Views attachment display so you can have different queries and/or fields next to each other.


Is is_front variable available in menu.html.twig template? When the page is actually rendered, the last suggestion is checked. If it exists, that suggestion is used. Otherwise the next suggestion up is checked, and so on. Of course, if none of the overriding suggestions exist, page.html.twig is the final suggestion. This also explains why page--front.html.twig,

is_front variable is not available in the menu template by default. You can add it there by adding this into your themename.theme file:

function themename_preprocess_menu(&$variables) {
  try {
    $variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
  }
  catch (Exception $e) {
    $variables['is_front'] = FALSE;
  }
}


Where can I find good, reliable Drupal freelancers? I've looked on Elance, Guru, etc for skilled, reliable Drupal freelancers without any luck.  Are there any suggestions for where to look for these folks?  Remote workers are fine for what I need done.

A lot of generic freelancer site members may have used Drupal but usually work with anything, wordpress, joomla etc. Drupal has a fairly high learning curve and to get the best out of it you would be best with a Drupal Expert. Maybe try something closer to the Drupal community.

Using a Drupal resource for Drupal freelancers might provide more Drupal expertise...

http://drupal.org/paid-services
http://drupal.org/marketplace-preview


Ctools modals without AJAX What's the sanest way to present a Ctools modal to the user while bypassing the normal AJAX workflow? For example, how could I show a completely JavaScript-generated "Are you sure you want to log out?" confirmation prompt to the user in a Ctools modal after the user clicks the "log out" link?

I know I can probably fake a box which would get the same styling as the Ctools modal, but I'd rather avoid silly hacks if not strictly necessary.

This should be possible by invoking Drupal.CTools.Modal.show directly. The function takes one argument (the modal-style), which either can be a string pointing to an object on Drupal.settings or the style-object itself.

After showing the dialog, it is possible to populate title and content using jQuery:

Drupal.CTools.Modal.show('my-modal-style');
$('#modal-title').html('my-title');
$('#modal-content').html('some markup here').scrollTop(0);
Drupal.attachBehaviors();

In your PHP code, you need to ensure that ctools modal.js and also misc/ajax.js gets loaded:

drupal_add_js('misc/ajax.js');

ctools_add_js('modal');
ctools_add_css('modal');

// Add your modal style to the settings. You find the defaults in modal.js near the top:
drupal_add_js(array(
  'my-modal-style' => array(
    'modalSize' => array(
      'type' => 'fixed',
      'width' => 250,
      'height' => 250,
    ),
    'closeText' => 'Dismiss',
    'closeImage' => ...
  ),
), 'setting');


Adding a logout, but not login Somewhat weird situation, but it is what it is.

Decreed that user accounts are no longer required for access to spec documents. That's good.

However, we have various editors who will still edit content and will need to log in. The simple thing is to just give them a url to bookmark with the ?q=user added. Works fine.

However, I need to add a logout link so they can actually sign out. So, I need to somehow tell Drupal, based on role authentication, show this link.

I tried putting the default User Login block in the header and checked the domains and roles of the various editors and authenticated web user but they aren't showing. Could this be due to login/logout links of the Primary menu being disabled?

Next, I tried making a block with simple text: logout with the link of logout but it's not showing up in the header either. And yes, I tried other pages using the basic page.tpl.php template to make sure the block was in a used region.

I'm not afraid to slam some php somewhere, but I'd like to think I'm just missing something.

You can add a standard menu item to any menu with a path of user/logout.


When confirming installation of modules, I get a server error (500) I setup my D7 websites using MAMP and since a while I failed to activate modules... Whenever I save certain modules, I get a 500-error.

I don't think it has something to do with a memory_limit since the error appears almost instant...

I already tried to increase the permissions (777) on the sites folder, but no luck there.

This is what my apache_error.log says:

Any advice?

Hoeray! I found it myself :)
It appears, you can increase the limit on multiple places like described on this page.

Thanks @Clive for the effort though!


How do I use hook_views_query_alter()? Following what reported in the documentation for hook_views_query_alter(), I created a file named alterform.views.inc and put it into an enabled module called alterform. I added  the following code in alterform.views.inc.but it doesn't work.

function alterform_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'myViewName':
      echo 'test test'; // test
      $query->orderby[0] = "FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') ASC";
      $query->orderby[1] = "node_title ASC";
      break;
  }
}

why doesn't it output "test test"? What's wrong with my code?

there is still no output of test and views. what's wrong with my code? thank you

Right. In order to "do" anything with views in a module, you have to implement hook_views_api. Without this, your module won't be recognised by Views, at all, ever (AFAIK).

Please add the following to your module code:

/**
 * Implementation of hook_views_api().
 */
function alterform_views_api() { // your module name into hook_views_api
  return array(
    'api' => 2,
    // might not need the line below, but in any case, the last arg is the name of your module
    'path' => drupal_get_path('module', 'alterform'),
  );
}

This should fix it so your module is at least recognised, then you can start debugging it :)

A good way to start debugging a view (i.e. a baby step) is to put dpm($view); right at the start of the views function you're implementing. In most cases, that will dump info onto the screen that will help you see where you're at. Would suggest doing this with devel.module installed/switched on.

Edit: This assumes Views 2 and Drupal 6. You'd best ask around if those aren't your weapons of choice.


How do I stop content overlap with Display Suite on mobile/narrow screens? Building a site where sugar glider breeders and vendors can list their businesses and wares and find informational articles, links to exotic vets, and more.

The site is built on Drupal Core 8.2.7 with Adaptivetheme 8.x-2.0 and uses Display Suite 8.x-2.6 with the Fluid two column stacked layout applied to the Full Content view to display business information in a columnar format with contact info and links on the left and tags from several Taxonomies on the right. Field Group 8.x-1.0-rc6 was used to construct several Fieldset groups, and custom CSS was applied to those fieldsets to give them a unique look and border.

This works pretty well on desktop displays, tablets, and some landscape smartphones:

But looks awful if you narrow down a desktop browser or view the site on a portrait smartphone. The boxes adjust well down to a certain size, then "responsive" goes out the window and they start overlapping. The About Us section is in the Footer of the Display Suite layout, so it is unaffected.

The site exhibits the same behavior, where the Right and Left Display Suite regions overlap on small displays instead of stacking (as would seem logical), regardless of whether the fields are in a Field Group or whether any custom CSS has been applied. This leads me to believe it is something to do with Display Suite, but I have not been able to find any way to control how its regions are rendered. I can control the flow of regions for the theme (e.g. Sidebar 1, Main Content, Sidebar 2) from the theme's Layout settings, but I cannot find any similar functionality for Display Suite regions.

I assume this is possible because my other site (built on the same Drupal Core, Adaptivetheme, Display Suite, and most of the same modules) stacks its content vertically when the screen gets too small. The only significant differences I can think of are that the other site is mostly text next to images or videos rather than text next to text like this one, and the other site's Display Suite layouts are applied to Paragraphs instead of being applied to the Content type directly.

Any thoughts for what may be causing this and how to resolve or work around it are welcome.

Found the solution when I discovered a difference between this site and the other that did not register fully when I posted the question.

The Content Types on this site and the Paragraphs on the other both use Display Suite, but this site was using one of the default Display Suite layouts. I built the other one later and used the more flexible Adaptivetheme bootstrap-style layouts.

Turns out the layout is the reason that items were stacking vertically on one site and stubbornly staying side-by-side on the other. When I switched this site to an Adaptivetheme layout like the other, things were much improved:

In case anyone else has a similar issue and is stuck with a default Display Suite layout, I also found that the email field was the only field causing problems. You apparently cannot truncate an Email field, but I found that switching the content regions so the taxonomy tags were on the left and the location, contact, and links were on the right was better than the original layout because the email address could stretch its box without running into the box on the other side.


Programmatically disable content translation options in content edit form I want to programmatically disable the content translation options located at the bottom of the content edit form (see yellow area in screenshot):

I know that i can disable the revision information options with the following code in a form_alter hook:

$form['revision_information']['#access'] = false; // <--- works

But that doesn't work with the translation options, at least with what I tried:

$form['content_translation']['#access'] = false; // <--- doesn't work

So ideally, how can i disable the whole yellow area?

You can not access to content_translation property in the hook_form_alter but you can do it in after_build callback.

  after_build: runs after the form or element is built for display.

Try with the following:

Add #after_build to the form:

/**
 *Implements hook_form_alter().
 */
function myModule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_YouContentType_edit_form') {
    $form['#after_build'][] = 'myModule_after_build';
  }
}

Implement your after_build function

    function myModule_after_build($form, &$form_state){
      $form['content_translation']['#access'] = FALSE;
      return $form;
    }


Where is the logic located which determines the tpl file for the front page? We are using Drupal 6. When accessing http://www.mysite.com/, the tpl file which is displayed is named page-front_page.tpl.php. I cannot figure out where the logic is which decides that page-front_page.tpl.php will be used for the front page.

I created a second file, named page-front.tpl.php, and this will display instead of page-front_page.tpl.php, seemingly bypassing page-front_page.tpl.php.

Does anybody know how page-front_page.tpl.php is defined as a front page? Or is there some sort of automatic URL parsing happening here?

Edit 1.0: Please read my comments to answers below for more information.

please review in /includes/theme.inc near to the line if (drupal_is_front_page()) {...

if (drupal_is_front_page()) {
    $suggestions[] = 'custom-page-front-name-here';
  }

I changed the $suggestions[] value, and I saw that .tpl.php name to the front page can be customized.

According the comment of nmc,

  this file/code should not be modified as it is part of Drupal core

. this is only to locate where can be stablished the value.


Show Entity List Builder in Block base? I am making a custom block in Drupal 8 and I want to show my entity list builder in it.Is there any example or certain way by which I can show my entity list in the block.

render() builds are renderable array for a table:

  public function build() {
    return \Drupal::entityTypeManager()->getListBuilder('entity_type')->render();
  }

Reference: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityListBuilder.php/function/EntityListBuilder%3A%3Arender/8.5.x


Which PHP/MySQL version should I use? We plan on updating our Drupal 6 (with MySQL 5.5x and PHP 5.x) site to Drupal 7.

Which version of PHP and MySQL should I choose?

You will get the best speed performance using PHP 7.x. I've been running a few Drupal sites on PHP 7 with no issues, and definite performance improvements over PHP 5.x.

MySQL 5.5 or 5.6 is good.


Form API: Autocomplete Field in Chrome and Safari I'm working on a custom webform component to essentially look up entity properties in an autocomplete field.
All works perfectly in Firefox, but I'm just seeing an plain old textfield in Chrome and Safari. Nothing is printed to the console, and nothing is printed to watchdog.
This is what the field looks like on Chrome/Safari:

This is what is looks like in Firefox:

I'm wondering if this has something to do with my code, so I've extracted the relevant snippets below:
Form Definition:
  $ac_field_id = drupal_html_id('field_autocomplete');
  $element['field_autocomplete'] = array(
    '#type' => 'textfield',
    '#title' => $component['name'],
    '#description' => t($component['extra']['description']),
    '#default_value' => $value['field_autocomplete'],
    '#required' => $component['required'],
    '#autocomplete_path' => 'entity-auto-comp/' . $field_entity_type .
                                '/' . $field_entity_prop . '/' . $field_number_of_items_to_return .
                                '/' . $search_type . '/autocomplete',
    '#attributes' => array(
      'data-entity-auto-id' => $ac_field_id,
    ),
  );

How Autocomplete Path is being Handled:
 /**
  * Implements hook_menu() - this provides a URL route for our
  * entity data source
  */
 function entity_auto_comp_menu() {
    $items['entity-auto-comp/%/%/%/%/autocomplete'] = array(
      'page callback' => 'entity_auto_comp_autocomplete',
      'page arguments' => array(1, 2, 3, 4),
      'access arguments' => array('view published content'),
      'type' => MENU_CALLBACK,
    );
    return $items;
}

/**
 * Implements hook_autocomplete() - which allows us to return data
 * to the form field as JSON.
 */
function entity_auto_comp_autocomplete($entity_type, $entity_prop, $max_results = 5, $search_type = 'STARTS_WITH', $string = '') {

  //Get all relevant entity IDs
  $efq = new EntityFieldQuery();
  $efq->entityCondition('entity_type', $entity_type, '=');
  $efq->propertyCondition($entity_prop, $string, $search_type);
  $efq->range(0, $max_results);
  $efq_result = $efq->execute();
  $efq_keys = array_keys($efq_result[$entity_type]);

  //Load entities from database
  $entities = entity_load($entity_type, $efq_keys, false);

  $prop_values = array();
  foreach($entities as $entity){
    $prop_values[$entity->$entity_prop] = $entity->$entity_prop;
  }

  //If we couldn't find anything, say so
  if(count($prop_values) == 0){
    $prop_values[""] = "No results were found...";
  }

  drupal_json_output($prop_values);

}

Some JS I'm using to detect changes and populate a hidden form field:
(function ($) {
    Drupal.behaviors.ol_webform_manage_map_default = {
        attach:function (context, settings) {

          //Get the autocomplete field as a jQuery object
          var $autocomplete_field = jQuery('input[data-entity-auto-id="'+Drupal.settings['ac_field_id']+'"]', context);
          var $autocomplete_value = jQuery('#'+Drupal.settings['ac_field_id'], context);

          //Event listener for option selection
          $autocomplete_field.bind('autocompleteSelect', function(event) {
            $autocomplete_value.val(jQuery(this).val());
          });

        }
    };
})(jQuery);

I'm stumped. So I would appreciate any help you can provide!
Thanks,
Strainy
Update
Scratch that. Nothing to do with browsers. It's got something to do with how I'm handling permissions at either the form field level or the autocomplete path. Realised that I can only use autocomplete if I'm logged in!

If it works on Firefox, I suspect that the issue is with the javascript.  Here, the question you should be asking is: do you really need to write your own.

In Drupal 7, there's a default implementation of the javascript you need for this in misc/autocomplete.js.  In fact, by defining your callback via '#autocomplete_path', you are likely asking for trouble: both your javascript handler from your .js file and the javascript from misc/autocomplete.js may well be completing with each other to handle the textfield. I would not be in the least surprised if the behavior you saw was browser dependent.

Unless there's a specific reason you need the javascript you've written, I'd just use the default javascript, which will get automatically loaded for you when you use the '#autocomplete_path' Form API key.  AFAICT, your callback and your hook_menu definitions are just fine.

However, you can find a nice sample in the Examples Module (https://www.drupal.org/project/examples). Where your implementation differs, the simpler implementation in the Examples code may well be more cross-browser compatible.


How to call User::load with dependency injection I have code that worked, but I wanted to clean it up and use dependency injection. I'm working in a BlockBase that implements ContainerFactoryPluginInterface.

class DefaultBlock extends BlockBase implements ContainerFactoryPluginInterface {

I need to access some information from the user object. Right now I'm using Drupal\Core\Session\AccountProxyInterface. This works fine, but doesn't give me all the information I was expecting. I have a contrib module adding a field to the user. I can access that field if I use User::load($id) however, I get the warning that...

  User::load calls should be avoided in Drupal classes, use dependency
  injection instead

So I'm trying. And failing.

This code works...

$userIdx = \Drupal::currentUser()->id();
$userx = \Drupal\user\Entity\User::load($userIdx);
$countryx = $userx->country_iso_code_2;

But when I clean that up and do it the right way, I can't get that country_iso_code_2 information.

Here is the code I'm "trying" to work with...

<?php

namespace Drupal\country_selector\Plugin\Block;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Country switcher"),
 * )
 */
class DefaultBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $account;

  /**
   * Class constructor.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->account = $account;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $userIdx = \Drupal::currentUser()->id();
    $userx = \Drupal\user\Entity\User::load($userIdx);
    $countryx = $userx->country_iso_code_2;

    $userId = $this->account->id();
    $country = $this->account->country_iso_code_2;
    .....

When I debug, I see that:

  $userx is Drupal\user\Entity\User

  $user is Drupal\core\Session\AccountProxy

So I get that I'm working with two different things. I just don't understand how I'm supposed to call something like User::load with dependency injection.

I hope that makes sense. Would love some advice!

You should use entity_type_manage to get the user storage. Something like this:

<?php

namespace Drupal\country_selector\Plugin\Block;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\UserStorageInterface;
/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Country switcher"),
 * )
 */
class DefaultBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $account;
  protected $userStorage;

  /**
   * Class constructor.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account, UserStorageInterface $user_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->account = $account;
    $this->userStorage = $user_storage;
  }

  /**
   * {@inheritdoc}
  */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user'),
      $container->get('entity_type.manager')->getStorage('user')
    );
  }

  /**
   * {@inheritdoc}
  */
  public function build() {
    $build = [];

    $userIdx = $this->$acount->id();
    $userx = $this->userStorage->load($userIdx);
    $countryx = $userx->country_iso_code_2;
    .....

Hope this helps.


Why isn't my sub-theme using its CSS file? I created a sub-theme of the Drupal8 W3CSS theme and followed their directions about copying and renaming files, and editing the info.yml file. I installed it, and set it as default theme. It works. (I can see my custom logo.) The styles.css file is not coming from my files, but from the default sub-theme, which I haven't enabled. When I view the source of a page, I see the following tag, which doesn't contain the path for the CSS file used in my sub-theme.

<link rel="stylesheet" media="all" href="/themes/d8w3css/drupal8_w3css_subtheme/css/styles.css?qbo25b" />

It could be I missed a step.

Do I have to do something with Composer after changing any .yml file of the theme? I did clear all the cache bins.

In Drupal 8 you setup your subtheme libraries in subtheme.libraries.yml. These libraries are then loaded from subtheme.info.yml.

You should check the paths in those files if they are correct.

It's good practice to search for all occurrences of the base_theme's machine_name inside your subtheme folder and replace those with the machine_name of your subtheme.


show messages of drupal_get_form loaded forms in custom module In my case I use drupal_get_form in my custom module in order to load forms from other modules and show them combined in one page (menu callback). So in my custom module I have

  function mymodule_claim_menu() {
    $items['profile_edit/%user/%'] = array(
    'title' => 'Edit profile',
    'page callback' => 'connections',
    'page arguments' => array(1,2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'node.pages.inc',
    'file path' => drupal_get_path('module', 'node'),
  );
 return $items;
}

function connections($account,$tab = "profile") {
  $link_output = array();
  $rss_output = array();

  $link_output['linkedin_settings']= drupal_get_form('linkedin_user_enable_form', $account->uid);

  $rss_output['rss_input'] = drupal_get_form('activitystream_accounts_form', $account);

  $output = array_merge($link_output,$rss_output);

  return $output;
}

The (simplified) code above works fine except status messages (drupal_set_message) not getting displayed when a user submits one of the forms. I realise from the previous posts that it's something with the order but I'm not sure what I can change to make it work. Any suggestions?

I'm posting the solution in case anyone else faces the same issue.

This was finally related to the template file.
The messages were printed in a section that was not rendered when inside my module page. This tricked me because doing it as admin was actually showing the relevant section but for registered users didn't.

So I just had to add an extra printout of the $messages var in a section of the template that was always rendered to all users.


Migrating link fields to Drupal 8 I am trying to migrate a link field field_url from a Drupal 7 site to my Drupal 8 one. The link field is compound, it has a title and a url value. In my process plugin I am selecting the right values (field_url_title and field_url_url), but I don't know how to map them in my yaml definition file. What I have:

          field_url: field_url_url
          field_url_title: field_url_title

...maps correctly the url, but does not populate the title one. What's the destination field machine name I would need to use to add in the link title?

It is pretty simple mate, here is an example:

field_url:
  plugin: iterator
  source: field_url
  process:
    uri: url
    title: title
    options: attributes

Because in D8 the field_url_url database field changed to field_url_uri and the attributes to options, you can not use direct mapping on this field.


OpenDialogCommand how to include Buttons in dialog_options How can I inlcude buttons in OpenDialogCommand?

$options = [
        'dialogClass' => 'my-dialog-class',
        'width' => '700px',
        'buttons' => [
          'text' => 'Continue',
          'class' => 'btn-primary ok-button',
          'click'=> "function() { $(this).dialog('close'); }",
  ],
      ];

      $response->addCommand(new OpenModalDialogCommand($title, $content, $options));

This seems not to work. The class is set, but no buttons are shown.

In the $options array the element "buttons" must be a "multiple" array.
For example:

$options = [
  'dialogClass' => 'my-dialog-class',
  'width' => '700px',
  'buttons' => [
    [
      'text' => 'Continue #1',
      'class' => 'btn-primary ok-button',
      'click' => "function() { $(this).dialog('close'); }",
    ],
    [
      'text' => 'Continue #2',
      'class' => 'btn-primary ok-button',
      'click' => "function() { $(this).dialog('close'); }",
    ],
  ],


Commerce Search API with Custom Search Form I have a search form with multiple fields on my front page. After clicking on submit button,  user would be routed to search result page. The user fills out the form, clicks on a 'Search' button, and the browser replaces the front page with a results page. (Ideally, a Commerce search view). On search result page, all facets blocks are enabled.

I have created a page using Views exposed filter for front page and I am getting result as per filters. But I am not able to map that search filters with my facet search blocks on result page. Is there any way to do that ?

Another way I tried is created a custom form but not sure how to build URL so that user would be redirected to Search result page.

You should use the same faceted search block on front page too. You can invoke the faceted search block on front page.


Redirect user to language other than default So... i have set a drupal website with 2 languages, english (default) and portuguese. At some point during development the client asked me to change the default language to portuguese but as i've read all over the web that turning the default language to other than engish is not advisable. Is there a way to redirect the user to the portuguese version of the site?

Thank you all guys.
niebes

This might be the answer you're looking for:
Install profile with variable default language messes up translations

If the strings were originally written in english and not translated since you'll need to set the i18n_string_source_language variable to en rather than the site default (which is no longer en)


nginx rewrite for drupal I have installed Nginx and I have a Drupal site installed in a sub folder.
I also have a directory in /drupalpath/sites/default/files/books/ that stored some PDF in it.
I configure my nginx like this:

location /drupalpath {
    rewrite ^/drupalpath/(.*)$ /drupalpath/index.php?q=$1 last;
}

and it works nice.
But my problem is that the PDFs in /drupalpath/sites/default/files/books/ affected this rule and when I click to download my books it send 404 Error because this rule.
My question is that how to fix it?

location ~ \.pdf$ {
  try_files $uri =404;
}


How to offset an EntityFieldQuery when using pager? Is there some way to easily offset an EntityFieldQuery when using pager(), i.e. skip the first 3 nodes? range(3, NULL) doesn't work as the second value must be set, and range() also doesn't work when also using pager() which is a requirement.

Is there a substitute for something similar to this:

$query
  ->range(3, NULL) // <- Wishful thinking..
  ->pager(10)
;

Thanks,

First question, you've asked if you can offset the results, without having to set the limit for the total results. Logically it would make sense to be able to set $limit = FALSE, to return all results. But I believe range($offset, $limit) requires you to enter both the offset and limit. A workaround is to enter range(3,9999999999);.

Second question, you've mentioned that the -range() is not working when -pager() is set. It's a known limitation. I would assume you can run a separate query to create a pager, but that would require additional SQL requests.


How do I use a sub-string of a field? How do I convert SELECT title , SUBSTRING(title,13,4) as num FROM node_field_data ORDER BY ABS(num) to the format for Drupal 8?

I tried this code.

 $query = $db->select('node_field_data', 'nfd')
  ->extend('\Drupal\Core\Database\Query\TableSortExtender')
  ->extend('\Drupal\Core\Database\Query\PagerSelectExtender');
  $query->limit('50');
  $query->fields('nfd',array('title',substring(title,13,4) as num,'changed','nid'));
 ->orderBy('num', 'ASC')

You need to add an expression with SelectInterface::addExpression:

$query = $db->select('node_field_data', 'nfd')
  ->fields('nfd', ['title'])
  ->extend(\Drupal\Core\Database\Query\TableSortExtender::class)
  ->extend(\Drupal\Core\Database\Query\PagerSelectExtender::class);

$expr_alias = $query->addExpression('SUBSTRING(title, 13, 4)', 'num');

$query->orderBy($expr_alias, 'ASC')->limit('50');


Filter views by current user taxonomy profile field Entity type: Book

I have entity type called "Book".
It has one field called "book_id".

Ex: science book(Book_name) -> 100(Bokk_id)
Maths -> 101
english -> 102

User:

I have user, he has one field attached with user profile called "book_name".
"Book_name" is a taxonomy reference field.

"Book_name" has one field called "book_id"

"Book_id" is free text field, it has more than one value by comma separator. Like 100,101,102.

Ex: user->book_name(taxonomy reference field)->book_id

Using views, I want to filter entity type "book" by current logged in user "book_name->book_id".

Because this is a comma separated text field, your best bet is with custom module that gives your view the ids in a 2+6+36+98 format.

https://drupal.stackexchange.com/a/222876/53677

In that answer, I described how to pass one value from a user field. For you, you'd need to load the taxonomy entity and work with that.

Then, to do multiple, you just need to add a bit of php to split your text field and turn it into the format above with +. You still only pass one argument and in your view, enable multiple values in the contextual filter's settings.

I can't give a longer answer until tomorrow. Btw, if that text field has node ids for books, you should use the entity reference module.


Load and render all pages from main menu I'm trying to create a one-pager website in which I'd like to get all the main-menu links and load their complete content underneath each other on the homepage. So that's blocks, display etc. in all.

So I was thinking I could just get the page and render it in an each link; but I can't figure out how I can load and render multiple pages in one go.

I make a preprocess_page hook and got the menu links I want. How do I go about and get all those pages underneath each other now?

function myproject_preprocess_page (&$vars) {

    //Get ALL The pages from the main menu and ALL the content
    //And make one large content for all of it to create a one-pager
    if (isset($vars['node']) && strtolower($vars['node']->title) == "home") {
        $menu = menu_tree_all_data('main-menu');
        if ($menu) {
            foreach ($menu as $menuItem) {
                $a = menu_get_item($menuItem['mlid']);
                //echo render ($a); // Gives nothing
                //echo drupal_render_page($a); //time-out
            }

        }

}

}

I also tried with menu_load_links but I can't really see if I'm extracting the node now and how to render that.

$menu = menu_load_links('main-menu');

if ($menu) {
    foreach ($menu as $item) {
        $b = menu_get_item($item['link_path']);
    }
}

you cannot render menu entries, but render arrays. you need to get the node from the menu item's path (see here) and then you can use node_view to get its render array.

a way better solution would be to make a views page, with a menu_node relationship.


Node custom property exposed as extra field I'm trying to add custom property to node bundle, my code so far:

/**
 * Implements hook_entity_property_info_alter().
 */
function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['node']['bundles']['program']['properties'];

  $properties['last_episode_date'] = array(
    'label' => t("Last episode date"),
    'type' => 'date',
    'computed' => TRUE,
    'entity views field' => TRUE,
    'metadata controller class' => 'EntityDefaultMetadataController',
    'extra fields controller class' => 'EntityDefaultExtraFieldsController',
    'getter callback' => 'mymodule_last_episode_date_getter',
    'description' => t("Date of the last episode."),
  );
  return $info;
}

/**
 * last_episode_date property getter.
 */
function mymodule_last_episode_date_getter($data, array $options, $name, $type, $info) {
  return REQUEST_TIME;
}

The goal is to have this property available in views and in node as extra field - in views it is available, but I cannot make it to work as extra field. Anything is missing/is wrong? Documentation on this is kind of lacking :( .

Looking at Entity module's hook_field_extra_fields() implementation:

/**
 * Implements hook_field_extra_fields().
 */
function entity_field_extra_fields() {
  // Invoke specified controllers for entity types provided by the CRUD API.
  $items = array();
  foreach (entity_crud_get_info() as $type => $info) { ... }
  return $items;
}

It only looks for entity types provided by the CRUD API -- in other words, entities whose controllers inherit from EntityAPIControllerInterface. Node entities use NodeController.

You can still do this conventionally, outside of Entity API -- implement hook_node_view() to insert your pseudo-field in $node['content'], then implement hook_field_extra_fields() to expose that pseudo-field to the node's "Manage display" tab.


show results for a view with certain node reference I have created two content types a home and a subdivision.  I have added a subdivision reference field in the home content type.

What i want to have is in each subdivision page, show a teaser of the homes that reference that particular subdivision.  I imagine that would be done using views, but I am not sure.

Any help on how to create this view block on the subdivision node would be appreciated.

This is what views is particularly good at, in my opinion. You should be able to get started by creating a subdivision page view. Then you should be able to create a relationship based on the reference field. This would give you access to sort based upon whether the home appeared in that subdivision.


What are the contextual links? Drupal 7 defines the "use contextual links" permission. Which links are defined as contextual links?

In Drupal 7, some modules supply contextual links that allow privileged users to quickly perform tasks that are related to regions of the page without navigating to the Admin Dashboard. For example, when you hover your mouse over a block or node, links are displayed that allow you to make changes to the block or node.

According to drupal.org.


Add div to checkboxes only I would like to add a
 containing only checkboxes. The output I want is similar to the following.

  1<input type="checbox" id="check1" name="check1">
  1<input type="checbox" id="check2" name="check2">
  1<input type="checbox" id="check3" name="check3">

<input type="text" id="text" name="text">

<input type="submit" value="submit">

In template.php I have THEME_form_alter() with the following code.

  $form['basic'] = array(
    '#prefix'=> '

',
    '#suffix'=> '

'
  );

  $form['basic']['keys']['check1'] = array(
    '#prefix' => '
Check1',
    '#suffix' => '
',
    '#type'=>'checkbox',
    '#value' =>'0',
    '#pre_render' => '',
    '#id' => 'check1',
    '#name' => 'check1'
  );

  $form['basic']['keys']['check2'] = array(
    '#prefix' => '
Check2',
    '#suffix' => '
',
    '#type'=> 'checkbox',
    '#value' =>'0',
    '#pre_render' => '',
    '#id' => 'check2',
    '#name' => 'check2'
  );

  $form['basic']['keys']['check3'] = array(
    '#prefix' => '
Check3',
    '#suffix' => '
',
    '#type'=> 'checkbox',
    '#value' => '0',
    '#pre_render' => '',
    '#id' => 'check3',
    '#name' => 'check3'
  );

  $form['basic']['keys']['text'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type'=> 'textfield',
  );

How should I write THEME_form_alter() to be obtain the HTML output I want?

With the form elements you are using, the output you obtain is the following one.

        Check1

          <input type="checkbox" id="check1" name="check1" value="1" class="form-checkbox">

        Check2

          <input type="checkbox" id="check2" name="check2" value="1" class="form-checkbox">

        Check3

          <input type="checkbox" id="check3" name="check3" value="1" class="form-checkbox">

        <input type="text" id="edit-text" name="text" value="" size="60" maxlength="128" class="form-text">

 is wrapped to all the elements because it's a prefix for $form['basic'], which contains all the form elements.

I would use the following code.

  $form['basic']['keys']['check1'] = array(
    '#type'=> 'checkbox',
    '#title' => 'Check1',
    '#value' => '0',
    '#pre_render' => array(),
    '#prefix'=> '

',
    '#suffix' => '
',
  );

  $form['basic']['keys']['check2'] = array(
    '#type'=> 'checkbox',
    '#title' => 'Check2',
    '#value' => '0',
    '#pre_render' => array(),
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['basic']['keys']['check3'] = array(
    '#type'=> 'checkbox',
    '#title' => 'Check3',
    '#value' => '0',
    '#pre_render' => array(),
    '#prefix' => '
',
    '#suffix' => '

'
  );

  $form['basic']['keys']['text'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type'=> 'textfield',
  );

Its output is the following one.

        <input type="checkbox" id="edit-check1" name="check1" value="1" class="form-checkbox">
        Check1

        <input type="checkbox" id="edit-check2" name="check2" value="1" class="form-checkbox">
        Check2

        <input type="checkbox" id="edit-check3" name="check3" value="1" class="form-checkbox">
        Check3

    <input type="text" id="edit-text" name="text" value="" size="60" maxlength="128" class="form-text">


Display different fields based on a URL parameter I have a content type called section with 5 custom fields, and I need to display each field as a different page, e.g. section/1/fieldA, section/2/fieldB.

I would like to override node.tpl.php, and output the desired field based on the third parameter (fieldA, fieldB, ...).

How can this be done? Do I need to create a custom module or can be done via theming?

What should I do if I wanted to replace the node ID with a string?

Use a custom module. Implement hook_menu to declare a page handler for your path pattern that return the value of field_view_field().

function MODULE_menu() {
  $items = array();
  $items['section/%node/%'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'MODULE_node_field_page_view',
    'page arguments' => array(1, 2),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
  return $items;
}

function MODULE_node_field_page_view($node, $field_name) {
  if ($node->type !== 'section' || !field_get_items('node', $node, $field_name)) {
    drupal_not_found();
  }
  else {
    return field_view_field('node', $node, $field_name)
  }
}

Then use alias and pathauto to use path like section/{node-title}/{field_name} instead of numeric node id in URL.


How to expose paging data in REST export views How to allow views to export paging data along with entities?

I can set pager, and it works of course, for example my_view?page=1
displays something like

[
  {...},
  {...}
]

but I only get list of filtered or paginated entities, and I would like to include paging information, something like

[
  paging_info: [
    total: 4,
    per_page: 2,
    current_page: 1,
    ...
  ],
  data: [
    {...},
    {...}
  ]
]

Enable pager Exposed option "Allow user to control the number of items displayed in this view" in rest display, then build custom module with views style plugin - to return results and pager data, and set in rest display

short code from custom style plugin:

$ret = $this->serializer->serialize(
 [
   'results' => $rows,
   'pager' => [
     'count' => $count,
     'pages' => $pages,
     'items_per_page' => $items_per_page,
     'current_page' => $current_page,
   ]
 ],
 $content_type
);

full code in gist: https://gist.github.com/svetlio/79f3c32667b21d89ed03cdb660308668

thanks to Dan's post here: https://www.mediacurrent.com/blog/8-insights-and-useful-snippets-d8-rest-module


Embedding a view from a page with php I need to put three view blocks next to each other on a page. Therefore, I thought i could put some php code in a new page and manually put them next to each other with DIVs.

The problem is that I can't seem to output the views block.

I have tried multiple things:

//load the view by name
$view = views_get_view('woensdag');
//output the view
//var_dump($view);
--> this returns the view, so it is being loaded

$view_name = 'woensdag';

views_embed_view($view_name, 'default');
--> outputs nothing

views_get_view_result($view_name, 'block');
--> outputs nothing

echo views_embed_view('woensdag', $display_id = 'block')
--> outputs nothing

The delta  name of the view is woensdag-block_1, I have tried that as well.

Any ideas? I am using Drupal 7.

views_embed_view($view_name, 'default');
// does not work because you need to print/echo the result. eg.
print views_embed_view($view_name, 'default');

views_get_view_result($view_name, 'block');
//does not work because the function returns an array (and you aren't even trying to print the array anyway)

echo views_embed_view('woensdag', $display_id = 'block')
// Trying to set a variable in a function call? It probably would have worked like this:
echo views_embed_view('woensdag', 'block')


How to capture form fields to programmatically create new users I briefly worked with Drupal several years ago, and now have come back to it for a single project. For all intents, I'm a total beginner. I need to create a new user from a custom form (html in a block.) I've found some info on how to do the back-end processing (this and this), but can't figure out how to capture the form submission values in my custom module. Can I just use $_POST values? Is that allowed? Or is there some other way I'm supposed to go about it?

My initial module code looks like this:

function create_vector_user_block_info() {
    $blocks['create_vector_user'] = array(
    // The name that will appear in the block list.
    'info' => t('Create Vector User'),
    // Default setting.
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

function create_vector_user_submit() {
    //This will generate a random password, you could set your own here
  $password = user_password(8);

  //set up the user fields
  $fields = array(
    'name' => 'user_name',
    'mail' => 'user_name@example.com',
    'pass' => $password,
    'status' => 1,
    'init' => 'email address',
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    ),
  );

  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);

  // If you want to send the welcome email, use the following code

  // Manually set the password so it appears in the e-mail.
  $account->password = $fields['pass'];

  // Send the e-mail through the user module.
  drupal_mail('user', 'register_no_approval_required', $email, NULL, array('account' => $account), variable_get('site_mail', 'noreply@example..com'));
}

What I need to do is get the value of a username and email field in my custom block and pass them to the elements in the $fields array.

As AyeshK pointed out there are several examples out there. This should have all the elements you need.

First you must create a form to use in your block with hook_form, create your custom submit handler, and use your form values found in $form_state.


Is it safe to allow domain.com/username? Are there any security risks if we create pathauto roule so that the user account pages are at domain.com/username

On a site that is not using a mechanism like the one implemented from the Two-factor Authentication (TFA) module, letting visitors know usernames of existing accounts is giving out half of the credentials. It doesn't mean it is easier to log in on somebody else's account, though.
Somebody who got my password for a site could probably try to use the same password for another site's account where I am using the same username. If I were using the same credentials for more sites, that could work, but somebody could argue it is my fault for using the same credentials on different sites.

On my experience on Drupal.org, the bigger issue was not the username being publicly available, but third-party software used on the server, which caused  unauthorized access to account information to emails, usernames, and hashed passwords.

That said, Drupal 8 core code is being changed to use the output of User::getDisplayName() every time links to user accounts are given in a page. User::getAccountName() should be used when displaying the name to administrator users, the user who owns the account, or for the username in the login context.
Using domain.com/username for the user account pages is going on the opposite direction. I would rather use the output of User::getDisplayName() to build the path alias of user accounts pages.

As you are asking for a Pathauto pattern, this would mean using the [user:display-name] token when creating the pattern on admin/config/search/path/patterns.

Instead of domain.com/username, I would rather use domain.com/users/username or domain.com/u/username to avoid conflict with existing routes, or other path aliases.

To make an example of what could happen, I created a test site on simplytest.me where the user #1 is set with admin as username. I installed the Pathauto module and its dependencies, and I created a pattern for user entities using [user:display-name]. The result is that the URL for the user #1 became (after I bulk-updated the path aliases) https://dqth.ply.st/admin-0. (See the -0 part added not to create conflicts between the registered route and the path alias).
This is happens when the route is already defined when the path alias is created. I cannot predict what would happen when a module using a route with a path that already exists as path alias is installed.

Also, if you look at the code of User::getDisplayName(), you will notice that by default it returns the username (the output of User::getAccountName()). It will return something different only if there is a module that implements hook_user_format_name_alter() and that module does alter the value of the $name parameter it gets.

$name = $this
  ->getAccountName() ?: \Drupal::config('user.settings')
  ->get('anonymous');
\Drupal::moduleHandler()
  ->alter('user_format_name', $name, $this);
return $name;

This means that you need to use the [user:display-name] token in the Pathauto pattern, but also install a module that implements hook_user_format_name_alter(). For example, you could use the Real Name module which adds a Real name field to user entities, containing the value Drupal 8 will use as display name. You can also implement a custom module for that.


Add paragraphs to a node via jsonapi Added a paragraph to drupal8 via jsonapi and want this paragraph to be in an articles body. I thought it is as easy as

    "relationships": {
        "field_body": {
            "data": [
                {
                    "type": "paragraph--text",
                    "id": "b0247bf8-a3c0-4a45-8e05-4f4901011000"
                }
            ]
        }
    }
},

but the article is created and the field_body result is empty. It works already with other entities just fine. And the jsonapi gives me the paragraph /jsonapi/paragraph/text ...What is the problem, am I missing something?

Did you gave node type ? Try the following body data.

{
 "data":
  {
     "attributes": {
            "title": "title of your new node",

        },
         "relationships": {
            "field_body": {
                "data": {
                    "type": "paragraph--text",
                    "id": "b0247bf8-a3c0-4a45-8e05-4f4901011000"
                }
            }
        },
      "type": "node--yournode"
    }
  }


Is there a way to position my Article title in Drupal 8 teaser? I have In teasers  and other custom display types I would like the image to appear above the title.  However, when I try to manage the display fields from the admin menu there is no way to change the  title or byline.

In other words  the only field I choose to display from that menu is image, but on the page the title, date and author appear.

 <title>
 Submitted by <author> on <date>

Is there a way outside CSS to move these things around

You either need to do it in node templates or you can try out Display Suite, but I'm not sure about the exact state of it in Drupal 8.

Update: Didn't see that you also mean the byline. That one is easy, that's a setting on the node type form whether it should be shown or not.


Content Type name not translated I created a custom Drupal 7 module that creates a custom content type. It looks like this:

$type = node_type_set_defaults(
array(
    'type' => 'featured',
    'name' => t('Featured'),
    'description' => t('The description of the featured item.'),
    'base' => 'node_content',
    'locked' => 0,
    'custom' => 1,
    'modified' => 1
)
);

node_type_save($type);

I have a nl.po translation file that contains the following entries:

msgid "Featured"
msgstr "In de kijker"

msgid "The description of the featured item."
msgstr "De beschrijving van het in de kijker item."

The description gets translated as I expect when switching between languages. The content type name does not get translated at all, only English is shown.

Any ways to fix this?

Thanks in advance.

I hope this like help you

How to Translate Content type name using i18n module?


Trying to alter SKU field on ubercart product that is also a course I'm trying to modify a course (from the course module) and a product (from ubercart). I want to remove the SKU (right now I'm just testing how to remove the required bit) and a few other fields as I'm selling only online products. I'm not great at using hook_form_alter() yet.

I'm trying to follow this tutorial, http://www.ubercart.org/comment/8749/Re-Removing-SKU-product-edit-page and I'm not quite sure where he is getting $form_id == 'product_node_form' - is that related to the content type?

I'm trying to do this on a course content type, so if so, that would explain why it isn't working for me.

The ID for a node form is built up in node_forms():

$forms[$type . '_node_form']['callback'] = 'node_form';

Where $type is the name of each type retrieved from node_type_get_types().

So generally speaking, if the content type is product, the form ID will be product_node_form, if the type is course the form ID will be course_node_form, and so on.