What is the SQL query to filter og Admin Accounts? I currently have the following SQL statement that gives me a list of all of my og nodes and their associated owner. I am having trouble nesting my JOIN statements to add the name of the owner from the users table. Any hints? Thanks

SELECT
    label AS `Group Name`,
    gid AS `Group ID`,
    etid AS `Node ID`,
    type AS `Type`,
    b.nid AS `Owner ID`
    FROM `prefix_og` a
        LEFT JOIN `prefix_node` b
            ON a.etid=b.nid

This worked nicely... how can I make this available in a view?:

SELECT
a.label AS `Group Name`,
a.gid AS `Group ID`,
a.etid AS `Node ID`,
b.type AS `Type`,
b.uid AS `Owner ID`,
c.name AS `Owner Username`,
d.realname AS `Owner Realname`,
e.rid AS `OG Role ID`
FROM `prefix_og` a
LEFT JOIN `prefix_node` b
ON a.etid=b.nid
LEFT JOIN `prefix_users` c
ON b.uid=c.uid
LEFT JOIN `prefix_realname` d
ON b.uid=d.uid
LEFT JOIN `prefix_og_users_roles` e
ON b.uid=e.uid


Change entity reference field widget based on condition? I am using Drupal 8. In user registration form, I use an entity reference field to a profile. I wanted to display inline entity reference form widget or entity select widget based on role.
For this, I tried to use hook__field_widget_form_alter(), but it didn't work.
Is there any way to solve this problem?

For D7, you use hook_field_widget_properties_ENTITY_TYPE_alter but the problem is that in D8 this hook no longer exists.
Took a while to figure out an answer for D8, but here it is.
Since D8 allows you to create Form Display Modes:
1) Add a form mode

2) Select the entity type, User in this case

3) Add name to it

4) In Manage Form Display, click on Custom Display Settings and checkmark it

5) Click on the alternate view mode and change widget

Then in custom module you change the view mode if it has a certain role
/**
 * Implements hook_entity_form_display_alter()
 */
function mymodule_entity_form_display_alter(\Drupal\Core\Entity\Display\EntityFormDisplayInterface &$form_display, array $context) {
  if ($context['entity_type'] == 'user' && $context['bundle'] == 'user') {
    $current_user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    if ($current_user->hasRole('administrator')) {
      // change the display mode
      $id = $context['entity_type'] . '.' . $context['bundle'] . '.alternate';
      $storage = \Drupal::entityTypeManager()
        ->getStorage('entity_form_display');
      $alt_display = $storage->load($id);
      $form_display = $alt_display;
    }
  }
}


How to create a url pattern for a specific node I have a node with the path: http://www.example.com/test

I would like all paths that begin with /test/ to go to this node. url like these:
http://www.example.com/test/a/b/c
http://www.example.com/test/a?bc

all should be redirected to this node.

How can this be accomplished?

To accomplish this, you can use Pathauto module. To set a specific path for a specific node, go to admin/modules/pathauto/config and set the path for that specific node in the textbox as you want. For your case use test/[node:title] in the Pattern for all test paths text field.


Views Using Current Month +- One Month I am trying to get a list of seasonal items that dynamically display items based on the current month. It also includes items from the prior month and future month.

I have created a content type for this type of item, with an integer checkbox list. The values are 1|January, 2|February, 3|March, etc. When creating/editing a seasonal item. I check the checkboxes for the month(s) that the item is used.

I have created a view for current items, but have yet to find a way to dynamically set the filter for the item month. At the beginning of each month, I have to remember to go into the view, and uncheck the checkbox from (now) two months ago, and check the checkbox for the future month to maintain that three-month spread.

How can I make this filter dynamically create a three-month list based on the current month?

You should not have used List as your field type, you need to use Date as your field type. Using the Date module and enable Date UI and Date Views.

Then in MORE SETTINGS AND VALUES, Date Entry, select Custom Format and put F Y

Now in Views for filter add your date filter, in my example my Date field is called kewl

then use is in between previous month and next month


Is there a way to generate thumbnails within Drupal? I see that Drupal 7 natively includes the GD toolkit. Looking at the documentation, there are Several Functions available to me that would seem to make it possible to, from an existing image, generate temporary thumbnails. The issue, however, is that any of the resizing methods seem to be destructive, and there is no simple way to copy images. PHP, of course, offers facilities that are low-level enough to handle this...and I'll use those if I have to...but is there a simple, Drupal way to programmatically create a thumbnail to a specified size?

First, create an image style from the Drupal UI, or by implementing hook_image_default_styles in a custom module. An image style contains the resizing and cropping rules for your thumbnail. After that, you can use theme_image_style to create the html output for an image using the thumbnail style. Do not call theme_ functions directly though; call it like this: theme('image_style', ... ). The thumbnail will automatically be created in a non-destructive way when it is first requested.


Get Order Object on Checkout Complete Page I'm trying to develop a new module but just can't get the correct solution, I hope you can help me.

On the checkout complete page i need the order object with all information of the just created order to print out an javascript code which will be created with the order data and execute when the user completes the checkout process. With the hook "myModule_footer" I am getting into the footer to print my code and with "arg(2)" I can check if the URL is "complete". But now I need to get the order object but I just can't find the right way to do it.

I also tried other hooks like "myModule_checkout_complete" but they won't work:

function myModule_checkout_complete($order, $account) {
drupal_set_message('It works');
}

Is there an better solution to hook into the checkout complete page, get the order object and return some code to the frontend?

Thanks

The hook hook_uc_checkout_complete() is the function you're looking for. However, you're going to have problems here since the function runs after the page display.

One way to get around this is override the theme function on the complete sale page:

function THEME_uc_cart_complete_sale($variables) {
  $order_json = json_encode($variables['order']);
  drupal_add_js('jQuery(document).ready(function () { var order = '.$order_json.'; console.log(order); });','inline');

  return $variables['message'];
}

This will execute JS code with the order object upon sale completion.


hour - based context I would like to add body classes by context depending on the time of the day. One class for the morning, another for the midday, another for evening.
I expected the context date  module to do thatm, but it does not work when I do not put the date in (i.e. it accepts the condition, but there's a bug and the whole condition disappears afterwards).
Any ideas?

If you are adding classes which will be styled by your theme then it is best to add them with the theme in template.php. Each theme might handle this differently.

For example, if your theme is based on Fusion then you can add new classes by implementing hook_core_preprocess_html()

<?php
function mytheme_core_preprocess_html(&$vars) {
    $vars['classes_array'][] = mytheme_hour_based_class();
}

function mytheme_hour_based_class() {
    // Return a CSS class based on the current 24 hour time
    return 'hour-of-day-'. date('H');
}
?>

If there isn't an existing context module which serves your purpose then you would have to create your own module which implements the context API. You can learn about the context API here.

http://drupalcontrib.org/api/drupal/contributions!context!context.api.php/7

Telling you how to do that would essentially require writing the module for you, which seems outside the scope of an answer.


$user-> removeRole('administrator') doesn't remove role I got php code that is suppouse to remove one role and add a new one to all users in given array. But unfortunatelly it just add new role but doesn't remove one. I tried alphanumeric values as $rid and straightforward numeric $id but still no effect. I tried putting error_logs inside loops and it's executed and printed to error_log.php.
Here's my code
foreach($users as $usr){
            $user = user_load_by_name($usr);
            $user->addRole('roleToAdd');
            $user->save();
        }
        foreach($users as $usr){
            $user = user_load_by_name($usr);
            $user->removeRole('roleToRemove');
            $user->save();
        }
}

Array
[0] => client1
[1] => client4

#edit
I think it is worth to mention that roleToRemove is assigned to every new user that is registered using registration role module
FIXED check answers

Ok i found an answer.
The code is proper and it works. The problem was that I got module installed that assigned a role to new created users. I found out that it not only assign role when someone create new user but also when you was updating any of them.
I've patched this bug and i got this hosted on my repo so if anybody needs it.
repo


Redirecting anonymous user to specific page I have a view (d7, views3) that is set up as a table with several fields and the far right column is a global custom text field containing some html like this in the text box:

Enroll

When an anonymous user comes to that page and clicks on that link, it forces them to the login page.  But then after they log in, it takes them to their main user page instead of the node that they would have gone to if they had been logged in.  Is there a way to send the user to the page they should have gone to after login ??

you can set destination after login to which you want the user to redirect to.

So consider this example a login link like  www.sitename.com/login?destination=node/1 will take user to node/1 after login.

More detail:

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_get_destination/7

one of you comment says you are using login redirect module, I have not used this module before the module page on drupal.org itself says it covers the functionality you are looking for.

  A simple module providing a method to redirect users according to an
  URL-defined parameter after logging in. Allows redirects toward
  non-Drupal location.

So the reason the that ?destination is not working, might be because of you a redirect rule triggered by login redirect module.

So solution can be set conditional redirection in login redirect module which can be checked using the parameters in url.


Easy noob custom PHP question in views... Editing recent news stories view <?php
$href = $data->node_data_field_news_external_link_field_news_external_link_value;
if($href == ''){
    $href = 'node/' . $data->nid;
    $href = url($href, array('absolute' => TRUE));
}
echo '
' . $data->node_title . ' (' . date("F j, Y", $data->node_created) . ')
';
?>

I'm sorry but I've searched for something that can help me with this.  I know it is simple, but I've already spent hours while trying to teach myself PHP in the process.  I hope that this will take someone 30 secs and allow me to keep learning.

Anyways... I have an attribute (field_successdate) in the News content type that I'm trying to use.  It's a date of when the News happened.  In the view, the customPHP field uses the node's created date and appends it to the node's title to create a link to the object.  I'm trying to replace the node's created date with my field_successdate.  I've added it to the fields and then referencing it in the customPHP code, but no luck.  Do I have to add the field_successdate to the fields in the view and then add an argument? (I've tried that too)

Can any one help?

Thanks!!!

It's probably easier to add the field to the field list (field_successdate). Then use Views rewrite display option to write the node: title link to include the date from field_successdate.

The rewrite will require the Token module to be enabled. rewrite the title as: [node:title] [node:field_successdate]

