How do I export all of my customers (not users) from Drupal into a CSV file? I'm working on integrating a new accounting system and crm (Xero & Capsule) for a client - and they have just under 10,000 clients - only stored in their Drupal website. I need to export these with all their details (e mail, full name, address etc) - into a csv or excel file.

Currently under Store Administration I can "View Customers" - but this gives me no option to export.

But under Reports > Customer Reports it gives me the option to export each page to a csv - however the information is not what we need - it only gives me usernames.

Any suggestions?

With the https://www.drupal.org/project/views_data_export module you can create views and export to CSV, Excel, XML, etc.

It also supports exporting in batches (default activated if the views has 1 000 or more rows). So 10 000 clients shouldn't be a problem.


look up page View by its path We can search all the default views on our relatively new Drupal 8 site, to see what view resides at a particular path, with a query like:

$view_trim_path = 'blog';
$query = $this->entityQuery->get('view')
  ->condition('display.page_1.display_options.path', $view_trim_path)

Unfortunately, this relies upon a hardcoded display name of page_1, which will not hold true in general.  In my dreams I would use a wildcard query like

  ->condition('display.page*.display_options.path', ...)

Is there a way to do either of the following?

create a set of entityQuery conditions to find views that have display.*.display_options.path equal to a certain value, no matter what the value of * ... preferably when * begins with the page_ prefix
use another Drupal / View function to look up a view ID from its path (I can't find one)

I can see how to find this by loading the config entities for all views and traversing all those arrays, but my guess is that Drupal has provided a simpler means for this.  Also it seems the database abstraction layer would be of use, and if that's the best practice then it would really help me to have an example of how to use it for the above query.

The page prefix is meaningless, it can be changed by the user and can be anything.

So you just want display.*.display_options.path.

It would match on other displays that have a path setting (e.g. REST or feed). If you want to avoid that, you add a second condition on display_plugin = page.


How do I auto enable modules within an install profile I have created an sample installation profile (based on one that I grabbed from the Acqua Drupal install profiles. Thus far I understand the basic architecture. I add dependancies, but I cant figure out how to enable the modules. For instance, I want to require views, views_ui, and features, and I want those modules to be automatically enabled when I install the profile. I'm assuming I add code somewhere in my .install file within the profile. Can someone give me an example of how I would require and enable views for instance?

You need to add them as dependencies in the .info file. To take a segment from standard.info:

dependencies[] = block
dependencies[] = color
dependencies[] = comment
dependencies[] = contextual
dependencies[] = dashboard

To add a little reference from How to Write a Drupal 7 Installation Profile:

  The contents of the profilename.info file are as follows:

  The name, description, and core assignments are all required.
  The dependencies list includes all modules that will be enabled when this profile is installed (the ones above are the defaults from the Standard install profile).
  You can optionally include other declarations that can also appear in module .info files.

(Emphasis mine).

So enabling views would just be:

dependencies[] = views

And if you want the UI:

dependencies[] = views_ui


MigrateSQLMap how to instantiate if table has no primary key Guys how do you instantiate this MigrateSQLMap if my destination table has no primary key?

here's my code:

 $table_name = 'taxonomy_index';
    $this->map = new MigrateSQLMap($this->machineName,
      array('id' => array(
              'type' => 'int',
              'unsigned' => TRUE,
              'not null' => TRUE,
             )
           ),
        MigrateDestinationTable::getKeySchema()
      );

im trying to import to the taxonomy_index table in drupal which we know has no primary key.

how to make this possible?

To migrate content into Drupal taxonomy terms, use the MigrateDestinationTerm class, not MigrateDestinationTable. Here is example code

    $this->map = new MigrateSQLMap(
      $this->machineName,
      array(
        'term_id' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'Term ID',
        ),
      ),
      MigrateDestinationTerm::getKeySchema()
    );


Get Field Name Being Deleted From Configuration Updates/Delete Form Trying to get the field_name being deleted when viewing a route like entity.field_config.user_field_delete_form.

Example path: /admin/config/people/accounts/fields/user.user.field_name/delete

Some Hooks I've tried:

hook_preprocess_html()
hook_preprocess_page()
hook_preprocess_page_title()
hook_preprocess_form_field_config_delete_form_alter()

But the best I have found is an argument [%label] => Field Label.

I have an array of field_names and want to check if the field_name being deleted matches one of the values.

The goal is to add a custom \Drupal::messenger()->addWanrning($warning);.

This would be altering an existing delete form/page.

Try with hook_form_alter something like

/**
 * Implements hook_form_alter().
 */
function MyModule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == "field_config_delete_form"){
    $field = $form_state->getFormObject()->getEntity();
    \Drupal::messenger()->addWarning("You are going to delete field : " . $field->getName());
  }
 }


Openlayers views , center map to each geofield I have setting geofield in profile for each user , and make a view that list the location of the current user post (" I'm here ") , but the map isn't centered well to show up the marker , and when you zoom out it shows the markers.

So how do I get my map centered for each user geofield ?

Go to /admin/structure/openlayers/maps
Choose the map you are using to display your geofield on the user
Select the behaviors tab
Check off Zoom to Layer
Select geofield_formatter
Enter your zoom level

Note: If I misunderstood your question, and you were actually referring to centering on the markers on your view that compiled all of the users, then just select your view name in the 'Zoom to Layer'.


How to change the url the core search form submits to? The action value for the core search form is /search/node.
How could I get it to go instead to a different url for a custom View?

You can use hook_form_alter or hook_form_FORM_ID_alter to alter a form.
Core's search block form has a form id of search_block_form, so you could implement with hook_form_FORM_ID_alter() like:
use Drupal\Core\Form\FormStateInterface;

function mymodule_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['#action'] = '/my-custom-path';
}


Dropdown Menu Dummy Link One of my menu items I have, I want to make it so that only the child links are clickable, and the parent is not. Is there a way to make the parent a sort of "Dummy Link" just to set a hierarchy for a menu?

The Special Menu Items module will do exactly that for you:

Special menu items is a Drupal module that provides placeholder and separator menu items.
A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it.


Do one time action after logging in I need to add a Javascript file only once immediately after logging in - which will open another URL in a new window.

Without using _SESSION what'll be the right place to add drupal_add_js function only once after logging in?

Is there a hook which is called in the very first logged-in page?

Add the JS file inside the implementation of hook_user_login().
Function docs:

  The user just logged in.
  Parameters

  $edit: The array of form values submitted by the user.

  $account: The user object on which the operation was just performed.


Creating a form that only show form fields for editing the node title, body, and any fields created using the field API I have created a content type with some field API fields.

How can I create a edit form that allows to edit just the title, the node body, and those fields?

The normal node edit form contains extra form fields that are not necessary for my purpose (i.e. they are not for editing the parts of a node I listed).

I get you want to show a form where the users can enter the values for the fields implemented using the field API, the node body, and the title; other form fields should not be shown.

Using the following code, you can achieve what you want.

function mymodule_node_form($form, $form_state, $node) {
  global $user;

  if (!isset($form_state['node'])) {
    if (!isset($node->title)) {
      $node->title = NULL;
    }
    node_object_prepare($node);
    $form_state['node'] = $node;
  }
  else {
    $node = $form_state['node'];
  }

  $form['#node_edit_form'] = TRUE;

  $form['#attributes']['class'][] = 'node-form';
  if (!empty($node->type)) {
    $form['#attributes']['class'][] = 'node-' . $node->type . '-form';
  }

  foreach (array('nid', 'vid', 'uid', 'created', 'type', 'language') as $key) {
    $form[$key] = array(
      '#type' => 'value',
      '#value' => isset($node->$key) ? $node->$key : NULL,
    );
  }

  $form['changed'] = array(
    '#type' => 'hidden',
    '#default_value' => isset($node->changed) ? $node->changed : NULL,
  );

  $function = node_type_get_base($node) . '_form';
  if (function_exists($function) && ($extra = $function($node, $form_state))) {
    $form = array_merge_recursive($form, $extra);
  }
  if (isset($form['title']) && !isset($form['title']['#weight'])) {
    $form['title']['#weight'] = -5;
  }

  $form['#node'] = $node;

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
    '#value' => t('Save'),
    '#weight' => 5,
    '#submit' => array('node_form_submit'),
  );
  if (!empty($node->nid) && node_access('delete', $node)) {
    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#weight' => 15,
      '#submit' => array('node_form_delete_submit'),
    );
  }

  // Add the validation handlers.

  field_attach_form('node', $node, $form, $form_state, entity_language('node', $node));
  return $form;
}

This code is taken from node_form(); it is a ripped off version that include only what necessary to allow to enter the title, the body content, and the values for any field implemented using the field API.
As you see, the code still need to define the form validation handler, and the form submission handler. You use the code of node_form_validate() as guideline for your
validation handler.

The form builder can be used for a menu item as the following one.

function mymodule_menu() {
  $items['mymodule/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_node_form', 1),
    'access arguments' => array('the permission users should have to see this menu item'),
  );

  return $items;
}


How to configure Facet displays that comes with Commerce kickstart Commerce kickstart comes with some filtering when viewing all the products, I do not have idea how to make my own facet displays, and I cannot find anything in the drupal configuration about facet displays. Can someone explain it to me?, would be great if it is with an example

Ok I could figured it out thanks to this great tutorial

http://vimeo.com/53404289

There is how you can manage your own commerce facets


Disclaimer screen when adding new content I'm looking for a way to have a disclaimer page/popup be a part of creating a certain type of content, in this case a OG group. Is this something that could somehow be done with Webforms?

I found http://drupal.org/project/legal but it just doesn't quite do the trick... Any other ideas? :)

One way to accomplish this would be to make a small custom module utilizing hook_form_alter().  Substitute "example" with your module name to implement.

example.module

/**
* Implementation of hook_form_alter()
* Add Disclaimer Message to Article Create Form
*/
function example_form_article_node_form_alter(&$form, $form_state) {
  if (arg(1) == 'add') {
    drupal_set_message('Legal Disclaimer: By filling out this form you are agreeing.','warning');
  }
}

