Is it possible to use an Oracle database for Drupal 8? We are evaluating Drupal 8, and one of our needs is to use Oracle as the main (and only) database.

Is it possible to use Oracle as the Drupal 8 database? Can be a problem with the external modules?

And another question: The database access layer in Drupal 8 is Doctrine, or module developers can use hand-written queries (so, MySQL dependant queries)?

As of now no. only in Drupal 7 we have.
Drupal 8 supports MySQL 5.0.15 or higher (or MySQL 5.1.30 or higher) with InnoDB as the primary storage engine, and requires the PDO database extension.
https://www.drupal.org/requirements/database

https://www.drupal.org/project/oracle -  drupal 7

see the here for further info the thread is postponed as of now

https://www.drupal.org/node/2037119


How to convert user menu tabs to menu links? I have on user account 5-6 tabs created by some modules.My wish is to covert these tabs to menu items so as to insert to 2 separate menu links.
I have read that something like that could be possible with hook_menu_alter.
Is this correct?If so,how can I use it in my case?
thanks a lot

By creating an extremely simple custom module, you can Remove tabs using hook_menu_alter. Make sure to also clear the cache when you experiment with this.

Note: Consider refining your question to specify the path of each of those tabs you want to replaced.


check "checkbox is checked" before submit I created a template for a content type. This content type has a field of type radios, with values 0 and 1.

My requirement is to display a Submit Button if "1" is selected, and then hide when "0" is selected.

All you need are Form API's #states.

function MYMODULE_MYFORM($form, &$form_state) {

  $form['radio_buttons'] = array(
    '#type'   => 'radios',
    '#options' => array(0 => t('Hidden'), 1 => t('Visible')),
  );
  $form['submit_button'] = array(
    '#type'   => 'submit',
    '#value'  => t('Click Here!'),
    '#states' => array(
      'visible' => array(
        ':input[name="radio_buttons"]' => array('value' => 1),
      ),
    ),
  );

  return $form;
}


Show node hit counts in a VIEW? I have googled and found a few articles:

http://nossdutytask.com/drupal_config/step_by_step_enable_view_post_access_counter_on_drupal

Only I don't want to show the counter as a block but as a field in a VIEW. I followed the above article but when I add fields to my view I cannot find any stat or counter or anything.

Is this possible without writing a custom module or tweaking my template.php and populating this value programmatically?

You need to enable the Statistics module from admin/modules.

Configure what you want to track from admin/config/system/statistics

Then edit your view.  Add a Field.  There will be a category called Content Statistics that you can filter on.  Choose the stat you want, and then configure it.

The above is for Drupal 7 / Views 3.  The steps are mostly the same for Drupal 6 and Views 2 or Views 3, but the labels are a little different.

Just keep in mind that Statistics module can cause performance problems on busy sites.  You may also want to check out Radioactivity, and see if that will work better for you:

  This module provides a field type which can be used as a hotness
  metric or a regular view counter for entities and for much much more.
  In essense, entities receiving attention (views or actions defined by
  Rules) are heated while inactive ones slowly cool down.

Radioactivity does integrate with Views and a few places.


Permission to edit options per node In a content type there are tabs at the bottom for publishing options, add menu item, url alias, comments, etc. You can set defaults/access to these options when you create the content type. But what if you want to give the superadmin access to these options but not a lower level admin? And do this on a per node basis?

For example, I don't want the lower level admin to change the URL alias, publishing settings, or the menu position on a top section node, ie xyz.com/about. But he can make a revision.

The Override Node Options module looks like it would help you out. More details from the module's project page:

  The Override Node Options module allows permissions to be set to each field within the Authoring information and Publishing options field sets on the node form. It also allows selected field sets to be set as collapsed and / or collapsible.


Creating a view of relation fields limited to the relations that a currently viewed node is an endpoint of To first explain the set up, I have a custom content type that represents a candidate. I have a relation between candidate and users where the relation has some fields (using the relation module). I want to have a view that displays the fields of relation on the candidate page that has that relation.

So far I have tried Entity Views Attachment but the issue with that is it adds the relation view I have set up to every instance of candidate. I've also been trying view reference but that doesn't seem to be the module I'm after either.

I think I need to add something like an extra filter or something to the EVA view that only will show relations that involve the current candidate node, but I'm not sure if that is possible or not.

Instead of creating a view of relations, you should create a view of candidate nodes. Then you can use a contextual filter to limit the results of the view to the candidate node you are currently viewing. The fields of the relation can then be added via a relationship.

Create a view of content of type candidate, for example located at node/%/info; then under the Advanced settings of the view add a contextual filter with Provide a default value: Content ID from URL (i.e. the candidate node id) as the argument. You can use the same setting when the argument is provided by EVA instead of via the URL, with the default configuration of Use the ID of the entity the view is attached to (but the first example is useful to understand where the argument comes from).

Now in order to get the relevant Relation fields displayed, under Advanced add a relationship using Content: Relation: <your relation label> (node → relation).

Under Fields you can now add the desired Relation fields, specifying that it should use the relationship you just added.

Note the difference between relationship (≈ SQL table join) and relation.


Changing text "Create new account" in /user tab Does anybody know how to change the tab text "Create new account" in /user - I am using Drupal 7.

Many thanks

By writing a custom module that implements hook_menu_alter and alter the title of the menu.
Something like below.

mymodule_menu_alter(&$items) {
  $items['user/register']['title'] = 'New Text';
}

http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu_alter/7


Image Gallery Has Blurry Images My image gallery is showing the images blurry. Its using Ligthbox2. When I click on the images, they show clear in the lightbox. Is this a lightbox setting?

Setting my lightbox setting to Display: Single lightbox: large => large fixed the problem. thanks. :)


How do I add reCaptcha to a form programmatically? I have a custom form on my site, and I want to attach a reCaptcha to it. I wasn't successful using the Drupal 7 code for this. Suggestions?
This is the Drupal 7 code I'm using:

$form['recaptcha'] = array(
  '#type' => 'recaptcha'
);

Use the following (after installing the reCaptcha module):

$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);


Can't get narrow stylesheet to load in Omega commerce sub-sub-theme I've got a sub-sub-theme of Omega, namely, a subtheme of omega_kickstart_theme, which is in turn a subtheme of omega_kickstart, which is a subtheme of omega.

Here's my .info file (pastebin).

I've stuck the file freshstop-omega-alpha-default-narrow.css in the /css folder, and that's supposed to be all she wrote. It's supposed to load for the narrow layout.

But when I resize my browser and check for this file, it's not there, nor are its styles. Cache cleared, css aggregation off, etc. Firefox.

I've also tried freshstop_omega-alpha-default-narrow.css (note underscore instead of dash).

Hmm. Any deeper tips? Place to start debugging?

So it turns out freshstop-omega-alpha-default-narrow.css actually IS being added, just not at the breakpoint that I expected.

The problem is that I'm thinking from a more "mobile second" perspective. Here's the stylesheet cascade:

global.css
example-alpha-default.css
example-alpha-default-narrow.css
example-alpha-default-normal.css
example-alpha-default-wide.css

"Narrow" is included at 720px and wider, while global.css is included at all sizes. If one wants to target just mobile or smaller, one would have to create a new media query.

More information here: https://groups.drupal.org/node/156719


How do I embed views in node template Please how can I embed a view in a node template like node--blog--full.html.twig.

I have configured an about-the-author views to be embedded in full mode of blog content type using views-embed-view(), but it doesn't work. I have enabled the "Allow embedded displays" from views settings and followed a few tips online, but none seems to work.

Is there a better way to embed views in D8 node template?
How can I use views-embed-view correctly in D8?

Many thanks

Just to be sure, are you calling views-embed-view(), or views_embed_view() (Note the dashes/underscores). The second version (views_embed_view() is the correct one).

Also, how do you call the function? Which parameters do you pass?

As per this page, the correct way of embedding a view is 1 of the following ways.

Option 1:

// Get the embeded view and render it.
drupal_render(views_embed_view('VIEW_NAME', 'DISPLAY_ID'));

Option 2

// Get the embeded view and render it.
\Drupal::service('renderer')->render(views_embed_view('VIEW_NAME', 'DISPLAY_ID'));

In this example you will have to replace VIEW_NAME with the machine name of your view, and the DISPLAY_ID should be replaced with the ID of the display you want to use (Or can be omitted to use the default display).

Also note that the second option is the better one, since the drupal_render function is deprecated, and will be removed before Drupal 9.0.0 (More info).


How to use addField function when the field name is SQL keyword I have a field with name 'order' in the database. How to select it, using addField?

$query->addField('sco_groups', 'order');

Gives an error.

I fixed it, using this code:

$query->addField('sco_groups', 'order', 'field_order');


Theme_hook_suggestions not working I'm using hook_preprocess_node in a module. In that, I check whether the node type, and on satisfying the condition I'm doing a theme_hook_suggestions. My tpl.php files are inside my modules template folder, It is not taking the tpl file I have suggested. I have searched a lot, but didn't find any solutions

Any solution would be apprecaited
Here is my code

/**
 * Implements hook_preprocess_node().
 */
function mymodule_preprocess_node(&$varaiables) {
  if (isset($varaiables['node'])) {
    $node = $varaiables['node'];
    $field_template_list = $node->field_template_list[$node->language][0]['value'];
      if ($node->type == 'event') {
        $varaiables['theme_hook_suggestions'][] = 'module_name_' . $field_template_list;
      }
   }
}

Drupal will not look for template overrides in custom modules, only themes.

If you really want to put a template override in a custom module see the answer to this question.

Extra notes are:

Make sure to handle punctuation and any other undesirable characters in your field value.
field_get_items() is a better way to get the value of a field from a node.
It is generally best to keep your template suggestions in line with what is already there. For example starting this suggestion with 'node__' followed by your custom stuff, like maybe 'node__event__' . $field_template_list or something like that. It makes it easier in future to know what kind of template it is.


How do I alter the node entity? Maintainer of Custom Publishing Options here... trying to figure out how to port to 8 in a clean way.

https://www.drupal.org/node/2647410

I have config entities working, so I can define custom publish options in the admin.