Be sure you hide field_successdate if you dont want it literally shown in the view by itself somewhere. You may or may not need to move field_successdate to the top of the field list so its gets made into a Token to be used in the title properly.

I'd make a pic of this .... but that'd take like minutes....


Removing Email Address Required Field for Anonymous Users in Drupal Commerce I have an email address field that shows up at the top of my commerce checkout form for anonymous users. It's a required field. However I've added my own email address field to the form further down the page in the billing information area. I don't want the account information fieldset and associated email address field at all because only anonymous users use the site.

Does anyone know where I can find this email address field...is it in views somewhere? I'd just hide the whole fieldset but the field is required so I need to actually remove it from the code somehow.

You can disable Account info section by dragging it to disable section by visiting page 'admin/commerce/config/checkout'.

As in the screenshot Account Information is in Disabled instead of Checkout which is default configuration.

But remember there is a default rule which tries to create an account for anonymous user using the email id, you might have to disable it, or may have to turn in conditional.


Import users into Drupal with data from a CSV file How can I import users fom a CSV file in Drupal 8?

I’ve found this module but it is not updated for Drupal 8:

https://www.drupal.org/project/user_import

I think that I can make an import directly with a MySQL script but is it possible with Drupal (I know I can insert datas directly into database but I don't know if Drupal system will allow that method)?

I’ve found this question but it is not exactly what i need :
Importing a bunch of users from csv spreadsheet file into Drupal 8

I import data from a csv file and it is not a migration from a drupal site.

I think that I can make an import directly with a MySQL script but is
  it possible with Drupal (I know I can insert datas directly into
  database but U don't know if Drupal system will allow that method)?

Instead of MySQL this would be a Drupal method to insert users by using the Entity API:

$user = User::create([
  'name' => 'foobar',
  'mail' => 'foobar@example.com',
  'status' => TRUE,
]);
$user->save();

So if you don't want to use Migrate there are other ways for such a simple import task. You can use a php library of your choice to fetch the data and then add the user entities one by one. I answered a similar question for importing nodes at a time when Migrate was still in alpha: Is there a way to migrate only nodes?


Sort view by tag count I have to show all the tags and sort based on count. I am able to get the count of tag used by pages through views but not able sort based on count as this option is not available in views. Any suggestions?

It is possible with just core views.

Create a view that displays terms
enable aggregation
add relationship Content with term
add sort content uuid with aggregation type: count
add field content uuid with aggregation type: count
add field taxonomy term

Your view should look similar to the following


Import data with feeds that is not in the source file I need support to set a field on a feeds mapping that is not in the source.

I already have some code that for some reason is not working.

If I use hook_feeds_after_parse, I can set the value but I need to use the method below (new mapping).

function  MYMODULE_cronapi($op, $job = NULL) {
    $items['TEST IMPORT'] = array(
        'description' => 'TEST IMPORT',
        'rule' => '1 * 1 * *',
        'callback' => ' MYMODULE_testImport',
    );

    return $items;
}

function MYMODULE_testImport() {
    $test_field_value = 'this is a test';
    $feeds_importer = 'test_feeds';
    $feeds_source = feeds_source($feeds_importer);
    $field_mappings = $feeds_source->importer->processor->getMappings();

    $path_to_xml = 'http://.../sites/default/files/test_content.xml';

    foreach ($field_mappings as &$mapping) {
        if ($mapping['target'] == 'field_test_field') {
            $mapping['test_field'] = $test_field_value;
        }
    }

    $feeds_source->importer->processor->addConfig(array('mappings' => $field_mappings));

    drupal_static_reset('FeedsProcessor::getMappings');

    $feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);

    $feeds_config['source'] = $path_to_xml;

    $config = array(
        'process_in_background' => TRUE,
    );

    $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
    $feeds_source->importer->addConfig($config);
    $feeds_source->save();
    $feeds_source->startImport();

    while (FEEDS_BATCH_COMPLETE != $feeds_source->import());
}

function MYMODULE_feeds_processor_targets_alter(array &$targets, $entity_type, $bundle) {
  if ($entity_type == 'node' && $bundle == 'test_content') {
    if (isset($targets['field_test_field'])) {
      $targets['field_test_field']['callback'] = 'MYMODULE_set_test_field';
    }
  }
}

function MYMODULE_set_test_field(FeedsSource $source, $entity, $target, array $values, array $mapping) {
    if ($source->importer->id == 'test_feeds') {
        if (!empty($mapping['test_field'])) {
            $entity->{$target}[$entity->language][0]['value'] = $mapping['test_field'];
        }
    }
}

To get the importer's machine name from the source, instead of doing $source->id, this should be $source->importer->id.

I don't know what you are trying to do with $mapping['_ad_area'] exactly. $mapping contains target configuration (aka mapping settings). I don't see form_callbacks on your target code. The default taxonomy reference field also doesn't have an option called '_ad_area'. If you added mapping for the 'field_ad_area' target, values coming from the source should exist in $values.

You say you want to provide a value that is not in your original source. If this is a fixed value, you can use the Tamper plugin "Set default value" from the Feeds Tamper module. If you are using the CSV parser, on the mapping form you can just enter a source column name that does not exist in your CSV file. Otherwise, select "Blank source".
If you programmatically want to set a value, you can implement the hook hook_feeds_after_parse() in a custom module:

/**
 * Implements hook_feeds_after_parse().
 */
function mymodule_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  if ($source->importer->id != 'qc_data_generic_import') {
    return;
  }

  foreach ($result->items as &$item) {
    $item['Blank source 1'] = 'My value';
  }
}


How duplicate order automatically with commerce 2 How do I automatically duplicate an order?
I use Drupal 8 and Drupal Commerce 2. I need to duplicate some orders, each week, automatically.

Orders have a Boolean field (recurrent_order). When the field is filled, the web site has to create the same order at the end of the week.

I have achieved this with rules and VBO on Drupal 7: On maintenance task, a rule finds an array filled by a VBO view, and a component duplicates the content.

In Drupal 8 there isn't VBO view access from a rule.

How can I achieve this? Regards,

Here is the code for duplicate order with a cron job:

function commande_et_paiement_cron() {
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'abonnement');
$query->condition('field_livraison', 3);//livraison le vendredi
$entity_ids = $query->execute();

foreach ($entity_ids as $entity_id) {
$abo = Node::load($entity_id);

//utilisateur
$user = $abo->get('field_utilisateur')->getValue()[0]['target_id'];
$utilisateur = \Drupal\user\Entity\User::load($user);

//profile
$entity_manager = \Drupal::entityTypeManager();
$profile = $entity_manager->getStorage('profile')->load($user);

//abonnement
$nid= $abo->id();

//livraison
$date_livraison = new DateTime();
$date_livraison->modify('next friday');

//ligne de commande
$line_items = array();
$abo_array= $abo->get('field_abo_produits')->getValue();

foreach ($abo_array as $abo_item) {
    $ligne = $abo_item['target_id'];
    //load produit abonnement
    $item = \Drupal\commerce_order\Entity\OrderItem::load($ligne);
    $quantite = $item->getQuantity();
    $produit = $item->getPurchasedEntity();

    $order_item = \Drupal\commerce_order\Entity\OrderItem::create([
    'type' => 'default',
    'purchased_entity' => $produit,
    'quantity' => $quantite,
    //'unit_price' => $role_price,
    ]);

    $order_item->save();
    array_push($line_items,$order_item);
    }

//creation de la commande
$order = \Drupal\commerce_order\Entity\Order::create([
      'type' => 'default',
      'store_id' => 1,
      'checkout_flow' => 'boulangerie',
      'uid' => $user,
      'billing_profile' =>$profile,
      'field_abonnement' => $nid,
      'placed' => time(),
      'field_date_livraison' =>$date_livraison->format('Y-m-d'),
      'order_items' =>$line_items,
      'state' => 'draft'
    //'completed' => time(),

    ]);
    $order->save();
    $order->set('order_number', $order->id());
    $order->save();
    $order->set('state', 'complete');
    /*$comment = 'blabla';
     $logStorage = \Drupal::entityTypeManager()->getStorage('commerce_log');
    $logStorage->generate($order, 'order_comment', ['comment' => $comment])->save();      */
    $order->save();
   }
}


Hide view results with hook I am trying to not show a certain view result using hook_views_pre_render but I didn't find the correct way to not display the result.

I did manage to have access to the view and change each result title to a test title, code:

function MODULENAME_views_pre_render(\Drupal\views\ViewExecutable $view) {

  if($view->id() == 'tasks') {
    foreach($view->result as $task) {
      $task->_entity->set('title', 'test - ' . time());
    }
  }
}

I want to use something like $task->show = false;, is there any way?

Thank you!

Solved my problem with the following:

function MYMODULE_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view->id() == 'tasks') {
    $i = 0;
    foreach($view->result as $value) {
      if($i == 2)
        unset($view->result[$i]);
      $i++;
    }
  }
 }

The code above does not show the 3rd result from the view results. Add logic as you need.


Files (±50MB, audio) automatically repetitively deleted (after ± a couple of hours-days?) Might I ask you what can be the cause and solution of:

the automatic dissapearing of "large" files (±50MB, such as an audio file) that I have manually put into the root folder of my Drupal website/installation, using a FTP-client?

Does this has something to do with CRON (just a wild guess)? Is it not smart to manually (FTP) upload files into the root folder? Should a module be used at all times?

Does this has something to do with CRON (just a wild guess)?

No, drupal won't delete files in the folder, it must be something else on your server.

  Is it not smart to manually (FTP) upload files into the root folder? Should a module be used at all times?

Files should be in your files directory (usually sites/default/files) if you're uploading them via the UI so Drupal can manage them.  If they're more static, they should be in a module/theme folder.


How to use last parameter (term) as a filter in a view I'm using Drupal 7 as a document management system and I've got a taxonomy vocabulary called "Document Tags" with the following structure:

Accounting
  Best Practices
  Client 1
  Client 2
HR
  Forms
  Policies
IT
Office Management
   Photos
   Org Charts