example.info

name = "Example module"
description = "Adds a disclaimer to node/add/article page."
package = Example
core = 7.x

Or if you want a popup, you could instead use drupal_add_js and a little Javascript

example.module

/**
* Implementation of hook_form_alter()
* Add Popup Disclaimer to Article Create Form
*/
function example_form_article_node_form_alter(&$form, $form_state) {
  if (arg(1) == 'add') {
    drupal_add_js(drupal_get_path('module', 'example').'example.js');
  }
}

example.js

// if user agrees continue, else redirect
if (!window.confirm('Legal Disclaimer: Press OK if you agree.')) {
  window.location.href='http://example.com';
}

Of course this is all pretty simple and ugly.  One could combine both approaches and using CTools Modal or JQueryUI build a prettier dialog.  With JQueryUI you might do:

example.js

// if user agrees continue, else redirect using JQueryUI
// requires JQueryUI loaded (you can use [drupal_add_js()][5] for this too).
(function ($) {
  $(document).ready( function() {
    $("

Legal Disclaimer

Do you agree?

").dialog({
      resizable: false,
      height:140,
      modal: true,
      buttons: {
        "I Agree": function() {
          $( this ).dialog( "close" );
        },
        "No Way": function() {
          $( this ).dialog( "close" );
          window.location.href='http://example.com';
        }
      }
    });
  });
});


drush cc all giving me an unlink error I found a similar issue but it will not help me since I have not changed permissions.

I am running drush cc all and getting this error...

I have logged out and back in and nothing. I have not changed permissions and I have the admin rights to the account. Any ideas on what to do?

I've seen this problem when as unprivileged user you call drush cc all and drush tries to delete cache files created by the web server process. Those files are owned by the web server user and they don't have the 'all other users" write permissions enabled (the last three permissions group).

Fixing this is a file permissions issue. One fix is to put web server user and drush user in the same group and assure that files created by the web server process are writable by its group members.


how to use EntityFieldQuery by language? global $language;

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'events')
->propertyCondition('language', $language->language)
->propertyCondition('tnid', $output)
->execute();

I tried using this code and it is showing me empty page, any help on using EntityFieldQuery?

$language variable  is better to be in the function as:

 function getListNode(){
   global $language;
   $query = new EntityFieldQuery();
   $query->entityCondition('entity_type', 'node', '=')
         ->entityCondition('bundle', 'content_type', '=')
         ->propertyCondition('language', $language->language, '=');
   $nids = $query->execute();
   return entity_load('node', array_keys($nids['node']));
 }

it works for me
good luck


How to programmatically add a custom field to Address? I'm using Address module, and I need to add a Boolean field "Handicap access" for all addresses, whichever country is selected.

I digged into module issues, I carefully read provided docs, where there is an example about how to : Create a custom address field by repurposing an unused one.

  What about address field X? Can I add another property to an address
  field?

  No, not without great difficulty. But you can repurpose an unused
  property for a custom one.

But there is not any boolean existing field into Address fields. Any tip to put me on the right track is welcome. Thanks !

Not sure if this solves your specific problem, but you can create a custom paragraph type with an address field and a boolean field, then add a Paragraph Entity field on your content type. You can limit this paragraph reference field to your newly created paragraph type. This will allow you to have a field with both address/accessibility information.


Hidden form values updated with multiple submission I'm writing a backend validation function to prevent multiple submission for comments by logged in users in Drupal. Following is my code:

function MYMODULE_form_comment_form_alter( &$form, &$form_state, $form_id ) {
        if( user_is_logged_in() ) {
          $unique_bytes = openssl_random_pseudo_bytes( 8 );
          $unique_id = bin2hex( $unique_bytes );
          $session_key = 'comment_form_token_' . $form['form_id']['#id'];
          $_SESSION[$session_key] = $unique_id;
          $form['one_time_token'] = array(
              '#type' => 'hidden',
              '#value' => $unique_id,
          );
          $form['#validate'][] = '_MYMODULE_comments_validate_one_time_token';
        }
}
function _MYMODULE_comments_validate_one_time_token( $form, &$form_state ) {
  if( user_is_logged_in() ) {
    $form_id = $form['form_id']['#id'];
    $session_key = 'comment_form_token_' . $form_id;
    $one_time_token = $form_state['values']['one_time_token'];
    if( isset( $_SESSION[$session_key] ) && $_SESSION[$session_key] === $one_time_token ) {
      unset( $_SESSION[$session_key] );
    }
    else {
      form_set_error( 'comment_body', t( 'Please make sure that you have submitted this form only once.' ) );
    }
  }
}

The problem is that when the user submits the form multiple times by clicking the Submit button extremely fast, the one_time_token field's value gets updated automatically rather than submitting the original value.

To elaborate further, if my initial field value on form load was e8ac1824bf894e12, session value for that was also e8ac1824bf894e12 and submitted value was also e8ac1824bf894e12. But on processing second submission, my session value is 153695ec028bf151 but I expect my submitted values to stay e8ac1824bf894e12 but somehow that also changes to 153695ec028bf151.

Is there a way I can prevent that?

You can use jQuery to change the submit button to a loading gif when the save button is clicked. Thus, preventing any more clicks.

(function($) {
  $('.form-submit').click(function() {
     $('.form-submit').html('<img src="https://media.giphy.com/media/TtZqlvHid7BjW/giphy.gif">');
  });
})(jQuery);

JS Fiddle Example


Entity Query not returning all results For some reason, my EntityQuery is returning 60 articles.  There are actually 63 of them.  I am certain about this.

Here are some questions I have:

I don't think revisions are enabled for my content types, but how do I check? And, how do I do this programmatically? I'm not sure if my EntityQuery is returning nids or vids...
Why would EntityQuery be unable to find an article? It seems like it can't find it, even if I just search for nodes containing part of its title. It returns 0 results.

Here's what I've tried:

I did a loop and loaded the nodes from the nids, printed out the titles, and I copy pasted the node titles (filtered on articles) from the content list, did a diff with the alphabetized results to find the three articles which EntityQuery doesn't believe to exist.  They are all normal seeming articles, which can be viewed/edited.

I started debugging into the core EntityQuery files, but I'm afraid at this rate it's going to take me a while before I understand what's going on.  Does anyone know why an EntityQuery might not find certain nodes, or even have an idea where I should be looking in the core files, or what I might be expecting to look for in the DB tables?

I'm using MySQL 5.7, in case that's relevant at all.

EDIT: Someone asked for the code, I am doing an EntityQuery for all articles, yet I don't get all of them:

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article');
$entity_ids = $query->execute();

foreach($entity_ids as $id){
  echo $id->getTitle() . "\n";
  // Do I do Drupal entity node load, or do I load via revision ID?
  // Here I would like to load the node and then do stuff with it...
}

I added metadata to the query, running it as user 1, which allowed it to get all of the nodes:

$query = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->addMetaData('account', \Drupal\user\Entity\User::load(1)); // Run the query as user 1.
$nids = $query->execute();

echo "count: " . $query->count()->execute() . "\n";

foreach ($storage->loadMultiple($nids) as $node){
  //do stuff
}

Also, since revisions are allowed for nodes, it was returning $nids as revision_id => entity_id as Berdir said in his comment.


Views taxonomy contextual filter? I have taxonomy vocabulary called “Groups”, with 3 terms. I have two content types that both use a Groups term reference field. These content types are called “Media” and “Links”.

When displaying “Media” (node), I have an embedded view that shows “Links”. How can I only show “Links” that have the same terms as the actual “Media”?

Is it possible to do with contextual filters?

I have embed view that shows “Links”. How can I only show “Links” that
  have the same terms as the actual “Media”?

I'm not sure you used Entity Views Attach module to attach the View or just placing the View as a block.

Whatever it is, you can do it. But if you have EVA, you will be able to set the current node ID argument easily.

Add a new View as Show: Content, Of Type links. Continue and Edit.
Then, in the Views UI, you will see a filter to show only Link nodes are added. Now, add extra fields you want from the Link nodes.
Set configuration as marked in the image below.
Save the View.
Save the View and enjoy!

if you have EVA module, do not set to inherit node ID to the View (it will give wrong results). Send the term ID as argument(s) if possible.


Proper way of Link generation from string How can I generate a link in a proper way in Drupal 8? I have a field where the user can say an internal or external page/website.

Internal:
/node/6
/articles
/articles#Subheading
etc.

External:
www.google.com
//www.google.com
https://www.google.com

How can I transform these into a link with the following condition:
the site root is: www.mydomain.com/mysite/
internal links should have language versions: i.e. en/articles or pt/articles .

I've tried with Link::fromTextAndUrl('My link', Url::fromUri('internal:/articles')), but this requires a URI which is not my goal and it doesn't follow the selected user language.

You do not need internal:/ you just need to have some help text that says an internal path should begin with a slash.

After that, when you create the links, you can do:

use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Component\Utility\UrlHelper;

....
....
....

function or method.... {
  $path = // get config value
  $label = // get config value

  if (UrlHelper::isExternal($path)) {
    $url = Url::fromUri($path);
  } else {
    $url = Url::fromUserInput($path);
  }

  return Link::fromTextAndUrl($label, $url);
}

Of course I am assuming there is always a value... you'd have to add your own checks so you don't get errors calling Url:: for null or empty input, etc.

The return will be an renderable array to use. I am using a similar method to allow input for third party settings on a config entity. This way the value can be internal or external.


theme contact form block I am using contact_form_blocks-7.x-1.x-dev module. Using this module I have embedd contact us form in my website. For themeing I have created file named block--contact.tpl.php. Cleared cache, but it doesnt result anything.
How should I theme this contact us form?

If you want to theme contact form then you can do it using  hook_form_alter().

Use hook_form_alter(&$form, &$form_state, $form_id) in your theme's template.php and alter the form the way you want to theme it.