From here, I would like to add these options on the Node form(s), but they also need to be stored in node_field_data table. Previously hook_schema_alter / entity_info_alter was used to do this, example below:

D7:

/**
 * Implements hook_schema_alter().
 */
function custom_pub_schema_alter(&$schema) {
  $types = variable_get('custom_pub_types', array());
  foreach ($types as $type) {
    $schema['node']['fields'][$type['type']] = array(
      'description' => t('Custom publishing option @name', array('@name' => $type['name'])),
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
    );
  }
}

D8:

function custom_pub_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'node') {
    $fields = [];

    foreach (Drupal::entityTypeManager()->getStorage('custom_publishing_option')->loadMultiple() as $machine_name => $publish_option) {
      $fields['cpo_' . $publish_option->id()] = BaseFieldDefinition::create('boolean')
        ->setLabel(t('!label', ['!label' => $publish_option->label()]))
        ->setDescription(t('A status added by custom publishing options.'))
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE)
        ->setDefaultValue(FALSE)
        ->setDisplayConfigurable('form', TRUE);
    }

    return $fields;
  }
}

$fields looks good here, and no errors are thrown - yet, I do not see any change to the data in the database. I would expect fields to be added to the node_field_data table, what is missing here? hook_schema_alter() has been removed, is there a way to trigger this to update that I don't see?

The purpose of this module is to let admins define their own statuses to use with the default node statuses, which from there they can combine them for different Views/Rules/Action capabilities. Being set on the node similar to status/promote/sticky made it fairly quick.

When entities are created, I had to do this to create them in the node table:

$manager = \Drupal::entityDefinitionUpdateManager();

if ($is_new) {
      // create the field definition for the node
      $storage_definition = BaseFieldDefinition::create('boolean')
        ->setLabel(t('!label', ['!label' => $label]))
        ->setDescription(t('!description', ['!description' => $description]))
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE)
        ->setDefaultValue(0)
        ->setDisplayConfigurable('form', TRUE);

      $manager->installFieldStorageDefinition($id, 'node', 'custom_pub', $storage_definition);
    } else {
      $storage_definition = $manager->getFieldStorageDefinition($id, 'node');

      if (isset($storage_definition)) {
        // update the label and description on the definition
        $storage_definition
          ->setLabel(t('!label', ['!label' => $label]))
          ->setDescription(t('!description', ['!description' => $description]));

        $manager->updateFieldStorageDefinition($storage_definition);
      }
    }


Replacing logo.png in a subtheme So, I created a subtheme, and added a random logo.png (found a random icon online, and renamed it). It worked, of course. Then I got the .png that I actually wanted to use... and the site won't update. I replaced the old logo.png file in the root of the subtheme's folder. The old file doesn't exist anywhere (as far as I know), but it's still showing it over the new logo.png

I've tried clearing the cache probably 30 or 40 times.
I've tried clearing my browsers cache, and using different browsers and computers just to make sure it wasn't some local cache
When I upload a custom logo.png through the theme's administration page, it works, but when I go back to the "default", it goes back to the old one. (I'd like this icon to be the default, not to have to choose a custom one.)

I'm not sure what else to try.

Does your subtheme heritate from another theme? Maybe you can paste your logo in the super theme folder too to erase its default logo as well.

edit: Even if I think that it's not a good thing to change Drupal core or contrib modules/themes directly in the files.


What is the best way to calculate the price from selected line item field (a select line item field) What is the best way to calculate the price from selected line item field (List field or maybe taxonomy) in final price ?

Example: we sell T-shirt. We define a color (list) as line item field, (red, blue, black)
Then we want drupal to calculate the price with multiplying to the value specified for selected color.
Red = 4
blue = 5
black = 6
The concept is that we don't want to make different product for each option, instead we want to use line item field (Select list) to calculate the price. Maybe for T-shirt doesn't make sense but it fits in our need.

How we can accomplish this and what is the best way of doing it ? Rules or own module ?
How we can specify a value for each color option?

I am more interested in coding approach, because there are a lot of different options and we don't want to make many rules for those.

The only reason I used following solution, was because we didn't need to make a product type for variety of options we had, and we had a lot of options which didn't make sense to make it as individual product.

I used rules, if any one find better solution let me know, hope it will help someone.

1) defined an action function to multiply the price to a coefficient

2) checked to see what option has been selected and proper coefficient has been applied

/**
 * Rules action: multiply the unit price by some amount.
 */
function modulename_unit_price_multiply($line_item, $amount, $component_name, $round_mode) {
  if (is_numeric($amount)) {
    // Coefficient variable
    $cf = '1';
    if(isset($line_item->field_color[LANGUAGE_NONE][0]['value'])){
        $selected_color = $line_item->field_color[LANGUAGE_NONE][0]['value'];
        switch ($selected_color){
            case 'red':
                $cf *= 2;
                break;
            case 'black':
                $cf *= 3;
                break;
           case 'blue':
                $cf *= 4;
                break;
            }
    } else {
        $cf *= '1';
    }
    $wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    $unit_price = commerce_price_wrapper_value($wrapper, 'commerce_unit_price', TRUE);

    // Calculate the updated amount and create a price array representing the
    // difference between it and the current amount.
    $current_amount = $unit_price['amount'];
    $updated_amount = commerce_round($round_mode, $current_amount * $amount * $cf);

    $difference = array(
      'amount' => $updated_amount - $current_amount,
      'currency_code' => $unit_price['currency_code'],
      'data' => array(),
    );

    // Set the amount of the unit price and add the difference as a component.
    $wrapper->commerce_unit_price->amount = $updated_amount;

    $wrapper->commerce_unit_price->data = commerce_price_component_add(
      $wrapper->commerce_unit_price->value(),
      $component_name,
      $difference,
      TRUE
    );
  }
}


Alternate page for mysql connection error I have a drupal 7 site. Recently I changed my mysql password but forgot to update the settings.php file. My website showed Cannot connect to mysql server for 3 days before I noticed and changed the settings.php file. My question is

Is there a way to display a custom HTML page (Like a maintenance page) when there is a mysql connection error ? Is there a module for that purpose ?

Having a look in drupal_bootstrap() for D7 it looks like hook_boot comes after the database "phase" so you'd need to put something in the cache phase or the configuration phase if you want to trigger a redirect before Drupal tries to bootstrap the database.

Easiest way would probably be to attempt to open a connection to the database yourself near the bottom of settings.php with the connection string defined earlier in settings.php and then if you detect a fail adapt this approach for "fast 404 pages" - http://2bits.com/drupal-planet/reducing-server-resource-utilization-busy-sites-implementing-fast-404s-drupal.html

You could print some html straight to the screen and exit().


Which is the best way to create an entity? I would like to use entity concept in my next project.So , is it good to use Entity Construction kit for creating entities ?
How about Model Entities ?
Which is better ?

The Entity Construction Kit (ECK) is a module to assist developers with creating their own entity types. If you want to export your entity types to code for version control and deployment use the Features module. If you don't want to do this (i.e. take the long way) write your entity type code using Model module as an example to follow (essentially the same thing).


use EntityFieldQuery to find user based on profile field value I have a field within the user's profile set with their payroll. What I'm trying to achieve within my module is find the uid, based on the value of a payroll field.

I've tried a few things, but I can't get it to work. What I'm currently trying is this, but it returns unknown field of user

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'user')
  ->fieldCondition('user', 'field_user_payroll', $payroll, '=');

$result = $query->execute();
$account = user_load($result);

$wrapper = entity_metadata_wrapper('user', $account);
$mimemail = $wrapper->mimemail->raw();

watchdog('Photo Import', "Mimemail: %mimemail",
  array('%mimemail' => $mimemail), WATCHDOG_INFO);

Any help would be really appreciated. It's driving me crazy!

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_user_payroll', 'value', $payroll, '=');
$results = $query->execute();

$users = user_load_multiple(array_keys($results['user']));
foreach($users as $user) {
    $wrapper = entity_metadata_wrapper('user', $account);
    $mimemail = $wrapper->mimemail->raw();

    watchdog('Photo Import', "Mimemail: %mimemail", array('%mimemail' => $mimemail), WATCHDOG_INFO);
}

as per EntityFieldQuery::fieldCondition(), EntityFieldQuery doc

......


prevent file upload renaming for each node I would like to re-use some pdf files that doesn't change for my product content type and avoid to have by example:

node/product01-> product-datasheet-01.pdf

node/product02-> product-datasheet-02.pdf
...

but instead:

node/product01->|

                  | --> product-datasheet.pdf

node/product02->|

Already tried "File (Field) Paths" and "File (Field) Paths" modules but doesn't really fit on my needs because they works on single node.

Conf: D7+Ubercart3

thanks!
LS

Sounds like a job for:
filefield_sources

Re-use files by an auto-complete textfield
Attach server-side files uploaded via FTP
Transfer files from a remote server (cURL required)
Select existing files through the IMCE file browser


How do I initialise store in-app-purchase? I am experimenting with DrupalGap and it's great what it already provides out of the box. One feature that module  is missing is in-app-purchasing (where payments go via Apple).

Cordova provides a great cross-platform plugin with some good documentation.

This is a full example, and this a minimal example.

document.addEventListener('deviceready', initializeStore, false);

function initializeStore() {

// Let's set a pretty high verbosity level, so that we see a lot of stuff
// in the console (reassuring us that something is happening).
store.verbosity = store.INFO;

// We register a dummy product. It's ok, it shouldn't
// prevent the store "ready" event from firing.
store.register({
    id:    "com.example.app.inappid1",
    alias: "100 coins",
    type:  store.CONSUMABLE
});

// When every goes as expected, it's time to celebrate!
// The "ready" event should be welcomed with music and fireworks,
// go ask your boss about it! (just in case)
store.ready(function() {
    console.log("\\o/ STORE READY \\o/");
});

// After we've done our setup, we tell the store to do
// it's first refresh. Nothing will happen if we do not call store.refresh()
store.refresh();
}

How can I add the document.Eventlistener and the initalization function within DrupalGap?

The cordova plugin is installed, the products are set up in iTunes and the provisioning profiles with in-app-purchasing feature are created.
I have created a custom module with a menu link in DrupalGap where the user can make his in-app-purchases.