I created a block view using Views Tree and set up the tree structure that works well so that the categories are nested and expand properly, and are each linked like so:

mysite.com/docs/accounting
mysite.com/docs/accounting/best-practices
mysite.com/docs/accounting/client-1
mysite.com/docs/hr
mysite.com/docs/hr/forms

My document view uses the contextual filter "Content: Has taxonomy term ID" and then in the filter as shown.  When I click on a first level category (Accounting, HR, IT, Office Management, etc.) it works great but anything underneath only displays the documents tagged with the top level, so it's evidently only using the first parameter in the display.

Is there a way to have the filter always pull the last URL parameter (e.g. "forms" in the URL mysite.com/docs/hr/forms)?

UPDATED - here are screenshots of the two pages and their results:
http://tentenstudios.com/storage/page_1_filter.png
http://tentenstudios.com/storage/page_1_results.png
http://tentenstudios.com/storage/page_2_filter.png
http://tentenstudios.com/storage/page_2_results.png

Yes, you can add a separate block with the same settings and in the contextual filter get form from the url.

Add the blocks in the same region and in the visibility settings select Only the listed pages and add docs/*/* for child terms and to the other block add docs/* for the parent terms.

UPDATED:

If you have a Taxonomy type page view then you can do the following thing.

Create tow pages with path as docs/* for parent terms and docs// for child terms i.e. form.

In the contextual filter add term id and select This Page override. and check Provide default value. In the Type drop-down select Raw value from URL and then from Path select 3 for docs/%/% path and 2 for docs/% path.


How can I programmatically add webform elements to an existing webform? I have a webform that is very simple, it's a questionnaire. It is attached to a content type called "event". e.g.

discussion_1:
  '#type': likert
  '#title': 'Discussion 1'
  '#questions':
    'Question 1': 'Question 1'
    'Question 2': 'Question 2'
    'Question 3': 'Question 3'
  '#answers': likert_five_scale

Is it possible to alter this webform when the webform is rendered by populating the questions from another source such as a view?

i.e. there will be a variable number of discussions with variable numbers of questions.

I am trying to dynamically build a webform based on data that is coming from the node to which the webform is attached

So I spent a full day investigating on something similar. Kudos to @jrockowitz for providing the right direction. Below is something I wrote to work.

$webforms = \Drupal::entityTypeManager()
  ->getStorage('webform')
  ->loadByProperties([]);

$new_field = [
   'new_field'=>[ '#type' => 'textfield',
     '#title' => 'Question one',]];

foreach ($webforms as $webform) {
     // Applying to all forms.
      if (!in_array('new_field', $webform->getElementsDecoded())) {
        // $webform->getElementsDecoded() will get all the previous elements of the webform.
        $new_element_arrangment = array_merge($webform->getElementsDecoded(), $new_field);
        $webform->setElements($new_element_arrangment)->save();
    }
}


Select All checkbox and sub fieldgroups I am looking for a way to present the following to users. This will be a list of checkboxes:

[ ] Region 1 A
[ ] Region 1 B
[ ] Region 1 C
[ ] Region 1 D
[ ] Region 1 E
[ ] All of Region 1
[ ] Area 2
[ ] Area 3
[ ] Area 4

This would all be stored in the same field.

So there are two main things I want to be able to do:

1) When entering the data, the admin/user should be able to choose any of the options, but if the select "All of Region 1", it automatically selects all of the Region 1 choices along with the "All of Region 1" choice.

2) When site visitors are searching this field (through an exposed Views filter), if they choose to filter for "All of Region 1" they should get anyone who chose any one of the Region 1 areas as well as anyone who chose "All of Region 1".

One solution would be to just remove the "All of Region 1" option from the exposed filter.

Or have the "All of Region 1" option in the exposed filter also check all the region 1 options automatically.

Is this necessarily a hook_form_alter solution?

This is a possible solution using javascript that shows how to select the child checkboxes with JQuery.


Rule to check if a date value is a specific day of the week I want to set a rule which checks a date of format "2014-09-24 08:43:39" is a Monday using the data comparison rule. I have tried to manipulate the data selector for the date using the ":custom:N" format however data comparison wont accept it.
I'm trying to do it from within the rules module as my PHP is a bit limited.
Any ideas?
Thanks
Adrian

I had myself many troubles with Rules and dates too. There are several open issues in Rules about dates. So the solution that I offer is very cumbersome and to be honest I don't like it too, but it seems to be the only thing to work. Improvements are of course welcome. Maybe there is also some module which I miss.

Note that this is about Rules ver. 7.x-2.7. The solution involves both some PHP code and components.

So the first issue at hand is that it seems Rules cannot change the format of a date variable in a data comparison, or to properly convert the data type.

Therefore I am using a rule to get the weekday from the variable, then pass it to a component as a variable (integer). In that component I can easily do a data comparison for the interger and procedd with any actions.

In order to get the weekday, I create an action "Add a variable". In there, I use some PHP code in order to directly get the week day. Here is the second issue: Rules do not seem to properly expose the variables in PHP. Therefore I specify the type of the variable as text, and then I specify the value using one of the replacement patterns in the direct input mode (otherwise a date will not be available in the data selection mode). Now we have the date as a string in a variable. Let name the variable variable_added.

The second action is to "Set a data value". In there, you specify:

<?php
$datetime = new DateTime(DateTime::createFromFormat('D, d/m/Y - H:i', $variable_added));
return $datetime->format('w');
?>

We create a DateTime object from a hard-coded format. This has to be the Drupal long date format which Rules seem to use for their date formatting. There got to be an API function that returns the current format which atm I miss, and so we have it hard coded to get us going. Replace this with your installation's custom format from /admin/config/regional/date-time, also consult this. Then we use DateTime::format to get the day number.

So now we have the day number as a string. The third action would be to convert the above variable to an integer, and then in a fourth action you would call the rules component passing on the converted variable along with any other variables you would need.

Appendix: My test case rule export.

{ "rules_test_date" : {
    "LABEL" : "Test date",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php" ],
    "ON" : { "cron" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[site:current-date]" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "data_set" : {
          "data" : [ "variable-added" ],
          "value" : "\u003C?php\r\n$datetime = new DateTime(DateTime::createFromFormat(\u0027D, d\/m\/Y - H:i\u0027, $variable_added));\r\nreturn $datetime-\u003Eformat(\u0027w\u0027);\r\n?\u003E"
        }
      },
      { "drupal_message" : { "message" : [ "variable-added" ] } },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "variable-added" ] },
          "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
        }
      }
    ]
  }
}


Why ConfigFormBase does not goes through custom construct() when using managed_file? First I want to state that this is a question. My Form is working, but I had, strangely, to add clauses for the case when my CustomForm extending ConfigFormBase did not goes as expected throught the __construct()
I created a config property in the __construct(). Then, I could access it from any function, and it worked fine.
As soon as I added a managed_file, things went wrong. Specifically, $this->config was null in validateForm and submitForm. I could restore the property easily by calling the factory again (and that's what I end up doing), but I'm confused.
What I see is the managed_file module send the form in XHR when updating the managed_file input. So when I'm validating the form, maybe there is a cache version or something that gets loaded, or the callback_func works differently. Anyway, the __construct() is executed on the XHR request (I checked with xdebug) but not after when I'm (re) submitting the form with the button.
I compared the stack when $this->config is null and when it's not, and did not spot any difference.
Maybe it's part of a multi-part Form functionality ?
I'm sure I'm getting it wrong somewhere.
Relevant parts as follow :
  /**
   * Constructs a \Drupal\system\ConfigFormBase object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->setConfigFactory($config_factory);
    $this->config = $this->config('custom.settings');

    parent::__construct($config_factory);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
    );

     }

/**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {

    $form['section5'][self::TAB_IMAGE] = [
      '#type' => 'managed_file',
      '#title' => $this->t("Image de l'onglet"),
      '#default_value' => ($this->config->get(self::TAB_IMAGE)) ? [$this->config->get(self::TAB_IMAGE)] : NULL,
      '#upload_location' => 'public://',
      '#upload_validators' => [
        'file_validate_extensions' => ['gif png jpg jpeg'],
        'file_validate_size' => [Bytes::toInt(Environment::getUploadMaxSize())],
        'file_validate_image_resolution' => ['300x300'],
      ],
    ];
}

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // When submitting a Form with managed_file, weirdly no __construct().
    if (!$this->config) {
      $this->config = $this->config('custom.settings');
    }

The difference could be that managed_file is using Ajax which is caching the form object.
If you want to have this property cached you would need to declare it as protected property:
class CustomForm extends ConfigFormBase {

  protected $config;

Normally $this->config() is the method FormBase::config as the main entry point to the config API, not a property you populate when constructing the form object. Using the same name could be quite confusing and it's also recommended to use the mentioned method to retrieve the config and declare the config in ConfigFormBase::getEditableConfigNames() if you intend to save it.


Ajax not getting triggered on change event of selectbox field I've tried all options to trigger an ajax event on change of a selectbox option inside form alter hook, but nothing works. Below is the sample code
$form['field_select_box']['#ajax'] =
   [
     'callback' => 'toggleOptions',
     'event' => 'change',
     'wrapper' => 'edit-field-target'
   ];

If I just try to attach the ajax event to a simple text field (like title), it WORKS.
$form['title']['widget'][0]['value']['#ajax'] =
  [
    'callback' => 'updateSubdomain',
    'disable-refocus' => FALSE,
    'event' => 'change',
    'wrapper' => 'edit-field-subdomain-0-value',
  ];

Help is appreciated

For select list, the ajax should be
$form['field_select_box']['widget']['#ajax'] = [
  ...
];

and please try to code as Drupal standard.


Drush Hangs on wget but wget Works Every drush command I run hangs on wget. However, if I run wget outside of drush, it works just fine. I am behind an http proxy and suspect that's factoring into the problem. I don't understand why wget isn't looking at my http_proxy environment variable when run through drush.

Might this help... http://www.xandermar.com/blog/may-20-2014/using-drush-proxy ?

(sorry, I know this is more of a comment, but I don't have the points!)

If not, have you run the drush commend in verbose mode to get more info?


Is there a function for drupal that can identity if a certain page and its children are being viewed? So I have nav that looks like this:

  Parent Url</>

       Child Url

       Child Url

I would like to add an "active" class to the Parent URl if a user is on the page with url "some-parent-url" or any of it's parent url?

Ideally something like

<a href="/some-parent-url" <?php if (some_drupal_code_for_this){ echo 'class="active"'; } ?>>Parent Url</>

You could use Menu Trail By Path module.

  Menu Trail By Path sets the active-trail on menu items according to
  the current url.

For example if you are at yoursite.com/blog/category1/article1
Menu Items with these paths will get the active-trail class on them and expand accordingly.


What is the best way to pass values from one form to another with fapi? I have one form that is just an options input.  When I select a value then go to the next page there is another form that I want to have three hidden values based upon the chose value of the first form.

With Form API, what is the best way to pass the value from the first form to the next and have three values from the second form be determined by the single value chosen from the first form?

You can do a multistep form, there is a clear usage example in the Examples module. Here is an excerpt about it from the module's project page:

The Examples for Developers project aims to provide high-quality, well-documented API examples for a broad range of Drupal core functionality.
The Examples project contains many modules which hopefully illustrate best practices for implementing various Drupal APIs. These modules can be enabled individually, and will typically add menu items to your site, which should guide you through their features. You can then look through the code to see what they are doing.
Developers can learn how to use a particular API quickly by experimenting with the examples, and adapt them for their own use.
Note also that these modules demonstrate internals for Drupal development in PHP (and some JavaScript). Not all Drupal users will need these examples. There are many contributed modules which will do the majority of what a Drupal site-builder could need. Be sure and explore other contributed modules to see if you can find one that meets your needs.


Custom forms for custom post types in D7 I am sub-theming Bartik and have a content type called "support_query" with 3 fields... "title" (which comes with all content types), "field_support_body" and "field_support_date" (which is a simple date field from the Date module).

I would like to create a custom form so users can send me queries of this custom post type... what's a good way to do something like that?

You should use your content type's form, customized to suit the basic user.

You'll have to give the allowed users role the right permission (like `Create the content type').

Then you'll have to change the form to mask all irrelevant information. There are many ways to do this :

Implement a module with a `hook_form_alter'. Flexible but involves coding.
Use a module or a combination to achieve the same goal. This one for example seems to be interesting.


How to make a Shortcuts menu that open with new window or tab? In Drupal 7, I added the "IMCE" url(www.mydomain.com/imce) into the Shortcuts menu for user to upload file. How to make this menu to open in a new window or tab?

Shortcuts are menu items, so you might be able to use Menu Attributes to set the target to _blank.


Force Rebuild of Custom Entity's Task Menu My module has a custom entity along with custom menu tasks. I would like the tasks shown for a specific entity to be dependent on its properties. Once the properties change I would like the task menu to refresh.

I use custom permissions to determine which menu tabs to show.

I have tried to invalidate the entity's tags after a user changes properties but the task menu does not change (I don't see the permissions being checked again either).

\Drupal\Core\Cache\Cache::invalidateTags(array(
        '[my_custom_entity_type]:' . $entity->id()
)

If I clear all caches, the entity's menu changes as needed but that is a very expensive operation.

Would love some help.

After days of painful searching and reading code, I figured it out on my own. It was super easy once I got it. Since I am using a custom permissions handler to determine if a user should see an entity's task, I added cache tags to the AccessResult object that the custom handler returns:

$cache_tags = array('my_custom_entity_type:' . $my_custom_entity->id());

$access_forbidden = AccessResult::forbidden()->addCacheTags($cache_tags);

Later when my custom entity changes, I invalidate the tag(s) in the submitForm() function of my custom forms:

\Drupal\Core\Cache\Cache::invalidateTags(array('my_custom_entity_type:' . $my_custom_entity->id());


The calendar_style style requires a Date argument error when Using CCK as a date argument Can´t use a date CCK field when setting up a calendar as a view
When I want to save the view I´m getting this error message:

The calendar_style style requires a Date argument.

I´ve added the same CCK field to the fields so views would stop complaining about another error message that in the new versions of views was added..that the same argument has to be present on the fields

Still ..the date type of the CCK isn´t recognized as a valid date argument...
Works with node updated date though...

I have Drupal

Date 6.x-2.7
Calendar 6.x-2.4
Views   6.x-2.12
and Drupal 6.22

When building a calendar in Drupal 6, you should clone the default calendar views in order to create a new on instead of trying to make it from scratch (Error when changin Date argument).

Have a look at these tutorials if you need some extra help:
- Drupal Calendar Setup
- How To: Create a Drupal Calendar


How can I get file field url in drupal 7 from views of its content type? It has been a few days I'm trying to get the uploaded file urls in drupal7 (using default file filed in drupal content type) from a view. I must get this url in page which a view is embedded inside it, this view shows 10 items of its content type per page, how can I get the url of filefield?

should I use preprocess function or any thing else?

I have tried many ways suggested in many websites but I have failed. is there any straight forward solution?

It's not really clear what you mean by 'access' in this context, but if you're looking to get the details for a file uploaded through a file field:

$node = node_load(1);
if ( ($field_items = field_get_items('node', $node, 'field_file')) ) {
  $file = file_load($field_items[0]['fid']);

  $uri = $file->uri;
  $external_url = file_create_url($uri);
}

Or to grab the external URL directly with an EntityMetadataWrapper:

$node = node_load(1);
$wrapper = entity_metadata_wrapper('node', $node);
$external_url = $wrapper->field_files[0]->file->url->value();


Combing View Formatters with Custom Formatter So I'm tearing out my eyes for a solution here. I have a view,and all I want to do for the image content is to use two different formatters effects. Example I want to use Adaptive Image formatter and Lightbox2 formatter. I started tinkering with custom formatter html+token but I guess I'm not that advance to figure out how to combine html + token variable to create a custom formatter of two formatter effects.

Are there any examples of combing two formatter effects to create a Custom Formatter?

Custom Formatters module is a (another) good way for this, you can check more samples in official website at: http://customformatters.com.

You probably need to use PHP code for this and get all advantages of powerful Drupal API,  tokens are limited uses for simple outputs without rewrite.

Example for render image fields (do NOT include ):

$output = '';
foreach ($variables['#items'] as $item) {
    $output .= theme('file_link', array('file' => (object) $item));
}
return $output;


Execute a custom shell script before the aegir verify Every actions in aegir trigger a verify.

I would like to automatically execute a shell script before that verify (rsync of plateforms).

How could I proceed ?

You could implement a drush_hook_pre_COMMAND() hook in drush to run any code you'd like.

See the docs page for more details: https://docs.aegirproject.org/extend/altering-behaviours/#running-extra-code-after-a-task


Using OR in views Argument filter Is it possible to use OR in arguments?
I have content types "Sport Match" and "Sport Team". "Sport Team" can be in "Host" field or in "Guest" field of Sport Match (node reference).
How can i make view containing all "Sport Match" for one "Sport Team"? I would like to display such view on every "Sport Team" node. So i'm thinking that simple two arguments with OR would to the trick.

I would like to get NID of current "Sport team" node and pass it to arguments filter which will looks something like this:

field_host = NID

OR

field_guest = NID

Is there way to do this in views?

In SQL this is easy, can anyone point me how alter view so I manualy insert OR filter.

Or some other idea how to do this?

(I'm using D6 and Views 2)

I'd convert that argument into a filter, then use http://drupal.org/project/views_or for it.

To convert an argument into a filter, you can use hook_views_query_substitutions or hook_views_pre_view to replace a specific value (for example ***NID***) with what you need (e.g. arg(1)).


Cannot install Open Atrium I've been trying to install Open Atrium for at least 6 hours and cannot find a solution. There seems to be a permissions problem…

Here's where I'm at: I successfully installed a Ubuntu VM, and installed Drupal 6. I then downloaded Open Atrium, copied its contents into the example.php folder. I then went to the default folder and changed the settings file to settings.php, etc. Install Atrium launches through Firefox, but then says:

Forbidden

You don't have permission to access / on this server.
Apache/2.2.16 (Ubuntu) Server at example.dev Port 80

Update:

I installed everything using the drush commands per quickstart tutorial. I created the example1.dev folder, then replaced its contents with Open Atrium. I then renamed the Default.install.php file to install.php, and created a files folder inside default.

I'm not sure why I'm having this problem, but it looks like a permission issue with the file folder. I can't figure out how to open up read/write permissions through Ubuntu. Any ideas?

I followed these directions verbatim, and wiped out the appliance and started over a few times as well. I'm at a loss. I think if I knew how to open permissions to Apache I'd be all set. Any ideas?

You said you downloaded Drupal, then downloaded Open Atrium?

Open Atrium is a specialized version of Drupal, you install it standalone.


hook_init() is executed more than once When running xdebugger in hook_init(), I noticed that the debugger was stopping at same break points more than once.
Why is this so? Will it not affect the page load time?

If I print some text within hook_init(), it is being printed only one time. This will not reduce the performance. Also hook_init() is called only once, from Drupal core.


Hiding a tab on a user profile based on the user role I'm making a site using Drupal 8 and I have several roles defined, one of them is Writer. I made a view to show as a tab in the user profile pages called Backlist. If the user is a writer, they can add a list of their books they have written. Everyone visiting the site has access to the backlist information under that tab. What I'm trying to do is make it so the tab ONLY shows in profiles that are writers.
This is very similar to this question: Hide views tab display on user profile to profile owner
That answer didn't work for me because it seems that the 'hide view' is no longer in the validation settings.
As I have it now, the tab shows all the time, and if there's no content, it just shows a message.
So is it possible to hide a views tab, in a profile, based on the owner's role?
Contextual filters:

Configure contextual filter: User: User ID
validation criteria: User_ID
Restrict user based on role: Writer
Action to take if filter value does not validate: Display Contents of No results found

Just under Display content of "No results found" I see Display "Access denied" you need to use that one.
Denied users won't see the tab anymore.
If the display of your view is a page you can even manage the access directly into the "page's parameters" block and restrict the access by user role without using a contextual filter (unless the view really needs one).


Should I declare the usage of a new template.php file? How should I declare the usage of a new template.php file in a Drupal 8 sub theme?
I ask since I didn't find anything about this in the documentation, like this example.
For example, I created a template.php file and put the following function inside, saved and flushed all Drupal cache, but the desired change did not occur.
function garku_process_html(&$variables) {
  $variables['styles'] = preg_replace('/.css\?.*"/','.css"', $variables['styles']);
}

Drupal 8 themes don't have template.php files. Now they use a mytheme.theme file, which needs to be located inside the directory containing the theme. (Replace mytheme with the machine name used by the theme.)
Preprocessing and modifying attributes in a .theme file shows an example of preprocess function, which is placed in the mytheme.theme file, instead of the template.php file.


How to theme the table view mode which is showing entities in inline entity form I am looking for a D8 solution to theme the table view mode.
To start, I would like to remove the main title (the "Legend" tag of the html fieldset).

Note: I know how to use hook_inline_entity_form_table_fields_alter to add/remove columns, I would like to theme what is outside the table.

After the remove of the title, I would like to remove the headers of the table ("Title", "Status", "Operations"...)

In fact, if someone have a solution, I would like to get rid of this table view mode.. My final goal is to have a very simple view mode showing only one field and the 2 action button..

Here is the solution I found to remove the header and the title: this is to preprocess fieldset and table hooks

/**
 * Implements hook_preprocess_fieldset().
 */