how to give node alias dynamically Each time I add a content, I see a node number gets created (i.e. node/2). When I go to the node, I see in the address bar as xxx.com/node/2. Is there way node/2 can be replaced by a value of any field(i.e. title) of the node dynamically? In this case new URL will be xxx.com/nissansentra. [nissansentra is the value of the title field of that node).

I know I can go to config > url alias and give a alias name manually. Instead, I am trying to make it dynamic so I don't have to manually give a alias to each node.

Thanks.

D

Yes there most definitely is. Checkout Pathauto. There are many contrib modules for this type of common functionality at Drupal.org.


hide a field in webform components I want to hide the field "form key" in all of the webform components.
I tried doing it with "*hook_form_alter*" and with "[#access] = false" but I can't succeed in this.
I also tried to use "*hook_webform_component_load*".

But in all of those, i can't understand exactly what I need to do to hide the form key field in all of the components in all of the webforms. I can't even hide one component's "form key" field. I don't understand which is the field that i need to modify.

p.s - im using form_builder too.

I'm doing something wrong.

any help will be appreciated.
thanks, alexandra.

The webform_civicrm module does this (actually it disables it rather than hiding it)

You can see the relevant code here (note this function runs in the context of hook_form_alter).

You could hide it by doing something similar but setting $form['form_key']['#type'] = 'hidden';


Is there a way to quickly copy the same ordering and layout from manage fields to manage displays? I have a content type I made in Drupal that has over 50+ fields and all sorts of fieldsets, divs, and horizontal tabs.  I got the Manage Fields ordering and look to be what I want, but the manage display is all out of order and missing some field groups like the divs, fieldsets, and horizontal tabs.  I would need to add them all back in one-by-one!  Is there a quick way I can just click a button that would automatically take the existing layout from "Manage Fields" and use that for "Manage Display" for a content type?

Since this has been posted for more than a week and nobody has responded, then I am going to assume that there is no quick and easy way.  I just ended up recreating the display by hand.  Oh well.


Use CKEditor on textarea in custom module's controller response I am trying to figure out how to use Drupal 8's CKEditor on <textarea></textarea> tags that are part of a controllers markup and not generated from a Drupal form.

Has anyone done this or can Drupal 8's integrated CKEditor only be used with Drupal Forms?

When I try to use ckeditor with the standard way of CKEDITOR.replace('element'); I get the error that config.js and styles.js are missing.  Which should be the case because Drupal has consciously excluded them from their integrated CKEditor. https://www.drupal.org/project/drupal/issues/2604052

After digging around I found the javascript call Drupal.editors.ckeditor.attach(element, format) but I can't figure out what to pass in for the format parameter.  Looking at other javascript code it appears they they use the drupalSettings global variable in javascript to pass it in but it's not there.

Any help on this would be greatly appreciated.

My code is below.

my_module.routing.yml

my_module.myroute:
  path: '/my-route'
  defaults:
    _title: 'Test Module'
    _controller: '\Drupal\my_module\Controller\HomeController::view'
  requirements:
    _access: 'TRUE'

my_module.libraries.yml

scripts:
  js:
    my_script.js: {}
  dependencies:
    - ckeditor/drupal.ckeditor

my_script.js

window.onload = function () {
    let element = jQuery("#testelement");
    let format = "filtered_html";
    Drupal.editors.ckeditor.attach(element, format);
};

HomeController.php

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\Markup;

class HomeController extends ControllerBase
{

    function view()
    {
        return [
            "#attached" => [
                "library" => ["my_module/scripts"]
            ],
            "#markup" => Markup::create("
                <textarea name='testelement' id='testelement'></textarea>
            ")
        ];
    }
}

I'd imagine you just return the same element you'd build into a form, and use a format that's configured to use a WYSIWYG:

return [
  '#attached' => ...,
  '#type' => 'text_format',
  '#title' => 'Foo',
  '#format' => 'full_html',
];

See the TextFormat class for more options.


Best approach to set up a collection I've got a bunch of internet links with the properties "Name", "Description", "URL", "Banner (image)" and "Category".

What is the best approach in Drupal to get these organised? Should I create a content type for it and then use e.g. Views etc. to format the output or is there a better way, maybe a module?

Create a content type, e.g "Website"

Add fields:

URL ( link field )
Banner ( image field )
Category ( term reference field, create taxonomy vocab 'Category' first )

Name and Description will be the default node title and body fields

After that, you can create / manage your content.

Use Views and/or Panels to control the output on your site.


Search template suggestions from a module I have created a custom search module that integrates with Drupal 7 Search Interface. My module is called history_search and in the module I have two files: history_search.module and history_search.info.

These are the contents of my history_search.module:

<?php

function history_search_search_info()
{
    return array(
        'title' => 'History',
        'path' => 'history',
        'conditions_callback' => 'history_search_search_conditions_callback',
    );
}

When I try to use it, it works correctly: Drupal creates a search tab for me and uses the results data I provide. However, I can't figure out how to get it to use my template suggestion for a single search result. I created a file in my module's folder called search-result--history_search.tpl.php, however it doesn't seem to be used when I perform searches in my module. However, if I place this file in my theme, then it suddenly works fine with no problems.

So my question is, how do I get Drupal to use search-result--history_search.tpl.php when I place it in my module's folder?

Thanks to the comments from @AlexGill and @Beebee I was able to figure out what's the actual suggestion name for my template file. Here's how I solved it:

<?php

function history_search_theme()
{
    return array(
        'search_result__history_search' => array(
            'template' => 'search-result--history_search',
            'path' => drupal_get_path('module', 'history_search'),
            'base hook' => 'search_result',
        ),
    );
}


How can I customize the node/add form for a content type? How can I add some help text above the form used to create a node of a specific content type?
What is the best way to do it in Drupal 7?

On the content type edit/creation page there is a field labeled Explanation or submission guidelines with a help text of:

  This text will be displayed at the top of the page when creating or
  editing content of this type.

Simply put your instructions for the content type form in that field and save your changes.

Example:


How do I retrieve the query parameters from a path? How do I retrieve the query parameters from a path. Here's my path:

/search?keys=hello

Here is what I've tried:
$test1 = \Drupal::request()->request->get('name');
$test2 = \Drupal::request()->query->get('name');
$test3 = \Drupal::service('path.current')->getPath();
$test4 = \Drupal::request()->server->get('REQUEST_METHOD');
$test5 = \Drupal::request()->query->get('q');
$test6 = \Drupal::request()->request->get('keys');
$test7 = \Drupal::request()->query->get('keys');
$test8 = \Drupal::request()->query->get('destination');
$test9 = \Drupal::request()->request->all();
$test10 = \Drupal::request()->getRequestUri();

Here are the results:

Test 1: NULL
Test 2: NULL
Test 3: '/search'
Test 4: 'GET'
Test 5: NULL
Test 6: NULL
Test 7: NULL
Test 8: NULL
Test 9: array ( )
Test 10: '/search'

Why is this not working?

The problem was the block was cached.  See Clive's comment:

public function build() {
  $test = \Drupal::request()->query->get('keys');
  return array(
    '#markup' => $test,
    '#cache' => array(
      'contexts' => array(
        'url.query_args:keys',
      ),
    ),
  );
}


How get access special field value? I want to get access to a special field value, do some processing or manipulating on it and then place it back in theme. For example, I've created a custom content type that name is "News" and has a field with below properties:

label: News Number
machine name: news_num
value: Number (float)

I did content-type node theming with name node--news.html.twig, Now I want to understand Is there any preproccessing hook to modify or altering the field value and in addition I want to learn right way for manipulate the field value, I wrote something like below code:

ThemeName.theme:

function ThemeName_preprocess_node(&$variables) {
// Get access to field value:
  $value = $variables['node']->news_num();
/**
* Makeing some manipulation on $value here.
*/
  $variables['value'] = $value;
}

The type of operation is not really important; I'm most looking for a solution to learn standard method and general format to access and modify the field value.
I just want to overview the field value (alter the field value before rendering) and not doing any override or change the field value in the database.

Any suggestions?

I suggest you two solution one based on what you tried to did

First solution

in yourthemename.theme

if ($variables['node']->getType() == 'YOUR_CONTENT_TYPE') {
    $variables['My_Field'] = $variables['node']->get('YOUR_FIELD')->value;
  }

and in your custom node template

   {{ My_Field }}

  Tips: Those of "YOUR_CONTENT_TYPE" and "YOUR_FIELD" are
  machine names for your content type and your content field.

Second solution

in your content type node template file ( I mean if your content type name is News in node--news.html.twig) try to add your custom value to it with:

  {% set My_Field = node.YOUR_FIELD.value
      {# Make your manipulation here #}
   %}
   {# And then print it back wherever you like with below code: #}
  {{ My_Field }}


Removing Divs of form elements with profile2 fields I want to remove the extra divs that get added like in the following example (user-register-form):

    phone number *
    <input class="text-full form-text required" type="text" id="edit-profile-parent-field-phone-number-und-0-value" name="profile_parent[field_phone_number][und][0][value]" value="" size="60" maxlength="255" />

I already did YOUR_THEME_form and YOUR_THEME_form_element in template.php to get rid of extra divs. But this only works for the standard fields of a form it seems.

I am using profile2 and profile2_regpath modules and it seems as if they add themselves extra divs for the fields that are specific to the profile fields. But I can't figure out how to overwrite this behavior.

Any help or hint appreciated.

And just in case it is already written somewhere: I used the search function and could only find the standard solution for normal fields. Nothing specific to profile2 module.

Oh and some details: I'm using Drupal 7. If anything else is needed, please tell me.

Thank you, best regards.

You can use a theme_field override to adjust the field markup.

e.g, for body field on article content type:

Copy theme_field to template.php
Rename function to THEMENAME_field__body__article($variables)
Clear theme registry cache
Modify theme function markup to suit.

Note, the theme function naming convention required the "field_" prefix on field names, e.g THEMENAME_field__field_example__article()


What linux user accounts should be created prior to Drupal 7 install? When preparing to install Drupal 7 on a clean linux installation (Centos 7 in my situation), what linux user accounts should be created?

I ask this question because I seem to be having problems with file permissions or ownership when installing new modules with Drush.  When I do so I get an error like the following:

... /sites/all/modules exists, but is not writable. Please check directory permissions.

I only have 2 linux accounts on this system, root and myself, and typically run Drush as myself rather than root.  I have run 'Drush fp' to fix file permission problems, but this error persists.

So what linux accounts besides root should be created for use with Drupal and what should the user file permissions be?  Thanks

With your own user is enough.

If you want know how setup permissions check securing file permissions drupal community doc. It's referenced in this related issue.

In that specific case (setting up permissions for modules folder), it says the following:

  drwxr-x--- 32 greg-user   www-data    4096 2008-01-18 11:48 modules/

Now docs examples are for D8 but it works for D7 too.


Is it possible to use random submission number for webform? In order not to let users know how many webforms are submitted, can the $sid config to increase by a random range?

You are probably looking for something like Webform Submission UUID module:

  This module provides a UUID integration for Webform Submissions

UUIDs are hashes that looks random and are not based on submission order, so they would meet your need. Note that this module is in dev version only, so you can expect errors. On the other hand it's GPL, so you can use it as an example how to interact with submission IDs.


How to configure CkEditor's styles dropdown? I have made changes to the configuration of CKEditor for the basic_html rule set as follows:

When I then try to use the editor, however, I get the following:

I have tried clearing the cache multiple times.
I have tried rebuilding the cache with drush cache-rebuild.

Is there something else you are suppose to do to be able to configure CKEditor in Drupal 8?

1. Your Custome style should be present in your CSS file. 2. Your FILTER SETTING should be proper. To check, same way as yours, I just enabled style and and put h1.heading-a|Title(which I took from css/base/elements.css for example purpose) in style dropdown and and it did show up as shown in the second image.

Second Image

Hence, the issue is, to properly put the Class|Key in the Styles dropdown section and make sure that it is available in CSS.

Later to check custom one, I did put h2.myclass {color: red} in elements.css and saved and cleared cache. And as you can see it showed up in following image

UPDATE-1: FILTER SETTING

Now the reason why, Horizontal line and Underline iCon are not visible as you have stated in your comment. For that you need to check the FILTER SETTINGS. Have you played with Limit allow HTML tags and correct faulty HTML list which you can see at the bottom of the basic HTML setting page as shown in following image. If you delete
 from the list the icon will not shown up. Just I checked, if I remove
 form list the icon also gets disappeared.

And your Enable filter setting should be as shown in following image.


Restrict product availability to certain languages/countries in Commerce I need to make a commerce shop where certain products (containing alcohol) should not be available to a certain country/language. How to do this?

Jonas

I am assuming you have shipping enabled for your site. In that case, you can add a country field to your product display, say "Unsupported countries". And while creating a product, you can chose countries for which you are not going to sell. On checkout, add a rule to compare this field's value and the shipping address and If the shipping country is one of unavailable country, show a message and re-direct to cart page asking them to remove this product from their cart.


Different order for cart product I have using Commerce Kickstart and Commerce Marketplace. I have added 2 products into the cart (products from different stores).The problem is when I taken review order page it shows as different order, also different order created. What is wrong with me.I wish to add these two product as the same order.

It sounds like you have something misconfigured. With the Marketplace module, you'll actually have 3 orders created. One is a Marketplace Order and one is a Store Order. It appears that your Store Orders are being displayed instead of the Marketplace Order. Check your pane configuration and ensure that you've enabled the proper marketplace modules and that your Views are showing the Marketplace Order.


Multi-media files not showing Uploaded multi-media files to:

public_html/sites/default/files

no error messages
permissions: 0775
files do not appear (in Content, as do files uploaded through the media editor)

Switching from Wordpress to Drupal.  New to Drupal.  Not a programmer.  It would take a long time to upload 1,000+ files through a media editor.  How do I get Drupal to see these files without uploading them one-by-one?

You need to tell Drupal about your files somehow.

You could write a script yourself.

Another approach would be to use the archive upload of File entity, but you won't be able to upload hundreds of them in a single archive either, the file will simply get too big.

Maybe there is also a module for this, but it's likely not available yet for Drupal 8.


How to prevent admin role from changing "Updated date" of content The updated date of the content is displayed on each node with this code in template file.

<?php print strftime( "%Y-%m-%d", $node->changed) ?>

Now when I save the content with admin role the date displayed is the date I updated (of course). But I only want to display the date updated by the author of the content. So how can I prevent admin role from changing "updated date" and only keep the date updated by the content author?  Or is there a way to display only the updated date by the author of content?

You can't really, it's hard coded into the node_save() function with this bit of code:

$time = time();
if (empty($node->created)) {
  $node->created = $time;
}

// The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
$node->changed = $time;

Short of implementing your own node form which bypasses node_save() there's not really much you can do (except hacking the core node.module file which is never advised).


Fatal error: Call to undefined function entity_view_mode_prepare() /sites/all/modules/field_collection/field_collection.entity.inc on line 600 I get this error as I was doing my work. How do I fix this fatal error?

  Fatal error: Call to undefined function entity_view_mode_prepare() in
  .sites/all/modules/field_collection/field_collection.entity.inc on
  line 600

This error has been removed in latest drupal 7 versions. Please upgrade your drupal core version to the latest.

OR
Temporary solution:
Copy and paste the below function in includes/common.inc file

function entity_view_mode_prepare($entity_type, $entities, $view_mode, $langcode = NULL) {
if (!isset($langcode)) {
$langcode = $GLOBALS['language_content']->language;
}

// To ensure hooks are never run after field_attach_prepare_view() only
// process items without the entity_view_prepared flag.
$entities_by_view_mode = array();
foreach ($entities as $id => $entity) {
$entity_view_mode = $view_mode;
if (empty($entity->entity_view_prepared)) {

  // Allow modules to change the view mode.
  $context = array(
    'entity_type' => $entity_type,
    'entity' => $entity,
    'langcode' => $langcode,
  );
drupal_alter('entity_view_mode', $entity_view_mode, $context);
}

$entities_by_view_mode[$entity_view_mode][$id] = $entity;
}

return $entities_by_view_mode;
}


Putting multiple Add to cart links / buttons on a page I'm writing a series of blog posts on my eCommerce site. For example, "10 easy breakfasts for the busy mom/dad". Under each "breakfast idea", I want to put a small block like "Items you'll need". This "items you'll need" will have links to products in our shopping site.

The idea is that if someone likes a blog post or one of the "receipes", they can immediately click on the products below and add them to cart. I don't want them to be taken away from the page they are reading though, because that would be annoying.

They will need some indication that the product was added to cart, so maybe a green tick or "Added!" label will need to show up.

When you get to bottom of the blog post, there should be a block "Products you have in your cart" so that they review and can choose to check out if they want.

I've found these articles & modules:

Creating Drupal Commerce add to cart links
,

Commerce Add to Cart Ajax,

Custom Add to Cart Link

But I'm not sure which is the way to go considering my requirements:

Curated product links / thumbnails in blocks
Clicking sends ajax signal to cart to add product
There is an indication that the product was added "Added!" or a tick or border highlight.
If the same product is on multiple blocks in the page, when I click one block, it should update on all the blocks.
Ajax stuff should be robust on mobile devices

I've never done this before, Drupal ajax & custom cart stuff, so I wanted to ask your advice on what to consider before moving ahead. I want to do it in the simplest and most robust way possible. If I can avoid custom code and sandbox code, that would be ideal. Thanks.

jQuery is our friend.

Create a DIV for every product that will perform an ajax request (on click) to a path that will update your cart and then retrieve the cart contents. Ex. /ajax/cart?op=add&pid=idOfProduct

Create a path (hook_menu) where you will send the add to cart message or other messages that you want to send to the cart (item removal for example).

This path will update the cart to your needs based on the parameters you send it.

The response of the path could be in full HTML for simplicity, with the updated and already rendered cart.

Replace the current cart with the new contents. It's not simple but it will work.

Hope that helps!


Why are `drush pm-list` & `drush pm-updatestatus` disabling the default theme? I have a Drupal 7 site with 3 themes enabled:

Foo
Adminimal
Shiny

Foo is a custom theme for the front-end, located in /sites/foo/themes/ and set as the default.

Adminimal and Shiny are both installed via drush make into sites/all/themes/contrib/.

Running drush pm-updatestatus disables the default 'Foo' theme.

$ drush pm-updatestatus
Checking available update data ...                             [ok]
Failed to check available update data for Foo settings.        [ok]
Checked available update data for Administration menu.         [ok]
...
Checked available update data for Adminimal.                   [ok]
Checked available update data for Shiny.                       [ok]
Failed to get available update data for one project.           [error]
Checked available update data for 64 projects.                 [status]
 Name                                                        Installed Version  Proposed version  Message
 Administration menu Adminimal Theme (adminimal_admin_menu)  7.x-1.6            7.x-1.7           Update available
...
 Adminimal (adminimal_theme)                                 7.x-1.21           7.x-1.24          Update available
 Shiny (shiny)                                               7.x-1.6            7.x-1.7           Update available

The Failed to check available update data for Foo settings. & Failed to get available update data for one project. [error] lines from the output clearly look relevant, but I'm struggling to identify the underlying cause.

With the Drush's -d debug flag enabled the output includes this line before the Failed to get update data for on project [error]:

Undefined index: foo theme.inc:100 [1.78 sec, 35.7 MB]            [notice]

drush pm-list has the same effect.

Presumably there's something wrong with the declaration, or location of the Foo theme?

Checking the status report via the Drupal admin does not disable the Foo theme.

Why would drush pm-list & drush pm-updatestatus disable the default theme?

Your themes for Drupal 7 should live here:

/sites/all/themes/THEMENAME - for all sites and all themes
/sites/example.com/themes/THEMENAME - for example.com of a multisite setup

Now in your case there is an additional note: You have the option to put your theme in a contrib and a custom subfolder. Themes in the custom subfolder would be skipped during the update process (see /r/drupal for cross reference). There is a caveat though: Apparently once you use contribyou also have to use custom otherwise it seems the whole tree breaks (see disqus)

Try to move the foo theme too: /sites/all/themes/custom/foo or /sites/example.com/themes/custom/foo then run drush rr and drush cc all


Edit display of commerce kickstart shopping cart How can I display the output of a view in a menu?

I made a views that displays the information I want correctly but I don't know how to display the  as a block in a menu. I've tried Menu attach blocks and Menu Views but couldn't get it to work.

Is there another option?

Solved with the Menu Minipanels module. Here is a quote from its project page:

  A system for building "megamenu" -style dropdown menus using Mini Panels, which provides tremendous flexibility in what can be displayed.

The project page also points to an interesting Click-by-click beginner's tutorial


sync drupal users to open ldap We can find many discutions on how to sync ldap to drupal, or use ldap to auth drupal users, but my goal is totally different :

My goal is this :
Use drupal to manage user accounts (add/edit/delete users), then
use LDAP to share drupal users with an other website (redmine)

So the idea is that drupal send users to LDAP then redmine website use LDAP for login.

Drupal users don't have to ssh login into my server of course...

I've found no doc, no tuto on how to setup drupal LDAP module to match with my use case. So here i am.

Considering :
I have installed openldap on my debian server, and also ldap authentification module in drupal. More over i have setted up drupal and can querry my ldap server from drupal admin panel.

Questions :

1) Is there a doc or tuto somewhere explaining how to sync drupal users to LDAP?

if no

By default posix user template contains useless attributes for me, like homedirectory or loginshell

2) So, do i have to define LDAP templates to match with drupal?

3) i've made some tests to sync users, but drupal display no info, what is going wrong? how to debug?

