Bootstrap site, not mobile friendly anymore I made a website with Ubercart and Bootstrap. It was all running fine until a while ago. For some reason the website stopped being mobile friendly. When on mobiles it would show the desktop version and the navigation bar would not become the three bars button for example. Weird thing is when resizing the browser window on the computer it works as expected, but when trying it in developer tools it just doesn't care and remains as desktop version, on mobiles as well. I'm pulling my hair at this point. I have tried disabling a ton of modules but nothing changed. If you can look at the website and go into developer tools and check if there is some sort of an error or something that could help.

In your page's <head>, somehow the viewport got removed.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Without this, Bootstrap in general and @media in bootstrap.css don't know what width the screen is initially.

This should generally be auto-generated or put into html.tpl.php.


Can anyone recommend a good Drupal module for managing/displaying videos I would like to put together a video gallery on my website and am wondering if there are any existing Drupal modules to manage that. I'm using Drupal 6 and most likely the videos will be hosted on YouTube.

Ideally, I would like to arrange them in topical albums in which each video could be annotated with a description of the videos.

Thanks.

Drupal 6: Embedded Media Field. Now has a D7 version too.

  This extensible module will create fields for content types that can be used to display video, image, and audio files from various third party providers. When entering the content, the user will simply paste the URL or embed code from the third party, and the module will automatically determine which content provider is being used. When displaying the content, the proper embedding format will be used.

Drupal 7: Media

  The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site - it is commonly referred to as a 'file browser to the internet'.


pager query with join I plan to list all polls in the most recent order where I need to join my "poll" table with the "node" table and display them with pager. Here is what I do:

$polls_query = db_select('poll', 'p')
              ->extend('PagerDefault')
              ->limit(3);
$polls_query->join('node', 'n', 'n.nid = p.nid')
            ->fields('p', array('nid'))
            ->condition('p.active', 1, '=')
            ->orderBy('n.created', 'DESC');
$result = $polls_query->execute();
foreach ($result AS $poll) {
  $polls[] = array('data' => drupal_render(node_view(node_load($poll->nid), 'teaser')));
}
$content['pager_list'] = array(
  '#theme' => 'item_list',
  '#items' => $polls,
  '#title' => t('Listing Consensus'),
  '#type' => 'ul',
);
$content['pager_pager'] = array('#theme' => 'pager');
return drupal_render($content);

Unfortunately I see a white screen of death and the php error log says "PHP Fatal error:  Call to a member function fields() on a non-object in  .. " and thats the line where I mention after fields. If I dont use join, everything works fine.

If anyone else has had similar problems, please share the solution.

The join() method doesn't return the query object to isn't chainable.

If you change your code to this you should be fine:

$polls_query = db_select('poll', 'p')
  ->extend('PagerDefault')
  ->limit(3);

$polls_query->join('node', 'n', 'n.nid = p.nid');

$polls_query->fields('p', array('nid'))
  ->condition('p.active', 1, '=')
  ->orderBy('n.created', 'DESC');

// etc...


Referring created users to 'admins' that created them I know user can be given a permission to create other users. However, it doesn't seem that user table has any created_by field to store the ID of the creator. Does it?

Is there a way not only to create a field like that (could do it through profiles management) but also to actually put creators ID in it with just using drupal base config or some module?

I simply need to be able to list users created by a particular 'admin'

Add a field (e.g. created_by) to the user profile by going to /admin/config/people/accounts/fields.

Then implement hook_user_insert to populate the field whenever a new user is added.

hook_user_insert is called after "A user account was created."
So both $edit->uid and $account->uid have the user id present.

If you changed any values in either of these objects you would need to call user_save in order to save your changes.

An alternative to avoid calling user_save again, just after the initial user object has been saved would be to use hook_user_presave that is called when "A user account is about to be created or updated"

The description of hook_user_presave goes on to say:

This hook is primarily intended for modules that want to store properties in the serialized {users}.data column, which is automatically loaded whenever a user account object is loaded, modules may add to $edit['data'] in order to have their data serialized on save.

So another option here would be instead of creating a new field (with a new table), this information could just be stored as a serialized array in the data column of the user table.

This would mean it would be slower to search for users created by a certain admin, but would would have less storage overheads.


Drupal node templates which apply to more than one content type. Possible? I've started looking at content type specific node.tpl.php files. However, say I have two content types, and wish both to be displayed in a similar manner, but not apply this to every content type (at the level of node.tpl.php).

It seems a bit of an overkill to have two identical files for node--contenttype_1.tpl.php and node--contenttype_2.tpl.php which are the same? Is there a way to have a multi-content-type template for this?

In case you're wondering the reason for having two different content types in the first place, one is a simpler version of the other, has different URL generation rules (via pathauto), and fewer fields associated with it.

Implement a preprocess function that adds a template suggestion.

Assuming your theme is called EXAMPLETHEME, your content types are content_type_1 and content_type_2 and the template file is called node--example.tpl_php, add the following function to the file template.php of your theme:

function EXAMPLETHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'content_type_1' || $node->type == 'content_type_2') {
    $variables['theme_hook_suggestion'] = 'node__example';
  }
}


Is there an alternative Drupal 7 module for the Advertisement module? We are looking to upgrade a site to from Drupal 6 to Drupal 7 that uses the Advertisement module. There is an alternative module to the Advertisement module for D7?

Just released is the SimpleAds module for Drupal 7. This module provides a way to feature advertisements on a Drupal website. It displays graphical ads in configurable blocks. It records and reports useful statistics. It is easy to configure and does not depend on other contrib modules.


Is it possible to render a twig template for "later use"? I have been asked to create a custom module that outputs a node's content in a way that it will be easy to print or export to pdf.

I came accross this question and this is litteraly what I'd like to do, but I can't manage to adapt it to Drupal. I've seen quite a lot of potential solutions, but I don't know if they'd help.

Here is what I did so far:

// My module's route is '/pdf/node/{nid}

$route_match = \Drupal::service('current_route_match');
$node = $route_match->getParameter('nid');
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$result = $node_storage->load($node);

$response['title'] = $result->getTitle();
$path = DRUPAL_ROOT . '/modules/custom/mymodule_pdf/templates/node.html.twig';

// It would look like so:
$template = $this->get('twig')->render($path, 'title' => $response['title']);

So far, the twig file just contains the following:

{{ title }}

So $twig would contain
The node's title

And all I'd need to to is to put the $twig content as my future pdf's content, but this is the easiest part.

Is this possible to do this?

Normally you don't render twig templates directly, but build the content in a render array and use the render service:

public function nodeExportPdf(NodeInterface $node) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $build = $view_builder->view($node, 'full');
  $html = \Drupal::service('renderer')->renderPlain($build);
  ...
}

This will use the node template configured for the view mode you specify in the view builder. In this example full, but probably you want to create a custom view mode for the pdf.

When you are in a controller you get the route parameters in the function arguments. How to build the route for this see https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes


How to increment variable in Twig file? I'm using a view grid template and a views-view-fields--view-machine-name.html.twig template file in order to render some pictures in grid format. I want to assign dynamic CSS classes to every picture that is being rendered, for example, using the following markup.

{{ fields.field_picture.content }}

I have set a variable in Twig with the following code, but since there is no loop, it doesn't get incremented.

{% set id = 0 %}

So for every picture I have the same CSS classes (profile-pic pic0).

I want to get the following.

Picture 1
profile-pic pic0
Picture 2
profile-pic pic1
Picture 3
profile-pic pic2
Picture 4
profile-pic pic3

If I use the following code, the same imagine is rendered instead of the pictures I have.

{% for field in fields -%}

{{ fields.field_picture.content }}

{%- endfor %}

How do I get the counter to be increased, and all the images to be rendered?