UPDATE:

This code works (Thanks, Tyler) and connects to the iTunesConnect store and pulls the requested/registered products.

You don't need a sandbox user to pull the products.

You do need to submit Apple the 3 legal documents even if you only use a development provisioning profile. It takes a few hours until the docs are submitted.

Here is another useful link (when your product is invalid): http://troybrant.net/blog/2010/01/invalid-product-ids/

/**
 * Implements hook_deviceready().
 */
function my_module_deviceready() {
// Let's set a pretty high verbosity level, so that we see a lot of stuff in the console (reassuring us that something is happening).
//store.verbosity = store.INFO;
store.verbosity = store.DEBUG; // even higher

// We register/request a product:
store.register({
id: "130points", // this is id of your product in iTunesConnect
alias: "130points_alias",
type: store.CONSUMABLE
});
// When every goes as expected, it's time to celebrate!
// The "ready" event should be welcomed with music and fireworks,
// go ask your boss about it! (just in case)
store.ready(function() {
console.log("\\o/ STORE READY \\o/");
});
// When any product gets updated, refresh the HTML.
store.when("product").updated(function (product_item) {
console.log("product_item: " + JSON.stringify(product_item)); // this is the response from iTunesConnect
});
// After we've done our setup, we tell the store to do it's first refresh. Nothing will happen if we do not call
store.refresh();
return true; // Let DrupalGap know it is OK to continue.
}

In a DrupalGap Custom Module, you'll use hook_deviceready():

/**
 * Implements hook_deviceready().
 */
function my_module_deviceready() {
  // Place your initializeStore function's code here...

  return true; // Let DrupalGap know it is OK to continue.
}


Change a node page with views module If you have for example http://www.example.com/node/5 and you go to that node page you get the page created by Drupal. My node is about an organization and I want on the bottom of that page a list with all the employees. Is there a way that I can do this with the views module?

Because I don't want to use PHP or HTML in the file for that. I know how to create a new view but if I create a new one I cannot use the same page link.

I think that this is a common problem but can't find a solution.

Whatever your employees are, if you can create a view of them (and you say you can), you can use Viewfield module.

  Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Exactly what you want to do, without any snippets of PHP.

Specifically, you need to use this capability:

  Administrators may supply a common value that will be used for all entities in a content type.

Just set viewvield to display "employees" view for all organization nodes, and filter views by whatever association between employees and organizations you created, using contextual filters.

Viewfield has built-in passing mechanism, token-based on node / content type configuration side. It can pass node id, author, creation date and any field value you have. On the Views side, these will be contextual arguments as usual.

Benefit over blocks: it will work no matter how and where node is displayed - display configurable just as any other field. You don't need do care to alter block configuration if you want, for example, change path from /node/50 to /organization/drupalangels. Blocks may get left behind. Viewfield will simply continue to work. Also, you can place it directly between other fields without any problem, should the need arise.

Of course for each his own, Viewfield is not flawless either. Blocks was always faster for me to configure, for example. And bit easier to theme. I just found the bit of extra time at first configuration worth it in the long run. For short and fast project, for a client that does not pay well and don't want you to manage site after it's done, it might be not worth to bother.


Add edit link to a view for admins only I have created a view in Drupal 7 that uses the node's content for display. I would like to add an edit link to this view that only displays if you are an administrator viewing this page. I know how to do this if I am using fields as the display type but not when the display type is set to content. How do I accomplish this?

You can implement hook_field_attach_view_alter to hide the field you've mentioned.

my_module_field_attach_view_alter(&$output, $context) {
  global $user;

  // check if the content is what you want to alter
  if ($context['entity_type'] != 'node'] || $content['view_mode']=='my_display') return;

  // only user with 'administrator' role can see
  $output['my_field']['#access'] = in_array('administrator', $user->roles));
}

enter link description here


Create chapter titles within a view Hoping for some ideas on how I can create chapter titles to a group of videos that I have on my Drupal 7 site.

Currently each video series is shows with a custom view and grouped with a taxonomy term. I have each video weighted to then display them in the order that I want. Everything works fine. I just need to break them up and create "chapters" to better organize them.

An example of a page on my site can be seen here.

And example of what I am looking for:

Heading
-Video 1
-Video 2
-Video 3
Heading
-Video 4
Heading
-Video 5
-Video 6

What I would is to use another field (assuming that the chapter names are unique) to identify which chapter it is a part of and do a secondary grouping with the field in views.


How can I hide a node flag using twig I want to hide the flag on a node if a boolean field is unchecked.

My Code in node.html.twig

{% if node.field_registration_status.value == 0 %}

    {{ content|without('content.flag_class_registration') }}

{% endif %}

{% if node.field_registration_status.value == 1 %}

     {{ content }}

{% endif %}

My CSS classes print as expected when the field is checked or unchecked. However, the Flag is not being removed from the output.

The without() filter's argument should be just the name of the key itself, which in this case is flag_class_registration without the content.. Consider - the filter only receives the expression that comes before it, so it's already inside the content array.

   {{ content|without('flag_class_registration') }}


Custom page with panels in two languages I created two pages with panels in Drupal 7; they have different names and different languages, but only one can be active as home page.

You can only have one page as the front page, which I assume is what you want. The way to do this, is using a "Selection rule" on language, and two variants, not two pages.

See Learn Page manager for a deeper introduction to Page manager.


How to select a node reference field when querying the database I am using db_select to query the database to get some fields, one of the fields is a node reference and I don't know how to select it or join its table.

My content type contains a node reference, and this node reference contains another node reference (nested relationship), how can I from the original content type get the first node reference fields and the fields of its node reference ?

My current query :

$query = db_select("node", "n");
$query->fields("n", array("nid", "created", "type"));
$query->fields("f1", array('field_field1_value'));
$query->fields("f2", array('field_field2_value'));
$query->leftJoin('field_data_field_field1', 'f1', 'f1.entity_id = n.nid');
$query->leftJoin('field_data_field_field2', 'f2', 'f2.entity_id = n.nid');
$query->condition('n.type', 'my_content_type', '=');

$query = $query->orderBy('n.created', 'DESC');
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);
$result = $query->execute();

I was able to join my node references using db_select, I just needed to add two relationships for each node reference (I have two node references (nested)), a first relationship to the specific table (which follows the pattern data_field_THE_NAME_OF_THE_NODE_REFERENCE_FIELD_IN_YOUR_CONTENT_TYPE) and a second relationship to the node itself with another alias (I mean by relationships JOINs).

Here's my code now :

$query = db_select("node", "n");
// joins
// setting up the first relationship
$query->leftJoin('field_data_field_X_ref', 'r', 'r.entity_id = n.nid');
$query->join('node', 'x', 'r.field_X_ref_nid = x.nid');
// setting up the second relationship
$query->leftJoin('field_data_field_Y_ref', 'r2', 'r2.entity_id = x.nid');
$query->join('node', 'y', 'r2.field_Y_ref_nid = y.nid');
// joining other fields
$query->leftJoin('field_data_field_field1', 'f1', 'f1.entity_id = n.nid');
$query->leftJoin('field_data_field_field2', 'f2', 'f2.entity_id = n.nid');
// ...
// fields
$query->fields("n", array("nid", "created", "type"));
$query->fields("f1", array('field_field1_value'));
$query->fields("f2", array('field_field2_value'));
// ...
$query->fields("x", array('title')); // title for the first node
$query->fields("y", array('title')); // title for the second node

// adding conditions
$query->condition('n.type', 'voiture_d_occasion', '=');

$result = $query->execute();

note that the two nodes references have a title, and in the query->fields() we mentioned that we want the title of both, drupal will return title for the first field, while the name of the field will be y_title for the second, you can use dsm on the query result to see the name of your fields.


Is it possible to style the new node page? Is it possible (with Drupal 7) to style the new node page?

I can add content by going to node/add/article, but I want this to be on its own URL and styled like my site's theme.

Is this the correct way to go about this? Or is it better to create a new module with validation to submit data back to the database?

You can style your node edit or add form by adding page--node--edit.tpl.php

or check here and here for more Suggestions.


Edit Drupal Commerce Confirmation Email I've been searching everywhere but i do not know how to edit the confirmation email sent when the checkout process is complete.

Where can I edit this?

Its in rules

admin > config >  workflow > rules


Append an  tag to entity field view hook On a field of field type = LINK and widget = LINK, I want to add an  tag on the rendered output.

The reason is to be able to add a class, not to the whole  tag output, but to append a FontAwesome icon.

Hook_page_alter, of course shows all of the rendered HTML. I really don't want to mess with that.

I tried hook_entity_view_alter. That works in a clumsy fashion but two problems:

1) It only affects the output from the node displayed via a view
2) It appends the  tag in new  after the displayed link.

It appends the  tag in new  after the displayed link.

You can theme individual fields: https://api.drupal.org/api/drupal/modules!field!field.module/function/theme_field/7

You can either have a theme function in template.php or a tpl.php template file, the former is preferred for performance reasons.

Using a theme function you could do something like:

THEMENAME_field__link($vars) {
  $output = '';
  foreach ($vars['items'] as $delta => $item) {
    $link = l($item['#title'], $item['#href']);
    $output .= '
' . $link . '&nbsp;</>
';
  }
  return $output;
}

Though you'll have to check $vars for specifics.  As for checking the widget I think you can get a clue from $vars['element']['#formatter']


Checkout flow broken I'm trying to make a webshop with commerce 2.0 in Drupal 8.

But when I have added a product to the cart, and I've filled in the Payment Information pane, and I press "Continue to review", the same page is being reloaded and there's a duplicate of the product I tried to purchase.

So I'm stuck in the check out flow.
If I disable the Payment Information pane, then I can continue in the checkout flow, but then I'm missing the payment information.

Does anyone have an idea for a work around or a fix? or maybe knows what's causing this?

Turns out it was because of a module called commerce_variation_cart_form.
After uninstalling it, everything worked as expected.


How to select all the field in content type How to select all the fields created in custom content type using select query.

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node', '=') // select nodes
 ->propertyCondition('type', 'testimonials', '=') //type testimonials
 ->propertyOrderBy('created', 'desc') //most recent first
 ->range(0,2) // limit
 ->execute();