after one day, i finnaly figured out how to :)

I've first found some help on those both discutions :

a)https://www.drupal.org/node/1920682 (see kenorb answer)

b)Create a new user in LDAP, not wherever Drupal normally creates it (see kernorb answer again)

HOW TO :

1) from LDAP server create manually an inetOrgPerson account (in phpldapadmin it is called a "Courier Mail Account") , let's call it 'myuser'

next steps will be done in drupal admin=>configuration=>people=>LDAP configuration

2) setup LDAP server, and test it (see links above for further details)

3) again in server test page, set myuser into 'Testing Drupal Username' field.
Start the test, then copy somewhere 'testing_drupal_user_dn' value from test result.

4) now 2 things must be done :

a) choose a user schema, inetOrgPerson is a good schema for drupal as it contains email, username, and password fields

b) find witch fields are requiered by your LDAP server for this schema

so search on google [NameOfTheSchema] [NameOfYourLdapServer] attributes

(e.g : "inetorgperson openldap attributes")

then note witch fields are marked as requiered.

for example i found this :
http://www.openldap.org/lists/openldap-software/200001/msg00079.html

there we see that

objectClass, sn, and  cn are marked as required

To resume, you have now noted somewhere: the dn (step 3) and the required field (this step)

c) now, how to set objectclass?
get back to phpldapadmin, display 'myuser' account that you have manually created, then click on export =>LDIF

as example here my result :

# Entry 1: uid=myuser,ou=drupal,dc=mydomain,dc=lan
dn: uid=test1,ou=drupal,dc=mydomain,dc=lan
cn: myuser
description: my description
mail: email@email.com
objectclass: inetOrgPerson
objectclass: top
sn: myuser
uid: myuser
userpassword: mypassword

it is important to respect the order of objectclass fields. In my case i'll have to set in drupal :
UserToken => inetOrgPerson=> [objectclass:0]
UserToken => top => [objectclass:1]

5) go to admin=>configuration => LDAP configuration => user
then "Basic Provisioning to LDAP Settings" section

Check all checkbox into "LDAP Entry Provisioning Events "

Now fill the table bellow

For each line created, you'll have to check both "ON LDAP ENTRY CREATION" and "ON SYNC TO LDAP ENTRY" collumns

a) You MUST have a line with [dn] as target, this is here that you use the dn retreived in step 3.

Example :
i had this : testing_drupal_user_dn = uid=myuser,ou=drupal,dc=mydomain,dc=lan

so i add this line :

--user tokens-- => uid=[property.name],ou=drupal,dc=mydomain,dc=lan => [dn]

b) You MUST set objectclass lines . If we refere to my result in step 4) c) , i have to add 2 lines :

--user tokens-- => inetOrgPerson => [objectclass:0]
--user tokens-- => top => [objectclass:1]

c) you MUST add as many lines as there is required fields in the schema. If we refere to my case step 4) b) i have to setup objectclass , sn and cn, so i have to add two more lines :

Property:UserName => => [cn]
Property:UserName => => [sn]

To Resume :

3 steps to follow :

Setup connection to LDAP server then test it
Give a correct path to user entries (path is called DN with lpda)
Choose a user schema (inetOrgPerson is a good one) and fill all fields required by this schema (this is specific of your LDAP server so refere to its doc)

How to test :

in admin=>configuration=>people=>LDAP configuration=>Settings , check " Enabled Detailed LDAP Watchdog logging.", then edit a user in drupal to trigger the sync with LDAP (assuming you followed my howto). when you save an user in drupal, you'll see an LDAP error message if something goes wrong.


Additional twig suggestions for menus Unlike other elements, the base twig suggestions for menus are only "menu.html.twig" and "menu-[menu_name].html.twig".

I am aware that I can generate additional suggestions through the hook THEME_theme_suggestions_menu_alter, but the $variables array does not contain any useful data. Case in point, I want to retrieve the current region, is it possible?

All steps described here work for me with some minor modifications.

GOAL: show main menu in both header and footer region, but use a different template file for both (based on their region).
PREMISE: your theme has regions (like header and footer) and you have used the drupal block system to place the main menu in both your header as in your footer.

I did this in mytheme.theme file:
Dont forget to add the Block use statement in the beginning of your .theme file:

use Drupal\block\Entity\Block;

Now here's the magic for region based menu templates. Also inside your .theme file:

/**
 * Implements hook_preprocess_HOOK().
 *
 * Pass block region value to content so this can be used in
 * MYTHEME_theme_suggestions_menu_alter.
 */
function MYTHEME_preprocess_block(&$variables) {
  if (isset($variables['elements']['#id'])) {
    $region = Block::load($variables['elements']['#id'])->getRegion();
    $variables['content']['#attributes']['region'] = $region;
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * Provide region based menu suggestions.
 */
function MYTHEME_theme_suggestions_menu_alter(&$suggestions, array $variables) {
  if (isset($variables['attributes']['region'])) {
    $suggestions[] = 'menu__' . $variables['menu_name'] . '__' . $variables['attributes']['region'];
  }
}

RESULT when inspecting the main menu inside the header:

<!-- FILE NAME SUGGESTIONS:
* menu--main.html.twig
* menu--main--header.html.twig
* menu.html.twig
-->

RESULT when inspecting the main menu inside the footer:

<!-- FILE NAME SUGGESTIONS:
* menu--main.html.twig
* menu--main--footer.html.twig
* menu.html.twig
-->


Alter submitted by text and retain RDF tags I am looking to change the submitted by text from:

Submitted by author on Sun, 20/03/2011 - 22:54

to:

Date posted: 20 March 2011

I know how to alter the text in node.tpl.php but I do not know the function that will return the date formatted with the RDF tags around it. Does anyone have experience in this area?

The function that returns the content of that tag is date_iso8601().
To understand how those tags are output, you should look at rdf_preprocess_node() and rdf_process().


IMCE and user privileges I have a taxonomy like this in our Drupal 7 website.

(Group1)
 |
 +---- (Group1SubGroup1)
 +---- (...)
 +---- (Group1SubGroup10)

(Group2)
 |
 +---- (Group2SubGroup1)
 +---- (...)
 +---- (Group2SubGroup4)
 ...

And we've use a module (I dont remember the name) that gives users rights depending on the term. For example, for user1 we give him CRUD rights on Group2SubGroup4, but nothing on Group2SubGroup1.

There's a shared directory where you can upload media files when you create an article.

So, when the user1 want to create a new article with term Group2SubGroup4, we'd like to  give him rights to upload a file, but only in a sub-directory of the "shared multimedia files directory" called Group2SubGroup4.

For example if the directory is /www/htdocs/multimedia, when the user1 want to create a new article with term Group2SubGroup4, he will have rights to upload multimedia files but its "base" directory will be /www/htdocs/multimedia/Group2SubGroup4

How would you do this?

And if you have an easy solution for this, I'd like to do more: have the rights to write on the right directory (/www/htdocs/multimedia/Group2SubGroup4) and still the possibility to read everything else (/www/htdocs/multimedia and other subdirectories). How would you do this?

The solution was easy: it's already integrated in Drupal. Just activate the media module and go to Administration->Configuration->Media and there's a very, very, very²²³ powerful IMCE configuration panel.


Get referenced node fields in twig where reference is on remote node only I have a reference field with reference on node 2 to node 1.

On node 1 I want to find those nodes node 2 with reference to node 1.

How can I access those in twig?

Your node is unaware of the fact that it is referenced by other nodes. So you need to query the nodes that are referencing your node in a preprocess hook:

/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $storage = \Drupal::entityTypeManager()->getStorage('node');
  $nodes2 = $storage->loadByProperties(['field_reference' => $node->id()]);
  $variables['nodes2'] = $nodes2;
  $variables['#cache']['tags'][] = 'node_list';

}

Then you can use the nodes you've found in Twig directly:

{% for node2 in nodes2 %}

This node is referenced by {{ node2.label }} ({{ node2.id }})

{% endfor %}

Rendering of the nodes

Or better build a entity view of those nodes by specifying a custom view mode, which you have configured to display the fields you want:

if ($nodes2) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $nodes2_rendered = $view_builder->viewMultiple($nodes2, 'custom_view_mode');
  $variables['nodes2_rendered'] = $nodes2_rendered;
}

and render those nodes in Twig:

{{ nodes2_rendered }}