As you mentioned, there's no loop, so you can't do this in the template file (well you could, but it wouldn't be worth the effort).

Instead, you could maintain a static variable in a preprocess function:

function MYTHEME_preprocess_views_view_fields__view_machine_name(&$vars) {
  static $counter = 0;
  $vars['counter'] = $counter++;
}

And refer to it in the template as normal:

{{ fields.field_picture.content }}

You might need to tweak that, for example if the View is rendered twice on the same page.


Upload picture in custom register form I'm building a multistep register form in a custom module. I'm using profile2 module to save other custom fields. I want to let the users choose an image from their computers. This is the code that I use to upload the picture that saves in the file_managed Drupal table but without the user uid because at this point I don't create the user.

$form['empresa']['logo_empresa'] = array(
        '#title' => t('Logo de la empresa.'),
        '#type' => 'managed_file',
        '#description' => t('Tamaño máximo 3Mb y formato aceptado jpg,jpeg o png'),
        '#upload_location' => 'public://',
        '#upload_validators' => array(
        'file_validate_extensions' => array('png jpg jpeg'),
        'file_validate_size' => array(3*300*300),
        ),
);

When all fields are OK I submit the form and create the user as follows:

function empresas_registration_signup_form_submit($form, &$form_state) {

$nombre = $form_state['storage']['field_nombre_contacto'];
$apellidos = $form_state['storage']['field_apellidos_contacto'];
$mail = $form_state['storage']['email'];
$comunidad_autonoma = $form_state['storage']['field_comunidad_autonoma'];

$provincias = $form_state['storage']['field_provincia'];
$razon_social = $form_state['storage']['field_razon_social'];
$cif_nif = $form_state['storage']['field_cif_dni'];
$telefono = $form_state['storage']['field_telefono'];
$web = $form_state['storage']['field_web'];

$municipios = $form_state['storage']['field_municipio'];
$poblacion = $form_state['storage']['field_poblacion'];
$direccion = $form_state['storage']['field_direccion'];
$codigo_postal = $form_state['storage']['field_codigo_postal'];

$razon_social = $form_state['storage']['field_razon_social'];
$clave = substr($razon_social, 0, 3);
$cif_nif = $form_state['storage']['field_cif_dni'];

$usuario = $clave.$cif_nif;
$password = password(8);
//$imagen = $form_state['values']['field_logo_empresa'];

$roles = user_roles();
$newuser = array(
        'name' => $usuario,
        'pass' => $password,
        'mail' => $mail,
        'status' => 1,
        'roles' => array('7' => 'empresa'),
        'access' => time(),

);
$existing_user = user_load($usuario);
if (!$existing_user->uid) {
    $account = user_save(null, $newuser);

    $profile = entity_create('profile2', array('type' => 'empresa'));
    $profile->uid = $account->uid;

    //Datos a guardar para el perfil

    $profile->field_nombre_contacto[LANGUAGE_NONE][0]['value'] = $nombre;
    $profile->field_apellidos_contacto[LANGUAGE_NONE][0]['value'] = $apellidos;
    $profile->field_razon_social[LANGUAGE_NONE][0]['value'] = $razon_social;
    $profile->field_cif_dni[LANGUAGE_NONE][0]['value'] = $cif_nif;
    $profile->field_direccion[LANGUAGE_NONE][0]['value'] = $direccion;
    $profile->field_codigo_postal[LANGUAGE_NONE][0]['value'] = $codigo_postal;
    $profile->field_telefono[LANGUAGE_NONE][0]['value'] = $telefono;
    $profile->field_web[LANGUAGE_NONE][0]['value'] = $web;
    $profile->field_poblacion[LANGUAGE_NONE][0]['value'] = $poblacion;
    $profile->field_comunidad_autonoma[LANGUAGE_NONE][0]['value'] = $comunidad_autonoma;
    $profile->field_provincia[LANGUAGE_NONE][0]['value'] = $provincias;
    $profile->field_municipio[LANGUAGE_NONE][0]['value'] = $municipios;

    $profile->save();

    $account->profiles['empresa'] = $profile;
    entity_save('user', $account);
    drupal_goto('user');

}
}

My question is: How could I set the fid from the table and assign it to the user?

@Luism, you should use field widget for it. field_attach_form attaches fields to form, field_attach_form_validate validates all attached fields, field_attach_submit prepared entity to be stored. Regarding values in $form_state['values'] you will have big structure inside $form_state['values']['FIELD_NAME'][LANGUAGE][INDEX] but you need only $form_state['values']['FIELD_NAME'][LANGUAGE][INDEX]['fid'], it will contain File ID from file_managed table (with status=0) for uploaded files and after profile2_save() file will be activated or deleted otherwise.


How do I get a URL variable in a template? I am trying to include a certain .html file if the URL has ?work=1.

So far I have this, which I got from
Check URL for string in a Twig file.

 {% if 'work' in url %}
    {{ include('work/index.html') }}
 {% endif %}

They say I need a function in my .theme file to actually get the URL variable.
Is that right? Is there any way to get it with just Twig?

Ok nevermind. On the other stack I mentioned the function was

function riptide7_preprocess_page_title(&$variables) {
  $variables['url'] = $_SERVER['REQUEST_URI'];
  $variables['#cache']['contexts'][] = 'url.path';
    echo "What?!";
}

and I just had to change preprocess_page_title to preprocess_page


How are upload files stored? I have a custom content entity. For this entity, I want add multiple uploaded files.
After I set this up, I looked at the database and saw:

file_managed => stores all files uploaded by a managed_file field
file_usage => links between your entity and the table file_managed

So for the managed_file field form, I don't need to create a field into my entity content (database), I just add a field into the EntityForm directly:
  $form['image'] = array(
      '#title'=>t('Image du produit'),
      '#type' => 'managed_file',
      '#upload_location' => 'public://produits/',
      //'#default_value' => array(),
      '#description' => t('png jpge jpg'),
      '#upload_validators' => array(
          'file_validate_extensions' => array('png jpg jpeg'),
      ),
      '#multiple'=>true,
  );

And then I can upload multiples files.
Then in my submit :
public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;

      foreach ($form_state->getValue('image') as $image) {
          $file = \Drupal\file\Entity\File::load($image);
          $file->setPermanent();
          $file->save();

      $file_usage = \Drupal::service('file.usage');
      $file_usage->add($file, 'boutique', 'produits_entity',$entity->id());

      }
}

I store image reference into the file_usage table and set it permanent. At this point all is good.
But I need to load all files when user want edit my entity, I can load this from the file_usage table and build my

'#default_value' => array($images)

I want to know if it's a good practice and if Drupal 8 work like that.

I don't need to create a field into my entity content (database), I just add a field into the EntityForm directly
...
I want to know if it's a good practice and if Drupal 8 work like that.

No, what you described is not good practice. For a Drupal entity to interact easily and correctly with a field, you should add the field to the entity, not add the widget to the form.  It is probably possible to make it work but it will be harder to build and maintain.


How do I update an old project? I have been tasked with updating my code shop's long-abandoned Drupal 7 codebase to the most recent Drupal core, in order to bring in the latest security fixes (it's currently using v7.67). But all the knowledge I had about how to use drush seems to now be completely worthless.
What is this "composer" thing that it keeps complaining about? We never used anything like that back when we were still developing this Drupal 7 project (we abandoned PHP and switched to Python/Django a few years ago). I tried installing Drush through composer require drush/drush, which worked (and dumped a load of new code into my repo for some reason...). But even though I'm running it in the root of my repo, it says this:
! [NOTE] Drupal root not found. Pass --root or a @siteAlias in order to see Drupal-specific commands.

When I pass the root folder name via --root, it says the same thing. Thus, my old strategy of just running drush up drupal, which worked dozens of times in the past, no longer works.
Could someone who understands how Drush works these days explain to me how I can use it to update my codebase? Or maybe there's a way to install an old version of Drush that can actually understand my repo's layout? That'd be even better.

I came across this issue myself when starting my first Drupal 8 project.
This is most likely due to the version of Drush you are using being not compatible with Drupal 7. You can check your Drush version by running drush --version in the command line.
If Drush 9 or above, you should downgrade to version 8, i.e. composer require drush/drush:^8.
Tip: if ever wondering which Drush (local or global) you are using, type which drush in the command line.


Drush API for downloading module from a script I am trying to download module using Drush API via drush script as following:

#!/usr/bin/env drush
<?php

// check if we can bootstrap
$self = drush_sitealias_get_record('@self');
if (empty($self)) {
    drush_die("I can't bootstrap from the current location.", 0);
}

// goes to site directory
drush_op('chdir', $self['root']);

drush_include_engine('drupal', 'environment', drush_drupal_major_version());

//****how to download module

drush_module_enable(array('uuid'));

drush_print("Done.");

While i see an Drush API for enabling, i don't see for downloading a module
How to download a module via Drush API from the script? Is there Drush API for automatically detect dependencies, download them and enable? Thank You

Drupal 7, Drush 5.8, Mac

If there's an API for this, I think it would be drush_invoke_process. I believe Drush uses that function internally when one command wants to execute another.

The primary function that executes the download work is drush_pm_download(), so you could probably just call it directly as well.

And of course, as a last resort, you could use exec(drush @alias dl $module).


Ubercart vs Drupal commerce for french ecommerce site This is my first experience with french e-commerce site . I want to know which solution will speed up the developing of the website .

Also is there a module payment for Carte bleu  in drupal commerce, and is it ready for production site ?

Check this article which compares Ubercart & Commerce modules. Winner is commerce module for most advanced features and simplicity.

Commerce module is written from scratch to solve usability and other issues in Ubercart. Commerce module will be obvious choice for E-commerce portal.

As far as i know there is no out of the box module for Carte bleau payment gateway. But, if you know the module development you can write one and contribute to community using commerce payment gateway API. This will help you.

Best of luck :-)


How to clear Text in search box once the user selects other option I have created a view for to search my channels. But when user searches for a specific channel, and when he clicks any other option or on any other event,he redirects to other page but text in search box is not cleared,what i want is, the text in search box should get cleared once he clicks on other option.How can i do this??

I think you can do it in 2 ways:

You can use javascript to clear the value of textfield after
page load or on click.
You need to rewrite field or rebuild form when option changes.