function my_module_preprocess_fieldset(&$vars) {
  //Remove the fieldset title/legend for field_myfield
  //as it is a multiple value field, I check only the
  //first part of the id to target field_myfield
  if (strpos($vars['attributes']['id'],'dit-field-myfield')>0){
    unset($vars['legend']);
    unset($vars['legend_span']);
    $vars['attributes']['style'][]='padding:0';
  }
}

/**
 * Implements hook_preprocess_table().
 */
function my_module_preprocess_table(&$vars) {
  //In my use case, I need to target only table that are
  //generated by ief module. I use the first part of the
  //id to target it
  if (strpos($vars['attributes']['id'], 'ef-entity-table')>0 ) {
    //remove column headers
    unset($vars['header']);
    //adpat layout;
    $vars['attributes']['style'][]='margin:0;border-collapse:separate';
  }
}

Most simple solution should be to override the table.html.twig template. You can simplify it to your needs in your theme's template directory. Use the core/themes/classy/templates/dataset/table.html.twig file as source to start your theming.

If you don't want to "re-theme" all tables, add "suggestions" for other templates to your tables and create template files accordingly.


Confused about Owl carousel with Paragraph I'm very new to Drupal and not (yet) familiar with the terms and namings.

I came across a web site in Drupal 8 that uses Paragraph. I'm trying to reproduce the slideshow that apparently uses Owl carousel. But I'm confused about how they made that slider:

(These images slide from right to left)

In the Inspector, the code shows that Owl carousel used in the div wrapper and each item. But there is no owl included in the template twig file.

Inspector screenshot:

Template twig file:

{{content.field_title.0}}

{{content.field_description.0}}

       {% for item in paragraph.field_client_image %}

        {% endfor %}

              {{ content.field_button.0['#title'] }}

I assume the below code generates the classes owl-item, owl-item cloned:

{% for item in paragraph.field_client_image %}

{% endfor %}

Anyone can enlighten my candle?

PS: I have access to all templates files and even have access to the site: no Owl carousel module installed but the libraries is present.

Thanks for your time.

You have to separate between two components:
A) Markup generated on server-side by Drupal, which is used as base structure for Owl carousel.
B) Markup modified by Owl in the client's browser.

Drupal render's something like

  {% for item in paragraph.field_client_image %}

  {% endfor %}

The code above is not really depending or specific for Owl carousel.

The thing transforms it to a carousel is a JS call similar to

$(document).ready(function(){
  $(".partners").owlCarousel();
});

somewhere else in a JS file of your theme or a module. This is the "magic" that transforms the server-rendered HTML to something like your screenshot is showing (adding additional
s, classes and styles)


Is there a nodequeue module for ordering and selcting taxonomy terms instead of nodes for used in a view? Currently I want to make a curated slideshow of taxonomy terms displaying the name of the term with an image field thats attached to the term. Typically this is easily done with a basic node and the module nodequeue. The thing is I want to be able to do this with taxonomy terms.

I found entityqueue module that could work, but its crashing on my site for some reason. It works on a new install and I cannot pin point the issue since the site is fully built out already. I was wondering what other ways or possible modules I can do this with?

What I'm building is just a curated slideshow view of taxonomy terms.

*edit -- found the culprit module that was conflicting with the entityqueue module. whenever i turn on the entityqueue module the entire site would crash and i would end up having to do a DB restore. The module that was causing this conflict was "admin_menu"! O_O

You can try out Flag module, which supports flagging entities, combined with flag_weights and draggableviews you can create ordered slideshows of flagged taxonomy terms.

  Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

If you want to use Flag-3.x with flag_weights you will have to apply this patch: https://drupal.org/node/1877304 works for me so far.


Allow CSS styling in node filtered HTML view? I'm working through my first major Drupal 7 implementation.  My users need to create nested HTML ordered lists, with the various styling in Roman, numeric and alpha formats as listed at http://www.w3.org/TR/html401/struct/lists.html#type-values . The current project is taking place on a node of content type "book page."

This install is using CKeditor, which properly shows the various format types in edit mode.

In node view mode, though, the styles disappear, reverting to 1,2,3 format.  I found in the Filtered HTML settings the statement "... and CSS are always stripped."  Since CKeditor applies style commands to create the formatting method, it seems that Drupal filters them out.

Is there a method to allow styling in node view?  I just discovered http://drupal.org/project/css_injector but can't yet determine if it will do what I need.

Found this discussion which appears to be related.  http://drupal.org/node/259527

I recommend using the WYSIWYG Filter module.
In the "HTML elements and attributes" textarea there is a list of allowed HTML tags. 'ol' should be present. If it is, add '[class|style]' to it which will make it look like this:

ol[class|style]

Or, you can add @[class|style] to the list to enable the style and class attributes on all allowed html tags.


How to have SimpleSaml create a new account only when the user doesn't have a Drupal account already? I'm new to Simplesaml...I feel like I'm missing something obvious in the configuration. Could someone point me in the right direction?

Drupal - 7.53

simpleSAMLphp Authentication - 7.x-2.0-alpha2

We have this setup running, and it does not register a new user each time but only the first time a user logs in, as expected. I just remember running into problems when unique identifier and user name where set to different values (my old bug report is possibly related).
To further manage the displayed user names you could use Drupal modules like RealName.

configuring SimpleSAMLphp_auth to register new users

In the admin interface, navigate to admin/config/people/simplesamlphp_auth

Under the tabs

USER PROVISIONING
check - Register users (i.e., auto-provisioning)

and

USER INFO AND SYNCING
Which attribute from simpleSAMLphp should be used as user's name *
eduPersonPrincipalName

(enter an attribute that uniquely and consistently identifies the user in your realm and that your SAML IdP provides, some attributes change with each invocation and are therefore not suitable, eduPersonPrincipalName is suitable for most educational entities, email could also work fine here)

Which attribute from simpleSAMLphp should be used as unique identifier for
the user *
eduPersonPrincipalName

(enter an attribute that uniquely and consistently identifies the user, make sure to use the same attribute as in user's name before)

From the documentation:

  Determines wether or not the module should automatically
  create/register new Drupal accounts for users that authenticate using
  SimpleSAMLphp. Unless you've done some custom work to provision Drupal
  accounts with the necessary authmap entries you will want this
  checked.

Checking which SAML attributes are available

Navigate to the admin interface of your simplesamlphp install (you might need to activate the interface and look up the password of the install from config.php).
 navigate to the Tab Authentication and "Test configured authentication sources" (/module.php/core/authenticate.php), log in to the same authentication source that is configured in the drupal plug-in under "Autenticaton source for this SP (default: default-sp)" and an overview of all SAML attibutes for that user will be displayed.

The attributes that can be used are possibly best obtained from the documentation of the identity provider, example: https://www.feide.no/attributelist


How can I stop full page HTML from being cached? I am having an issue with my whole page's HTML being cached. This is getting in the way of some dynamic block content that is based off of a user preference value (both authenticated and anonymous users).

I have located the cache entry in the cache_render table of the DB and it has a CID of:

http://dev-mysite.pantheonsite.io/:html

(this would be the entry for the front page)
I do have the block that builds this dynamic content configured with cache settings:

[#cache]['contexts'] = ['session', 'user'];
[#cache]['max-age'] = 0;

I am only having this caching issue when code is push to the Pantheon servers, local development environments with default cache config settings do not have this issue.

(Anyonymous) Page cache can not be controlled by max-age or contexts. You need to call \Drupal::service('page_cache_kill_switch')->trigger(); to prevent that kind of caching.

However, if it is a block that is displayed on all pages, then that becomes pretty pointless to even try and you could uninstall the page_cache module completely.


how do I programmatically save nodes with multiple photo uploads? I have a very straight forward content type created in Drupal - Title, Body, Taxonomy term (drop down select, 1 value only), and Photos (multiple permitted, up to 8, alt and title tags are enabled).  I also have the meta

I have a set of CSV files with data for those fields with corresponding photos. I need to iterate over these programatically and use node_save() to get these in the database as well as upload the related photos.

I followed the direction here, and while it was a good start, I am still confused as to how to handle multiple uploads.

Bulk saving nodes with a file field

Can any suggest a tutorial or provide some sample code that can better illustrate how to do this?

EDIT:
Based on the direction below, this is the code I have come up with

$images = array();
foreach ($file_data_array as $csv_data) {
    foreach($image_array as $file_data) {
  $file = new stdClass();
  $file->filename = basename($file_data['filepath']);
  $file->filepath = $file_data['filepath'];
  $file->filemime = $file_data['mime'];
  $file->filesize = filesize($file_data['filepath']);
  $file->uid = $uid;
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  $images[] = array(
    'fid' => $file->fid,
    'alt' => $file_data['alt'],
    'title' => $file_data['title']
  );
}
$node = new stdClass;
$node->type = 'baby_clothes';
$node->body = 'body';
$node->title = 'title';
$node->uid = 1;
$node->status = 1;
$node->active = 1;

//the name of my actual field is 'product images'
$node->field_product_images[LANGUAGE_NONE] = $images;

//this is my actual taxonomy field
$node->field_baby_clothes_category[LANGUAGE_NONE][0]['tid'] = 2; //actual ID of the taxonomy for this node

node_save($node);
}

Thoughts?

You would normally just build up the files in a loop like so:

$images = array();

foreach ($file_data_array as $file_data) {
  $file = new stdClass();
  $file->filename = basename($file_data['filepath']);
  $file->filepath = $file_data['filepath'];
  $file->filemime = $file_data['mime'];
  $file->filesize = filesize($file_data['filepath']);

  $file->uid = $uid;
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);

  $images[] = array(
    'fid' => $file->fid,
    'alt' => $file_data['alt'],
    'title' => $file_data['title']
  );
}

$node = new stdClass;
// Build up the rest of the node as normal

$node->field_images[LANGUAGE_NONE] = $images;

node_save($node);

This assumes you have your CSV data loaded into an array called $file_data_array.

fid, alt, title, height and width are the only columns available to an image field type so there's no need to build up an array for each field entry containing all the file details (you can ignore that bit in the other answer you linked to as it's unnecessary).

Also note the use of file_save() instead of drupal_write_record() to commit the file to the database...it's much better to use file_save() as it fires the necessary system hooks to let other modules react to your files being added.

Hope that helps


Is there any module to create different menus per user? I would like to have different menus per user.

How can I achieve this?
I searched on drupal.org, but I found a module that creates a menu per role, not per user.

Yes. You can try OM Maximenu. It is really flexible and this means you will need some time getting the configurations right but it's really good especially when it comes to controlling menus per role.


How to create a homepage exposed views search box drupal 7 I'm sure this is really easy to do, but I've spent the best part of 2 hours trying to get Views to accomodate and I'm stuck.

Simply, I would like to create a single search function using Views in Drupal 7 which can go on a homepage to search for both "subject" and "town/ZIP" (ie "English Teachers" available in "Detroit". then the user hits the GO button. This will search the node fields and return a list which (ala a general google search engine style). I'm ambitious in moving forward with D7, but it's painfully slow at the moment).

OK, I'm new to D7 but not IT, but the lack of helpful books or tutorials is making self-learning takes 'years' and not 'months' (I'm upskilling during this downturn and I need to get back into employment like now not next year!).