How do I link menu to certain section in one page theme? How do I link menu to certain section in one page theme?

What is the path should I add if "about" menu link to "about" section?

The single page is combination of different blocks.

You can do this by giving path of your menu to id of that block. BUT there is a problem, Default Menu path in Drupal will show you invalid entry as ID of the block are not real path so it is not allowed.

To solve this Void Menu module comes in picture,

Follow following steps:

Download and enable the Void menu module.
Get your block-id by inspecting the HTML.

Go to Modules/Void menu/Configuration, in the section of <void1> save the Id of that block e.g. I have a id="block-block-4", so I will paste #block-block-4 and save it.

Go to Structures/Menus/Your menu/About link, In the path just paste <void1>, save it.

Now, you are good to go, when you will click that about menu link it will scroll you down to that block on same page.

Note: In  Drupal-8, You do not have to do anything, just save the Id in path, and that's it. This feature is provided by default in  Drupal-8.

JQUERY Effect

Till above procedure it is just fine, you can go ahead with that. BUT if you want the Smooth JQUERY effect like whatever is provided in your example website.

Just download Scroll to destination anchors, enabled it, That's it. Now it will Scroll down with smooth Jquery Effect.


Dynamic dependent form select inputs I'm building a custom dependent dropdown form with 2 select inputs.

I've managed to build the form inputs and update them accordingly, but I'm not able to get the dependent select's value in the submit hook.

I think this happens because I changed (via AjaxResponse()/ReplaceCommand) the $form in the AJAX callback, and as such, the second input values aren't updated in the $form_state.

My problem is that I have no simple way of knowing which options will be available either in the first-level select nor in the dependent select, since they come from a 3rd-party API.

Is there any way I can trigger the update of the #options in the dependent select, without having to render the nested dropdown and changing the $form so that the nested values are available in the submit hook?

Or, alternatively, is there anyway I can update the $form_state so that it knows the newly added #options of the second select?

With @4k4's help I managed to find the root cause of my issue and fix it.

I was wrongfully assuming that the $form elements could be somehow modified in an AJAX call to produce my desired effect.

While it is true that the elements could be modified and re-rendered in an AJAX response, that is not the correct way to alter a form after an AJAX call.

The 2 main things to know are:

forms are rebuilt everytime an AJAX call is made (when it is declared in the #ajax array of the form element triggering the call)
the AJAX function being called should (ideally) only return the element suffering modifications. It cannot modify the $form in any way, otherwise those modification will either be lost when it is rebuilt, or trigger the An illegal choice has been detected. Please contact the site administrator. message.

This being said, the general flow for this should be:

create the buildForm function with code that builds both your select elements. Wrap in a conditional clause code that tests if the parent select was already changed or not. This will be used to determine if the nested select should be populated or not;
set an #ajax property in the parent select element of the form, referring a callback to be used;
define the callback to return only the element which needs to change in the form, ie, the nested select;
when Drupal tries to rebuild the form, your parent select will already have a value that can be used in the above mentioned test-clause to allow for population of the nested callback.

@4k4's suggested documentation was difficult for me to find, but clear enough to follow trough once found - link here. (Even though it is for Drupal 7, in Drupal 8 it functioned exactly the same way).


How can I display the Google rich snippets when a view is on "Show: fields" and the panel enabled? I am building a site using Drupal 7 and the schema.org module and the microdata module.
The site is live on production server (and works good).
When checking a url from my site site on the google rich snippets tool, I can't see all the fields I want to appear in the snippets.
When using panels, views, microdata module and schema.org module -
the snippets does not work.
When I deactivated the microdata module, and disabled the specific panel on the page the snippets work! So, I decided to disabled the microdata module, and work only with the schema.org module.
With the the schema.org modules:

When views is on "show: content" and the panel Enabled - snippets work!

When views is on "show: fields" and the panel Disabled - snippets work!

When views is on "show: fields" and the panel Enabled - snippets do NOT work!
Can I use the Rewrite option on a view to add some code to fields and make it work?
How can I display the Google rich snippets when a view is on Show: fields and the panel enabled?

I see that you are using views fields mode for populating the values. That might be the issue.

In your overall HTML check that an entry for itemtype="http://schema.org/Recipe"> is present. In your current html I feel you wouldn't have this. If that is the case then change the mode in your views to node from fields.

Then recheck your HTML and you should find the entry. If you do find the entry then the reason is that your fields(in old view mode) are not enclosed within a recipe tag.

In the above case you can install schema tokens module and then in your fields view, hide all the fields and then add a Global text field within which you can use these tokens to get the desired output.


Preprocess node in module It's more general question. Just to clarify. I can use preprocess function in my template.php file in a way:

function mytheme_preprocess_node(&$vars) {
  // Do some stuff
}

But is there a way to preprocess node in a module? I've been searching for function hook_preprocess_node() in drupal API, but there's no such function for D7, although it does exists for all other versions of drupal, including 8. May I treat template_preprocess_node() as a function which I can use in my module? For example, if my module has name 'custom' then can I use it this way?

function custom_preprocess_node(&$vars) {
  // Do some stuff
}

How can I override node in custom module?

In Drupal7, both modules and themes are able to use preprocess functions in the same way, and a given theme hook can have many preprocess implementations, originating from both modules and themes.

As with anything like this in the Drupal framework, knowing the order in which these functions run is important. Preprocess implementations from modules run first, and implementations by themes run last.

A quick search of Drupal core modules will give you examples in the node and rdf modules.


how to delete the nodes having a specific entity reference but not the parent I have a content type "students" and another "courses".
Student nodes are created with an entity reference to a course node.

I need to delete all students of "couses123" in a quick way.
How can I make a view which has a dropdown of all course names and when selected it shows list of all students.

From there, I can use the VBO to show a checkbox next to them for selection and deletion .

How can I achieve this?

If this a one-time need, you could build a custom query DB query if you wanted to go the developer route. However, if this is an ongoing need you're better off with the site builder route you've hinted at in your question.

In your case, you want to a create a node view filtered by content type Students. Add a Entity Reference: Referenced Entity for the field that contains your references to Courses. The last step is to add an exposed filter for the same Courses field making sure enable relationship that you added; that will present a select list of referenced Courses from which you can filter down the Students and present your VBO delete widget.


Sending notifications to users from other users dependent on certain conditions Is there a way to alert users of the content in a node field? I'm trying to get users to be able to mass message other users based on certain taxonomy terms they're selecting as part of their login process.

So essentially the process (as I'm envisioning it, but I'm open to other methods) would work like this:

User1 selects a county as part of their profile creation.

User2 wants to send an alert to all users that are signed up to that county.

They create a node with the content type, "Alert", which consists of the title, the actual alert information (a text field), and a county.

This is then sent to all users (i.e. user1) with that county.

My guess would be to use the notification and messages modules, and have a user subscribe to a given taxonomy term(s). I'm only seeing how to send messages on content update/creation though, not the actual content of the node.

Are there any solutions for this problem (one to many communication between users dependent on certain criteria)

I put a hierarchical taxonomy term in a user profile, and then had rules send to any user with that county selected.


How to disable the title field in a content type? i'm using drupal 7
How to disable the title field in a content type?

I think the Automatic Nodetitles module is what you're after:

  "auto_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.


How to refresh all views in Panels with a time interval without page refresh? I have some views that I want to refresh in a time interval (15sec) OR if there is changes in the content. For that I tried to use module "Views Auto Refresh". It works fine for a time interval but only if I have one view in a page.

If I have multiple views inside a panel (using Panels module), only one of the views is refreshed.

Is there any other way (module or custom code) to achieve this behaviour?

Thanks!

EDIT: As suggested, I tracked the ajax requests. In my case I'm refreshing every 15seconds. In a panel with 2 views I notice that I have only one request every 15sec, should I have two?!?!? Anyway, below is the piece of code I get when clicking in the function in red in the picture (I think is this one). The debug highlights the following line:

$(anchor).trigger('click');

Drupal.views_autorefresh.timer = function(view_name, anchor, target) {
  Drupal.settings.views_autorefresh[view_name].timer = setTimeout(function() {
    clearTimeout(Drupal.settings.views_autorefresh[view_name].timer);

    // Turn off "new" items class.
    $('.views-autorefresh-new', target).removeClass('views-autorefresh-new');

    // Handle ping path.
    var ping_base_path;
    if (Drupal.settings.views_autorefresh[view_name].ping) {
      ping_base_path = Drupal.settings.views_autorefresh[view_name].ping.ping_base_path;
    }

    // Handle secondary view for incremental refresh.
    // http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object
    var viewData = Drupal.settings.views_autorefresh[view_name].ajax.submit;
    var viewArgs = Drupal.settings.views_autorefresh[view_name].view_args;
    if (Drupal.settings.views_autorefresh[view_name].incremental) {
      if (!viewData.original_view_data) viewData.original_view_data = $.extend(true, {}, viewData);
      viewData.view_args = viewArgs + (viewArgs.length ? '/' : '') + Drupal.settings.views_autorefresh[view_name].timestamp;
      viewData.view_base_path = Drupal.settings.views_autorefresh[view_name].incremental.view_base_path;
      viewData.view_display_id = Drupal.settings.views_autorefresh[view_name].incremental.view_display_id;
      viewData.view_name = Drupal.settings.views_autorefresh[view_name].incremental.view_name;
    }
    viewData.autorefreshRequest = 'autorefreshRequest';
    Drupal.settings.views_autorefresh[view_name].ajax.submit = viewData;

    // If there's a ping URL, hit it first.
    if (ping_base_path) {
      var pingData = { 'timestamp': Drupal.settings.views_autorefresh[view_name].timestamp };
      $.extend(pingData, Drupal.settings.views_autorefresh[view_name].ping.ping_args);
      $.ajax({
        url: Drupal.settings.basePath + ping_base_path,
        data: pingData,
        success: function(response) {
          if (response.pong && parseInt(response.pong) > 0) {
            $(target).trigger('autorefresh_ping', parseInt(response.pong));
            $(anchor).trigger('click');
          }
          else {
            Drupal.views_autorefresh.timer(view_name, anchor, target);
          }
        },
        error: function(xhr) {},
        dataType: 'json',
      });
    }
    else {
      $(anchor).trigger('click');
    }
  }, Drupal.settings.views_autorefresh[view_name].interval);
}

I have done this in the past with the help of Views Auto-Refresh

Try the module and let us know if it work.


Can I find the term depth via $node without resorting to a taxonomy_get_tree or an SQL query? I'm trying to find all terms in a vocabulary associated with the current node, that do not have any children.

The most obvious way might be to use taxonomy_get_tree() and match with the returned array to find the childless. Another way is to use a function like this one, and it involves a MySQL query. While my current taxonomy is small and the performance concerns are minimal, I would like to avoid this if this info is already available somewhere.

So, how can I find the depth of a taxonomy term, in a more performance friendly way?

The data for taxonomy is in the database. If you want to get that data there is no way to do so without running a database query.

Any function that retrieves this data (including taxonomy_get_tree() and the function you link to above) has to run database queries to get at the data.

taxonomy_get_tree() is a bit heavy so I'd advise using the term_depth function you link to. If you want to increase performance slightly you can improve that function to offer a static page load cache. This will only make a difference if you call the function more than once in a single page load though:

function term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_result(db_query("SELECT parent FROM {term_hierarchy} WHERE tid = %d", $tid));
    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + term_depth($parent);
    }
  }

  return $depths[$tid];
}