It`s all that i can say without some code.


How to get height and width of image style? We have a custom module mymodule where we call mymodule_tokens so that we can assign custom token values from the current node. These custom tokens are used to insert values in the Article's MetaTag fields.

Problem

When fetching the default value based on an Image Style (e.g. medium), I cannot get the Height and Width based on the Configuration for the Image Style. How can I get the height and width from the Image Style?

What I have tried, but cannot get the height and width:

function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  $node = $data['node'];
  $node_image = $node->field_image;
  $field_image_style = 'medium';

  if($node_image->isEmpty()) {
    $field_info = FieldConfig::loadByName('node', 'article, 'field_image');
    $image_uuid = $field_info->getSetting('default_image')['uuid'];
    $image = Drupal::service('entity.repository')->loadEntityByUuid('file', $image_uuid);
    $field_image_url = ImageStyle::load($field_image_style)->buildUrl($image->getFileUri());
    $image_style = ImageStyle::load($field_image_style)->getEffects()->getConfiguration();

    // Both give me error messages.
    $image_style_height = $image_style->get('height');
    $image_style_width = $image_style->get('width');
  }
  else {
    $field_image_url = $node_field_image->entity->getFileUri();
    $image_style = ImageStyle::load($field_image_style)->getEffects()->getConfiguration();

    // Both give me error messages.
    $image_style_height = $image_style->get('height');
    $image_style_width = $image_style->get('width');
  }

  foreach($tokens as $name => $original) {
    switch ($name) {
      case 'custom_image_url':
        $replacements[$original] = $field_image_url;
        break;
      case 'custom_image_height':
        $replacements[$original] = $image_style_height;
        break;
      case 'custom_image_width':
        $replacements[$original] = $image_style_width;
       break;
    }
  }

  return $replacements;
}

Error Message

  Error: Call to a member function get() on array in mymodule_tokens()

When printing ImageStyle::load($field_image_style) using Kint this is what we get.

When printing $image_style, I get the following.

Using core or contrib tokens rather than custom tokens

Using the following tokens only work when there is a value added to the field_image field, but when the field_image is not populated, the token is not able to return the default image that is populated on the field's settings page.

[node:field_image:medium:height]
[node:field_image:medium:url]
[node:field_image:medium:width]

No Sssweat's answer inspired this.

I added this before if statement (if($node_image->isEmpty())) to get the height and width.

$image_style_config = (ImageStyle::load('medium')->getEffects()->getConfiguration());

foreach($image_style_config as $config) {
  if(isset($config['data'])) {
    if(isset($config['data']['height'])) {
      $image_style_height = $config['data']['height'];
    }
    if(isset($config['data']['width'])) {
      $image_style_width = $config['data']['width'];
    }
  }
}


Inserting custom HTML using tokens I'm trying to reduce repetitive coding by adding my own static HTML content into some form of reusable token that can be added into page bodies amongst regular code, but can't find a method. Here's what I'm looking for:

Desired content to be inserted into page body

I type this all the time and want to automate it

Token idea to insert this into a page Body

Here is some regular content

[token:my-repetivie-div]

and some more content appearing after my-repetitive-div

End result

Here is some regular content

I type this all the time and want to automate it

and some more content appearing after my-repetitive-div

This question is similar to this one, but he didn't quite get a straight answer, so I'm spelling it out here.

The Token Filter module wasn't what is needed, as it only addresses using pre-existing Tokens not creating custom ones. Would the Custom Token module achieve this?

If there's a better way to achieve this other than Tokens, i'm all ears!

I would recommend you to use Wysiwyg API template plugin module

  In TinyMCE, CK Editor and FCK Editor, there is a template function, which allows a user to select a HTML template from a drop-down and insert it into the WYSIWYG text-area. This module supports those features for use with the WYSIWYG API.


Calendar View Remove Duplicate Items I'm using Calendar module to display a list of nodes with fields related to that specific days. I am handling multiple date fields using contextual filters.
For example, if an item has a Preview Date of 7/1 and a Review Date of 7/2, the node item will show for each date.
The problem is each node item is showing for each date, i.e. 7/1  and 7/2 show the item twice.

How do I remove the duplicate items? So each date only shows one of each node? I've tried aggregated fields/Count Distinct and Query Distinct but had no sucess.

you can try views distinct module
from module page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

I hope it helps, be carefull in features, the module settings are not exported in features. If you use features, once you push your code, on production site, set your view UI settings again, it's easy and simple.


From theme() to drupal_render() I'm a Drupal themer, learning how to develop for Drupal. Currently I'm reading a book called Drupal 7 Module Development in which the following code is used.

/**
 * Implements hook_block_view().
*/
function first_block_view($delta = '') {
  if ($delta == 'list_modules') {
    $list = module_list();

    $theme_args = array(
        'items' => $list,
        'type' => 'ol'
    );
    $content = theme('item_list', $theme_args);

    $block = array(
        'subject' => t('Enabled Modules'),
        'content' => $content,
    );

    return $block;
  }
}

Its a simple module that returns a ordered list of all the enabled modules. Notice they are using the theme() function.

As a themer, I wanted to know more about this function, so I looked it up on drupal.org, and saw this:

  Avoid calling this function directly. It is preferable to replace direct calls to the theme() function with calls to drupal_render() by passing a render array with a #theme key to drupal_render(), which in turn calls theme().

So I tried replacing it with drupal_render(), and came up with this:

/**
 * Implements hook_block_view().
 */
function first_block_view($delta = '') {
  if ($delta == 'list_modules') {
    $list = module_list();

    $theme_args = array(
        '#theme' => 'theme_args',
        'items' => $list,
        'type' => 'ol'
    );
    $content = drupal_render($theme_args);

    $block = array(
        'subject' => t('Enabled Modules'),
        'content' => $content,
    );

    return $block;
  }
}

This however, is giving an error: Theme hook theme_args not found.
Am I missing something? I would appreciate any help, and if possible, an explanation of what I did wrong. (since I'm learning this stuff.)

I've seen a similar question posted here, and followed its instruction, but no success.
How to rewrite this theme call to drupal_render

I think there is a typo.

Just replace

'#theme' => 'theme_args',

with

'#theme' => 'item_list',

There is no theme called "theme_args".


Tracking clicks on each link separately I have create a website that, on the same page, will offer several links to the exact same section (node).
For example the link to the "Contact us" node appears 3 different times (in 3 different places) on the home page.

Is there any way to track each click separately and to know which links were clicked to reach the contact us page?

I am already using the "Google Analytics" Drupal module, but the same link is tracked as a single unit, regardless of the number of times it appears on a page.

You can append a different query string to each link, which will allow you to track each one individually. Lets say your contact page is at mysite.com/contact. You can create several url's with a query string that lead to the same page. Ex:

mysite.com/contact?link=1

mysite.com/contact?link=2

mysite.com/contact?link=3

etc.

You can always append a query to a URL without creating any aliases or anything. Simply add ?key=value (obviously you can change 'key' and 'value' to anything you'd like). Google Analytics will track all of these separately.

The only downside is that Google Analytics won't batch all your contact page visits under 1 url anymore, but instead each different query will be listed separately.


render() is not returning anything on custom theme I am using the newsletter_export module to allow users to select multiple nodes and export them as html. The node this action is performed on is a content type which uses entity reference to grab content from selected other nodes. The newsletter_export is also the name of the template file which renders it. It depends on the node_export module to do this.

However, it doesn't work on the theme that I am working with. It works fine on the Bartik theme. The code in the module that doesn't work is below: the variable for $raw_markup is always empty.

This level of coding in Drupal is new to me so any tips on fixing or just where to look to fix the problem is really appreciated! The variable $item is just the nid of the node.

$node = node_load($item);

  // TODO: Should we add the check for view hook back in for custom node modules?
  // Filter and prepare node in our custom build mode
  $render_array = node_view_multiple(array($item => $node), 'newsletter_export'); //, $weight = 0, $langcode = NULL)

  // TODO: Allow modules to change $node->content before the node is rendered.
  //node_invoke_nodeapi($item, 'view', $teaser, FALSE);
  $type = 'node';
  drupal_alter(array('node_view', 'entity_view'), $render_array, $type);

  // TODO: Set the proper node property, then unset unused $node property so that a
  // bad theme can not open a security hole.

  $raw_markup = render($render_array);

Simple, and frustrated I spent so long on this.

I copied the tpl file from the module to my theme assuming I could customise it there. But when I deleted it from my theme directory it just started working. The template page inheritance is confusing...


Drupal 6 clean urls without domain name (accessing via IP Address) Is there a way to do clean urls without a domain name; just using an IP Address. The option is disabled when using ip address.

Clean URLs is not dependent on domain names it is disabled because your server doesnt support it. You need to enable mod_rewrite module in apache to get that option enabled.
Check out the server configuration section here.


FBOauth: how to pass arguments to the callback function? I am trying to create a facebook event through a drupal content type "event". I call the hook_node_insert() to make a POST on Facebook.

function fb_event_create_node_insert($node){
    if ($node->type == "event"){
        // get field values submitted when a new content type "event" is saved
        $event_name = $node->field_event_name['und'][0]['value'];
        $event_start_date = $node->field_event_start_date['und'][0]['value'];

        // get facebook app_id & secret from fboauth variables
        $app_id = isset($app_id) ? $app_id : variable_get('fboauth_id', '');
        $app_secret = isset($app_secret) ? $app_secret : variable_get('fboauth_secret', '');

        // Get the link to get the facebook code (generated by fboauth module)
        $link = fboauth_action_link_properties('fb_event_create');

        print l(t('Create event'), $link['href'], array('query' => $link['query']));
        // output a link to https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=http%3A//localhost%3A8888/cs/%3Fq%3Dfboauth%252Ffb_event_create&scope=manage_pages%2Ccreate_event
        // parameters are created by the fb_oauth action (scope=permission) and some settings of the module (client_id & redirect uri).

    }
}

So I then have a link after having saved the node: when I click on it, it connects to facebook and gives me back a code as a parameter in my redirect uri (code has been modified):

http://localhost:8888/cs/?q=fboauth%2Ffb_event_create&code=AQDEvaeupRO-FE6lWaKXZFqvoSRnSuKlIdVjMDeGoy5su-hXpgCcGnBsyCzcPDl5YGGc3hj1yPAXheBjmFtGuivmM-lm5jlm5QG2UeFLPg3gQfnWM3UvB10Y-yrYPyr176dyuMI2Q3vvHGM8z-YVKpYkzPPgYUEifEDIbvADokgniNFiiwpyWZCS72GD32zWLxWCBkCThRk8o3MnO2vWXAmc#_=_

It goes to the callback function defined earlier:

function fb_event_create_fboauth_actions() {
  $actions['fb_event_create'] = array(
    'title' => t('Create events on behalf of CS'),
    'callback' => 'fb_event_create_fboauth_action_event_create',
    'permissions' => array(
      'manage_pages,create_event'),
  );
  return $actions;
}

And here is the callback function:

function fb_event_create_fboauth_action_event_create($app_id, $access_token) {
    $result = fboauth_graph_query("EVENT_ID/events", $access_token, array("name" => "test", "start_time" => "2013-04-04T19:00:00-0700"), 'POST');
}

WHAT I WANT:

Insert parameters to this callback function to be able to insert the $event_name and $event_start_date (that we find from the node_insert() hook above) to have the callback function like :

function fb_event_create_fboauth_action_event_create($app_id, $access_token, $name_fb_ev, $start_fb_ev) {
    $result = fboauth_graph_query("EVENT_ID/events", $access_token, array("name" => $name_fb_ev, "start_time" => $start_fb_ev), 'POST');
}

Thank you for any help guys!

I modified the fboauth_action_menu() to make it accept arguments:

function fboauth_menu() {
  $items['fboauth/%fboauth_action/%/%'] = array(
    'title' => 'Facebook connect',
    'page callback' => 'fboauth_action_page',
    'page arguments' => array(1, 'foo', 'foo'),
    'access callback' => TRUE,
    'file' => 'includes/fboauth.fboauth.inc',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

But then I had another problem with the function fboauth_action_page()it executed because it called the another function to get the access token because the two redirect_uri parameters were not the same between the code request to FB and the access token. All this, because the function to get the access token was not taking into account the parameters.

function fboauth_access_token($code, $action_name, $app_id = NULL, $app_secret = NULL) {
  $app_id = isset($app_id) ? $app_id : variable_get('fboauth_id', '');
  $app_secret = isset($app_secret) ? $app_secret : variable_get('fboauth_secret', '');

  // get the parameters from the redirect_uri by the drupal function arg() and includes them in the redirect_uri to get the access token.
  $query = array(
    'client_id' => $app_id,
    'client_secret' => $app_secret,
    'redirect_uri' => fboauth_action_url('fboauth/' . $action_name . "/" . arg(2) . "/" . arg(3) . "/", array('absolute' => TRUE, 'query' => !empty($_GET['destination']) ? array('destination' => $_GET['destination']) : array())),
    'code' => $code,
  );

// rest of the function

}

Now, both redirect_uri are the same and my callback function defined earlier must also catch parameters from the url:

function fb_event_create_fboauth_action_event_create($app_id, $access_token) {
    $event_name = arg(2);
    $event_start_date = arg(3);

    $result = fboauth_graph_query("EVENT_ID/events", $access_token, array("name" => $event_name, "start_time" => $event_start_date), 'POST');

}

Hope this helps someone!


how to use image styling on a image url field I understand that on an image field, you can create a image style. However, I have a field which is a url and I use that url in a template to produce a picture. Is there any way for me to use the image style ui to style this?

Try using the Imagecache External drupal module: https://drupal.org/project/imagecache_external

In your template file you could then call (from the drupal project example) and replace 'path' with your path from your url field:

<?php
  print theme('imagecache_external', array(
    'path' => 'http://larsjung.de/h5ai/sample/screenshots/h5ai-v0.7-icons.png',
    'style_name'=> 'thumbnail'),
  );
?>


Entity Reference & View I am in the process of setting up a listing and review type scenario.  I have set up the separate entity types, one for the listing, and three for the types of reviews.  I kind of get how (from here and other sites) to set up these relationships using entity reference.

What I don't understand, is when I have a published listing, and I want the user to navigate to one of the three reviews, how do I make this happen?  ie what do I do to set up this link and in what module?  Is there a 'link' field to the review type, and the 'entity reference prepopulate' will take care of it?

So when it comes time to publish, I will have the listing and three columns for the different types of reviews.

Any help is much appreciated, new to drupal, having trouble connecting all the dots...

Check out Entity Connect Module

  Entity Connect now expands both Entity reference and References
  (node_reference and user_reference) fields by adding "add new content"
  and "edit current content" buttons.

Exactly what you need.


Empty space on top of the page I coded some modules (basically only PHP and no alter of Drupal functions), and on mysterious way, two of my modules are producing an empty quote on top of my meta tags in the body.
This causes a 20 empty pixels on top of my page, and destroys my slider.

As mentioned, two modules are producing this; I figured out that the first module produces this when I use include_once("config/rewards.inc");. If I comment it out, everything works fine.
include_once("config/rewards.inc"); is already included in one of my other modules, but I used include_once, to include it, obviously, only once.
include_once("config/config.inc"); doesn't produce this error.

This is a screenshot of Firebug (the arrow point at the margin).

In my first module, the problem happens when I uncomment the line containing require_once("config/rewards.inc").

<?php
//      *****************************************
//      **      Donate Script for Trinity      **
//      **             by Leandros         **
//      *****************************************

//module_load_include('inc', 'donatescript', 'rewards');
//module_load_include('inc', 'donatescript', 'config');
require_once("config.inc");
//Produce problems (for some reason I dont know ^^)
//require_once("config/rewards.inc");

if(user_is_logged_in()){
global $user;
global $donatepoints;
$userip = $user->hostname;
$userid = $user->uid;
$username = $user->name;
$usernameuc = strtoupper($user->name);

//$GLOBALS['reward_items'] = $tab_rewards;
//$GLOBALS['reward_texts'] = $reward_texts;

//Get Variables from config.inc for realmd DB
$db = $realmd_DB['1']['3'];
$host = $realmd_DB['1']['0'];
$dbuser = $realmd_DB['1']['1'];
$dbpassword = $realmd_DB['1']['2'];

//Connect to realmd DB
$connect = mysql_connect($host, $dbuser, $dbpassword) or die (mysql_error());
mysql_select_db($db, $connect) or die (mysql_error());

//query overall donatepoint value
$donate_points_select = mysql_query("SELECT points FROM donate_points WHERE id='$userid'");
while($row = mysql_fetch_array($donate_points_select)) {
    $donatepoints = $row['points'];
}

if($donatepoints == 0) {
    $GLOBALS['donatepoints'] = 0;
} else {
    $GLOBALS['donatepoints'] = $donatepoints;
}

//mysql_query("INSERT INTO `donate_points` (`id`, `name`, `points`) VALUES ('$userid', '$usernameuc', '$donatepoints')");

//Close DB connection
mysql_close($connect);
}
?>

I found the error in the second module: It was because the opening <?php tag had a tab before it.

I fixed the second module, too. I don't know which produced the empty space, but I created for every file I used a new file and pasted my code into, renamed the module and enabled it. Everything now works.


Why doesn't my custom OutboundPathProcessorInterface work anymore? I wrote my own implementation of OutboundPathProcessorInterface to rewrite the URL of nodes to use the content of their field_project_url field.

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\PathProcessor;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\node\Entity\Node;
use Symfony\Component\HttpFoundation\Request;

class MymoduleFieldRedirectPathProcessor implements OutboundPathProcessorInterface {

  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {

    if (isset($options['entity']) && is_object($options['entity']) && method_exists($options['entity'], 'hasField')) {
      $node = $options['entity'];

      if ($node->hasField('field_project_url') && !$node->field_project_url->isEmpty()) {
        $project_url = $node->field_project_url->getValue();

        if (preg_match("/^\/node\/[0-9]+\/(edit|translate|delete|translations)$/i", $path)) {
          // dont alter operational paths
        }
        else {
          $path = $project_url[0]['uri'];

          dpm($project_url[0]['uri']); // 'http://url.com'

          $options['absolute'] = TRUE;
          $options['external'] = TRUE;
          $options['base_url'] = null;
          $options['prefix'] = null;
        }

        if ($bubbleable_metadata) {
          $bubbleable_metadata->addCacheableDependency($node);
        }
      }
    }
    return $path;
  }

}

The teaser of that view has a title, an image linked to the content, and smart trimmed version of the body field, also linking to the content.

The value is appended, giving (for example) http://localhost:8888/myprojecthttp%3A//url.com.

This used to work, but I can't even get this right with older Drupal 8 versions.

What am I doing wrong?

That's the right code of the processOutbound method
  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {

if (isset($options['entity']) && is_object($options['entity']) && method_exists($options['entity'], 'hasField')) {
  $node = $options['entity'];

  if ($node->hasField('field_project_url') && !$node->field_project_url->isEmpty()) {
    $project_url = $node->field_project_url->getValue();

    if (preg_match("/^\/node\/[0-9]+\/(edit|translate|delete|translations)$/i", $path)) {
      // dont alter operational paths
    }
    else {
      $path = ''; //Don't use $path variable at all

      dpm($project_url[0]['uri']); // 'http://url.com'
      $options['base_url'] = $project_url[0]['uri']; //Add your url as base_url

    }

    if ($bubbleable_metadata) {
      $bubbleable_metadata->addCacheableDependency($node);
    }
  }
}
return $path;

}


syncronize drupal 7 users with magento 1.7 customers The Module that is available in drupal is supporting the previous versions of Drupal (D6) and Magento(1.6). You can find it here

http://drupal.org/project/magento

I am using D7 with Magento 1.7, Is anybody out here can suggest me a flow how to add records in customer table while users are registering in drupal, Since i am very new to drupal as well as magento i am finding it a bit difficult to hack into D7 functions

Can this method be followed?

http://mysillypointofview.richardferaro.com/2010/09/07/how-to-pull-the-list-of-customers-from-magento-to-an-external-site/

Does this method have any security vulnerabilities associated with it?

I only need to add a few fields like

First Name
Last Name
Email
Password
Entity_type_id

Rest of the customer details can be updated using the magento engine itself once the user is logged in

Thanks

I would use Rules to trigger an action whenever a new user is created (and/or updated which will also matter in your scenario). This action can be a PHP script so the possibilities you have to interact with other software (Magento) are endless.


Filters dropdown based on a parameter I have a taxonomy, say 'Unit'. Besides the name of the Unit, there is a field called 'SubUnit'. All users in my Drupal site have assigned a Unit.

On the node add forms (and on the Views, for filtering), I would like to get only the 'SubUnits' corresponding to the assigned Unit per user. That is, only visualize on the dropdown list 'his' units.

I have seen around this answer, but it's from 2011, maybe there is an updated and easier way to do it? there is no way to create a filter based on the results of a view? (i can pass Únit as contextual filter and get its subunits)

Try the Hierarchical Select  module. This module integrates with Taxonomy.

This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!


How to implement a Drupal Commerce multi-select membership donation form? Something like this using Drupal Commerce? You select from a select list multiple options of which everyone has a price right? And so it adds it as a total below in a field like a cart, but in a same page and then below you fill your details and continue?

Or not a chance with Commerce and have to go with some other alternatives? Note I'm looking for Drupal friendly solution, not a PHP programmer here.

Cheers everyone for help!

I know you are asking about the form specifically, but it isn't clear to me how you are actually managing your 'memberships'. Something like CiviCRM that has full membership management tools can be integrated with both Drupal and with Commerce. There is a module for the latter, but we have found it problematic and have instead done the Commerce to CiviCRM integration using Drupal Rules and the CiviCRM Entities modules.


How to access an element's value in field validation function Drupal form api reference example for #element_validate accesses element's value with $element['#value'] in field validation function:

function myelement_validate($element, &$form_state, $form) {
   if (empty($element['#value'])) {
     form_error($element, t('This field is required.'));
   }
}

But $element['#value'] is always empty for me. indeed in print_r($element) there is no key named #value in first dimension of the array. instead, it is in somewhere like $element['und'][0]['#entity']....

My code:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
   if (isset($form['field_myfield'])) {
      $form['field_myfield']['#element_validate'][] = 'myfield_validate';

   }
}

function myfield_validate($element, &$form_state, $form) {

   //print $element['#value']; exit; // returns nothing

   if (!empty($element['#value']) && !is_numeric($element['#value'])) { // always false
      form_error($element, t('Error'));
   }
}

Is anything wrong?

Get a value using $form_state like as follow

$form_state['values']['field_myfield'];


How to resave all user accounts on a schedule? I want to re-save all user accounts on my site weekly because I wrote some code in hook_user_presave() that I want to update every week.
Specifically, my hook_user_presave() code updates the values of some fields like Total number of comments posted and Total number of articles posted, and it sends an email if the user hasn't logged in for more than a month. (This info is only available to the site admin, which is me, so it doesn't need to be perfectly in sync.)
Right now, I have a View with VBO that I can use to re-save all the user accounts manually. I want to automate this process by saving all the users automatically at 3 am on Sunday.
How do I schedule all user accounts to be saved?  Is this a task for Queue API or does core/contrib provide something more appropriate for this use case?

Ultimate Cron
Provides a UI where you can schedule all the cron jobs. Example:

Job Scheduler
Provides an API to schedule jobs.
Simple example:

// Declare scheduler.

  function example_cron_job_scheduler_info() {
    $schedulers = [];
    $schedulers['example_unpublish'] = [
      'worker callback' => 'example_unpublish_nodes',
    ];
    return $schedulers;
  }

// Add a job.

  $job = [
    'name' => 'example_unpublish',
    'type' => 'story',
    'id' => 12, // must be unique
    'crontab' => * 3 * * 0, // Every Sunday at 3 AM
    'periodic' => TRUE, // set to false if you want to just run once.
  ];
  $service = \Drupal::service('job_scheduler.manager');
  $service->set($job);

// Work off a job.

  function example_update_users_total(\Drupal\job_scheduler\Entity\JobSchedule $job) {
    // Do stuff.
  }

There is more examples & info in the READ.ME, so read it.

Important
It's important to note that the above in reality is scheduled to run the next time someone visits the site after 3am on Sunday. So if no one visits the site until say 9am on Sunday, it will not run until 9am. This is because Drupal's Cron can only run when Drupal is initialized.
The only way to be sure that it runs at 3am, you have to set a cron job in your server (just know that your server time may not be the same as your timezone, so you'll have to check that), using the crontab -e command (for linux) will open the file where you can add jobs to the server. Have this server job run a file that contains code that performs a GET request on your site. OR alternatively a custom Drush command like Kevin commented.


Filter nodes by date ( excluding year ) show upcoming/previous based on today i have content type called Race. This races happens every year so i want to have a page that show latest 5 upcoming races and past 5 races.

Is there a way that i can disable year in date api when adding a new race so that only month and day are taken for reference?

And not really sure how to setup views to filter this?

I am not sure how you are displaying your date, but if it is 'post date' then in Views on the lower left column choose 'Sort Criteria' and search for date. I will have multiple granularity and you can choose to filter by month.

If you have a text field where you manually type the date associated with the content, then you can use the 'Sort Criteria' and sort by that specific field in 'ascending' or 'descending' order.

If you want to keep the 5 newest and the older separate, you might need to create two different blocks and display them next to each other.

Finally you can do a 'Filter Criteria' by date and select a range of' 'Is greater than or equal to' a specific time period. For example from today to 5 months ago will only display content created within that month period, and anything beyond 5 months will not be displayed.


How do I create a custom plugin? Basically, I want to port a custom ctools plugin created for content type from Drupal 7 to Drupal 8. This is the code I want to port.

function my_module_ctools_plugin_directory($module, $plugin) {
  if (($module == 'ctools') && ($plugin == 'content_types')) {
    return 'plugins/content_types';
  }
}

In my_module/plugins/content_types/my_module.inc file i have following code:

/**
 * Plugin array() of ctools plugin.
 */
$plugin = array(
  'title' => t('My Module'),
  'single' => TRUE,
  'content_types' => array('my_module_custom_content_type'),
  'render callback' => 'my_module_render',
  'required context' => new ctools_context_required(t('Node'), 'node'),
  'edit form' => 'my_module_settings_form',
  'edit form validation' => 'my_module_settings_form_submit',
  'category' => 'Widgets',
);

/**
 * Render callback function.
 */
function my_module_render($subtype, $conf, $args, $context) {
  $node = $context->data;
  if (empty($node)) {
    return;
  }
  $data = \Drupal::formBuilder()->getForm('my_module_form', $context, $conf);
  $block = new stdClass();
  $block->content = $data;
  $block->title = '';
  $block->id = 'my_module_form';
  return $block;
}

How do I port the plugin to Drupal 8?

There are no ctools plugins anymore in Drupal 8. There's just the Drupal 8 plugin API.

Page Manager, Panels and so on use standard block plugins now in 8.x, so you basically have to port this to a block an then it should work fine.

Also, the "code" you posted only defines that you have such a plugin in your module, nothing else. If you need more specific support, you will need to post your actual code, and ask specific questions (which are probably better as a follow-up question).


Set parent service when registering a service in a ServiceProvider I want to create dynamic services, therefore I added a ServiceProvider class to my module.

I have created a base service that my other services will have as parent.

When doing this in my_module.services.yml, I can just use:

parent: service_name

But I can't find out how to do in the ServiceProvider class.

My class looks like this:

class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritDoc}
   */
  public function register(ContainerBuilder $container) {
    // Create services for our base normalizer classes.
    $container->register('MY_MODULE_rest.entity_normalizer_base', EntityNormalizerBase::class)
      ->addArgument(new Reference('entity_type.manager'));

    // Create node normalizer service.
    $container->register('MY_MODULE_rest.node_normalizer', NodeNormalizer::class)
      ->addTag('normalizer', ['priority' => 1])
      // How can I set "MY_MODULE_rest.entity_normalizer_base" as the parent for this one?
      ->addArgument(new Reference('path_alias.manager'))
      ->addArgument(new Reference('language_manager'));
  }
}

You can find your answer in the symfony docs, How to Manage Common Dependencies with Parent Services. In the third snippet we see:

use AppBundle\Repository\BaseDoctrineRepository;
use AppBundle\Repository\DoctrinePostRepository;
use AppBundle\Repository\DoctrineUserRepository;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Reference;

$container->register(BaseDoctrineRepository::class)
    ->setAbstract(true)
    ->addArgument(new Reference('doctrine.orm.entity_manager'))
    ->addMethodCall('setLogger', [new Reference('logger')]);

// extend the AppBundle\Repository\BaseDoctrineRepository service
$definition = new ChildDefinition(BaseDoctrineRepository::class);
$definition->setClass(DoctrineUserRepository::class);
$container->setDefinition(DoctrineUserRepository::class, $definition);

Looking at the docs and your code, my understanding is you'd do something like:

use Symfony\Component\DependencyInjection\ChildDefinition;

class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritDoc}
   */
  public function register(ContainerBuilder $container) {
    // Create services for our base normalizer classes.
    $container->register('MY_MODULE_rest.entity_normalizer_base', EntityNormalizerBase::class)
      ->addArgument(new Reference('entity_type.manager'));

    $node_definition = new ChildDefinition('MY_MODULE_rest.entity_normalizer_base');
    $node_definition->setClass(NodeNormalizer::class);
    $node_definition->addTag('normalizer', ['priority' => 1]);
    $node_definition->addArgument(new Reference('path_alias.manager'));
    $node_definition->addArgument(new Reference('language_manager'));

    // Create node normalizer service.
    $container->setDefinition('MY_MODULE_rest.node_normalizer', $node_definition)

  }
}


How do I construct a thin controller with a dependent service? For the first time I am trying to architect a reasonably complex Drupal 8 module, and not sure of best practice for the controller.

I need to route paths to a controller.
I intend the controller to be
thin (very little logic, doesn't need to testable)
Heavy lifting will be via service class/es configured and defined by the module.

Extending ControllerBase should be the right path for a thin controller, however when I look in Core at the moment I notice a number of controllers that both extend ControllerBase and implement ContainerInjectionInterface. I would only implement ContainerInjectionInterface to be able to inject a different container for testing, not just selection of service in the create method, but Core is still in flux and I am not sure exactly why they are doing this.

I feel that I should extend ControllerBase, add a __construct that fetches the container and pulls in the non-standard service/s that I require via $this->container()->get() and indeed that does work. I also don't need the create method required to implement ContainerInjectionInterface.

Am I correct? I know I will need to go through a few iterations of getting the services right but want to get THIS bit right from the start and understand why I am doing it.

Thanks in advance.

ContainerInjectionInterface is used as a part of a static factory method pattern.

This way, a class's constructor can specify all of the services it needs, and its factory method, in this case create(), can satisfy the constructor by retrieving services from the container.

The instantiated controller should never have its own copy of the container, if at all avoidable.

A brief example:

<?php

namespace Drupal\book\Controller;

use Drupal\book\BookManager;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class BookController extends ControllerBase implements ContainerInjectionInterface {
  protected $bookManager;

  public function __construct(BookManager $bookManager) {
    $this->bookManager = $bookManager;
  }

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

  public function bookRender() {
    $book_list = array();
    foreach ($this->bookManager->getAllBooks() as $book) {
      $book_list[] = l($book['title'], $book['href'], $book['options']);
    }
    return array(
      '#theme' => 'item_list',
      '#items' => $book_list,
    );
  }
}

This would be declared as a controller in a routing file like this:

_content: \Drupal\book\Controller\BookController::bookRender


How do I add custom content fields to content types in Open Social? I am trying to add fields to my new custom content type in Open Social (OS), the Drupal social networking distribution. I follow the regular procedure of adding a new custom content type from /admin/structure/types/add.  OS will add the custom content type fine, but then after the new content type is created, the list of content types at /admin/structure/types shows only Edit or Delete operations in the combo box for the operations, with Edit being the default. Normally, there are possible operations of Manage fields, Manage form display, and Manage display as well in the combo box for the operations. Furthermore, when I use the normal path for adding a custom field for the content type, namely /admin/structure/types/manage/<content type>/fields where <content type> is the content type I just created, I get an error message of The requested page could not be found. OS exhibits the same behavior for existing content types like Topic. I have found this to be the case for version 8.7.8 and 8.8.10 of OS.
Does anyone know how to enable to ability to add and manage custom fields for new content types in Open Social?

Simple answer after I looked into it more. The issue is just whether the Field UI module (field_ui) is enabled or not. This is a Drupal core module and by default it is not enabled in Open Social. But once field_ui is enabled, then all of the custom fields can be managed appropriately.


Multivalue field with Twig and its length I am playing around with Twig and D8. I created a content type called community and it contains a field called field_banner_images which is an image field with a max limit of 10 images.

I am trying to get the length of field_banner_images via Twig, but the number I am receiving is incorrect. My current node has 10 images on it. It also has alt text enabled if that makes a difference.

I created a file called node--community.html.twig and inside I have:

{{ content.field_banner_images|length }}

which outputs 26, which is wrong. I would expect it to output 10.

Furthermore, I add

{% for item in content.field_banner_images %}
  {{ content.field_banner_images[loop.index0] }}
{% endfor %}

and while it does output the 10 images wrapped in span elements, I also get 16 empty span elements since it is looping 26 times.

What am I doing wrong here?

How to count in page or node template

content is the render array of the fields, that is build according to the view mode you have configured. The render array contains a lot of additional elements, that are not field items.

If you want to count the items in the field that are in the database, use the node object:

In php:

$node->field_banner_images->count();

In twig:

count() is not on the whitelist of allowed methods. Use .getvalue() instead, which gets the complete field array and count the array keys with the filter length:

{{ node.field_banner_images.getvalue|length }}

Better solution with field template

But you don't have to code the loop yourself in the node template, you can add the wrapper in the field twig.

Put the complete field in the node template:

{{ content.field_banner_images }}

And then put the wrapper in:

field--field-banner-images.html.twig

{% for item in items %}
    <span>{{ item.content }}</span>
{% endfor %}

You can remove the content of the field twig and replace it with the code above. You know the content of this field and you don't need the div containers, when you want span's.


Monitoring strategies for infrastructure Lately, I have been facing some downtime on some of the Drupal sites I have deployed. I would want to approach the problem pro-actively, rather than reacting to those downtimes by restarting services or the server itself. I have read about monitoring tools like nagios, munin, cacti, etc to monitor the health of your server/infrastructure, but I haven't really tried one in production. I deal with Drupal almost 99% of the times, and I would like to find out suggestions for both server level monitoring, and Drupal (application code) level monitoring.

Basically, I would like to be notified when the server load is high, possibly being pointed to the culprit (or the victim), so that I could take informed decisions. I would also like to know what people use for Drupal level monitoring (such as emailing) when there is a PHP error/warning. (What happens when the email server itself is down?)

If you want monitor several Drupal sites from the same place with alerts, etc... I can say you are not the only one . It's starting to be a business niche, by now filled by:

Droptor
New Relic   (Acquia is using it for their
customers)

Both are commercial SaaS approaches, with free limited options to try the service.

Also there is the Open Source Zabbix monitoring option with its Drupal module http://drupal.org/project/zabbix , but then you should configure and build yourself the server.

All these options have their Drupal modules to send server and drupal-specific information to the monitor server.

UPDATE.  Munin has also a specific Drupal Module , with a 2.x branch based on Drush.


Inline class annotation with /** @var or just comments? I found in some drupal commerce modules class comments in way I haven't seen so far

/** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */
$payment = $this->entity;
/** @var \Drupal\commerce_paypal\Plugin\Commerce\PaymentGateway\ExpressCheckoutInterface $payment_gateway_plugin */
$payment_gateway_plugin = $payment->getPaymentGateway()->getPlugin();

I am not sure what to google to get to know more about this, why was it used like that and is this annotation or just plan comment?

I checked more about annotations and it doesnt makes sense to have them in places other then outside the class, as stated on d.org, so this is just plain comment for IDE's to connect what is used there.

  In addition, there is a performance bonus as it makes Drupal use less
  memory when discovering plugins. The original implementation had a
  getInfo() method on each class, similar to Drupal 7 test classes. This
  meant each class had to be loaded into memory to get its information
  and the memory was not freed until the end of the request, thus
  greatly increasing the peak memory requirement for PHP. Instead, the
  implementation used by Drupal to parse the annotation simply tokenizes
  the text of the file without including it as a PHP file, so memory use
  is minimized.


Content type to Drupal commerce I currently have a Drupal site with a content type of Training where a variety of different training courses are listed. We are looking to sell these courses with Drupal commerce.

How do we go about turning these courses to items visitors can buy?

EDIT:

OK. I think I may have it now. Sorry for the poor comment, it was late and I hadn't messed around with commence much - Now I have!

My query is how and where best to have the fields, which I believe is a common Commerce question

Each Training has the fields of:
- Title
- Body
- Who should attend this course
- Course Structure
- Dates

How is best to sort the content fields for a Training course:

1)
Product Variation type to have all the fields above - So each course will essential be a product variation?

OR

2)
Content type to have the fields with only reference to product for the price?

My reasoning for this question is I don't have the experience to know what is best for future development where I might be looking at managing available places (Which I fore see done with stock?)

I recommend making a sandbox install of Commerce Kickstart to see how they set up "Product display node" and "Product entities" to work together. Your "Training" content type would be the Product display node, and each course offering would be the product. To replicate this on your existing site, the high-level approach (you will need to sort details) is this:

Install Commerce and create references from Commerce product entities to your Training content type
Create some products that represent your courses. You can add custom fields where needed.
Display the products that are referenced to the Training nodes using Views module or methods similar to those used in Commerce Kickstart
This should give you a list of courses on each Training node that can be added to Commerce cart.


Search using view and facet as block In my project I need facet search as block view that need to be included in content region. So I created View as block and added facet block in header of the view. Also need infinite scroll, so enabled ajax in view. So issue is that facet search ajax and View ajax causing conflict so that the query parameters are duplicating in URL.

http://localhost.com/sample-page?q=/sample-page?q=/sample-page?filter[0]=category_filter:171&_wrapper_format=drupal_ajax&filter[0]=category_filter:171&filter[1]=category_filter:173&filter[2]=category_filter:174

Is there any workaround to fix this? Any patch is available for this ?

I applied this patch
https://www.drupal.org/files/issues/2019-07-31/facets-3070461-3-Facet-links-break-in-modal_0.patch and issue resolved. Hope this will be helpful for others.


Where do I put the Houzz Badge code? I'd like to add a Best of Houzz badge on our site.  I have the code, but don't know where to put it.

Is it Admin --> structure --> ... then what?

Since the site was built by someone else and now I'm maintaining it, I really don' want to mess anything up by poking around and "experimenting."

Go to: YOUR_SITE/admin/structure/block/add and fill the info like this:

In Block body field you must put the code of the badge and go to the bottom of the page to Save block.

Then in the YOUR_SITE/admin/structure/block page search your block, in this case the name is "Best of Houzz badge" then select the region where the block will be displayed (in this case Sidebar first)

Go to the bottom of the page and click in the Save blocks button.

And you will see the block in your site.


Is there a way to render a node with view mode via token? Is there a way to render a node with view mode via token? Like:

[node:5:teaser]

So the question is how to insert something like [node:5:teaser] into a formatted text area and get the teaser view of node 5.

This can be done with a combination of modules:

Token Filter (D7,D8)

  Token Filter is a very simple module to make token values available as an input filter.

So (after adding that filter to the text format), for the current node, we can use e.g. [node:title] in formatted text.

Token Entity Render (D7, D8 Issue)

  Provides tokens ([entity_type:render:view_mode_name]) that render full entities using view mode specified.

Advanced Entity Tokens (D7, D8 Issue)

  Through AET you can query the DB for entities using Tokens.
  Examples: [aet:node:1]

Putting it together

In the end you should be able to use [aet:node:5:render:teaser] in your formatted text.


References vs. Books If you were about to create a hierarchy of nodes that can have parents and children, which way would you go for? Using "References" module or the "Books" module that is included in the Drupal standard installation? And why please?

For a strictly hierarchical organization (i.e. an inverted tree) I would use the core Books module.  With a book, you get some "extras" to help you with maintenance and navigation. E.g. you get a drag and drop UI to help you re-organize the entire book (or parts of it), you get up/down/sideways navigation links automatically created and inserted, and you get meaningful breadcrumbs.  You also get a "Create child node" link at the bottom of any node that is part of the book.

Also note that in Drupal 7, any node content type may be included in the book (i.e. you're not restricted to the "Book page" content type. However, you can't include non-node entities such as taxonomy terms, files and users.

I would not use the References as it is more restricted than the Entity reference module.

And I would only use the Entity reference if I wanted to create a linked structure that is not hierarchical but some sort of directed graph, or I wanted to include non-node entities in this structure.

A typical use case for the Entity reference module would be the "Related issue", "References", "Referenced by" (directed graph); and "Parent issue", "Child issue" (hierarchical) links that are maintained in the new issue tracker system at the D7 version of Drupal.org.

To sum up.  You get a lot of tools for maintaining the structure for free with the core Books module, but you're restricted to having a hierarchical structure made up if nodes.

With Entity reference, your structure can be made up from any entity type, and it can be a directed graph, but there is no tools to help you maintain the structure or to navigate it (beyond clicking on the links).


View only content created by that particular user I want the user to view only the content created by him.

Used "content access module". And change permissions for the user to "Grant own Content Access".

But other users also able to see the content created by other users.
Below is my permissions page:

Not able to find what went wrong.
Please correct me.

If any other module is there please suggest me.

Follow below steps to resolve the issue !

Enable Content Access Module
Clear Cache
Go to Edit Content Types, and Select Access Control
Set Access Control As shown below. Remove checkbox view any article content for anonymous and authenticated users.
Save Settings
Go to "admin/reports/status/rebuild" and rebuild permissions
Create a Content of content type that you set access permissions.
Logout and Login as another normal user and check for access.

Let us know if still fails :-)


Drupal 7 Ubercart Rest Services Module (API) I'm looking for the best way to retrieve Ubercart orders and customers from a remote server.
I'd like to plug in a connector the same way it works with Magento.
I've played a little bit with Services but didn't figure out how it works with Ubercart.

Does anybody knows where I can find the right module and documentation ?

You could use the Bee Colony - Ubercart synchronization Web Service module.

  Bee Colony is a communication service (based on services module) for Ubercart based sites. Bee Colony allows site administrator to provide full remote control over Ubercart orders and products.

  Main objective is to build a client/server system to allow external software to synchronize its database with Ubercart.

  This project mission is to evolve Bee Colony to provide an easy and powerful way to create client-side software for companies and promote in this way Ubercart use.


D8 - How to create a view to show content with a field that is a User Reference to currently logged in user only In Drupal 8, I have a content type Medical Records that has a field that is an Entity Reference to Users. I want to create a View which will display Medical Records with that field for the currently logged in user.

How can I do that?

you have to create a contextual filter, which will take current user as default value, you can find nice explanation and screenshots here:

http://redcrackle.com/blog/adding-contextual-filter-view-drupal-8

Just filter on Content: your field name instead of Content: Authored by


Module is reported to be missing, but it's present and active I have a field type that have some default dependencies, such as Ctools and Views.
I need the Able Player module, which is for Drupal 7.
I installed this module, configured the Able Player libraries and checked that all is OK in the report section.
This module is installed in /sites/all/modules/able_player folder.
In my info file I wrote the following line.

dependencies[] = able_player.

When I attempt to activate my module, Drupal says that the Able Player module is missing, but it is present and active.

For a test, I tried some other modules, such as the jQuery Update module, and it works fine.

Why does Drupal say the module is missing?

You can not install a Drupal 7 module on Drupal 8. That's not possible.

The module needs to be converted to Drupal 8. Drupal reports the module as missing because the .info file is now info.yml, so Drupal does not find a able_player.info.yml file anywhere and correctly reports the module as missing.


What determines who can view an unpublished node? The Node Access documentation explains that there are three things that affect node permissions, used in this order of preference until an answer is received: an overriding bypass node access permission; hook_node_access (used on single nodes and not in listings); hook_node_grants (which compares against the node_access table).

What I can't see is how (un)published content is handled. The only default implementation of hook_node_access is node_node_access which you can see completely ignores the 'view' mode, answering only for create/delete/edit modes.

The hook_node_grants docs say explicitly that (un)published content is "not handled by the system".

But there are the checkboxes in the user permissions table for view published content and view own unpublished content etc. Where are these implemented?

It is handled by node_access:

it checks for the "view published content" - without this permission every operation is denied, published or not.
it checks the view own unpublished content permission.
it checks if hook_node_access gives either deny/allow. If not...
If no module implements hook_node_grants then there's a default allow for published nodes (and therefore a deny if not).
If modules do implement hook_node_grants then the node_access table is consulted. I found that published content receives a "default grant" in the node_access table thanks to node_access_acquire_grants, meaning anyone can view it. Unpublished content has no default grant so is therefore denied.


Sanitized text input for EntityMetadataWrapper set() Through searching, I've found plenty of examples using the EntityMetadataWrapper set() function to update entity fields, and have implemented it successfully in my module. However, I haven't been able to find much in the way of documentation / best practices on the different array options you can pass to set(). I want to make sure the way I'm updating data won't cause unforeseen issues later on.

I am doing a straightforward update of text field values in a form submit callback:

function hook_FORM_ID_submit(&$form, &$form_state) {
  // Get the node.
  $node = node_load($form_state['nid']);

  // Create entity metadata wrapper to get and set values easily.
  $node_wrapper = entity_metadata_wrapper('node', $node, array('bundle', $node->type));

  // Set fields
  $node_wrapper->field_quip->set(array("value" => $form_state['values']['field_quip']['value']));
  $node_wrapper->field_short_sentence_summary->set(array("value" => $form_state['values']['field_short_sentence_summary']['value']));

  // Save node.
  $node_wrapper->save();
}

I am passing set() an array with only one key: value. This seems to be working fine. However, I notice that when I call value() on that same field before I set a new value, it returns an array with three keys:

$original_value = $node_wrapper->field_quip->value();

// Output of $original_value:
// Array (
//   'value' => '
The original value
',
//   'format' => 'general',
//   'safe_value' => '
The original safe value
',
// )

The way I am current setting fields, I lose the sanitized value. Will this come back to bite me? Should I be running check_markup() on the value and passing format and safe_value to set(), rather than an array with just value? I might be splitting hairs here, but I want to make sure I do things right.

It turns out that if you just set the value, Drupal will not display your HTML without converting your tags to entities. So the value
Foo bar
 will be displayed literally in Views (and other areas) as &lt;p&gt;Foo bar&lt;/p&gt;.

Rather than attempt to create a sanitized safe_value myself before calling set(), I found that if I passed a format value, Drupal will take care of the sanitization for me with the filter settings defined for that format.

So the correct syntax is:

$quip = array(
  "value"  => $form_state['values']['field_quip']['value'],
  // Change to match the text format of your field.
  "format" => "general"
);
$node_wrapper->field_quip->set($quip);


Alternate of using "delivery callback" $items['mymodule/%user'] = array(
  'title' => 'My Module',
  'page callback' => 'mymodule',
  'page arguments' => array(1),
  'access arguments' => array('access user profiles'),
  'type' => MENU_CALLBACK,
  'delivery callback' => 'mymodule_ajax_callback',
);

Above code is from D7, I've used "mymodule_ajax_callback" as my "delivery callback" in D8 but I'm unable to find a way.

Tried finding solution here Structure of routes but I'm unable to get the solution.

You are looking for responses. For example, in a controller, you can return a renderable array, a Symfony Response object, or specific responses (AjaxResponse, JsonResponse) to respond to the request.

For example, AjaxResponse in the docs, and here is an example of a controller responding with it:

https://www.mike-miles.com/blog/creating-ajax-callback-commands-drupal-8


How to have different displays for the same node type using Display Suite? I use display suite module to manage the display of node types. So far so good.

I know that there is a way to have different display for the same node type. Let's say I have 2 nodes of the basic page node type. Then I'd like to set 2 column stacked for the first one and single column for the second node.

But I don't know hot to do it.

You can easily do this with display suite but you need to enable the DS extras module.

First create 2 different view modes using different layouts to cover your specific use case.

Next go to admin/structure/ds/list/extras and enable 'View mode per node'.

Now when you create content you can choose which view mode you would like the content to use.

This is a great way to give your content editors control over layout choice.


Json views not displaying in json format, instead displaying in web view I created a json view for a CCK.
I am trying to display the view on my webpage. The data is rendered as a web page. But i need something like exact json response.
Here is the screen shot

Please help to find out the solution.
Thank you

ya i got the solution. Just un_check the Viewa API
Hope this will help some one


How do I change html structure of menu (primary links for example) to my own? The default HTML structure of the primary links menu is not what I'd like it to be. How can I override it with my own version?

I am assuming you are working with drupal6 and you have basic understanding of variables and arrays. Default html structure of the primary links is formed at different places in drupal. First if you start with the wrapping div id, in your theme's page.tpl.php file where you print $primary_links change it as the following example:

 <?php print theme('links', $primary_links, array('class' => 'links primary-links dk_two')) ?>

In order to change what is in $primary_links use the following code in template.php file of your theme.

    function yourThemeName_links($links, $attributes = array('class' => 'links')) {
  $output = '';

  if (count($links) > 0) {
    $output = '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = $key;

      // Automatically add a class to each link and also to each LI
      if (isset($link['attributes']) && isset($link['attributes']['class'])) {
        $link['attributes']['class'] .= 'dk_three ' . $key;
      }
      else {
        $link['attributes']['class'] = $key;
      }

      // Add first and last classes to the list of links to help out themers.
      $extra_class = '';
      if ($i == 1) {
        $extra_class .= 'first dk_four ';
      }
      if ($i == $num_links) {
        $extra_class .= 'last dk_five ';
      }
      $output .= '
 $extra_class . $class)) . '>';

      // Is the title HTML?
      $html = isset($link['html']) && $link['html'];

      // Initialize fragment and query variables.
      $link['query'] = isset($link['query']) ? $link['query'] : NULL;
      $link['fragment'] = isset($link['fragment']) ? $link['fragment'] : NULL;

      if (isset($link['href'])) {
        $output .= l($link['title'], $link['href'], $link['attributes'], $link['query'], $link['fragment'], FALSE, $html);
      }
      else if ($link['title']) {
        //Some links are actually not links, but we wrap these in  for adding title and class attributes
        if (!$html) {
          $link['title'] = check_plain($link['title']);
        }
        $output .= '' . $link['title'] . '';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

Clear your cache and you will see dk_one dk_two dk_four dk_five  div ids and classes in your html structure of your primary menu. Please let me know if it works for you.


Applying CSS to sub theme created by Omega I am creating responsive theme. To create a theme I have created subtheme of Omega theme.

Until the creation of subtheme every thing was easy. Now after creating the subtheme I want to apply the CSS provided by the designer. But the problem is that designer has created different class name and div tags than Omega.

I am stuck now, I don't know from where should I start ?

What will be the best practice in such type of cases when subtheme and CSS provided by the designer has different class and divs

Two solutions:

rename in the CSS
rename in ALL .tpl.php file's theme

There are no other solutions.


How to ONLY display an image in the teaser for Drupal 7 I'm currently using a modified version of the Stark Theme, customized to what I need, on this site tobyNews. However, following some new design inspiration, I've decided that instead of showing text in the teaser I want to ONLY display an image. Each image would be displayed as a grid. What I need help on is getting the teaser to show just an image and not the title, date, or author.

The display suite module will give you this feature. It will give you advanced teaser-templates where you will be able to display one or multiple fields (and the option to display title or not) + you will get along quite easily!


Print specific block from a region in drupal 7 The region name is "sidebar_first". and it has two blocks. How can I print this block separately. Please help. I can not find the way to print a specific block from a region in drupal 7.

You can use this method:

$module = 'my_module'; // This is the module that provides the hook_block_view
$delta = 'my_block'; // you can get $delta from moduel hook_block_info
$block = module_invoke($module, 'block_view', $delta);
print render($block['content']);


Login Process Redirect Back to Page I'm working on a process to prompt users to a login when clicked on a link first. For instance, if click on http://www.example.com/tester, the user will be prompted to log in. After loggin in, the user will be redirected to the current page http://www.example.com/tester.

I've tried LoginToboggan as well as Login Destination.

Login Destination should allow for "current" but it doesn't work.

Both of the modules have similar ways to do it i'm sure.

Check Redirect 403 to User Login

  Redirect the HTTP 403 error page to the Drupal /user/login page with
  an optional message


Add class to template based on boolean field I want to add a class to my custom Display Suite template if a boolean field is checked on the form. I have the following code:

if (isset($node->field_boolean_field[LANGUAGE_NONE][0]['value']) == 1 ) :
    $class = 'this-is-the-class';
endif;

And then in the appropriate place:

<a href="#" class="<?php print $class ?>">link

This always returns the class regardless of whether the boolean field is checked or not though.

link

Any thoughts on what I could be doing wrong here?

Many thanks

You have written wrong logic in if statement. Correct way is following:

 $class = NULL;
 if (isset($node->field_boolean_field[LANGUAGE_NONE][0]['value']) && $node->field_boolean_field[LANGUAGE_NONE][0]['value'] == 1 ) :
        $class = 'this-is-the-class';
 endif;


How to use Php code in Views page contextual filter with dynamic URL i.e using %? I have a content type App with a term reference field called App category.

I'm creating a view page with path app/%. I don't want to use App ID or anything numeric in URL in place of %, so I'll be using app/cooking-app where cooking-app is URL Alias of App Category.

How can I display all the nodes whose value in App Category field is cooking-app? I can easily do this using PHP code but PHP code in contextual filters is not working.

I'd highly recommend not using PHP code to do this; tying PHP code to configuration can be error-prone and it won't exist in Drupal 8's Views.

Rather, you can use the solution in Drupal 7 views contextual filters taxonomy name where you can use the Validator, Taxonomy Term, instead of PHP Code, with the Term name converted to Term ID filter.


How can execute batch api over cron jobs I am working on Drupal 8 and batch API. I created the batch api calling importingmatch and it should automatically importing every 1 hour.

My solution is use Drush for make it works without the browser, but I don't know how I can get the batch id.

Here is my code about the Batch API:

// Set up the Batch API
    $batch = array(
        'operations' => $operations,
        'finished' => 'importingmatch_finishedBatch',
        'title' => t('Import match'),
        'init_message' => t('Starting import match.....'),
        'progress_message' => t('Completed @current step of @total.'),
        'error_message' => t('Import match deletion has encountered an error.'),
    );

    batch_set($batch);

Currently, this batch is runing perfect if I access from my PC. Url: www.mysite.com/importing_match
I am not sure how make it working from the server Centos with Drush, I need the batch ID for execute: Drush batch-process

UPDATE:
- Interesting with the Command for Drush, I created custom Command from my module. Following from here: https://www.chapterthree.com/blog/how-to-create-custom-drush-commands. But it's still not working, it's showing:

The drush command '<name>' could not be found.

I changed from localhost to 127.0.0.1 from the settings.php but it's not helpful. Any idea?

You don't. Batch API is to do long-running processing with user-interaction.

For cron, you either use queue API or you just process for N seconds/things in your hook_cron() implementation, and in both cases, cron will be calling you repeatedly until it is eventually done.

If you want to process as fast as possible then either use a different queue processing that doesn't run on cron or make a custom script/drush command that you execute separate from cron, so that you don't block other cron jobs.


Last-Modified header is changed, even if the resource hasn't changed Unless I'm mistaken, Drupal is changing the "Last-Modified" HTTP header for a page any time the page cache is regenerated - even if the raw content remains identical.  This means that clients end up having to re-download exactly the same information any time the page cache is regenerated even for pages that have not changed at all.

I realize that I can improve this situation by trying to engineer things such that the page caches are not regenerated unless the resource has changed, but is there any way I can set things up such that the Last-Modified header genuinely reflects whether or not the content has changed?  This would seem to me to be a more robust solution.

The code that is causing the issues you're describing lives in drupal_serve_page_from_cache(). Instead of using a hash of the contents of the cache; Drupal uses the $cache->created value. Looking over everything hacking core is the only option at the moment. I'll see if there can be a way of not hacking core if one has total control of the cache backend; if there is a way look for an update inside of https://www.drupal.org/project/apdqc


Create custom signup block with mailchimp module? I'm looking for code examples for creating custom mailchimp signup forms that use the mailchimp api integration provided by the mailchimp module.

Context: I have a D7 site using a standard embedded sign-up form for mailchimp. I just recently switched the site to https, which unfortunately causes some browsers (e.g. firefox) to throw a scary message when a user clicks the submit button on the sign-up form, because standard mailchimp embedded forms can only use http.

The mailchimp module uses the mailchimp API, which allows secure connections, so that's the obvious solution. And the mailchimp module automatically provides a block for each list. But the module makes assumptions that I don't want. So, instead of the automatic block provided by the mailchimp module, I'd like to create my own block(s) with a sign-up form that uses the api, so that I have more control over the look and feel of the form.

Also, I know the webform mailchimp module provides a mailchimp component for webform, (there's a good write up here) but I'd like to explore creating my own forms as a first step.

In the end, this is what I did:

Installed the mailchimp module and connected drupal to a list in mailchimp using normal instructions and an API key that mailchimp provides.
Created a new custom module that creates and displays blocks using standard hook_block_info and hook_block_view code.
Created a very simple form with hook_form, with a companion submit function, hook_form_submit, and add this form to the block(s) created above.
In hook_form_submit, I open a connection to the mailchimp api with:

$q = mailchimp_get_api_object();

Then subscribe the user with:

$success = $q->listSubscribe($list_id, $email, $merge_vars, 'html', TRUE, TRUE);

The above functions are documented in the mailchimp api.

So, in the end, I'm not really using the Drupal mailchimp module for anything other than providing access to mailchimp api over a secure connection (the drupal site is running https). The main advantage of this approach is complete control over the look and feel of the forms that appear in the blocks, and the actions taken when a user submits.

Another advantage: Because I'm using hook_form_submit to control processing once the form is submitted, I can add the form location (using request_path()) to the merge variables that are passed back to mailchimp. That way, the form is the same on every page that it appears, but the location is passed back to mailchimp as part of the sign-up process.


Domain based on alias Currently we use the Domain Access module to make a couple of domains.
Our current domains are for example:

www.domainemployer.com
www.domainclient.com

But our client now wants it to be like this:

www.domain.com/employer (<--- previously domainemployer)
www.domain.com/client (<--- previously domainclient)

I don't see if this is possible with the domain access module. Can anybody point me in the right direction?

Should we do this with rewrite rules (but is this going to clash with the current existing rules)?

I think Domain Path module can solve your issues.

  The Domain Path module allows the creation of separate path aliases
  per domain for nodes created using the Domain Access module.


Round Commerce Price: in tpl.php or template.php Currently I'm using Commerce and Commerce Multicurrency to our currency in Indonesia.

Sometimes there is a price to numbers that are not rounded.

With print render ($ content ['product: commerce_price']) I get the original price.

I've tried to edit the tpl.php file and the results are as desired.

number_format (round ($ price, -4), 0);

2,511,000 into 2,500,000
2,565,000 into 2,600,000

But after some reading and hopefully not misread. That is not good in tpl.php, but should be in template.php or modules.

Please advise to help me.

A better way to adjust currency formatting, using the relevant Commerce currency hooks, is with

hook_commerce_currency_info_alter

and adding your own commerce_currency_format handler

e.g:

/**
 * hook_commerce_currency_info_alter
 *
 * Add custom currency format to selected currencies
 */
function MY_MODULE_commerce_currency_info_alter(&$currencies){
  $currencies['IDR']['format_callback'] = 'MY_MODULE_commerce_currency_format';
}

/**
 * Currency format callback
 *
 * Remove decimal places from output
 * while keeping commerce_amount_to_decimal formatting the same
 *
 * See: commerce_currency_format
 */
function MY_MODULE_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {

  // Format the price as a number.
  // In our case, we remove decimal places
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  // Establish the replacement values to format this price for its currency.
  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

  return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}


Can you change the list builder class used by an entity? There's an entity created by another module and I'd like to change some of the fields used on a listing page. Currently that page is using the entity's list builder class. Is there a way I can define a new list builder class, make my changes, and use that for this entity? I have tracked this down to where D8 get's entity definition and loads the list builder class from that. I can't find a way to alter the definitions or another way to inject a different class here.

In more specific terms, I have created an entity with ECK and want to override the functionality around EckEntityListBuilder.

You want something like this:

<?php

/**
 * Implements hook_entity_type_alter().
 */
function MY_MODULE_entity_type_alter(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['node']->setListBuilderClass('Drupal\MY_MODULE\NewListBuilder');
}