Can anyone point me to a decent 'How to' tutorial for the above, or suggest the real easy way option in Views? I'd rather use Views and not have any .tpl

Add filters for this fields to your view.
Mark this filters as exposed.
Go to blocks and make sure your exposed filter is visible.


Why doesn't the option "User:roles"  show in "Contextual Filter"? I can't see the option "User: roles" in the contextual filter, and when I select "Relationships" I don't see "User Roles".  What happens?

You should add a relationship "Content:author"; then, the "User:role" filter will appear in "Filter criteria."


Why does my Rules Condition about registration code seem to fail? I'm using the Rules module and the Registration code module and I've tried configuring a rule like so:

Rules Event: upon saving a new user account(event).
Rules Condition: if the registration code used is "123456"(condition).
Rules Action: add a role for a user.

The rules export is as shown below:

{ "rules_give_trial_version" : {
    "LABEL" : "Give trial version",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "regcode" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [ { "data_is" : { "data" : [ "regcode" ], "value" : "123456" } } ],
    "DO" : [
      { "user_add_role" : { "account" : [ "user" ], "roles" : { "value" : { "10" : "10" } } } }
    ]
  }
}

However, the Rules Action is not working (nothing works).

Any idea how to get this to work?

Note: The Rules Action works with the event "User has used a registration code" without any Rules Condition (if I temporarily remove that Rules Condition). But I'm badly in need of the condition as we want to check if a user has used a specific code. If yes, that user should be assigned a role.

The typical Rules Condition doesn't seem to work here

Typically when using Rules, you can always give it a try to see if you can add, as a FIRST Rules Condition, a condition like "Entity has field". Or any other variation of a condition that informs the Rules module that you want to test the value of that field in a subsequent rules condition. Without that, Rules has no clue about which data to make available for subsequent processing ...

But, that doesn't seem to work/help for this particular case. For more details on that (if you really want to know why it doesn't work), you may want to look at the active Major task (not bug!) about Make better use of the Entity system ... (from Fago, who has quite a Rules "reputation" ...).

Rules debugging

If that doesn't help, I typically add a (temporary) Rules Action to just "Show a message on the site" (eg to show the value of a field ...). That might result in other unexpected results, to help you further debug it ...

But that doesn't seem to help either (grrrr), so time to move on to Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Try to find (and read) the documentation

Too bad, this module doesn't seem to have a lot of documentation, and the README.txt is not of much help either.

If anything else fails, read the sources

OK, the advantage of open source ... lets go read the sources ...

Aha, I see the regcode.rules.inc (regcode in this filename is the machine name of the Registration code module), so let's see what this module's Rules integration has to offer:

A Rules Event with machine name "regcode_used" and label "User has used a registration code". Fine, that's also what's used in the rule in the question here (nothing new).
A Rules Condition with (a loooong) machine name "regcode_rules_condition_regcode_available" and label "User has used a registration code". Huh??? That's the same label as in the Rules Event, confusing!!! But that Rules Condition is what intrigues me. Time to fabricate a variation of the rule in the question.

Rule prototype (1st attempt)

Have a look at this variation of the Rule in the question (also in Rules export format, use the Rules UI to import it in your own site):

{ "rules_give_trial_version" : {
    "LABEL" : "Give trial version",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "regcode", "rules" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [
      { "regcode_rules_condition_regcode_available" : { "user" : [ "user" ] } },
      { "data_is" : { "data" : [ "regcode" ], "value" : "123456" } }
    ],
    "DO" : [
      { "user_add_role" : { "account" : [ "user" ], "roles" : { "value" : { "10" : "10" } } } }
    ]
  }
}

The only difference in this rule (as compared to the original rule in the question) is the very first (confusing labeled) Rules Condition with machine name regcode_rules_condition_regcode_available.

That additional Rules Condition seems pretty close to the typical Rules Condition as I mentioned in the beginning of my answer (and Fago's issue I mentioned before makes a lot of sense to me now). And since the question states "... badly in need of the condition ...", I thought I'd leave the QA-testing of this variation of the rule in the question to the OPer of the question ...

Too bad, but that 2nd Rules Condition can never work, since the "[regcode]" token is not the token we're looking for (ie something that is a string, and which we want to check if it yes or no matches the registration code we're interested in to assign that special role). Read on for a new (2nd) attempt ...

Rule prototype (2nd attempt)

With some additional eyeballing and experiments, I noticed that within "Rules Actions" (not Rules Conditions!) there is the token [regcode:code], apart from all sorts of other regcode related tokens. So that opens another opportunity to get it to work anyway: let's just grab that [regcode:code] string and pass it on to a (new) Rules Component, in which we're going to do our thing (ie verify the registration code and grant the role if the code is what we want it to be. Below is the adapted rule from the previous attempt, and the (new) Rules Component:

a) Adapted Rule:

{ "rules_grant_a_role_after_using_a_registration_code" : {
    "LABEL" : "Grant a role after using a registration code",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "regcode", "rules" ],
    "ON" : { "regcode_used" : [] },
    "IF" : [
      { "regcode_rules_condition_regcode_available" : { "user" : [ "user" ] } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Value of token \u0022regcode:code\u0022 is: [regcode:code] and will be used as parm for the subsequent Rules Action, which invokes a Rule Component." } },
      { "component_rules_grant_role_for_specific_regcode" : { "actual_regcode" : "[regcode:code]" } }
    ]
  }
}

b) Rules Component:

{ "rules_grant_role_for_specific_regcode" : {
    "LABEL" : "Grant role for specific regcode",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "actual_regcode" : { "label" : "Actual Regcode", "type" : "text" } },
    "IF" : [ { "data_is" : { "data" : [ "actual-regcode" ], "value" : "123456" } } ],
    "DO" : [
      { "user_add_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "10" : "10" } }
        }
      },
      { "drupal_message" : { "message" : "Since you used registration code \u0022[actual-regcode:value]\u0022, you have been granted a special role that corresponds to it." } }
    ]
  }
}

Note the 2 extra "Show a message" actions I added (to simplify QA testing).

Curious to hear if with this 2nd attempt it does work, or if you can MAKE it work from here on ...


How to create a filter in views which only shows contents that current user can edit? I set content access permission using nodeaccess_userreference module, I need a view to shows contents that user can change.

It's probably not a very well-elaborated patch/module but it might solve your problem: https://www.drupal.org/node/620392 I've just found it...


Same node different template via url I want to use different node templates if the url is appended with ?template=x

Content type is called image

Default Node template using node--image.tpl.php:

blakedesign.co.nz/testsite/node/1

Same node with different template via URL possibly node--image--templateX.tpl.php:

blakedesign.co.nz/testsite/node/1?template=2
blakedesign.co.nz/testsite/node/1?template=3
blakedesign.co.nz/testsite/node/1?template=4

How do I go about doing this?

You can create custom template suggestions for node using hook_preprocess_node... In your case it should be below code in your theme template.php file... You can read query arguments using $_GET variable..

function YOURTHEME_preprocess_node(&$variables) {
  if ($variables['type'] == "image" && isset($_GET['template'])) {
    $variables['theme_hook_suggestion'] = 'node__image__template' . $_GET['template'];
  }
}

Your template file should be...

node--image--template1.tpl.php

node--image--template2.tpl.php

node--image--template3.tpl.php etc...


Can't override module css for Mega Menu in Zen theme I am a fresh convert to Drupal and still a novice overall. My problem seems simple, but I just can't figure it out.