Short of building your own cache mechanism that doesn't rely on the database (which would be a massive amount of overkill for this situation) I don't see any way of making this more performant.


How do I do a simple GROUP BY? I've got a view which represents a list of redirects. The view has two fields:

'Destination'
'Source'
'Hash' (an indexed has based on the destination)

I'd like to generate a view which lists destinations along with the number of times a visitor has been redirected to that destination. If I were to write the SQL myself, I'd simply do:

SELECT destination, count(*) as redirects FROM redirects GROUP BY hash

However, no matter what I do I can't get Views to ONLY group by hash. This is what I've done:

Enabled aggregation (Advanced > Aggregation>
Enabled COUNT on the 'source' field.

What happens now is that Views COUNT on the 'source' field, but groups on both the 'destination' AND 'hash' field:

SELECT destination, hash, COUNT(source) FROM redirects GROUP BY destination, hash

How do I get Views to only GROUP BY the 'hash' field?

I am not 100% sure but I would suggest you simply do the following:

Choose Format = Table
Then click on the settings for Table
Change the grouping field to the "hash" field

Then aggregate the results based on the destinations.

However, when you use the redirect module in Drupal 7 there is a field available called "Redirect: Clicks". I wonder if this may help you.

I hope this may helps.


Using AJAX in blockform I'm attempting to allow a user to add text fields by clicking a button in a configuration form for a block plugin. I'm currently populating the form like so:

public function blockForm($form, FormStateInterface $form_state) {
    for ($i = 0; $i < $this->configuration['linkNum_submit']; $i += 1) {
        $form['link'][$i] = array(
            '#type'          => 'textfield',
            '#title'         => 'Link',
            '#default_value' => '',
        );
    }

My form is populated using a for loop that takes into account a configuration field noting the amount of textfields that should be displayed.

I also have a button that's meant to add another $form['link'] textfield by doing an ajax callback.

$form['add_link'] = array(
    '#type'     => 'button',
    '#value'    => $this->t('Add link'),
    '#ajax'     => [
        'callback' => array($this, 'Drupal\my_module\Plugin\Block\LinkList::addLink'),
        'event'    => 'click',
        'progress' => array(
            'type'    => 'throbber',
            'message' => t('Adding link...'),
        ),
    ],
);

Below is the ajax function that is called. It attempts to increase the configuration field the for loop in bockForm is based on.

public function addlink(array&$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $this->configuration['linkNum_submit'] += 1;

    return $response;
}

I believe my issue is that the form isn't being rebuilt, but I'm not sure how to force it to. I found documentation on the rebiuldForm() function here https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Form!FormBuilder.php/function/FormBuilder%3A%3ArebuildForm/8.2.x but I'm not sure how to implement it in this case.

The issue is not about the form rebuild, the form is being automatically rebuilt on every AJAX call.
The issue here is of the wrapper is not being defined in the '#ajax' array and the wrapper attribute should be given to a "container" type of field and then all of the updated fields should be part of the respective "container" field.

or some ajax command should be called on $response object in the ajax callback method above.

e.g.

public function blockForm($form, FormStateInterface $form_state) {

$form['link'] = array(
  '#type' => 'container',
  '#attributes' => array('id' => 'link-wrapper'),
);
for ($i = 0; $i < $this->configuration['linkNum_submit']; $i += 1) {
    $form['link'][$i] = array(
        '#type'          => 'textfield',
        '#title'         => 'Link',
        '#default_value' => '',
    );
$form['add_link'] = array(
  '#type'     => 'button',
  '#value'    => $this->t('Add link'),
  '#ajax'     => [
    'callback' => array($this, 'addLink'),
    'event'    => 'click',
    'wrapper' => 'link-wrapper',
    'progress' => array(
        'type'    => 'throbber',
        'message' => t('Adding link...'),
    ),
],

);

and then in the ajax callback

public function addlink(array&$form, FormStateInterface $form_state) {
  return $form['flipper']['front']['settings']['link'];
}


Changing user edit form I am trying to change my Drupal 8 theme user edit form but can't find a template to override. I want't to make something like this: http://keenthemes.com/preview/metronic/theme/admin_1/page_user_profile_1_account.html

Is it possible? Thank you!

To preface, changing the Drupal user edit forms is not the most straightforward thing to do (when compared to changing the templates for regular site's theme), but it is possible, just as anything else.  Firstly, are you currently using one of the stock admin themes (e.g. Seven)?  If so, you will need to sub-theme that, which is done in the same way as you create a normal theme, then you just configure your site to use that admin theme.  Then, you can override templates.  In the case of the user edit form, it will depend the level of customization you want to do to the form. If you turn on debugging (see https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates), then you will be able to see the templates you need to override at the form and field level.  Of course, if you can do what you need to do with CSS or Javascript (and it's not too kludgey), that is something to consider as well to avoid the pain of having to mess with the generation of the actual markup.


Best way to create outbound link with node field content I am looking for the best way to create a button that I attach to each node's page that directs to an outside site.  The url of the button will information that is in one of the node's fields.
I know this should be easy, but I am still new at drupal....

Thanks in advance

//btw, it's drupal 7.

There are many ways to do it, depending on the field type you are using. The easiest is with the Link or Url field type (link is better as url field is lightweight). You can just set the display formatter correctly, and style it in CSS as a button. If it is in a text field, then you have to output the field in anchor tags setting it as the href attribute value. You can do it in a preprocess node template function in your theme's template file where you rewrite or replace the field value to be an anchor or if you are more of a site builder than a coder then you should look at Display Suite module and use the code field option.

Another easy option is to override the node.tpl.php file for your node type (use the proper override in the naming) and in the template file output the link using the url() function. Depending on the order of your fields you might have to then also hide the field if the content variable is rendered before you need the anchor.

My personal preference is to use Display Suite as it is such a versatile module.


Views Grouped Filters turns Radiobuttons into Select? I have a grouped filter in a view with lets say 3 items. For the Widget i choose Radios and Allow multiple selections. For 3 Items everything works fine and i have some checkboxes. Wenn they are more then 3 items instead of checkboxes there is a select list! But i want to have checkboxes. Even Better Exposed Filters only shows select as an option for that filter.
Whats wrong ?

I  came up with writing a simple hook:

 function  MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
  {
    if ($form['#id'] == 'MYFORMID') {
      $form['field_MY_VALUE_FIELD']['#theme'] = 'select_as_checkboxes';
    }
  }


Exclude Views field from displaying and just print it in field template? I have a field (title) in my View that I want to print in another views field template, using:

print ($fields["title"]->content);

However, when I use the above code, the field now prints twice. So I tried to Exclude it from the display in Views, but then my above print stopped working. How can I exclude the field, but still print it somewhere else??

Thanks for the help

P.S. I am referring to Views fields, not Content Type fields.

Excluding the field from display empties the $field['name']->content, so that when the renderer gets to the default field template, there's nothing to print.

If you absolutely cannot achieve your intended result using tokens and Rewrite Output then I suggest you:

Do as you have already done to print the title in a different field's template
Create a field template for title that is empty


Shipping amount incorrect when hitting "Go back" on checkout I am using Drupal Commerce with Commerce Flat Rate and I have setup various different rates depending on the total order amount.

The normal use case works as expected, however if I am at the shipping checkout pane and I hit go back,hit continue, and then arrive again at the shipping pane again, the shipping amount is recalculated based on the previously calculated (order_total + shipping_cost), not on the original order_total if you know what I mean.

What hook and code should I use to remedy this so that the shipping cost is based on the original order_total the second time around like it was the first time around?

Is it possible to remove the shipping component of the order total on the first checkout page?

Should I try to detect when I am on the first checkout page whether I arrived from the shipping pane, and so try to remove the shipping price component from the order total?

Check out Per Product Shipping Buggy

Import this rule or a variant of it and adapt it to your use case:

{ "commerce_shipping_service_free_shipping" : {
"LABEL" : "Rate Free shipping",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_shipping" ],
"USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
"DO" : [
{ "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
{ "commerce_shipping_service_rate_order" : {
"shipping_service_name" : "free_shipping",
"commerce_order" : [ "commerce-order" ]
}
}
]
}
}


REST resource for specified content type Drupal 8 has a REST resource for all content type "Content" and let us to specified settings for all of content type in admin/config/services/rest/resource/entity%3Anode/edit ,but is globally, I mean if let users post data to Content type, they can Post data to all of  content types  and(But what I need is I don't let them to do this), I didn't find any option to restrict to specified content type.

I also take a look at permission and  RESTful Web Services permission is for "Access POST on Content resource" and there is not any option for content types individually.

I want to know how can achieve this that REST POST feature exists for specified content type(s) and for some content type GET exists and for some content type REST not allowed?

Update(more deatils about what I want)
I want anonymous user can POST  contenttype1 content with REST ,
I give permission to anonymous user to  create contenttype1 content, and
Authentication providerssection I checkcookieandbasic_auth`  methods, but when try to post data with following code it told me authentication required
(I ran this snippet  in browser console )

(function($){

                    jQuery.ajax({
                        url: '/rest/session/token',
                        method: 'GET',
                        success: function (token, status, xhr) {
                            var postData = {}
                            postData.title = [{'value': 'My Basic Page'}];
                            postData.field_enroll_email = [{'value': 'zhilevan@gmail.com'}];
                            postData.type = 'enroll';
                            jQuery.ajax({
                                url: "/entity/node",
                                method: "POST",
                                data: JSON.stringify(postData),
                                headers: {"Accept": "application/json", "X-CSRF-Token": token, "Content-Type": "application/json"},
                                success: function (data, status, xhr) {
                                    console.log(data);
                                }
                            });
                        }
                    });
})(jQuery);

I mean if let users post data to Content type, they can Post data to
  all of my content types and I didn't find any option to restrict to
  specified content type.

Doesn't /admin/people/permissions stop them?

Permission

Basic page: Create new content
Article:  Create new content

  and for some content type GET exists

Don't you have to create a views rest export first before data is available to GET?

You can restrict here by adding a filter of type to your view.


how to get count of total record I'm using drupal pagination here i have add some part of my code pagination is working perfect while I'm trying to get the total no of record it is always displaying 10. As i understand i have set the limit 10 so it displaying only total 10

$query->orderBy('r.published_date', 'DESC');
        $pager = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
    $results = $pager->execute()->fetchAll();

This $results variable I'm getting data with the set of 10 values.

I would like to display total no of data for that i have created other variable where i have directly executed query in $result so it could give total no of records but its not working it displaying only 10

$result = $query->execute();
        while($data = $result->fetchObject()){
           $count_ret[]=$data->published_date;
        }
             $total=count($count_ret);

please  guide me where i'm doing wrong

Until the issue Convert pager.inc to a service is solved you find the pager information still in global variables:

global $pager_page_array, $pager_total, $pager_total_items, $pager_limits;

$count_of_total_records = $pager_total_items[$element];

Where $element defaults to '0' if this is the first pager with no element id set.


Aggregation with count that includes empty field values I saw other questions regarding the aggregation but i didn't found anything similar to what i need.
I've a view with enabled the aggregation, results are grouped by a field value (a text field) with also the count for that field.
Everything is ok, but i'd like to include also the count for the empty values, and i can't make this thing to work...
Now i've something like

| FIELD VALUE | COUNT |
|-------------|-------|
| value 1     | 10    |
| value 2     | 3     |

And i'd like to have something like

| FIELD VALUE | COUNT |
|-------------|-------|
| value 1     | 10    |
| value 2     | 3     |
| -empty-     | 5     |

Is there any way to achieve this? i tried writing something like "-empty-" in the no results behaviour, but the only thing i manage to have is a line with always the counter to 0, like

| FIELD VALUE | COUNT |
|-------------|-------|
| value 1     | 10    |
| value 2     | 3     |
| -empty-     | 0     |

I really don't know what to try now..
Thanks!

I've not found a way to do this thing, but if any other needs something similar, i end up using Computed Field to handle this case, so i can store the actual field value normally, or another text (in my case 'Not filled').

Using this computed field instead of the actual field makes everything works...

But i'm open to change this thing if there's a better way to do this, as this sound a bit hacky...


Multiple instances of a field, differently formatted - how? And if I wanted a particular field displayed on a node twice, but each instance built with a different formatter - what should I do?
Example: a term reference field - formatted as plain text at the top, and as a link - at the bottom of a page.

I would use Panels. You can add each field as many times as you want and pick a different formatter every time.

Install the Chaos tool suite (ctools) module, and Panels.
Enable the Page Manager and Panels.
Enable the node template
Create a variant of type "Panel".
Pick a suitable layout.
Go to the "Selection rules" settings and add a "Node:type" setting so this is used for a single node type.
Add your fields and select your formatters.
Save

Using Panels requires a bit of understanding of the tools it provides. There are a few videos here.


Transliteration- Is it possible to transliterate filenames (and update the DB) after files have been uploaded? I have a website that allows users to upload pictures.  To reduce the amount of space used by pictures files on my site, I attempted to use a script to remove orphaned files.  However, this script chokes on Unicode file names; there are dozens of pictures with Unicode file names on my site:

  query:You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 's Adorable Kitty EDIT.jpg'' at line 1

I have enabled the Transliteration module so that new files will not have this problem.  However, what can I do about the old files?  Is there a way to change their names and update the Drupal DB?  I am willing to do this manually if necessary, but I don't know how to approach this.

EDIT: Upon closer inspection, the problem is not unicode, it's the quote marks in the filename.

As far as I am able to tell, the script works OK with Unicode.

But the script doesn't sanitize the file names, and that is what invalidates the query.

It could be a a lot worse. If somebody uploads an image named image'); DROP TABLE *;--.jpg, and you use that script, they would erase your site (as shown in the XKCD cartoon below):

Source: xkdc - Exploits of a mom

I would strongly advice postponing the use of that script until somebody who understands database security has cleaned it up.

Suggestion: hand edit the file names with quotes in them by removing the quotes, and edit the corresponding names in table file_managed.

I am also puzzled that the Drupal file upload module does not sanitize file names by not permitting quotes in file names.


change the body and the title of my content type by css I'm using the zen theme
I would like to customize with css, the "content type" that I created. Set a different font for the title and body. What should I do?

Install the Firebug and find the appropriate class or id.
Look for kick start inside the zen theme and follow the instructions to crete a sub theme.
Adjust the CSS found with firebug to your needs.

After all this is basic drupal theming stuff. Check this out to get a bigger picture.


Solr Indexing Error showing "EntityMalformedException: Missing bundle property on entity of type taxonomy_term" In Drupal 7.14, when i Index my Whole Site, Solr is showing following error:

AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows.
Path: /batch?id=1938&op=do StatusText: Service unavailable (with message)
ResponseText: EntityMalformedException: Missing bundle property on entity of type taxonomy_term. in entity_extract_ids() (line 7539 of /project/path/includes/common.inc).

So when i look into the lines in /includes/common.inc (around lines: 7537):

// Explicitly fail for malformed entities missing the bundle property.
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

What is that chunk of code (in common.inc) is doing actually please?
How can i overcome that error?

Drupal tries to index an invalid item and throws this error.
To find out what document is causing the error, you can implement the hook_apachesolr_index_document_build hook with a watchdog statement inside.

This is from apachesolr.api.php

/**
 * Build the documents before sending them to Solr.
 * The function is the follow-up for apachesolr_update_index
 *
 * @param integer $document_id
 * @param array $entity
 * @param string $entity_type
 */
function hook_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {

}

My guess is that the last item in your dblog will be the offending item.


How to automatically unpublish / move to archive an article or node? I need to have a functionality that allows users to create an article and choose for how long the  user wants it to be published (for example 7 days or 2 weeks). After this time the node will automatically move to archive.

How can I achieve this in Drupal 7? I know that there were some modules (Node expire?) in Drupal 6, but I am not sure about Drupal 7. Any advice?

I think you can easily archive your goal with a bunch of module.

I guess with Rules that gonna help you to make some actions when the article will be unpublished. Flag module will help you to set a flag 'Archived article' and finally Scheduler that let your user to choose when the article will be archived.


How to organize this: traders have fruits and recipes too I'm building a site in D7 for a little community garden mall with 30 traders/shops. There is a trader which sells fruits, another one sells cakes, another one sells dairy products, and so on.

And I have a page with lots of recipes. The recipes should link to the traders. So for Spaghetti Aglio e Olio: The spaghetti you buy at the wheet farmer, the garlic at the vegetable farmer and a white wine at the liquor shop.

I have a content type trader. And a content type recipe.

How do I organize the products?
We even think about selling some of the products online one day. So that a site visitor could order a box of vegetables of a trader.

Thanks, Joerg

I would look into using the references module, you can reference one content type from another, for example on a ingredient page such as white wine, you could reference Spaghetti Aglio as a "you can make this from this ingredient".

Then on a traders content type you can refer to the ingredients etc


Context Module - not triggering menu active I need the menu called "Questionários" to be active/visible (and styled in different color) only for the node 115.

I've installed the context module and tried to use the path pointing to my node but it didn't work.

Here's a print (some things are in Portuguese but I hope you can understand):

Thank you!

The patch is here: https://www.drupal.org/files/issues/context-fix-menu-reaction-2374445-16.patch

It will fix the issue for the main menu set as a block.


How to render the 'actions' section of a form in twig template? given a form that is built like the following:

public function buildForm(array $form, FormStateInterface $form_state)
{
   $form['#theme'] = 'mymodule_testForm';
   $form['actions']['#type'] = 'actions';
   $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('submit'),
      '#button_type' => 'primary',
   );
   return $form;
}

How do I access the submit button in my twig template?

Hat tip to Clive who already answered the question as a comment:

{{ form.actions}}

To render the rest of the form, you can do something like {{ form | without('actions') }}

So you whole code will look something like this:

In my_module.module:

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  $result = [
    'custom_form' => [
      'render element' => 'form',
      'template' => 'custom-form',
    ],
  ];

  return $result;
}

And in custom-form.html.twig:

Form

    {{ form | without('actions') }}

Action

    {{ form.actions }}

For more reading:

Similar Q&A:

https://stackoverflow.com/questions/48997506/how-to-render-specific-form-elements-drupal-8
How to pass a custom Form to a Twig template

Drupal.org documentation on Twig filters in Drupal: https://www.drupal.org/docs/8/theming/twig/filters-modifying-variables-in-twig-templates

Hope that helps!