$testimonials = node_load_multiple(array_keys($result['node']));

If you don't mind my saying, you don't want to do that manually. Drupal has a rich API which you should use.

The standard method to load a node and all of its fields/extra data, is node_load():

$node = node_load($nid);

If you're trying to avoid the overhead of the 'extra' (non-field) data, then you can use field_attach_load() along with a basic DB query to get a reasonable node object with all fields attached.

// Get base node data (aka 'properties')
$node = db_query('SELECT * FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchObject();

// Attach the fields
field_attach_load('node', array($node));

It is possible, of course, to query the database manually for all of this data, but when the functionality has already been written for you there doesn't seem any point.


How to import multi-value fields into profile2 using the Migrate module I have users each with a profile using the profile2 module. I am using a cookbook based on the Migrate framework to create the users and import profile data.

Sample CSV data would be:

"member_nr","email","username","tel_1"
"1001","new.tester@example.com","new tester","00000 12345-213"

But one of the profile fields is a text list using the checkboxes / radio buttons widget. According to the GUI, the values are stored in the format key|label.

So the field has values:

soccer|soccer
weight lifting|weight lifting
boxing|boxing
tennis|tennis
cooking|cooking

So I am trying to import data similar to:

"member_nr","email","username","tel_1", "interests"
"1001","new.tester@example.com","new tester","00000 12345-213", "soccer, weight lifting, boxing, tennis, cooking"

However, when running the import, I get an error that says:

  SQLSTATE[22001]:String data, right truncated: 1406 data too long for column field_interests' at row 1: INSERT INTO... [the data from the CSV file]

How should multi values be formatted in the CSV file to be accepted?

Make sure you're mapping the field using the right separator, e.g.

$this->addFieldMapping('field_interests', 'interests')
     ->separator(',');

Then make sure you've the right length in the source field ($this->map) and your Drupal field support such lengths as well.

If this does not help, increase the length of the destination field by SQL, drush or hook_update.


Upload and insert image in-place Is there a module that allows images to be uploaded and inserted in place, like in a block or something similar?

I think you're looking for the Insert module.

Here is the description from the Project page on Drupal.org

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


How to populate select field from View result like in In a custom content entity, I have defined this field

$fields['from_seliste_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Offreur'))
  ->setDescription(t('Le SÉListe qui a rendu le service (qui reçoit les graines)'))
  ->setSetting('target_type', 'person')
  ->setSetting('handler', 'views')
  ->setSetting('handler_settings', [
    'view' => [
      'view_name' => 'sel_selistes',
      'display_name' => 'entity_reference_1',
    ],
  ])
  ->setDisplayOptions('view', array(
    'weight' => $weight,
  ))
  ->setDisplayOptions('form', array(
    'weight' => $weight,
    'type' => 'options_select',
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setRequired(TRUE);

In the corresponding form, the field appears as wanted as a dropdown list populated with the result of the View sel_selistes:

I'd like to create another form with the same functionality.
How should I code the field in the form?

$form['mySelectField'] = array(
  '#type' => 'select',
  '#options' => [], <-- ??????
  '#title' => $this
    ->t('whatever'),
);

I don't have time to provide an exact answer, but something along these lines.

// Programmatically execute view
$view = views_get_view('sel_selistes'); //  view machine name
$view->set_display("entity_reference_1"); // view display name
// $view->set_arguments($arg) // looks like you don't have arguments.
$view->execute();

$view_results = []; // create array
// loop through results
foreach ($view->result as $row_id => $row) {
  // some php magic so you add to array like this $view_results[$nid_value] = $some_field_row_value;
}

$form['my_select_field'] = array(
  '#type' => 'select',
  '#options' => $view_results,
  '#title' => $this
    ->t('whatever'),
);


Show a form element only to certain roles Drupal's form API has a visibility state property that allows you to hide certain Form fields depending on the options selected in earlier forms.

Is there something similar for User role (e.g. a particular form field will only display if the logged in user has a certain role).

I know I can hide unwanted form fields according to role via CSS, but I would rather not print out the fields in the first place. I am creating my form inside theme-settings.php

Edit Update:

Here is my code following Rooby's answer:

function legendarysettings_form_alter(&$form, &$form_state, $form_id) {
  // To get the currently logged in user.
  global $user;
  // To target the required form.
  if  ($form_id == 'system_theme_settings') {
    // Set the role ID of the role that can edit.
    $rid = 3;
    // If user doesn't have the role in question.
    if (isset($user->roles[$rid])) {
      // Deny access to the field.
      $form['theme_settings']['admin']['#access'] = FALSE;
    }
  }

This works, except it hides the 'admin' field for role 3 (which is the admin role) but shows it to all other roles. I want the admin field to be only visible to the admin role.

Generally when you are hiding fields from user roles there are security implications.

The visibility state functionality you mention just hides things on the front end, which is not secure in terms of stopping users editing fields they are not actualy allowed to use.

If you want to use custom code, you can do this:

/**
 * Implements hook_form_alter().
 */
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  // To get the currently logged in user.
  global $user;
  // To target the required form.
  if ($form_id == 'FORM_ID') {
    // Set the role ID of the role that can edit.
    $rid = ROLE_ID_FOR ROLE USER NEEDS TO EDIT;
    // If user doesn't have the role in question.
    if (isset($user->roles[$rid])) {
      // Deny access to the field.
      $form['FIELD_NAME']['#access'] = FALSE;
    }
  }
}

This is a basic example and you might have to change it to deal with multiple roles having access or something.

This is ok for custom forms or if you only need to control access to a couple of fields but if you want more control or don't want custom code, etc, the best option is the field permissions module.

With that module you can go to the field edit form and select to use custom permissions, after which you can select which roles can access the field.

EDIT
To answer the edit in the question, your code

// If user doesn't have the role in question.
if (isset($user->roles[$rid])) {

Is doing the opposite of what the comment says it is doing.
To do what the comment says you would want to do this:

// If user doesn't have the role in question.
if (!isset($user->roles[$rid])) {


Programatically render a view in twig template I want to render a particular view like Who's new,Recent content present in the core in my the twig template.Any suggestion on how to do it? I was thinking of using views_embed_view() because in Drupal 7 it used to work with php but I don't know how to do it Drupal 8. Thanks.
 For recent I tried following code:

function template_preprocess_module(&$variables) {
  $variables['view_output']=views_embed_view("Recent content");
}

and then in the twig template did this:

{{ view_output}}

Right, twig no longer allows you to execute php code anymore. This is a main feature of twig and its security model.

I'd suggest to use a preprocess function for now and there call the function or even better add a render array with #type view, with #view_id and #display_id, as it gives you caching as well.

On top, maybe add an issue against core. That sounds like a really helpful thing to have

Oh and views_embed_view should be changed to enable caching as well.


Insert urls on content body Is there any way to insert path to images or links on a content without hard coding it? Our development environment and our production environement have different base paths so the base path of the images and links must not be hard coded.

Try using the Pathologic module to help with this. Excerpt from the documentation...

Rule Order

Note that the order in which you include the rules may be important. In a scenario with three servers (for example, development on http://local.example.com/drupal, testing on http://example.com/drupal, and production on http://example.com) and using a WYSIWYG editor (as noted below), the following rules (paths to be matched) will work in order:

http://local.example.com/drupal/
http://local.example.com/
http://example.com/drupal/
http://example.com/
/drupal/
/

Pathologic works by stripping out the path as defined above and ensuring that what remains will work as a path relative to the site's $base_url (the URL you see in the location bar when looking at your  page), no matter which server it is on. It works down the list in order and only applies the first rule that matches a given link. Placing http://local.example.com first in the list, for instance, will rewrite http://local.example.com/drupal/about as /drupal/about, and this will NOT be rewritten further by the /drupal/ rule, so all possible permutations should be included in order of deepest to shallowest matching path. Some of the example rules may not be necessary for your situation, but it is safe to include even unlikely paths that you would like corrected (removed).

Now sit back and enjoy the fruits of Pathologic’s labor."


Views archive page showing year and months of article content type I am trying to build a view page that shows archives (content type is article) only by dates:

year (e.g.2016)
february (post count)
june (post count)
etc ..

year (e.g. 2017)
march (post count)
june (post count)

To top it off, months being linked to the respective posts.

i tried with contextual filters using content: created year and content: created month but I only end up with the year.

Using Drupal 8.3.3.

I am not sure if my set up is missing something because when using fields and/or contextual filters I do not have a date option ...

Any kind soul who can help me out?

you can use calendar module, from module page:

  This module will display any Views date field in calendar formats, including CCK date fields, node created or updated dates, etc. Switch between year, month, and day views. Back and next navigation is provided for all views. Lots of the Calendar functionality comes from the Date module, so any time you update the Calendar module you should be sure you also update to the latest version of the Date module at the same time.

this video is for D7, for D8 is very similar, you can change display format in any view, for example a table and add a special field that you can find ir in views UI under "global" named "views reasult counter"


How to load module include files in .test file? I'm trying to update the Drupal 7 version of the password_policy.test file that is included with the Password Policy module. When I run the tests, I'm getting "Fatal error: Call to undefined function password_policy_constraint_uppercase_validate()".

The function in question is in an include file in the constraints subdirectory, located inside the module's directory. I've tried adding to the test's setUp() function, along the lines of:

drupal_load('module', 'password_policy');
module_load_include('inc', 'password_policy', 'constraint_uppercase');

I've also tried adding the module_load_include line inside the individual test method generating the error. However, none of my attempts so far appear to be working and the error still persists.

How should I go about loading the ./constraints/constraint_uppercase.inc and other include files, so that the necessary functions are loaded prior to the tests being run?

You have a flaw in your code, module_load_include works by including files relative to the module base dir, so you should do

module_load_include('inc', 'password_policy', 'constraints /constraint_uppercase');

to include password_policy/constraints/constraint_uppercase.inc

When you do

module_load_include('inc', 'password_policy', 'constraint_uppercase');

You instead try to include password_policy/constraint_uppercase.inc which doesn't exist.


Custom block won't display in admin - Drupal 7 I am running into an issue where my block won't show up in the admin section of my site. I've added it to example_block_info() where the other existing blocks are declared. I've also added content in example_block_view():

/*block_info*/

$blocks['example'] = array(
    'info' => 'Example',
    'status' => TRUE,
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => 'example/1*',
            'cache' => DRUPAL_NO_CACHE
);

/*block_view*/

switch($delta){

...

    case 'example':
        $block['content'] = '
            //content
        ';
        break;

}

Am I missing something? All the other blocks show up and work fine. I can modify them as well. This one doesn't work/show up.

Try the next code below, it work for me:

/**
 * implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks['hello-message'] = array(
    'info' => t('Message'),
    'status' => TRUE,
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => 'example/1*',
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();

  if ($delta == 'hello-message') {
    $block['subject'] = t('Message');
    $block['content'] = t('Hello World!');
  }

  return $block;
}

See https://api.drupal.org/api/examples/block_example%21block_example.module/7


double slash '//' with drupal_goto I am using drupal_goto and url methods to try and direct the user to a page.

url returns a string like "/whatever/example" and then I pass that into drupal_goto and they get sent to

localhost//whatever/example

I checked the value for $base_url in settings.php that has no trailing slash. what else could cause this behavior?

Whatever you pass to drupal_goto() will in turn get passed on to the url() function. If you're using url() on the path before hand, it'll get run through again and you'll get a double slash.

You can just pass the router path to drupal_goto() directly, and it will handle the alias for you:

drupal_goto('node/1234');


Best method for multi-page user registration form? I am trying to set up a multi-page user registration form, and I would ideally like to use the Webform module to do so. Can webform fields be mapped to user registration or user profile fields?

Here's how I would like it to work:

User tries to access content page; they cannot because they are not registered, so they are prompted to create a new account.
They enter their name, email, password and are logged in. They are then redirected to "page 1" of the multi-page form.
After they go through all of the pages, they save the form. The info they entered into the pages of the form is saved in their user profile. They can go back in and edit it at a later date if they wish.

Is this possible with existing modules?

Thanks!

The Profile2 and Profile2 Registration Path modules can help to solve your problems. You can do the following:

You can create the profile for each role of users.
Have the different register pages for each profiles.
Can config the way to do after registration.
Have the edit user information with include the extra fields from Profile2 module.


Drupal and Session Limit I am using Drupal 6 with the Open Atrium distribution. Is there a problem if the same user connects from more than 100 different computers at the same time? At the moment I am unable to do a test but I would like to know if I can encounter any problem. So far I did try with 10 PCs and no problem whatsoever. Also is there a limit that I have to remove or by default there is no limit? Thank you.

There is no hardcoded limit, but sessions by default are kept in database, so user<->session queries will get slow like a hell pretty soon. Move sessions to memcache or apc if possible, and consider giving each of those 100 guys his own account.


Which tables and which data can I omit from backup? Which tables and which contained data can I omit from SQL backup?

There seem to be many different answers to this around Internet, but most answers do not make it clear whether they are specifying that tables can be omitted or the data in the tables.  My guess is it comes down to knowing which modules are robust and will re-create their own empty tables if they aren't there.

Without knowing the code innards of every module that is a possible candidate for omission, is there a good answer to the question?

At the moment, my intention is to start with the default lists built into Backup and Migrate; for anything else, I think could be omitted then omit the data from such tables not the table itself (playing safe).  It could be something published in the documentation for a module but I don't think it is.  Is there a completely definitive list somewhere?

It's very confusing seeing lists of "you can omit these" without knowing whether it's referring to the tables or their content.

You can omit the data from some tables. You cannot omit the actual table creation.

Tables for modules are created in one of two ways. Either when the module is first enable via hook_schema or when an update hook (hook_update_N) runs. Tables in hook_schema are only created when the module is first enabled.
After an update hook is run the system table is updated with the schema version so it's not run twice.

You can't expect modules (or core) to just recreate tables that they expect to exist but are missing on the fly. It's nothing to do with being robust - this is just how Drupal works. Also it would be very inefficient to check a table exists before running every query. You would be doubling the number of queries you have to run. This would be crazy!

If you have any missing tables you would need to disable, uninstall and then re-install the module to fix it.

This question has suggestions of which which tables contain data that can be excluded.


Changing title of node when saving Whenever an user saves a node I want to prefix it with table autoincrement-id so that the id is unique.

So if the title of node is "xyz" then it should be saved as unique id "299999-xyz". Ideally this id should be the node-id which is unique but it may not be possible to know the actual id until the node is saved in the table.

What is the best way to accomplish it?

I'm thinking of changing the title in the form validate function. This id can be numeric time() value.

*PS:*I'll have tons of such nodes so when linking them from other nodes (node-reference) this id will uniquely identify such nodes in "autocomplete textbox" in node forms.

Use the module "Automatic Nodetitles". This allows you to use tokens on the title field. Once enabled you can set any pattern for the title. Set your pattern on /admin/content/node-type/YOURCONTENTTYPE to "[nid] - [title]" for example. Already existing nodes can be updated automatically.


Extract zip to server and upload the files to the node? I allow users to upload zip files I extract, and look into them to see if they contain a .jpg file. I use that file to create a new node. The differences between the .jpg and the .zip file uploaded are that the first came as an object, while I don't know how I can take the second as an object.

I'm using the PclZip library.

This is part of the code I use when the uploaded file is a JPEG.

$file = $form_state['values']['file'];

$original_filename = $file->filename;
$original = file_unmanaged_copy($file->uri, 'public://work', FILE_EXISTS_REPLACE);
file_unmanaged_delete($file->uri);
list($file, $tfile) = some_fileprep($original_filename);

This is the code I use when the file is a .zip file.

include $pclzip_lib.'pclzip.lib.php';
$zip = new PclZip($file->uri);

for ($i=0; $i<$total_files; $i++) {
    $file_name = $list[$i]['filename'];
    list($f_name,$xt) = explode('.', $file_name);
    $xt=strtolower($xt);

    $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote('png gif jpg jpeg tif tiff html')) . ')$/i';
    if (preg_match($regex, $xt) and ($list[$i]['size'] < 10000000)) {
        $error[] = "File with conflict: ".$file_name;
        if((($xt == 'png') or ($xt == 'gif') or ($xt == 'jpg') or ($xt == 'jpeg') or ($xt == 'tif') or ($xt == 'tiff')) and ($f_name == 'preview')){
            $file->filename = $f_name.".".$xt;
            $file->uri = $f_name.".".$xt;
            echo "Yes: ".$f_name.".".$xt;
            $preview = true;
        }
    }

    if(is_null($error))
    {
            $to_extract = $GLOBALS['_SERVER']['DOCUMENT_ROOT'] . '/' . drupal_get_path('module', 'some') . '/testing/';
            $ar = $zip->extract(PCLZIP_OPT_PATH, $to_extract);
            $file->filename = $ar->filename;
            $file->uri = $ar->filename;

        }
}

You can simply use file_unmanaged_save_data(), as in the following code, where $data is the content of the .jpeg file contained the .zip file.

file_unmanaged_save_data($data, 'public://work', FILE_EXISTS_REPLACE);

As side note, Drupal includes the ArchiverZip class, which should probably be used instead of the PclZip class.
You don't normally deal with the class directly, but you use code similar to the following one, used by update_manager_archive_extract().

  $archiver = archiver_get_archiver($file);
  if (!$archiver) {
    throw new Exception(t('Cannot extract %file, not a valid archive.', array('%file' => $file)));
  }

  // Remove the directory if it exists, otherwise it might contain a mixture of
  // old files mixed with the new files (e.g. in cases where files were removed
  // from a later release).
  $files = $archiver->listContents();

  // Unfortunately, we can only use the directory name to determine the project
  // name. Some archivers list the first file as the directory (i.e., MODULE/)
  // and others list an actual file (i.e., MODULE/README.TXT).
  $project = strtok($files[0], '/\\');

  $extract_location = $directory . '/' . $project;
  if (file_exists($extract_location)) {
    file_unmanaged_delete_recursive($extract_location);
  }

  $archiver->extract($directory);

archiver_get_archiver() uses drupal_realpath(); this means it is able to get the realpath of a file when its filename is using stream wrappers, such as public://archive.zip.


How to use multiple submit within a CTools Modal I'm using a CTools modal to add a holiday. The topside of that form in the modal displays the already defined holidays with an "X" that will allow you to delete a holiday. I have created a submit button for each that is put in a table with this code (the rows are rendered in a table afterwards).

foreach ($locationVO->Holidays as $holiday) {
    $fid = 'delete' . $holiday['id'];
    $form['holidays'][$fid] =
            array(
                '#name' => 'delete_' . $holiday['id'],
                '#type' => 'image_button',
                '#src' => $crossimg,
                '#attributes' => array('class' => array('delete_holiday')),
                '#return_value' => $holiday['id']
    );
   $field = drupal_render($form['holidays'][$fid]);

   $rows[] = array($holiday['name'], ISOdate2DutchDate($holiday['from']), ISOdate2DutchDate($holiday['to']), $field);
  }

Everything is rendered ok, but if I try to delete a holiday, the triggering_element and the clicked_button arrays in form_state still always refer to the main submit that I defined in the CTools form_info array. I therefor cannot distinguish between the submits for adding and deleting.

What do I need to do to get my triggering_element to correspond with the selected submit? I also tried specifying a separate '#submit' handler for the delete buttons, but that is never called either.

Other solutions are welcome as well, as long a I can do it without closing/leaving the modal (I already tried with a link to a separate delete handler which worked up until the referral back to the modal).

Thanks!

Never figured out how to do this, but I worked around the problem by using CTools functionality. In a nutshell I used ctools_ajax_image_button in the table, specified a specific callback for the url and then alter the table with ajax_command_remove, ajax_command_restripe and finally returning it with ajax_render.

This is all based on the CTools AJAX example that deletes rows from a table.


How can write reffering page node or url in a field of entity form I have an entity form and need to know which page refered to form. How can write refferer url or node id to a field ?

Using an entityreference to the page the entity form is displayed on solved this for me. Here's some code providing a entity form block with the values prefilled and locked:

<?php
/**
 * Implements hook_block_info().
 */
function mymodule_contact_block_info() {
  $blocks['mymodule_contact'] = array(
    'info' => t('mymodule contact form'),
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_contact_block_view($delta) {
  $block = array();
  switch ($delta) {
    case 'mymodule_contact' :
      module_load_include('inc', 'entityform', 'entityform.admin');
      $entity_form_name = 'contact'; // machine name of entity form
      $render_contact_form = entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
      $render_contact_form['field_contact_page']['#access'] = FALSE; // machine name of entity reference field
      $block['content'] = drupal_render($render_contact_form);
      break;
  }
  return $block;
}

/**
 * Implements hook_entity_presave().
 *
 * set the page reference to the current active menu object
 */
function mymodule_contact_entity_presave($entity, $type) {
  if ($type == 'entityform' && empty($entity->draft) && $entity->type == 'contact' && $entity->is_new == TRUE) {
    $node = menu_get_object();
    if (isset($node->nid)) {
      $entity->field_contact_page[LANGUAGE_NONE][0]['target_id'] = $node->nid;
    }
  }
}


How to alter the name of downloadable excel sheet of webform Issue:

When I click on the link ofwebform Download as shown in below screenshot the default name of excel sheet before save to local disk appears like localhost_worklog.xlsx but I want something like localhost_worklog_02172017.xslx which is appended with _<current time>.

SCREENSHOT:

EDIT: After using iLLin's answer

Problem: How can I alter the name of localhost_worklog.xlsx before save?

I am using drupal 7.53.

The only way to do this is to change the $node->title on the loaded object for the webform.  That filename uses that title, so I am assuming you have a webform title of "Localhost Worklog".

The problem with that is you only want to change the node title, when you are downloading the webform (or atleast running through that process).

You have two options (I think).  You could implement a hook_entity_load() function and then check if the URL is

node/%webform_menu/webform-results/download
or

node/%webform_menu/webform-results/download-file

function MYMODULE_entity_load($entities, $type) {
  if (arg(2) == 'webform-results' && (arg(3) == 'download' || arg(3) == 'download-file')) {
    foreach ($entities as $entity) {
      $entity->title = $entity->title .'_'. now();
    }
  }
}

Docs

The other way I can think of is altering the page callback with a hook_menu_alter(), changing the title there and then calling their function to return the form or download file with the updated node object to include the time appended to the title.

EDIT

From reviewing your update, it seems it's changing the title too soon on that page.  So I think you will need a combo approach.  Using hook_entity_load and hook_form_alter.  The point is changing that title in the $node object that is passed around for download.  So try this.

/*
 * Implements hook_entity_load().
 */
function MYMODULE_entity_load($entities, $type) {
  // Change the node title to include the time when downloading.
  if (arg(2) == 'webform-results' && arg(3) == 'download-file') {
    foreach ($entities as $entity) {
      $entity->title = $entity->title .'_'. now();
    }
  }
}

/*
 *  Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == WEBFORM_DOWNLOAD_FORM_ID) {
    // Change the node title that is passed around for download.
    // @TODO: Check to make sure this is correct.
    $form['node']['#value']->title = $form['node']['#value']->title . '_'. now();
  }
}


Wrong date field format on mobile iOS / Android I created a form with Drupal's FAPI. The form includes two date fields. It works fine on desktop browser.

But on mobile (iOS and Android), the datepicker doesn’t show up. It is the native date selector which shows up.

The issue is that the native date selector doesn’t seem to apply the date format (in my case : '#date_date_format' => 'd/m/Y')

I see 2 possible solutions :

With JS, force the date format
Force the date picker to show up (i’ve seen this on other website
i’ve made but in wasn’t Drupal FAPI.

How do you handle this problem ?

Here is my code and a screen shot of the issue :

    $form['date_debut'] = array(
        '#type' => 'date',
        '#title' => $this->t('Date de début'),
        '#type' => 'date_popup',
        '#date_date_format' => 'd/m/Y',
        '#description' => t('Cliquez dans le champ et sélectionnez une date de début de congé dans le calendrier'),
        '#required' => TRUE
    );

The solution is not to use :

<input type="date">

but

<input type="text">

With Form API, replace :

$form['my_date'] = array(
    '#type' => 'date',
);

with

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

And attach a date picker like the jQuery Datepicker available in Drupal 8 or other library like Bootstrap Datepicker

In safari, i need to test in private mode because sometines the Safari cache prevents me to see update in my JS.


Using form_set_value() in Drupal 7 I am trying to update a value during the validate phase of a node-form, i.e. if the custom validation error is fired, just empty one of the fields.

for the last 30 hours I am trying to make sense of the drupal api, but I am giving up. I just do not seem to get the idea what the different values mean.

the function is: form_set_value($element, $value, &$form_state)

now i understand that the last value is simply the $form_state, that I am having through the validate function. but what about $element and $value?

I was trying a lot and apparently the desired value resides in $form['field_name']['und'][0]['value']['#value'] and only there.

but when I am trying form_set_value($form['field_name']['und'][0]['value']['#value'],'foo',$form_state) it raises

    Recoverable fatal error: Argument 2 passed to drupal_array_set_nested_value() must be an array, string given, called in /includes/form.inc on line 2436 and defined in drupal_array_set_nested_value()

and when I am trying:

    $newvalue = $form['field_name']['und'][0]['value'];
    $newvalue['#value']='foo';
    form_set_value($form['field_name']['und'][0]['value'],$newvalue,$form_state);

it raises:

    Warning: mb_strlen() expects parameter 1 to be string, array given in drupal_strlen()

Thanks for any help!

[EDIT]

My complete function is:

    function hook_node_validate($node,$form,&$form_state) {
      if(fancy_stuff){
        form_set_value();
        form_set_error();
      }
    }

[EDIT2]

    //calls when node is being created
    function eventcheck_node_validate($node,$form,&$form_state) {
      //checks if the node type is applicable
      if($node -> type=='article') {
        //checks if field 'field_event_choose' AND either 'field_event_title'
        //or 'field_event' is supplied, if so, fire form_set_value() and form_set_error()
        if ((array_key_exists('endpoints',$node -> field_event_choose['und'][0])) &&
        (($node -> field_event_title['und'][0]['value']<>'') || (isset($node ->
        field_event['und'][0]['value'])))) {

          //fire away
          $form_set_value(???);
          $form_set_error('event_checker_group',t('sorry blabla'));

        }
      }
    }

I hope that helps.

After a lot of debugging, I finally managed to make this work. The trick lies inside $form['complete form']. but first things first, how does form_set_value() work and what does it do?

The form_set_value() function

As the documentation suggests:

  If you want to update the value of $form['elem1']['elem2'], which should be stored in $form_state['values']['elem1']['elem2'], you would set $element['#parents'] = array('elem1','elem2').

Now what does that mean? In my case, I had a textfield called 'field_event_title', which is the name I gave it on creation. In $form, all fields have a sub-array in $form['field_name'], which in my case is $form['field_event_title']. This is where the submitted value also is stored. Since it is a textfield, Drupal maintains both the language and the delta [question for editors: is this right?] of the input data. So in fact, the value is not stored in $form['field_name']['value'], but in $form['field_name']['und'][0]['value'] (['und']=language; [0]=delta). Note that "und" is the Drupal key for the default language of the site; if it is in German, then it would be "de"; however, in most cases it should be "und."

To actually change the value using form_set_value(), one is ought to invoke the function by writing:

form_set_value($form['field_name'], array('und' => array(0 => array('value' => 'foo'))), $form_state);

Updating a form to repopulate it with different values than submitted (or clearing them)

Thus far, this was what Krister Andersson suggested, but that did not work in my case, since I wanted to clear fields once a custom validation error has been invoked. One would suspect that the form repopulates itself using the values inside $form_state['values'] (which is actually the place where the values are stored, the actual place that gets updated when using form_set_value() and the place which generates the $form later), but that is not the case: It uses the values inside $form_state['complete form'], which is a 'copy' of $form (notice that it is spelled 'complete form', with a space, not an underscore).

Using $form_state['complete form']['field_name']['und'][0]['value']['#value'] = 'foo'; is what updates the values that actually repopulate the form on a validation error. (Note: you can, as do I in my usecase, set it to =NULL to simply empty the field.)

Summary

Where is the difference between $form['field_name'] (e.g. updating through form_set_value()) and $form['complete form']? Well, the former updates the actual value, which then gets stored inside the database; the latter is being used to repopulate a form when it failed a validation.


Get fields from a collection field in .theme I would like to know how I have to collect the field collection to get the fields it contains

$fieldItemList = $node->field_collection_gallery;
$fieldCollection = $fieldItemList[0];
$fieldCollectionItem = FieldCollectionItem::load($fieldCollection->value);

Use the following code:

$fieldCollectionItems = $node->get('field_collection_gallery');

    foreach ($fieldCollectionItems as $key => $item) {
      $fcItem = FieldCollectionItem::load($item->value);

      if ($fcItem instanceof FieldCollectionItem) {
        $fcValue = $fcItem->get('field_name')->getValue();
      }
    }

The $fcValue variable should contain the value from the field in the field collection item.

You have to replace the field_name with your own field name in the last line in the foreach() loop.


Removing HTML rendered for Block Regions In my custom Drupal 8 theme, for all regions of my page, there is HTML looking like:

where xxxx is the region name.

There are also empty 's rendered around my blocks.

This is my block.html.twig

{% block content %}
    {{ content }}
{% endblock %}

as you see, no divs there.

Here's my theme.info.yml , region part:

regions:
  header: Header
  hero: Hero
  help: Help
  top: 'Page Top'
  content: Content
  sub: 'Sub Content'
  bottom: 'Page Bottom'
  footer: Footer

Here's a screenshot of the actual HTML tree rendered:

essentially I'd like to remove everything between the .row and the .col..

This may help some one else who is having this issue.
So how to remove the extra black divs inside a region you would do the following:
Find "core/modules/system/templates/region.html.twig"
Change it from this –
{#
/**
 * @file
 * Default theme implementation to display a region.
 *
 * Available variables:
 * - content: The content for this region, typically blocks.
 * - attributes: HTML attributes for the region <div>.
 * - region: The name of the region variable as defined in the theme's
 *   .info.yml file.
 *
 * @see template_preprocess_region()
 *
 * @ingroup themeable
 */
#}
{% if content %}
  <div{{ attributes }}>
    {{ content }}
  </div>
{% endif %}

To this –
{#
/**
 * @file
 * Default theme implementation to display a region.
 *
 * Available variables:
 * - content: The content for this region, typically blocks.
 * - attributes: HTML attributes for the region <div>.
 * - region: The name of the region variable as defined in the theme's
 *   .info.yml file.
 *
 * @see template_preprocess_region()
 *
 * @ingroup themeable
 */
#}
{% if content %}
    {{ content }}
{% endif %}


Rules: Do action on the field of referenced node I have an "Authors" Content-type, that users can add to their "Article" node while adding a new content as Co-Authors.

Note that it's a seperate content-type not users.

in "Authors" content-type I have an "Email field" which contains the email of the co-author.

What I want to do is using rules, send an email to the referenced node's email field

I juggled around in rules but couldn't really make it work, I'd really appreciate a step-by-step process of rules to achieve this, thanks.

If your rule is set to React on event: Before saving content or After saving new content of type Article, then do this:

Add condition: Entity has field

ENTITY: node:field-your_reference_field

FIELD: field_email

This makes the referenced node's email field available in to Actions. So then you can

Add action: Send email

To: node:field-your_reference_field:field_email

This should get you where you need to be.


How do I create tabs in an admin page? How do I create a tab in the admin page using a custom module?
The files defining the routes, links and task are the following.
cst_core.routing.yml
cst.admin:
  path: '/admin/MyCustomModule'
  defaults:
    _controller: '\Drupal\cst_core\Controller\CstController::content'
    link_id: 'cst.admin'
    _title: 'MyCustomModule Management'
  requirements:
    _permission: 'cst admin'

cst.admin_menu:
  path: '/admin/MyCustomModule/menu-mgmt'
  defaults:
    _controller: '\Drupal\cst_core\Controller\CstController::content'
    link_id: 'cst.admin_menu'
    _title: 'MyCustomModule Menu Management'
  requirements:
    _permission: 'cst menu'

cst.admin_menu_menu:
  path: '/admin/MyCustomModule/menu-mgmt/menu'
  defaults:
    _controller: '\Drupal\cst_core\Controller\CstController::content'
    link_id: 'cst.admin_menu_menu'
    _title: 'MyCustomModule Menu Management'
  requirements:
    _permission: 'cst menu'

cst.admin_menu_menu_taba:
  path: '/admin/MyCustomModule/menu-mgmt/menu/taba'
  defaults:
    _controller: '\Drupal\arm_core\Controller\CstController::content'
    link_id: 'cst.admin_menu_menu_taba'
    _title: 'MyCustomModule Menu Management tabs'
  requirements:
    _permission: 'cst menu'

cst_core.links.menu.yml
cst.admin:
title: 'MyCustomModule'
description: 'MyCustomModule System'
parent: system.admin
route_name: cst.admin
weight: -20

cst.admin_menu:
title: 'Menu'
description: 'Menu Management.'
parent: cst.admin
route_name: cst.admin_menu
weight: 0

cst.admin_menu_menu:
title: 'Menu'
description: 'Menus.'
parent: cst.admin_menu
route_name: cst.admin_menu_menu
weight: 0

cst_core.links.task.yml
cst.admin_menu_menu_taba:
route_name: cst.admin_menu_menu_taba
title: 'tab-menu A'
base_route: cst.admin_menu_menu

With this, I should have:
-- MyCustomModule
--- Menu Management
---- Menu
+++++ tab-menu A (as a tab) --> but this didn't happend T_T
something like this:

if I suppose cst.admin_menu_menu_tabA: is your sub-menu A then also add

  cst_core.links.task.yml for tabs or sub menu tabs in an admin page

then add the following code below

cst.admin_menu_menu_tabA:
  route_name: cst.admin_menu_menu_tabA
  title: 'sub-menu A'
  base_route: cst.admin_menu_menu

proceed so on for the rest of the tabs..

and also add a route for cst.admin_menu_menu_tabA in cst_core.routing.yml


what is a reasonable value for max_allowed_packet for Drupal 7 with moderate traffic？ I need to know some ball park number for this variable for my drupal 7 site. I recently got a "drupal "PDOException: SQLSTATE[08S01]: Communication link failure: 1153" error. I am a newbie to mysql and am using shared hosting. I probably need to ask the administrator to do it for me.

Thanks in advance.

I saw an interesting answer to a question about the biggest BLOB you may have. Here is the statement I saw in ServerFault : innodb_log_file_size and innodb_log_buffer_size combined must be larger than ten times your biggest blob object if you have a lot of large ones.
Based on that ServerFault post from Nils-Anders Nøttseter, you should query the table and find out which BLOB is the biggest, multiply that number by 11 or more, and use that answer as the max_allowed_packet going forward.
It's funny that I addressed another question where I suggested sizing the max_allowed packet to hopefully solve the issue.
CAVEAT
According to the Book

Here is what Page 99 Paragraphs 1-3 says about MySQL Packets:

MySQL network communication code was
written under the assumption that
queries are always reasonably short,
and therefore can be sent to and
processed by the server in one chunk,
which is called a packet in MySQL
terminology. The server allocates the
memory for a temporary buffer to store
the packet, and it requests enough to
fit it entirely. This architecture
requires a precaution to avoid having
the server run out of memory---a cap
on the size of the packet, which this
option accomplishes.
The code of interest in relation to
this option is found in
sql/net_serv.cc. Take a look at my_net_read(), then follow the call to my_real_read() and pay
particular attention to
net_realloc().
This variable also limits the length
of a result of many string functons.
See sql/field.cc and
sql/intem_strfunc.cc for details.

Knowing this about MySQL Packets allows a DBA to size them up to accommodate multiple BLOBs inside one MySQL Packet, even if they are obnoxiously large.
Regarding your situation, you should find out what is the biggest BLOB in your database, multiple that number by 11 and set your max_allowed_packet to that number. You should be able to set it for the server without a mysql restart (Personally, I would set it 256M because it would address other problems regarding migration and replication, which is beyond the scope of this forum). To set it to 256M for your database for all incoming connections, please run this:
SET GLOBAL max_allowed_packet = 1024 * 1024 * 256;

Afterwards, add this setting to my.cnf under the [mysqld] section:
[mysqld]
max_allowed_packet = 256M


How to read the field collection data I have a field collection with name as 'TELEPHONE NUMBERS AND DETAILS' and the machine key as 'field_telephone_numbers'.

When I use node_load getting the output as

[field_orgs_number_details] => Array

(

[und] => Array

(
    [0] => Array

    (
        [value] => Number 2
        [format] =>
        [safe_value] => Number 2
    )

)

)

[field_orgs_telephone_number] => Array

(

[und] => Array

(
    [0] => Array
    (
        [value] => 123456
        [format] =>
        [safe_value] => 123456
    )

)

)

How to read the data 'Number 2' and '123456' into a array.

Updated:

 [1] => Array

   (

   [entity] => Array

      (

        [field_collection_item] => Array

            (
            [15994] => Array
                (
                [field_orgs_number_details] => Array
                    (
                    [#object] => FieldCollectionItemEntity Object
                       (
                         [field_orgs_number_details] => Array
                             (
                                [und] => Array
                                    (
                                        [0] => Array
                                            (
                                            [value] => Number 3
                                            [format] =>
                                            [safe_value] => Number 3
                                            )
                                    )
                            )

                        [field_orgs_telephone_number] => Array
                            (
                            [und] => Array
                                (
                                [0] => Array
                                  (
                                [value] => 333333333333
                                [format] =>
                                [safe_value] => 333333333333
                                )
                            )
                        )

                    [rdf_mapping] => Array
                        (
                        )

                [entity_view_prepared] => 1
                    )
                )
            )
        )
    )
)

 When i use

 $data = render($content['field_telephone_numbers']);

 Getting output as

  Telephone
  123456  - Number 2

consider you have called like this $content = node_load(1);

then you can get the values like below

$content['field_orgs_number_details']['und'][0]['value']

Similarly you can do the same for getting the telephone numbers


Site behind a reverse proxy - subfolder We are using a public apache web server as a reverse proxy for to show a drupal instance (to the client). The website should come up in http://publicSite/path
The Reverse proxy contains basic apache configuration pointing a "subfolder" to the internal webserver. Something like:

ProxyPass /path http://internaldomain/
ProxyPassReverse /path http://internaldomain/

The problem is that Drupal 8 has no longer a $base_url and the site is broke (CSS, JS). Adding publicSite in the $settings['file_public_base_url'] does not help. CSS/JS and links to themes are still broken.

There is a settings section on a Reverse Proxy in the settings.php, but it does not address the issue on accessing the website from a /subfolder url.
Any hints to solve this issue!?

You just need to reverse proxy all the asset directories like here (this proxies site preosasde via real site proreos):

ServerName preosasde

ProxyPass /themes/ http://proreos/themes/
ProxyPassReverse /themes/ http://proreos/themes/

ProxyPass /core/ http://proreos/core/
ProxyPassReverse /core/ http://proreos/core/

ProxyPass /vendor/ http://proreos/vendor/
ProxyPassReverse /vendor/ http://proreos/vendor/

ProxyPass /sites/ http://proreos/sites/
ProxyPassReverse /sites/ http://proreos/sites/

ProxyPass / http://proreos/asde/
ProxyPassReverse / http://proreos/asde/

Take care about the order of that entries and be aware that you will loose your users credentials (cause of the different domain).


Is there a module or way to edit all my product's categories from one admin menu? Currently I have to go to admin>store>products and then go to each product individually to change their category. This is tedious when you have hundreds of products and need to change many of their categories. For just changing the title/name of a category/term I can just edit the taxonomy term but Ive also added many new terms. So is there a module or a setting to allow this? I am using ubercart.

Here are a couple of possibilities:

Perhaps try Views Bulk Operations - this might have an operation for changing taxonomy term in content in a batch.
If you are changing the same taxonomy term (old) to another term (new) on many products, I wonder if deleting the new term and then renaming the old term to what that new term was would do the job? The end result is that you now have products all using the new term. This idea would only be suitable if there isn't other content using that new term which is not part of the change.


Private file system, The upload directory private://webform/XXXX/_sid_ for the file field could not be created or is not accessible I am trying to set up the private file system for drupal 8. I have created a private folder /home/user/public_html/private_files with permissions set to 777

in settings.php i uncommented the $settings['file_private_path']= '/home/[USERNAME]/public_html/private_files';

the .htaccess file was created.

the status report page gives:
File system
Writable (private download method)

When i try to upload a file with either the webform file field or a drupal file field i get the error message: File could not be uploaded.

In the error log i get:
The upload directory private://webform/XXXX/sid for the file field could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.

Can anyone help me with this

Your path must exist outside of your webroot directory and be an absolute path, for example: /var/www/private )

Also check PHP configuration

file_uploads = On must be set to "On"
upload_max_filesize = 24M can't be larger than post_max_size
max_input_time = 300 small values may cause timeouts for large file
uploads
memory_limit = 64M small values may cause out of memory errors for
large file uploads
max_execution_time = 180 small values may cause timeouts for large
file uploads
post_max_size = 24M limits the size of input submitted to the website
(including attached files)

Information is taken from here.


Pager for multivalued node field There is a plenty of plugins for building all kinds of sliders and carousels with Views.

But frequently I find myself in a situation, when I need to make some kind of slider not for a whole node but only for one particular field with multiple values. Of course, I can attach a view using the EVA module and use it to output just one field of current node.

But is it a recommended way? Are there better solutions?


How can I programmatically reindex Commerce products to AWS Elastic Search? I am using Drupal 8 Commerce module.
I am using Elastic Search on AWS platform.
From the Admin whenever product is saved, those changes are directly applied on Elastic Search server, but when I try with $product->save() it is not working 100%.
So if I have to update 10 products in Elastic Search how to achieve that programatically?
In particular, I have to update one field only. Because what is happening that, it will update that field value in database but not on Elastic Search.
I found this useful post for Node How To Force Search API To Reindex a Node / an Entity

So I have some updates answer relies in search_api.module file
function search_api_entity_update.
So I am able to achieve for one product. Can loop & do for multiple.
use Drupal\commerce_product\Entity\Product;
use Drupal\search_api\Plugin\search_api\datasource\ContentEntity;

$entity = Product::load(1); // Replace 1 with your product id.

$indexes = ContentEntity::getIndexesForEntity($entity);

if (!$indexes) {
  return;
}

foreach ($indexes as $index) {
  $index->trackItemsUpdated('entity:commerce_product', ['1:en']);
}

It works like a charm :)


How are .inc files actually utilised in a module? I am trying to learn more about modules and have noticed several of the ones I've been investigating contain .inc files, eg: module_name.inc or module_name.theme.inc.

It's clear these contain hooks and functions and are probably separated out just for organisational purposes.

But how does the module/Drupal know these exist? How are they called upon? I see no reference to these files in the module_name.module file. Does Drupal automatically include all .inc files within the module's directory?

There are multiple ways .inc files can be included.

Hooks in general should all be included in the .module file, as that is the only file loaded on every page load by default, and hooks should always be available. However, hook_hook_info() can be implemented, telling Drupal that the hook should be looked for in another file. For example:

function hook_hook_info()
{
  return array
  (
    // Tell Drupal to look in a different file
    // for hook_form_alter:
    'form_alter' => array
    (
      // Tell Drupal to look in MODULENAME.forms.inc
      // for hook_form_alter:
      'group' => 'forms',
    ),
  ),
}

Next, you can use hook_menu() to look for a callback in an .inc file:

function hook_menu()
{
  $menu['some/path'] = array
  (
    ...
    'file' => 'includes/some_file.inc',
  );

  return $menu;
}

The same can be done with hook_theme():

function hook_theme()
{
  $themes['some_theme_hook'] = array
  (
    ...
    'file' => 'includes/some_file.inc',
  );

  return $themes;
}

.inc files can also be directly included with module_load_include():

// The extension is given in the first argument, and
// left off the last argument:
module_load_include('inc', MODULENAME, 'includes/some_file');

Though in forms, form_load_include() should be used rather than module_load_include():

// The extension is given in the second argument, and
// left off the last argument:
form_load_include($form_state,'inc', MODULENAME, 'includes/some_file');


How to check if field is empty and hide a css class in render array? I am new to drupal core development any help will be much appreciated.
I have a tab group from content type hidden from anonymous users (by default) when the field content within the tab is empty, how do I hide this tab when login in editors are viewing the same content.

This is what I have done so far in my node.inc using template_preprocess_node

function template_preprocess_node__event(&$variables, $hook)
{
//  kpr($variables);
$node = $variables['node'];
//  kpr($node);
$custom_tab = field_get_items('node', $variables['node'], 'field_route_text');
$custom_tab = (!empty($custom_tab)) ? kpr ('not empty from node') :  kpr('empty from node');

// jQuery UI accordion lib
drupal_add_library('system', 'ui.accordion');
}

I achieved this by the code below;

    function template_preprocess_node__event(&$variables, $hook) {
    $node = $variables['node'];
    $custom_tab = field_get_items('node', $variables['node'],    'field_override_group_label')
    if (! isset($custom_tab[0]['safe_value'])){
        drupal_add_css(drupal_get_path('theme', 'template some ') . "/css/customtab.css");
    }
    // jQuery UI accordion lib
    drupal_add_library('system', 'ui.accordion');
}

In customtab.css file, I add a css to hide the class.
I think this might have impact on the general site performance.


How to show a block on specific pages using the Node ID instead of an URL? Using the "Show block on specific pages" on a block configure field, is it possible to use the Node ID in lieui of URL.

I.E.

412 instead of about/contact-us/

If you just want use the node id you can use node/[id].
Example: node/1

It will works even you are using a path alias, because that route is allways avaiable for any node.


Create a new personal page instance for each user I have a content type named 'personal' and a node (page) also called 'personal' which is of that content type.

I want my users to have their own private 'personal' page on my website where every user can post their own private stuff. Like a blog page where the page layout is the same for everyone but each user has their own posts on their profile page.

I am trying to achieve something like  www.mywebsite.com/personal/username (or www.mywebsite.com/username/personal)

I am using the Rules module but each user is still getting re-directed to the one and only 'personal' page I have created.

You can create new Views page like this:

Let me explain underlined options:

Path: personal/% - let you to create dynamic path. In addition "%" sign is a wildcard used by contextual filter;

Relationships > Content:author - this relationship is required by filters to show only nodes created by its author. Without this we would be able to filter only by user ID.

Contextual Filters > User:name - this is value of URL wildcard. It allow you to filter nodes by put any user name instead of % sign.
For example: www.mywebsite.com/personal/john

Filter Criteria > Current User (Yes) - It shows only nodes created by current logged in user. Without this filter anyone can put any user name in url and see content created by this user.

Let me know if something is not clear to you.


How not to "fill up" a view when flagging I have a list of different tasks (about 100 items). Each time a user logs in, he should get a display of 5 tasks randomly selected out of this list. When he finished the task, he can flag them as "done" and the task will disappear from the list. I managed to do this with flag module and views module.
The problem is, that the task-list is much longer than the 5 tasks. So each time the user flags a task with "done" this task will disappear from the list, but a new task will show up at the same time.
How can I stopp a view to be "filled up" in order that the user can empty his task list? (And may be gets new tasks only the next da or on next login).

I figured out how to manage the problem without the need to write new code. I am posting it here, so that it may help others as well, even if the topic is very specific.

How to manage, that a view doesn't fill up immediately after flagging:

Create a "helper flag" and set the flag link to the helper flag on the nodes of your view.
Create a rule, that the flagging of the helper flag, adds the action of unflagging your original flag.
Put the filter in your view in this way, that not only all nodes are displayed that are unflagged with your original flag, but also those with the helper flag (or-filter)
Create a rules display of this view.
Create a rule that reacts on the event "user has logged out".
Add a view loop from the created rules display and add the action (unflag the nodes". choose the "helper flag" to be unflagged.

That's all. As long as the user stays logged-in, the view is not filled up, when he flags the nodes. As soon as he logs out, the helper flag is unflagged and the view is filled up.


Alter Reset Password Link When a user resets his password he/she gets an email with a link which adds a message to the website and a hyperlink which it redirects him to the /user/[uid]/edit?token=... page.

How can i alter this link ?

I would prefer mail a new link to user rather than altering the current link.

Use Tokens API to create user wise links.

function MYMODULE_token_info() {
  $info['tokens']['user']['passresetlink'] = array(
    'name' => t('Password Reset link 2'),
    'description' => t("Password Reset link 2"),
  );
  return $info;
}

and

function services_chat_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'user' && !empty($data['user'])) {
    $user = $data['user'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'passresetlink':
          //$user = user_load($node->uid);
          //$newlink = make your link here.
          $replacements[$original] = $newlink;
        break;
      }
    }
  }

  return $replacements;
}


Drupal 7 - Add Items to multiple places in a menu I'am trying to set up a menu layout which has two links to /our-public-awareness-campaign; one under "Voter", and one under "News centre". The problem I'am running into is that although I can have two links in different parts of the menu, when looking at the page it will always try to open the menu to only one of them. This means that if you are looking under "Voter", and you go to "Our public awareness campaign", suddenly you're in a different location of the site. Any ideas on how I can fix this?

Thanks, Ruslan

Unfortunately, this is a feature not available in Drupal core. The issue is being worked on, but does not currently have a solution: http://drupal.org/node/609542

In the meantime, one potential solution is to use path aliases to the same node. Thus you might have /voter/our-public-awareness-campaign and /news/our-public-awareness-campaign which both point at a particular node. Drupal should treat the two menu entries as unique/separate then, and thus only the one you want to show as the menu should be activated.