I installed a Zen theme, then a Mega Menu module. I am in the process of styling the collapsing menu, so I wanted to copy the CSS from the module to my theme CSS file.

First: I copied the tb-megamenu.tpl.php to my theme in order to add the correct glyphicon. That worked just fine.

Second: I copied the default.css from the module to my css folder. It didn't override.

Third: I changed the name of that file to custom-megamenu-default.css (in case there was some conflict with the file being named "default", and tried to register it in the .info file. It still didn't override the css.

What am I missing?

Note: I have cleared the cache at each step, and I (in the very beginning) created a custom.css file that overrides just fine, without registering in the .info file. I believe Zen aggregates all the css files in the css folder automatically.

Edit:  If it helps here is the address of the site I am using to learn Drupal: www.sandbox.thefinanceplanner.com

For something like this, I would suggest you first to unset the css file in the module with hook_css_alter. After that, you can use the css you added in the theme, you don't need two css files with the same info loaded.


SQL error when adding an other database table The Code:

In my module.install i am declaring my main database table. This works without any problems:

function my_module_install() {
  create_initial_roles();
  drupal_set_message("Installed module my_module.");
}

function my_module_schema() {
  $schema['my_module_foo'] = [
    'description' => 'Main table for my_module.',
    'fields' => [
      'id' => [
        'description' => 'The ID of the database entry of foo.',
        'type' => 'serial',
      ],
      // Many more fields ...
    ],
     'primary key' => ['id'],
  ];
  // Second table goes here (see code below).
  return $schema;
}

But as soon as i'm adding a second table, i am getting a SQL error:

// Inserted in shema function (see comment above).
$schema['my_module_bar'] = [
    'description' => 'Secondary table for my_module.',
    'fields' => [
      'id' => [
        'description' => 'The ID of the database entry of bar.',
        'type' => 'serial',
      ],
      // Possibly more fields.
      'primary key' => ['id'],
    ],
  ];

The Error:

The error occurs when installing the module:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DEFAULT NULL ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'Main table fo' at line 3: CREATE TABLE {my_module_bar} ( id INT auto_increment DEFAULT NULL COMMENT 'The ID of the database entry of the bar.', primary key DEFAULT NULL ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'Main table for my_module.'; Array ( ) in db_create_table() (line 2776 of C:\xampp\htdocs\drupal\includes\database\database.inc).

It looks like it is a problem with the character set (utf8) but it is a bit weird, that this error does not occur with only my main database table.

You're including the primary key as a field, which won't work. It needs to be on the same level as fields:

'fields' => [
  'id' => [
    'description' => 'The ID of the database entry of bar.',
    'type' => 'serial',
  ],
],
'primary key' => ['id'],


404 errors for pages other than homepage when uploaded to web-server I and new to php and I got started with drupal and this is my demo site http://sugandha.net63.net/ Yea and it works but when I try to click on any link it throws 404error message. What might be the problem? It works fine in localhost.

My setting is as follows :

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'a2256974_drupal',
      'username' => 'username',
      'password' => 'pwd',
      'host' => 'mysql1.000webhost.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

This is my database setting and

 # $base_url = 'http://www.example.com';  // NO trailing slash!

Do you have an .htaccess file in your root of your installation?

Its one of the most common problems because its a hidden file and people keep missing uploading it to their web server

if you have the .htaccess file then its got to be your base url..change it like Jorge Córdoba said...

Uncomment (remove #) and change example.com...Like this:

# $base_url = 'http://www.example.com';  // NO trailing slash!

to

$base_url = 'http://sugandha.net63.net';  // NO trailing slash!

if it still doesn't work:

try using ?q= before the relative url..eg:

http://sugandha.net63.net/admin to http://sugandha.net63.net/?q=admin

if that works then you have to disable clean urls on the online installation


Disable client- or proxy-side caching on anonymous pages (Cache-Control header), without disabling server-side caching? My CDN seems to cache the /user page, which means I can't access my account page after logging in. I could add it to cacheexclude's uncached list, but that would make PHP run for every bot that hits my server.

What could I do so that Drupal serves the /user page with "Cache-Control: no-cache", or something targeted at proxies (CDN), for anonymous users?

I solved this using context and context_http_headers (7.x-1.x) to add custom Cache-Control: headers on the user page.


How could I use both Rendered Entity and Fields in a view? I like my Rendered entity style, but I want to add in just a couple of extra fields.

Under "Fields", it says

  The selected style or row format does not utilize fields.

Is this possible in any way?

Figured out this IS possible, just have to switch things around.

Format to show Fields rather than Rendered entity. Then you have the option to use the rendered entity as a field. Something like this:

shows up in the Add fields list.


Template Suggestions Causing Undefined Variable I am developing a Drupal theme from scratch, and I have run into some trouble with template suggestions. Using the solutions discussed on Drupal support, I created a template.php file and included this code:

function stronger_preprocess_page(&$vars) {

  if (isset($vars['node'])) {

    $vars['theme_hook_suggestion'] = 'page__'.$vars['node']->type; //
  }
}

This has allowed me to successfully use page--nodetype.tpl.php template files, but I am also randomly seeing errors such as:

  Notice: Undefined variable: node in include() (line 24 of /Applications/MAMP/htdocs/strong-local-final/sites/all/themes/stronger/page.tpl.php).

I have read elsewhere that the node variable needs to be re-declared, but I am unsure of how or where to do this. Any help or references would be greatly appreciated!

hook_preprocess_page() is run for any page, even non-node pages. If you're getting that error it means your trying to access $node in the page.tpl.php file when you're on a non-node page. As no node is available on such a page, the variable won't have been set.

Because of the delay that can happen when messages are set in template files, you might only see this message when you've left a non-node page, and navigated to a node page. So it will look like it's that particular page complaining, when in fact it was the previous one.

You should be able to fix the problem by checking the $node variable is available in your template file as well as in the preprocess function. e.g.

<?php if (isset($node)) : print $node->something; <?php endif; ?>


Add text message under "Add new comment" title I would like to add a disclaimer message under "Add new comment" title and above the form in drupal 8 site. I changed the help text on this path /admin/structure/types/manage/article/fields/node.article.comment but nothing changed.
Any suggestions please?

You can override field--comment.html.twig template.

https://api.drupal.org/api/drupal/core%21modules%21comment%21templates%21field--comment.html.twig/8.8.x

  {% if comments and not label_hidden %}
    {{ title_prefix }}

{{ label }}

    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}

{{ 'Add new comment'|t }}

    // you can add your markup here
    {{ comment_form }}
  {% endif %}

clear the cache after add new template file


Embedding view in form breaks ajax EDIT4: As it turns out, the view was using exposed filters, which causes the view to return html for a form.  HTML isn't allowed to have multiple forms, so the browser might remove the second one, confusingly.  The only solution I could imagine was putting the view somewhere else, or putting it inside of an iframe.

I'm putting an embedded view into an existing form with hook_form_alter, and when I do this, it's causing the Add another item button for one of the form's elements to stop working.  It sends an ajax request and gets a 500 response.  Here's how I'm doing it:

$the_view = \Drupal::service('renderer')->render(views_embed_view('images', 'page_1'));
$form['newthing'] = array(
  '#type' => 'markup',
  '#markup' => $the_view,
);

The interesting thing is, it's not actually the second part that causes it, it's just the render() line that causes the problem.  The rendered view data doesn't actually have to be inserted into the form.

I've tried it with different views, and I legitimately can't figure out the reason why some views break my form's ajax and some don't.  It doesn't seem to be exposed filters, or having "Use ajax" enabled, or having a pager.

Whatever it is, it seems to cause the Form Data to not be sent, when clicking the "Add another item" button.  This information, which would normally be sent on the ajax request:

name[0][value]:
    form_build_id:form-eX_LK4K7R4X0csFlHfJGIZ7auabXu7kVIa1cctPA1iE
    form_token:1tBuaaaRRJ6RHJdTtHwGWpo3gieX4ukYsfkf1QFdeyw
    form_id:my_form
    user_id[0][target_id]:admin (1)
    field_story_reference[0][target_id]:
    field_story_reference[0][_weight]:0

...is missing.

EDIT: I guess I never really phrased it in the form of a question.  How do I get it to not break my Add another item button?  Should this be reported, or is there a known workaround?

EDIT 2: Thank you 4k4, but now something even stranger is happening, now that I'm not doing the render part. When I click the Add another story button, it now disappears and prints the message "An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports. But, obviously I'm not uploading any file. The ajax request is still not sending the form data that was missing when I did it the other way.

EDIT 3: I can see that after I've embedded my view, there is a  tag, which would normally have been at the end of the form, after the save button.  It hasn't been moved, it's just that there's an extra one.  When I embed the view, there are two forms, one inside of the other.  It looks like Chrome's Inspector had removed the second  tag automatically from the html, but left the extra closing  tag.  I can see it when I go to view page source, though.

You can remove the rendering, you don't need it:

$the_view = views_embed_view('images', 'page_1');
$form['newthing'] = $the_view;

In fact, you should not render yourself in D8. And if you have the rare case you need to do this, read this first:

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


How to trace PHP errors I am getting the following errors from Googlebot; I am getting about 5 of them per minute, and I want to find out what is causing them.

  Type php
  Date Friday, February 3, 2012 - 08:16
  User Anonymous (not verified)
  Location http://www.*/biblio?f%5Bkeyword%5D=70&f%5Bag%5D=C&s=...
  Notice: Trying to get property of non-object in eval() (line 3 of /home/sltruweb/public_html/modules/php/php.module(74) : eval()'d code).
  Severity notice
  Hostname 66.249.71.165

Notice: Trying to get property of non-object in eval() (line 3 of /home/sltruweb/public_html/modules/php/php.module(74) : eval()'d code).

If we break this down, we get:

Severity: Notice. From PHP's perspective, not a big deal.
Actual problem: "Trying to get property of non-object". You have something like this: $foo->bar, where $foo is not an object, and as such, ->bar does not apply
line 3 of /home/sltruweb/public_html/modules/php/php.module, where the problem is happening.
eval()'d code: Your actual problem.

PHP Supports something called eval(). Eval() has some, but very few legitimate uses, and in most cases should be spelled "Evil", instead. Unfortunately, it's used liberally in the Drupal world because there's a module in Core that makes it easy to use. To support my argument, "Don't use it", I quote from PHP's own documentation:

  The eval() language construct is very dangerous

Now somewhere in your site, you have an eval(). And that's one of the many issues with it, based upon your error message, I can't tell you any thing more meaningful than that. To track this down better, you need to update your question with a stacktrace. This however, is not necessarily easy to produce, and you may need the help of a skilled developer.


Error in Italian localization for datepicker Well, this is very funny :)

I have a datepicker localized in Italian. It works correctly, except that, apparently, the abbreviation for Wednesday was translated as it were a personal pronoun, since noi is the Italian translation for we.

The abbreviation for Wednesday is correctly set in core/assets/vendor/jquery.ui/ui/i18n/datepicker-it.js, but this file is not inserted in the HTML, so I suppose the translation is taken somewhere else.

In my libraries dependencies I have the following code.

dependencies:
  - core/jquery
  - core/jquery.once
  - core/jquery.ui.datepicker
  - core/drupal.locale.datepicker

Without the last line, the date picker is in English.

Am I doing something wrong?

I think you should download Italian initialisation jQuery UI js file and attached to your concerned page in your module or theme.


Redirecting after submitting content - why this code doesn't work? function MYMODULE_form_alter($form, &$form_state, $form_id) {
    if($form_id == "zdjecie_do_projektu_node_form" ||
       $form_id == "zdjecie_ze_szkolenia_node_form" ||
       $form_id == "referencja_node_form" ||
       $form_id == "zajawka_na_stronie_glownej_node_form" ||
       $form_id == "webform_node_form") {

        $form['actions']['submit']['#submit'][] = 'MYMODULE_node_submit';
    }
}

/**
 * Custom submit function.
 *
 * Redirect user to the site frontpage after node creation.
 */
function MYMODULE_node_submit($form, &$form_state) {
    $form_state['redirect'] = variable_get('site_frontpage', 'node');
}

The source for this solution is here: http://dropbucket.org/node/245

MYMODULE is of course replaced with real module name. The problem is that both functions are reached, however redirection  doesn't happen. Any ideas what am I missing here? Or what could interfere possibly with this code? I have no other custom modules and this is the only custom code. I tried with Overlay and without Overlay with no effect.

If you put a die in your MYMODULE_node_submit does it stop there after the form has been submitted? If it doesn't then your submit handler is not being called and you need to debug why that isn't happening.

I just tried your code on one Drupal site I have with a good 40 or 50 modules and I could not get my additional submit handler to fire. Could not work out why.

I then put the same code on a testbed Drupal site I have with only the core modules installed and it worked straight away.

Once you've made sure that you additional submit handler is being called the you just need to put:

$form_state['redirect'] = '';

to redirect to the front page.


How to reload page after ajax form submit I'm using FAPI #ajax to make the form more user friendly (it reloads in-place on validation). Works like a charm. However I would like to reload the page after form is submitted. How to that?

Obviously if I call for example drupal_goto(current_path()) inside submit handler it won't do anything since this function is called via AJAX call. The actual page that user is on is not reloaded.

Is there some neat Drupal AJAX API trick that will allow whole page reload after AJAX form submit?

For the purpose of the question, an easy-ish way to do a redirect after ajax is with ctools and ctools_ajax_command_redirect

// In your ajax form submit callback
ctools_include('ajax');
ctools_add_js('ajax-responder');
// Path to redirect to
$path = 'node/12';
$commands[] = ctools_ajax_command_redirect($path);
// you can also use ctools_ajax_command_reload() –  xurshid29
print ajax_render($commands);
drupal_exit();

Note, it depends on ctools, which is a popular contrib module.


How to set HTML value for taxonomy description field using entity_metadata_wrapper I've set my taxonomy description field to taking a filtered text value. Using the UI, I can edit a taxonomy term, write some HTML, save, and when I view it I see the HTML rendered by my browser.

However when doing this:

$wrapper = entity_metadata_wrapper('taxonomy_term', 123);
$wrapper->description->set('
My html
');
$wrapper->save();

And viewing the term's page, the description comes out with the html converted to entities, i.e. I see
My html
 instead of a paragraph with My html as its content.

I notice that

$wrapper->description->value(); //
&lt;p&gtp;My html&lt;p&gt;

Whereas if I load a term that I have edited with the UI, saving HTML to the description field,

$wrapper->description->value(); //
Some html

I've looked at $wrapper->description and $wrapper->value()->description and there's no difference between a term with/without the correct/desired behaviour.

Also, I note that with normal fields, when you set a formatted text field you pass/get an array [ 'format' => 'filtered', 'value' => '
the html
' ] whereas here I only ever get a string.

Is this something peculiar to taxonomy terms (and is there a workaround or extra code I need)? Have I misunderstood something?

Thanks.

I just encountered a similar situation myself and it looks like you're choices are either taxonomy_term_save() or to update the table directly via  db_update(). The format property belongs to the term itself, rather than the Description property of the term. If you execute $term->getPropertyInfo() you'll see that the format property is not returned. Keep in mind that the Description is a property of the taxonomy entity, rather than a field, but doesn't seem to be accessible via EMW.

taxonomy_term_save()

taxonomy_term_save((object)array(
  'tid' => $tid,
  'description' => $t($descriptions[$info['step']]),
  'format' => 'full_html',
  'vid' => $vocab->vid,
));


Custom Theme - Add page specific meta tags / title to pages I am new to Drupal, but I am very familiar with WordPress.

In WordPress, I am able to hook into the head of a document with wp_head to add things like page specific meta tags.

When using a custom theme based on Stable, how would you add page specific things in the <head> of a document in Drupal 8?

Note: I am wondering how this would be done without a custom module.

You can attach the tag to the page's render array via hook_page_attachments_alter().

An example from the related change record:

function MYTHEME_page_attachments_alter(array &$page) {
    $viewport = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
            'name' => 'viewport',
            'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
        ),
    );
    $page['#attached']['html_head'][] = [$viewport, 'viewport'];
}


Theming taxonomy nodes? Is it possible to theme a node based on taxonomy the same way you can theme a node based on its content type (something equivalent to node-news.tpl.php for example) or do I need to organize my content by content type to achieve this?

You can add new "template suggestions" using a preprocess function. Here's an article with more details.

Here's another example, but for different templates based on the vocabulary, rather than the term.


Performance implications of many user roles How does each additional user role affect Drupal performance? Looking for insights from benchmarking (preferred) and/or code analysis.

Specifically:

Do additional user roles impact performance on a per page request
basis? (e.g. every page view will be slower for every user, or no?)
Is the performance impact of additional roles proportional to the number of modules installed? (eg performance hit proportional to
#roles * #modules, or no?)

I don't have any hard stats but based on several years of experience and knowing how Drupal works I would be extremely surprised if adding another user role made any appreciable difference at the page request level. The only difference will be when a user has multiple roles, but the amount of extra data required per role is tiny.

I have profiled page loads for all sorts of different site setups and never seen an issue relating to the number of user roles.

Having said that, adding extra roles can make administration more complicated, so you won't want to add new ones without a good reason. If you were to create a hundred user roles the main permissions panel would be unusable but I would be willing to bet that the effect on normal page loads would be negligible.


How to add up price values when group by month? I have a Views table view that shows bank transactions. Each transaction has:

A price field (which consists of a single positive OR negative amount)
A date field

I would like to display the transactions grouped by month and then display a total of all the price fields for each month.

How can I do this?

Steps I have tried

1) Use Views built in tools

In the setting for a table view, you can chose to group entries by a field. So I group my fields by month.

I then go to other > Use Aggregation and set it to “on”.

Finally I select “Sum” in the aggregation options of the price field.

Results:

Entries are grouped by month Months are not in order (It goes March,
January, February, December)
The total of the prices fields for each
month is not displayed.

2) Use Views Calculation module

This requires a patch to support Group fields. Unfortunately, the patch does not work with price fields (see comment #118). My own testing confirms this.

3) Use Views Aggregator Plus

Views Aggregator Plus module is designed to be an alternative to Views Calc.

In Views format, I select a “Table with aggregation options”
I apply the “column function” to my price field and select “sum”
I apply the “group function” to my date field and select “group and compress”.

Results:

Only the first transaction for each month is show (The other
transactions are hidden)
The total is displayed, but it is incorrect
and doesn’t seem to relate to anything.

You can use views date format sql with simple in built views aggregation. No need to use views aggregator plus.


How to re-order a mini-panel in a Panel generated page? I've inherited a site and have been slowly unraveling certain aspects of its construction. Specifically right now, I want to change the order/region a page is loading a mini-panel in a page that I believe is being styled as a Panel due to the css-markup and lack of a template file.

I believe the content type and associated fields and panels were all loaded into the site structure via Features. The general layout of the pieces I want to change right now is like this:

    X

Where X is what I want to move to the div below, or another div below that so that I can display it on mobile devices below the main content. If I go to look at the admin/structure/mini-panels/list/mini_panel_name/edit/layout no matter how I change the location of the content, it doesn't seem to impact its layout in the nesting of the page overall.

There does not appear to be a Panel Page that is content-type/node% for the content type the panel and mini-panels are attached to or a template doc, so I'm not sure where to look to impact this. Neither are there published blocks associated with these.

I'm not very familiar with the Features module, but it's set to prevent rebuild and revert. Could there be something that's interfering with? Could there be something buried in the imported Features module that's controlling this layout outside of normal theming locations? This also all lives in Pantheon.

Okay, so I ended up finding my own answer while working on something else. I realized my scope was wrong, I was looking for an override page referring to a specific page type/section, but what ended up being the case was that there existed an override page for all nodes with unique content/layouts in use for each of them within the same area.

So there was ultimately a Panel Page doing the dirty deed as I had thought, but I was being too specific in where I assumed the changes were made, in part because I assumed an override page would have to maintain the same layout for all pages it overrides, but that's not the case I've learned.