Restrict users to view custom form(s) without complete other formalities I wrote 3 custom forms using hook_menu() for resetting password. All forms have these functionalities.

Form # 1. On submit, sends OTP (code) after entering mobile number and redirect to form # 2

From # 2. On submit, validate OTP and redirect to form # 3

From # 3. The last form where user can enter password and confirm password and submit.

How to restrict user from accessing form#2 without submit form#1?

                        AND

How to restrict user from accessing form#3 without submit form#2?

Check the referring page using $_SERVER['HTTP_REFERER'] if it doesn't match the previous page either throw an error or redirect him to the first page.


Getting the selected option value of a radio button in form_state storage I'm trying to make a step form which redirects to a special form depending on a radio button option chosen by the user.

My form always go to the default option value. I think I'm doing it wrong with the $form_state['storage'] getting the selected option.

function multiform_second_form(&$form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  $options = array(
  '0' => t('Simple'),
  '1' => t('Multiple'),
  '2' => t('Custom'),
);

  $form['qtype'] = array(
  '#type' => 'radios',
  '#title' => t('question'),
  '#options' => $options,
  '#description' => t('Chose a question type.'),
  '#default_value' => $options['0'],
);

  $option_value = $form['qtype']['options'];
  $form_state['storage'] = array(
      'qtype' => $option_value,
    );

  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Next step'),
  );

  $form['#submit'][] = 'multiform_second_form_submit';

  return $form;
}

function multiform_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  if (isset($values['next']) && $values['op'] == $values['next']) {

  switch ($form_state['storage']['qtype']) {
    case 0:
    $form_state['storage']['step'] = 'multiform_qsimple_form';
    break;
    case 1:
    $form_state['storage']['step'] = 'multiform_qmultiple_form';
    break;
    case 2:
    $form_state['storage']['step'] = 'multiform_qcustom_form';
    break;
}

  }
}

If somebody can give me some advices, it would be really great !

Try using a string for the step id, something like this:

function multiform_second_form(&$form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  $options = array(
  'simple' => t('Simple'),
  'multiple' => t('Multiple'),
  'custom' => t('Custom'),
  );

  $form['qtype'] = array(
  '#type' => 'radios',
  '#title' => t('question'),
  '#options' => $options,
  '#description' => t('Chose a question type.'),
  '#default_value' => 'simple',
  );

  $option_value = isset($form_state['values']['qtype']) ? $form_state['values']['qtype'] : 'simple';
  $form_state['storage'] = array(
    'qtype' => $option_value,
  );

  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Next step'),
  );

  $form['#submit'][] = 'multiform_second_form_submit';

  return $form;
}

function multiform_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  if (isset($values['next']) && $values['op'] == $values['next']) {

  switch ($form_state['storage']['qtype']) {
    case 'simple':
    $form_state['storage']['step'] = 'multiform_qsimple_form';
    break;
    case 'multiple':
    $form_state['storage']['step'] = 'multiform_qmultiple_form';
    break;
    case 'custom':
    $form_state['storage']['step'] = 'multiform_qcustom_form';
    break;
  }

  }
}


How to alter incorrect Join type generated by Views? I am suffering from a bug in Views 7.x-3.11 detailed here in relation to filter groups. Views incorrectly adds INNER JOINs when LEFT joins would be correct.

I am trying to alter the $query object using the code ( this approach is not based on any documentation, but simply a guess ):

function mymodule_views_query_alter(&$view, &$query) {
  if($view->name == 'my-view' && $view->current_display == 'my-display') {
    $query->table_queue['field_data_field_listing_type']['join']->type = 'LEFT';
  }
}

However this change causes the View to generate an ajax error "Fatal error: Call to undefined method stdClass::build_join in sites/all/modules/views/plugin/views_plugin_query_default.inc on line 1313".

Any assistance?

Complete operator error.  For the benefit of anyone else who encounters this error check your fieldname.  In my case I had misspelt the fieldname ['field_data_field_listing_type'] so it was generating a new incompleted entry in the table_queue array.


How do I create nodes with comments enabled using drush? I have a drupal 9.1.5 site with a custom node type. I can create test content for it using drush by running;
drush genc 1 --bundles=mynode --authors=test
However, half of the content has comments disabled. I think what is happening is that drush is randomly settings the COMMENT SETTINGS field:

Drush has a --skip-fields parameter, but I don't know what to put in there. I've tried a bunch of different things like field_mynode_comment (the machine name of the field) but none seemed to work. I'm basically guessing.
How can I use drush to create nodes that always allow comments?

This is more of a workaround;
I can coerce all nodes to enable comments by running a query like this:
drush sql-query "UPDATE node__field_mynode_comment SET field_mynode_comment_status = 2"

I had a look at the database and found the node__field_mynode_comment table, which has a field_mynode_comment_status column. I found that the nodes with that column set to 2 had comments enabled, so I ran the above query to set it for all nodes, and now all nodes have comments enabled.
Incidentally I also tried creating the nodes with that field name ignored (--skip-fields=field_mynode_comment_status) but that didn't seem to have any effect.


How do I silence PHP errors? Is there a way to silence all PHP errors, warnings and notices in Drupal?
They are usefull on the devel site but they are a big security risk, and make the site look bad on live.

I know on Drupal 6 the page at admin/settings/error-reporting can stop Drupal from writing errors to the screen, but where can I find this in Drupal 7? It seems it is missing.

The path changes, as in Drupal 7 the same page you would before see at admin/settings/error-reporting is now at admin/config/development/logging.


How to get the content type in the zone/region tpl files? How would I get the node type from within a zone/region or section (using omega theme) template file.  I know how to override templates at the page/node level for specific content types - but I can't seem to find a variable or anything that points to what type of single, node page content type is currently being displayed.

If you are visiting some node then arg(1) call would return node id.

$nid = arg(1);
$node = node_load($nid);
$node->type


Add percentage based fee/tax to specific product types on checkout In Drupal 7 Commerce, I have two product types, a service product and a physical product. I would like a 6% fee added to all physical products only when the user gets to the cart review page. Ultimately it would be a custom line item like a sub-total or tax.

Currently I've been able to add another sales tax to produce this functionality, however the tax is being applied to all products, rather than calculating the 6% on only the physical products. I'm not sure if this can be done with Drupal Rules, or if I'd need to use hooks.

In the interest of anyone else who is looking for an answer to this, here is how I solved adding tax to only specific product types, based on comment #1 here: https://www.drupal.org/node/1251444

Add elements to the rule applying tax to the line item

Entity has field: Parameter: Entity: [commerce-line-item], Field: commerce_product
Data Comparison: Parameter: Data to compare: [commerce-line-item:commerce-product:type], Data value: YourProductType

Add OR/AND for more based on needs.

Hope this helps someone!


How to validate and submit a form using AJAX? I've created a webform using the Form API. I'm using the #AJAX field option to add AJAX validation to each field.

Is it possible to validate and submit the form using AJAX without reloading the page. If validation fails I want to show an error message and if validation is successful then I want to show a message (ideally in a lightbox) and reset the form fields.

My code so far:

$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => '',
    '#maxlength' => '128',
    '#required' => TRUE,
    '#ajax' => array(
        'callback' => '_validate_name',
        'wrapper' => 'name-error-icon-container',
        'method' => 'html',
        'effect' => 'none',
        'progress' => array(
            'message' => NULL,
        ),
    ),
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#ajax' => array(
        'callback' => '_handle_form_submit',
        'effect' => 'fade',
    ),
);

callback functions look like this:

function _validate_name($form, $form_state) {

    if ($form_state['values']['name'] != '') {
    $output = 'OK';
    }
    else {
      $output = 'Enter a value';
    }

   return $output;

}

function _handle_form_submit($form, $form_state) {
}

But I'm not sure what should go in the _handle_form_submit function to validate and then either return a message or submit form and reset fields?

I know this is question has been lying around for a couple of years by now, but I don't feel any of the other answers really get the point of Drupal 7 ajax form submission, so I'll try to explain it.
Since your form should work as well without the ajax as per good practice, your ajax submit handler should do nothing but return the form. Everything else should be in your validation and submit functions.
function ex_form($form, $form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
     '#title' => t('Name'),
     '#default_value' => '',
     '#maxlength' => '128',
     '#required' => TRUE,
  );

  $form['submit'] = array(
   '#type' => 'submit',
   '#value' => 'Submit',
   '#ajax' => array(
     'callback' => 'ex_form_ajax_handler',
     'effect' => 'fade',
   ),
  );
}

function ex_form_submit(&$form, &$form_state) {
  // Submit logic - runs when validation is ok
  // You can alter the form here to be just a markup field if you want.
}

function ex_form_validate(&$form, &$form_state) {
  // Validation logic - invalidate using form_set_error() or form_error()
}

function ex_form_ajax_handler(&$form, &$form_state) {
  return $form;
}


Views of products just showing the first time a taxonomy term is used? OK, so I have my product in Drupal Commerce basically sorted by two major taxonomies - Sport and Product Category.

What I want to do is set up a view that prints out the available product categories for a particular sport (i.e. if a product has a particular sport associated with it, then sort through that list and find what product categories are available for that sport).

I have the view somewhat figured out - but it keeps giving me repeats of the product category, where I only want a particular product category name to show up once.

For instance,  if I search for the sport 'Football'  - I get a list that looks like this:
  - Balls & Tees
  - Shirts
  - Balls & Tees
  - Balls & Tees
  - Pads
  - Shirts
  - Shoes
etc. . .

What I want is for those duplicates to be removed (so Balls & Tees only show up once).

In my current view, I have it set up to return fields of content - with the Taxonomy name of  Product Category as my only field.

I have a conditional filter of the parameter set.

I do have a relationship set of Content: Taxonomy terms on node.

I tried using aggregation DISTINCT option, but that doesn't seem to help.

I have looked through this topic -https://drupal.org/node/1200536#comment-4957410 - but I am not sure if its related or not.

Any ideas?

Did you build your view based on nodes or on taxonomy terms? (https://drupal.org/node/770782)

I think a taxonomy terms based view is the preferred way. Maybe you already did this.

  1) add a new view of view type "term" (not the default "node" option!)
  by ticking the correct option after clicking 'add view'

  2) add the Taxonomy Term to the list of Fields

  3) Add a relationship "Taxonomy: Node" and make it obligatory

  4) In the basic settings enable the 'distinct' option.

  5) Add some filters to narrow the results as needed.

When setting filters you can try to use a contextual filter Term-ID with a default value set from the node page, only from the term list sports. You will also need to set a normal filter with term list product category.


How to get these content types to appear in my view based on role? I have two content types known as Generic Credit and Generic Expense. There are only three roles (Secretary, Admin, and Developer) that can create and view this type of content for administrative purposes. Additionally, these are important for a view that acts as a budget, which gathers several types of financially-related nodes. All of these content types are used for calculating a budget for teams (comprised of a coach and several students). This budget view can be viewed by the students and coaches, and it filters correctly, showing the appropriate budget for a team.

That is, unless it's pulling a Generic Credit or Generic Expense. When a student or coach without the three creating roles views the budget, these two content types don't appear. However, when a coach with the Admin or Secretary roles uses the view, they are able to see the Generic Credit/Expenses.

So far, I've tried using Node View Permissions, but that didn't have any affect on the views. I've also tried allowing students and coaches to create and edit the content types, but that has proved futile.

Am I missing something here with the permissions? What settings might I need to check?

You'll need to add a restrictions in your views. There's an access restriction section there where you can set it by role. Select which roles can view it, then save. That should work. Please refer to the picture attached where to find the permission access. Also, try Content Access module to restrict content type per role.


Set data value of entity reference field with rules Is there a way that you can "Set data value" of an entity reference field using rules. So I would like to set a newly created node's entity reference field to another node's entity reference field.

Thank you in advance!

If you can't work out how to do it with Rules, maybe try a custom module. It's been suggested to me that you could use hook_node_update(), or hook_node_insert() to populate that field.

Check http://drupal.org/node/1388924.


Send Mail to Specific Roles I need to send Emails to site users with specific role like "Administrator".

This is achievable using view on any action like "After saving new content".. etc..

But i want to send emails on one menu click event, I have menu item in Management Menu of Drupal and on click of that i want to send mails to all admin users.

How this is achievable?? Please suggest me guys..

Thanks in advance..!!

With custom module.
See hook_menu()

As page_callback define your "send mail" function for restricted user roles


different colors for different order statuses Is it possible on store/orders page to use different colors for different order statuses?
This feature can be handy. Or doe's someone know how to implement it?
thank you

Here's a possible Drupal-only solution that can get you there. You're going to need access to your theme css file to add a class for each of your order statuses, ex something like this:

.order-status-pending { color: yellow; }
.order-status-closed { color: green; }
.order-status-problem { color: red; }

Now go to views and edit the 'orders' view that is added by Ubercart and then select the field for 'order statuses' from the Fields display section. Next, select 'Style Settings', 'customize field HTML', 'Create a CSS class' and then use the tokens to add your custom class there, ex:

order-status-[status]

You could also rewrite the output of the field using the replacement tokens to something like this:

[status]

This won't work on multiple word order statuses, but you could use jquery instead to do this kind of conditional styling, using their much more powerful selectors.


How can I create a views with right-join relationship? I would like to create a view with a relationship between 2 tables, where the relationship must perform right-join instead of inner join.
How can I do?

I am not sure what you are getting at, but you might need to switch the chain around and start from the rightmost table and left join by not ticking the "this relationship is required".


Drush installation problem I've twice followed these instructions to install Drush 8.
At the end of the process I can run Drush anywhere and it responds as expected.

However, whenever my server connection is broken and I log back into the server, Drush no longer responds.

Can anyone point out why that is happening?

MORE DETIALS:

I honestly don't know what the issue is. I get the following message each time I go through the process of reinstalling Drush:

sisko@localhost:~/bin/drush-master$ drush
No command 'drush' found, did you mean:
 Command 'rush' from package 'rush' (universe)
drush: command not found

I tried another tutorial attempting to install it manually with no success - just the message I pasted above.

I tried running sudo apt-get install drush and it was not found.

If it helps, I am running PHP 7.0.22 on ubuntu 17.04 as shown in the following (and I'm trying to install drush for a Drupal 7 site):

sisko@localhost:~/bin/drush-master$ php -v
PHP 7.0.22-0ubuntu0.17.04.1 (cli) (built: Aug  8 2017 22:03:30) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.22-0ubuntu0.17.04.1, Copyright (c) 1999-2017, by Zend Technologies

The server shell:

sisko@localhost: echo $SHELL
/bin/bash

UPDATE:
I am still experiencing the persistent loss of the Drush command on my server each time the ssh connection drops.
I then have to re-introduce the Drush command by following these steps as detailed by @Sarika:

echo $PATH ---> confirms Drush is **NOT** included in the path
export PATH="$HOME/.composer/vendor/bin:$PATH"
source ~/.bashrc
sudo composer global require drush/drush:8.*

Did you get drush installed on your system? Check it with the following command.

drush --version

If it is a lower version please update drush using composer, if composer already installed skip the step to install composer.

cd ~
curl -sS https://getcomposer.org/installer | php
export PATH="$HOME/.composer/vendor/bin:$PATH"
source ~/.bashrc
composer global require drush/drush:8.*
drush --version


How to change the length of field settings? I have set once to a website a lenght limit to a field. And now the client wants to put more characters to that field.

I cannot change the maximum size from Drupal because I get the following error message:

  There is data for this field in the database. The field settings can no longer be changed.

However there must be a solution. Shall I change it in database (the field is one implemented by the Field-collections module)?

Dylan Tack solution is the easiest, but personally I enjoy exploring the inner wards of Drupal's database to seen how things are managed down there.
So, assuming you have a text field which machine name is field_text of 10 characters you want to grow to 25:

data will be stored in two tables: field_data_field_text and field_revision_field_text
definition is stored in field_config for the storage data, and field_config_instance for each instance of this field (stuff like label).

Now let's do a little heart surgery.

Alter the data tables columns definitions:
ALTER TABLE `field_data_field_text`
CHANGE `field_text_value` `field_text_value` VARCHAR( 25 )
CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;

ALTER TABLE `field_revision_field_text`
CHANGE `field_text_value` `field_text_value` VARCHAR( 25 )
CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;

Change the definition column, this one is very tricky because it's stored in a BLOB, but that's not something that will stop you for doing this.

Dissect the guts of this BLOB thing:

SELECT CAST(`data` AS CHAR(10000) CHARACTER SET utf8)
FROM `field_config` WHERE field_name = 'field_text';

This will give you something like:

a:7:{s:12:"translatable";s:1:"1";s:12:"entity_types";a:0:{}s:8:"settings";a:2:
    {s:10:"max_length";s:2:"10";s:17:"field_permissions";a:5:
    //a lot more stuff...

This is a PHP serialized array, the interesting part is s:10:"max_length";s:2:"10";, this mean this array has a property named max_length (which name is a 10 characters string - hence the "s") which value is 10 (which is a 2 characters long string). It's pretty easy, isn't it?

Changing its value is as easy as replacing the s:2:"10" part by s:2:"25". Be careful: if your new value is longer in character length, you have to adapt the "s" part accordingly. For example putting 100 will be s:3:"100" as 100 length is 3 characters.

Let's put this new value back in the DB, don't forget to keep the whole string.

UPDATE `field_config`
SET data = 'a:7:{...a:2:{s:10:"max_length";s:2:"25";...}'
WHERE `field_name` = 'field_text'

Flush your caches.

???

PROFIT!

By the way, PhpMyAdmin has some setting to allow direct modification of BLOB columns, but why go the easy way?
PS: This can also save your life when putting some PHP code in views and getting a WSOD because of an error in your code.


Migrate commerce products I am looking in to migrating our D7 Commerce site to Drupal 8 (just the product entities). I expect using the migrate module will be our best bet, but I'm not really sure where to start. Has anyone successfully set up a migration for this yet? Do I need a yml file for each field?

A migration has the following required components:

A source plugin, which provides the data to the migration system from D6/7, a CSV file or whatever it is it connects to.
A destination plugin that stores data in Drupal 8.
The migration config entity that connects the two by defining the mapping and any processing/transformation of those properties/values.

The destination plugins are provided for all entity types in a generic way. So you can import data into D8 commerce products. However, what's fairly certainly still missing is source plugin that reads data from a D7 site. You can implement that yourself, it's fairly easy and there are plenty of examples for node, user, .. in core.

The migration entity is then also something that you need to define since that won't exist either. Depending on how different the data is, this is often the complicated part and needs possibly various transformations/process plugins to re-structure the data for D8.

For an example, see the migrations the we are in the process of writing for simplenews.


Impossible to edit nodes, log to in etcetera after enabling Boost and editing .htaccess After installing and enabling Boost in my Drupal 7 site (locally on WAMP and I also tried it on a remote test site) it's not possible to send any forms, e.g. not possible to edit and save nodes, not possible to login etcetera.

The actual Boost caching works though. When I remove the generated htaccess rules from my .htaccess file, everything works as normal again (except that the Boost caching stops to work of course).

My guess is that it's something in the generated htaccess rules that my site does not approve of.

Here is how the added rows look like:

  ### BOOST START ###

  # Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
  RewriteRule .* - [E=boostpath:normal]

#  # Apache 2.4 bug workaround
#  # Enables Search from home page https://drupal.org/node/2078595#comment-8724321
#  RewriteCond %{REQUEST_METHOD} ^(POST)$
#  RewriteCond %{REQUEST_URI} /
#  RewriteRule .* / [S=3]

  # Caching for anonymous users
  # Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
  RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
  RewriteCond %{HTTPS} on [OR]
  RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
  RewriteCond %{ENV:REDIRECT_STATUS} 200
  RewriteRule .* - [S=2]

#  # Apache 2.4 bug workaround
#  # Enables caching of index/ home page
#  RewriteCond %{REQUEST_URI} ^/index\.php$
#  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}/\_%{QUERY_STRING}\.html -s
#  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}/\_%{QUERY_STRING}\.html [L,T=text/html]

  # NORMAL
  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

  ### BOOST END ###

Anyone who can help?

I finally found out that my question had an answer in this thread.

So I went back to Boost version 1.0, generated the htaccess code, pasted it in my .htaccess file and then updated to version 1.1 again (without changing the .htaccess file). Now everything seem to work fine.


Filter for field of current node I want to list (in a views block) only teasers of articles that are younger than the current node.

Somehow I have to use the current node from url->field_date for filtering. Is this possible with views via the UI (Contextual Settings)?

Or do I have to create a module for that? If so... which hook should I use.. how to tell the view to filter?

Don't think its possible with just configuration and/or contrib modules.

I believe you have to override hook_views_query_alter(&$view, &$query) and add  $query->addWhereExpression based on the current nodes date field.

Dig in core/modules/datetime/src/Plugin/views/filter/Date.php function opSimple($field)  and perhaps core/modules/views/src/Plugin/views/filter/Date.php function opSimple($field) to see how they properly use the addWhereExpression


Will Drupal 6 be left in a secure state after it becomes unsupported? I created a custom database interface using Drupal 6 + Views + CCK that works really well for my company and recently I had to migrate it to another server.

I thought "Hey, why not install Drupal 7 and then dump the database in it: then I can upgrade Drupal to the latest version while we migrate!?"

That turned out to be a bad idea. Drupal 7 doesn't seem to have the slightest clue what to do with the DB info I gave it. And the upgrade guide looks very time consuming to me, right now.

So my question is: will Drupal 6 be left in a secure state after it becomes unsupported? Or will the platform become deprecated and vulnerable forcing an even more massive upgrade on me?

Once Drupal 8 comes out, Drupal 6 will be marked "end of life": the Drupal security team will stop working on it and official security releases won't come out for it. If any new vulnerabilities come out, you'll have to patch it yourself. So it's really in your benefit to upgrade at that point.

But upgrade paths for Drupal are from the previous version to the current version: that is, an upgrade path is provided from the last release of Drupal 6 to Drupal 7, and an upgrade path will be provided from Drupal 7 to Drupal 8.

There won't be an upgrade path for Drupal 6 to Drupal 8: if you don't want to rebuild your site from scratch when Drupal 8 comes out, you'll need to first upgrade your Drupal 6 site to Drupal 7, then upgrade to Drupal 8.

So, it really comes down to economics and long term planning. Drupal 6 will be supported until Drupal 8, but when Drupal 8 comes out in a couple of years, will you have an opportunity to rewrite the site? If not, you should plan to upgrade to Drupal 7 at some point in the future.


How to get last list item in Rules? I have a multi-value field. How can I get the value with highest delta value in Rules? The only idea I have is to create a custom component a loop through all list values in it. Then I could use a auxiliary variable and compare each item with it (so that variable will correspond to highest value). This seems to be rather slow. Is there any better solution?

Or add a php script step to your form and simply use the Field API to extract the highest value of the delta as a variable to be used later in Rules execution.


Getting all the nodes NOT tagged with a taxonomy term I am a bit stuck with this... I am not a drupal expert (yet :D) so I really don't know if I am using the best approach...

I have few nodes tagged with some terms from a vocabulary. Let's say my node 1 is tagged with term 1 and node 2 is tagged with terms 2 and 3. My vocabulary has, let's say, 5 terms in total.

Is there a way of getting in a view all the nodes NOT tagged with a particular term? This mean if I had a content node in a view tagged with term1 (node 1 in our example) I could get in another display of that view (or even in another different view) a list of the remaining terms not tagged (2, 3, 4 and 5 in my example).

I know I can make it using "static" filters, but I need to extract the information (terms tagged) from the node itself, which is loaded dynamically using contextual filters.

I am using panels as well but I am not sure wether that details are worth explaining for my porpoise.

I hope my question is clear enough as English is not my mother tongue.

Thanks in advance for your help.

Create a new views page
Select/Add the node related fields that you would like to refer while filtering the nodes.
Add a filter to filter the nodes by content type
Add a filter: Taxonomy term: Term
Select: Expose this filter to visitors, to allow them to change it
Select: 'Expose operators' and 'Reduce duplicates'
Save the filter and view.
Now go run the url of the views page.

You will see the filter at the top of node fields.
1. Select the filter as (Operator: Is none of) and select the term (Term 1) as per your eg.
2. Click apply button
3. You will see all the nodes which are not tagged to Term 1


Drupal does rewrite url but can't load css/themes I have an url rewriting issue with my drupal 7

I'm trying to rewrite for example index.php?q=categorie&categorie=laars to categorie/laars.html

So I downloaded the default drupal 7 .htaccess file from https://code.google.com/p/drupalgooglecode/source/browse/trunk/.htaccess

Then in the section

# Various rewrite rules.
<IfModule mod_rewrite.c>
</IfModule>

I added:

RewriteRule ^categorie/([^/]*)\.html$ index.php?q=categorie&categorie=$1 [L]

Above the default (I also tried below but that didn't rewrite the url):

RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

But it doesn't seem to work. When the rewrite rule is added, my site's layout is all messed up. As if the themes/css is not loaded anymore.
The url does rewrite as I want, but it looks like drupal doesn't know where the theme files are. What may be the cause of this?

Thanks!
Stece

UPDATE: is it possible that url-rewriting of .htaccess conflicts with the drupal clean-url's module? Because theming that doesn't load, feels like something is conflicting. Not sure...

UPDATE2: also tried using a custom module with the hook_url_inbound_alter, but that's not working with me either (https://stackoverflow.com/questions/17176589/drupal-hook-url-inbound-alter-not-altering-my-url). That question is on stackoverflow, for some reason I hoped to get a quicker solution their.

Maybe I am missing something, but you shouldn't need the .htaccess rewrite.

It is likely that the 'conflict' is it rewriting the path to your styles. View the source and check what happens when you try to navigate to your css etc.

To achieve this effect all you should need to do (unless I am missing something) is to enable clean URLs, this will remove the index.php?q=.

Then to add .html go to admin/config/search/path/patterns (with pathauto installed) and add .html after [node:title] or [term:name], whichever you are using.

So your patterns would look like:
[node:title].html
and
[term:name].html


Don't show block until after a number of comments I have created a block and I don't want it to display until there are a number of comments posted on the node because if I just display the block the site will look ugly.

How would I go on to make it that when the node has lets say 6 comments the block or some content will show but when the node has less than 6 comments the block wont show.

If you are making the block using Views, you should be able to do this pretty easily by adding a view filter of "Content: Comment Count" is greater than or equal to "6"

It will then only show the block when it has results that meet your criteria.


Add rules to the email recipients in webforms I am currently working on a Drupal 7 site in which the contact form must email a particular representative based on whether the user belongs to a certain company or is in a certain location. The first check would be based on the company of the user so that if that company has a rep then they would get the email. If not then a country rep would be sent the email. Currently I am using webforms for the contact form.

I was thinking that if it was possible to add rules or conditions to the recipient emails of the webform based on fields in the form, that would be a good place to start. However after looking around and talking to a few people I'm not sure if this option exists at the moment. I would also be open to any suggestions on a different way to achieve this. Thanks to anyone who may have any advice.

What you want to do, certainly cannot be done with just webform.

But you may be able to pull it off when combining Webform with Rules and Webform Rules.

You can add a rule to fire at the event of a webform submission. As condition you will add the nid of the webform so you are sure this specific webform only triggers this workflow. You can also add you own php code as a condition (or no code at all if you are just going to do simple comparisons.). The good thing in this process is that all the submitted data are available through Rules so you can just grab them in your code/conditions to see if the data meet the criteria. If all the conditions are met then you will add an action to send an e-mail to either a specific user or all users of a role.


How can I add the full HTML format, and attach CKEditor to it? I have 2 Drupal sites running on Drupal 7. How can I add the full HTML format, and attach CKEditor to it?

Installation / Configuration

Unzip the module files to the "sites/all/modules" 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/modules/ckeditor/ckeditor" (or "sites/all/libraries/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.
For the Rich Text Editing to work you also need to configure your filters
      for the users that may access Rich Text Editing.
      Either grant those users Full HTML access or use the following tags:

  <map> <area>

          <quote>

 <address>
       <embed> <object> <param>

      To make copying the list easier, below all tags were placed in one line:

  <map> <area>

           <quote>

 <address>   <embed> <object> <param>

      If you are going to use CKEditor with the Filtered HTML input format,
      please refer to the "HTML Filters and Inline Styling" section.
To have better control over line breaks, you may disable the line break converter
      for a given text format in the "Administration panel > Configuration > Content authoring > Text formats" section (recommended).
Modify the ckeditor.config.js file to adjust it to your needs (optional).
      Configuration options are described here:
      http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
      Developer's documentation for CKEditor:
      http://docs.cksource.com/CKEditor_3.x/Developers_Guide
      WARNING: Remember to clear the browser cache after you have modified any of the JavaScript files. If you skip this step, you may notice that the browser is ignoring your changes.


change views global text field conditionally I am trying to either show a text field or hide it depending on the date of another field in a view.
I am trying to use the views_pre_render hook and so far have:

function MODULE_NAME_views_pre_render(&$view) {
if ($view->name == 'user_dashboards' && $view->current_display == 'my_tutorials')
{
    foreach ($view->result as $index => $value)
    {
        $tutorialtime = strtotime($value->field_field_tr_tutorial_start[0]['raw']['value']);
        if($tutorialtime < strtotime('now'))
        {
            $view->field['nothing']->options['alter']['text'] = '';

        }
    }
}

}

So I can successfully test whether to show the field or not, however I can't then change the field.  Using the code above changes every global text field in the view.  Is there a way to target just the row in the comparison?

Ok so credit goes to https://www.webfoobar.com/index.php/node/65 which basically gave me the answer.  The working code is as follows:

function MODULE_NAME_views_pre_render(&$view)
{
    if ($view->name == 'user_dashboards' && $view->current_display == 'my_tutorials')
    {
        foreach ($view->result as $index => $value)
        {
            $tutorialtime = strtotime($value->field_field_tr_tutorial_start[$index]['raw']['value']);
            if($tutorialtime < strtotime('now'))
            {
                $oldtutorials[] = $index;
            }
        }
        $view->style_plugin->render_fields($view->result);
        foreach ($view->style_plugin->rendered_fields as $index => &$rendered_result)
        {
            if(in_array($index, $oldtutorials))
            {
                $rendered_result['nothing'] = '';
            }
        }
    }
}


How do I programatically create a context? I'm using the migrate module to move content into a Drupal site. Some of this content needs to be created as blocks and added to a region using contexts. I have the creation of blocks (actually, boxes) working using a purpose-built module, but I don't know where to begin on the context side of things - looking for something like add_block_to_context() but I cannot find anything. Any ideas?

After checking the code used in the context test units for Drupal 6:

ctools_include('export');
$context = ctools_export_new_object('context');
$context->name = 'testcontext';
$context->conditions = array('path' => array('values' => array('admin')));
$context->reactions = array('debug' => array('debug' => TRUE));
$saved = context_save($context);

You can easily code your reactions or conditions then save the context.

BTW to get all context you can use context_context_list().


How to declare class that extends Drupal d2d Migrate class I am trying to follow the guidance from https://www.drupal.org/node/1819738 "Extending migrate_d2d classes".  I am using the Migrate d2d UI.  It brings back the nodes I want to migrate, but there are a couple of fields I need to add.  Essentially I want to extend the DrupalNode6Migration class to add these fields to the source query used by the UI.

I created this class (which appears to be exactly like the example given in the d2d document above):

<?php
class CadeMigrateFields extends DrupalNode6Migration {

  public function __construct(array $arguments) {
    parent::__construct($arguments);
  }

  protected function query() {
    // Get the default query
    $query = parent::query();

    // Get OG stuff as per: https://www.drupal.org/node/2033293#comment-9371471

    $query->leftJoin('og_ancestry','oga','n.nid = oga.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT og.group_nid)', 'og_group_ref');

    $query->addField('oga', 'group_nid', 'gid');
    $query->addField('oga', 'is_public', 'is_public');

    return $query;
  }
}
?>

This is supposed to include the additinal fields I want in the parent query.  I added the path to this file to my module.info file:

; Migrate from 6.x to 7.x
files[] = cade_fields.migrate.inc

My question is: How do I declare it in the Migrate api so that Migrate sees it and executes it correctly?

If I don't add it anywhere in the api, Migrate doesn't see it. It is ignored and doesn't work.

If I code it as a migration,

   $migrations = array();

   $migrations['CadeFields'] = array(
        'class_name' => 'CadeMigrateFields',
   );

  $api = array(
    'api' => 2,
    'migrations' => $migrations,
   );

  return $api;

I get errors saying that several arguments (source type, description, destination type, etct) are missing.  And it still doesn't work. This missing information should be provided by the arguments passed to the parent query (created by DrupalNode6Migration) by the UI, whose query I am simply trying to extend, not override.

So, how do I declare this type of class so that:

Migrate (d2d) sees it?
Migrate passes the arguments from the parent class (created by UI) it is extending to it?
It extends the parent class query to include the desired fields?

Thanks so much for any assistance!

Change your code like and try

 $migrations['CadeFields'] = array(
  'class_name' => 'CadeMigrateFields',
  'description' => t('Give your description abt this migration'),
  'source_type' => 'GIVE THE DRUPAL 6 NODE TYPE YOU ARE MIGRATING',
  'destination_type' => 'GIVE THE DRUPAL 7 NODE TYPE',
 );


Running cron without setting a cron job on web server I know that in Drupal 7 Poormanscron is part of the core, but to have cron running I need the site must be visited regurarly and it's not my case.
I can't set up a cron job on web server to periodically run cron.

Is there any way to run cron periodically without setting a cron job on web server?

Yes indeed, Drupal exposes a URL to invoke cron, e.g.

http://www.example./com/cron.php?cron_key=ka_88ikb7ZbkszCQo6_GtZclwUsUsskfH54oOJqqBcE

Which you can call from anywhere, using whatever method you like (pingdom jumps to mind, for example). Obviously if your site is an intranet or something you'll need to work out how to route that request either from the internal or external network, but Drupal has you covered however you decide/need to do it.

You can find your external cron URL by visiting the status report at /admin/reports/status.

Note that if you have an advanced cron module like Elysia cron, your external URL may be different. Check the documentation for the specific module to be sure.


Automatically cycle through full-page nodes Looking to implement something that will loop through nodes in the system. I'm not looking for carousel functionality, but instead want to load/display full-page node content, wait, and then load/display the next node.

The end result should be kinda like a TV channel, presenting nodes of various content types on big TVs in the common areas of our building.

I've got some ideas for how to build this, but would like to ask if there is a module that already accomplishes something similar?

I tried to implement this feature and I had almost achieved it. To try-out, click any preview button in this page, you can see the content cycling through nodes.
I suppose you want to cycle through a list of nodes generated by a View.
Procedure:
I used Views navigation module to preserve the list of nodes generated in a View. It also preserves the order of those nodes in cache.
In script:
(function ($) {
  Drupal.behaviors.module = {
    attach: function (context, settings) {

      //Posts the current position of node and Views-navigation cache ID - on clicking 'next' button
      $("body", context).on("click", ".next", function() {
        var pos = $(this).attr('data-pos');
        var cid = $(this).attr('data-cid');
        $.ajax({
          type: 'POST',
          url: '/navigation',
          dataType: 'json',
          data: 'pos='+pos+'&cid='+cid+'&dir='+dir+'',
          success: DoWhateverWithNextNode
        });
      });

    },
  };
})(jQuery);

In module:
//Menu callback for 'navigation'
function get_next_node() {
  if($pos = $_POST['pos']) {
    module_load_include('inc', 'views_navigation', 'views_navigation');

    $result = views_navigation_get_result($_POST['cid']);
    $max_index = count($result) - 1;
    $pos = ($pos > $max_index) ? 0 : (($pos < 0) ? $max_index : $pos);

    if ($nid = $result[$pos]) {
      $next_node = node_load($nid);
      return drupal_json_output($next_node);
    }
  }
}

In DoWhateverWithNextNode(data), you are required to increment 'data-pos' for '.next' element by 1. So that you can cycle through nodes.
P.S. This code may not be a working version. I just provided you an overview of my implementation.


How do you add type-property schemas from Schema.org into 8 sites? Some SEOers have reported good experience with enriching their websites with the formal schema vocabulary Schema.org.

Is there any way to implement such schemas on Drupal 8 webpages?

Update - July 9 2016:

Is it true to say to most of the functionality of this module got into the Drupal 8 core via the module Aggregator 8.x.x ? I read now in the modules' page (for Drupal 7 as linked in the answer) and that's what I understood; But if it did, then when why creating a new module is on the quine? It is written there the module has not yet been ported and that's why I'm confused.

Yes, there's a Drupal 7 module of the same name, schema.org.

  This project is a drop-in solution to enable the collections of
  schemas available at schema.org on your Drupal 7 site. The major
  search engines including Bing, Google and Yahoo! have agreed to
  recognized these in order to improve the display of search results.

Along with the core module, there's a UI that makes it pretty easy to setup; you specify the schema.org type on the content type settings page & then you specify the schema.org property names on the field settings page. It also has support for address field & fivestar fields.

In Drupal 8, the project has deferred to the RDFUI project, to provide the UI component, now that other parts of the module have been ported to core.

  The default RDF mappings of Drupal core have been updated to include
  schema.org in Drupal 8. Also, a lot of the backend code of this module
  was ported into Drupal 8 core. The User Interface allowing to set the
  mappings lives in the RDF UI, which is based on Sachini's Google
  Summer of Code project.


Specifying a confirmation page after you signup using the Signup Module When using the Signup module, the form just reloads itself after every successful signup. Is it possible to redirect them to a different page instead of seeing the same page all over again?

If this is a form then use hook_form_alter to add a submit handler with it and then define $form['redirect']. For illustration see the post


Font Awesome not working when using HTTP We have 2 subdomains for a website in order to test our development before moving to production. This is our structure:

subdomainA.mysite.com
subdomainB.mysite.com
mysite.com

When I enter to subdomainB.mysite using http protocol (http://subdomainB.mysite.com) the font awesome icons are not being displayed. Instead of that in the console shows up this:

  Font from origin http://subdomainB.othersubdomain.mysite.com has been blocked from loading by Cross-Origin Resource Sharing policy: The 'Access-Control-Allow-Origin' header has a value http://someWebService.ws that is not equal to the supplied origin. Origin http://subdomainB.mysite.com is therefore not allowed access.

With respect to "othersubdomain", that corresponds to another subdomain used for other applications and it shouldn't be interfering with subdomainB.

Now, if I enter the site using https (https://subdomainB.mysite.com) the icon fonts are being displayed and nothing goes on the console, which is good.

On the other hand, when I test in our first subdomain (subdomainA.mysite.com) either I am testing with http or https the iconfonts load fine.

We have the module CDN off in subdomainA and on in subdomainB. At first I thought this was the problem but I turned off the module in subdomainB, cleared registry and test for awhile and the problem remained the same.

Lastly, we have the font awesome library inside the core of our drupal installation so we are not calling this library from a remote location.

Not exactly sure if this is the issue, but when I've had CORS errors with web fonts the following Apache directive in .htaccess has worked for allowing any Origin for those files:

<IfModule mod_headers.c>
  <FilesMatch "\.(eot|otf|tt[cf]|woff)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>


How to theme the controls of an Openlayer map? The Openlayers module comes with a default set of maps. It's possible to add layer templates, but it seems that the controls are always the same (see image). The controls exist of images that are located on a CDN such as http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/img/zoom-plus-mini.png

Is there a way to style the controls of Openlayer maps? In other words to apply your own CSS or images to it?

The CSS is mostly contained in the js of the module. You can poke around in the openlayers user lists to maybe find a solution.


how to get all options values of simple hierarchical select in drupal $form? i have writed this code to unset empty terms :

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

  if ($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-projet-immobilier-page-1') {
    foreach ($form['field_r_t_tid']['#options'] as $tid => $term_name) {
      if (is_numeric($tid)) {
        $result_count = db_select('taxonomy_index', 'ti')
        ->fields('ti')
        ->condition('ti.tid', $tid, '=')
        ->execute()
        ->rowCount();

        // Removing the option for tags with no-content
        if (!$result_count) {
          unset($form['field_r_t_tid']['#options'][$tid]);
        }
      }
    }

  }
}

but is not worked, he show me this error : Undefined index : #options ...
how can i resolve this error?

In Drupal 7 you can use field_info_field(), while in Drupal 6 you can use content_field_instance_read(), which is defined in the CCK module.

You can also use list_allowed_values().

$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);


Associating Nodes with Anonymous User I created a new content type which anonymous users are allowed to create. However, they can only do so if they are authenticated into Facebook. What is a good way of associating the particular node with the user? Right now Drupal is assigning a uid of 0 to these anonymous users. Is it possible to overwrite that uid with the id of my Facebook login table? How else can i create a relationship?

The user ID Drupal uses is contained in the uid field of the {users} table. On that table, the user ID for the anonymous users is 0.

You cannot alter the user ID to be a different value, especially if that value is not even contained in the {users} table. If you alter the user ID associated with a node, you are changing the author of that node.

I don't think it is even possible to associate an anonymous user with a Facebook account. What for Drupal is an anonymous user is not really a single user but a multitude of users that access a Drupal site without logging in; also the Google bot is an anonymous user, and associating it with a Facebook account would not make sense.


How can I count a multivalue field's values in twig? I want to count the number of values of unlimited field in twig tempalate I tried

{{ node.field_mytext.count }}  => faced with error

and  in another try

{{ content.field_mytext.count }} => nothing returned

(in this method I checked my field is not in disabled field is display manager).

My question is how can I count the number of items of a field in Twig?

I hope I face with the solutions expect these solutions :D

add it in preprocess_node
use Twig Tweak

{{ node.field_mytext.count }} => faced with error

This does not work, because the method count is not allowed in twig policies:

  core/lib/Drupal/Core/Template/TwigSandboxPolicy.php

{{ content.field_mytext | length }}?

This does not work, because content is a render array with a lot of additional keys.

This works: Convert field to array and count

{{ node.field_mytext.getvalue | length }}


PDF viewer for Drupal I'm searching for a PDF viewer for Drupal 7 which doesn't renders as a Mozilla Firefox PDF or a google's PDF.

Does someone know anything that I could use?

Seems you're looking for the PDF module

Uses HTML5 to display PDF files if users don't have pdf plugin for their browsers.
With this module you can use pdf.js to display PDF file all the time or only use pdf.js when visitors don't have pdf reader plugin.


Per-group/node RSS feed aggregation? I am in the process of building out a community site where each 'network' (like an OG group) can set up it's own RSS feed (simply by pasting the URL into their network node's 'network_feed' field).

I am in the early stages of figuring out how to build and implement a system whereby I can run through all those feeds (for networks that have them) and aggregate them, posting new nodes that contain node references back to the main network for each new item in the feeds.

I have had some limited experience with the Feeds module, and it seems the best candidate for this (Aggregator in D7 core seems a bit less hardy), but I didn't know if there was something I was missing that would make this much easier.

I'm thinking, right now, that I'll build some sort of system that queues up all the URLs contained in 'network_feed' fields, then maybe hook into some of the feeds.module's methods to retrieve and parse the nodes. Instead of doing this manually, does anyone know if there's something prewritten for Feeds, Aggregator, or another solution that does this kind of thing?

I eventually wrote an entire module for this purpose. Basically, I have a 'feed' field for the group-type content type, and my module tracks that field and any changes through core hook_node_update, _delete, _insert, etc. hooks. Then I have a cron-based queue consumer that grabs the 5 feeds that were updated furthest in the past and checks for new content, then posts it into nodes under the feed's group.

I used SimplePie to help with the parsing, because even SimpleXML is somewhat of a pain. Anyways, I might try to make this functionality more formalized and port it to work with something like Organic Groups, but it's really purpose-built. If anyone would like some help doing something similar, give me a shout.


login programmatically not work according to this  I wrote below code to create temp user and login ,
, user create but it not logged in.
where is problem?

   $user_info = array(
  'name' => 'temp-payment-'.rand(1,999),
  'pass' => user_password(),
  'mail' => 'no@no.com',
  'init' => 'temp-user-'.rand(1,999),
  'status' => 1,
  'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),
                    'access' => time(),
                    );
  $user = user_save('',$user_info);

  if($user) {
   $GLOBALS['user'] = $user;
    drupal_save_session(TRUE);
    ym($user);
  }
  drupal_goto('/user');

Solution is

 $form_state['uid'] = $user->uid;
 user_login_submit(array(), $form_state);

and final code :

$user_info = array(
  'name' => 'temp-payment-'.rand(1,999),
  'pass' => user_password(),
  'mail' => 'no@no.com',
  'init' => 'temp-user-'.rand(1,999),
  'status' => 1,
  'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),
                    'access' => time(),
                    );
  $user = user_save('',$user_info);
//drupal_save_session(FALSE);
//$loggedin = user_authenticate($user->name, $user->pass);
//ym($loggedin);
$form_state['uid'] = $user->uid;
 user_login_submit(array(), $form_state);
//drupal_save_session(FALSE);
$GLOBALS['user'] = $user;
drupal_save_session(TRUE);
//drupal_goto('/user');

hope be useful for another users,.

This code generate and login to it programmatically


Unresolved dependency File Entity error I'm trying to run a serious of updates on Drupal.

However, I'm seeing to be running into the following error:

Unresolved dependency   File Entity (Version >7.x-2.0 required)
Media requires this module and version. Currently using File Entity version 2.0-beta2

Where would the directory structure be so I can update the file entity and do the updates.

Modules are typically found in sites/site_name/module. That's often sites/default/modules.

If your site was installed by a non-standard installation profile, they could also be at /profiles/profile_name/modules, or somewhere else under the profile folder, instead.

To find it quickly, run this from your web root:

find . -name file_entity.info


How to hide horizontal tabs on page load? I have installed the field group module for horizontal tabs, so I can put several nodes in a tab via rendered node.

The question is simple:

How can I hide these tabs on page load?
I want to show the links but only when the user clicks on it, the tab shows up.

Thank you for your collaboration.

Gael

Following @Janpan suggestion, I have hidden the tab content and then added a click function, so I have shown the rendered node inside the div.

here the code:

 $("fieldset").hide();
                $(".tab a").click(function(){
                    $("fieldset").slideDown({
                        direction: "up"
                        }, 300);
                });


How do I send out an email every Monday at 8:00am? How do I send out an email every Monday at 8:00am using rules?

For finer grained control over scheduled jobs, you sould have a look at the Elysia cron module. Drupal out of the box is not capable of that degree of scheduling control.


How to set a value using Rules I want to add an additional field on each orders, and that field can be edited. I've installed the Field Collections module. I've added a field in the order settings using the Field Collection field type. Inside that field, I've created a textarea, created by and edited by field. I've used entity reference in created by and edited by to check which user created the field and who edited the field.

How can I set a default value (created by and edited by) when the order has been edited/newly added using rules? or if not possible to do this in rules, is it possible to achieve this in hook_form_alter?

I don't know if it's simpler, it really depends on your set up, but you could look at the Field default token module:

  This module enables to use tokens as field default values.

with this you can assign default values using tokens, such as current user, etc.


Generate PDF with wkhtmltopdf after batch finished I would like to generate a pdf with wkhtmltopdf at the end of my batch.

I integrate the generation in the callback function but it does not offer me the download of the file

This is my finished function:

function csm_generate_pdf_finished($success, $results, $operations) {
  $message = 'some errors';

  if ($success) {
    if (($library = libraries_load('phpwkhtmltopdf')) && !empty($library['loaded'])) {
      $pdf = new WkHtmlToPdf();
      $html = $results['data'];
      $start = $results['start'];
      $end = $results['end'];
      $pdf->addPage( $html );

      $filename = 'document_'.$start.'_'.$end.'.pdf';

      $pdf->send($filename);

      $message = 'Generation PDF ok';
    }
  }
  drupal_set_message($message);
}

The Finish function runs in the background and you can't return file there, the solution for your case is redirected to another page and create and return pdf file there.

something like drupal_goto('your_custom_url_to_generate');


Truly Uninstalling Modules So being relatively new to Drupal development (I have experience programming in other Content Management Systems and writing bespoke functions in PHP/MySQL) I noticed something interesting...

I realised after some development that the custom modules I had installed by uploading to /modules/ should actually have been uploaded in /sites/all/modules/ to avoid being overwritten on a Drupal update.

So I swiftly deleted the modules via FTP, cleared the cache, reuploaded in the correct directory, cleared the cache and continued where I left off.

What I found interesting was that all of the settings I applied to these modules had been remembered.

So my question is, why did this happen?
Do modules have access to the DB and store variables there?

And so, if you want to truly remove a module and all its attachments from Drupal, how do you go about this (If it is just a case of storing in DB, then obviously you could delete through phpMyAdmin...but are there any other things to look for that could be left behind)?

Beginning to develop for drupal, it's good to know what is "under the hood" and that's why I ask this question.

Thanks so much for your time,
Scott

Without disabling/uninstalling the modules, you deleted and placed them in different folder. So here the beauty is Drupal will automatically scan for modules in modules/ and sites/ folder. Thta's why for Drupal the module is still in use.

Disabling a module means, the module is currently not in use, however its data(like DB tables), configuration and everything will kept.

Uninstalling a module means, the module is completely removed. Its data, configuration everything will be cleared.

However the particular module folder will not be deleted.


Field not rewritten even though "Hide rewriting if empty" not selected Simplified situation:

A view includes fields first_name and last_name.
first_name is marked "Exclude from display".
last_name has the label Full name (which becomes the column heading in the view).
last_name has "Rewrite the output of this field" checked and the rewrite text [first_name](space)[last_name].
last_name has neither "Hide if empty" nor "Hide rewriting if empty" checked in "No Results Behavior".
Records with both first_name and last_name or only last_name show properly in the Full name column.
Records with only first_name (i.e. empty last_name) show nothing.

Seems Drupal should rewrite the field for records with no last_name to show first_name since there is a specific "Hide rewriting if empty" checkbox that is not checked. Is this expected behavior? Or might there be a module interfering with things?

Although I don't understand why Drupal doesn't behave as I posit in my original question, I have found a solution. It is to use [first_name] as the No results text. If the last name is empty, the no results text is used, and the first name is displayed. If the last name is non-empty, the rewrite results are used, and the first and last names are displayed. Kind of roundabout, but it works.


Set a datetime field configured as date-only I'm developing a module where I have to set a user profile date_field. I tried several methods to implement this but not one worked for me.
This is the code I am using.
private function updateUser($user_import,$uid = null) {
  if (!$uid) {
    return false;
  }

  $roles = $this->matchRoles($user_import->roles);
  $birthday = $this->birthdayDate($user_import->profile_geburtsdatum);
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

  $user = \Drupal\user\Entity\User::load($uid);
  // $user->setPassword($this->randomPassword());
  $user->setEmail($user_import->mail);
  $user->setUsername($user_import->name);
  $user->enforceIsNew(false);

  // Optional settings
  $user->set("init", $user_import->init);
  $user->set("langcode", $language);
  $user->set("preferred_langcode", $language);
  $user->set("preferred_admin_langcode", $language);

  foreach ($roles as $role) {
    $user->addRole($role);
  }

  $user->set("field_profile_geburtsdatum", array('#default_value' => $birthday));
  $user->activate();
  $user->save();

  drupal_set_message("UPDATE: User " . $user_import->name . ' ( '. $user_import->mail . ')');
}

private function birthdayDate($import_date) {
  $date = null;
  if (!empty($import_date)) {
    $date = strtotime($import_date->day.'.'.$import_date->month.'.'.$import_date->year);
    $date = date('Y-m-d 00:00:00',$date);
    $date = new \Drupal\Core\Datetime\DrupalDateTime($date, 'Europe/Berlin');

    /* $date = array(
         'year' => date('Y',$date),
         'month' => date('m',$date),
         'day' => date('d',$date),
       );
     */
  }

  return $date;
}

Assuming field_profile_geburtsdatum is configured as a singular date-only datetime field, the following are all equivalent in the Field API (in order of my preferred usage):

$user->field_profile_geburtsdatum = '1999-12-31';
$user->field_profile_geburtsdatum->value = '1999-12-31';
$user->field_profile_geburtsdatum->set(0, '1999-12-31');
$user->set('field_profile_geburtsdatum', ['1999-12-31']);

The value you set should be a string in the DATETIME_DATE_STORAGE_FORMAT, which is 'Y-m-d', and not a DrupalDateTime object.  That is used internally by the field type.


Cannot Logon to Drupal ("The website encountered an error while retrieving...") I am trying to get a new Drupal site running on Ubuntu 12.10.  I believe I have what is either an Apache or permissions error.  I can get to the main logon page for the site, but after entering my credentials, I get the following error.

The website encountered an error while retrieving http://localhost/node?destination=node. It may be down for maintenance or configured incorrectly.

I set my permissions using the following script, and my apache setup is below that.  Can anyone tell me where else to look?

!/bin/bash

FILES="/var/www/localdrupal/cms/sites/default/files"
SETTINGS="/var/www/localdrupal/cms/sites/default/settings.php"
SITES="/var/www/localdrupal/cms/sites"
DEFAULT="/var/www/localdrupal/cms/sites/default"
THEMES="/var/www/localdrupal/cms/sites/all/themes"
MODULES="/var/www/localdrupal/cms/sites/all/modules"
DSETTINGS="/var/www/localdrupal/cms/sites/default/default.settings.php"

# Paths for binary files
TAR="/bin/tar"
RM="/bin/rm"
CHOWN="/bin/chown"
FIND="/bin/find"
CHMOD="/bin/chmod"

# Change permissions to be secure

$CHOWN -R www-data:www-data ${SITES}
$CHMOD 775 ${SITES}
$CHMOD 775 ${FILES}
$CHMOD g+w -R ${FILES}
$CHMOD 440 ${SETTINGS}
$CHMOD 440 ${DSETTINGS}
$CHMOD 755 ${DEFAULT}
$CHMOD 755 -R ${THEMES}
$CHMOD 755 -R ${MODULES}

Apache:

    DocumentRoot /var/www/localdrupal/cms
    <Directory />
            Options FollowSymLinks
            AllowOverride  None
    </Directory>

    <Directory /var/www/localdrupal/cms/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

Check your setup.php, probably you should set the baseurl variable there, since your drupal root is not the default /var/www


Create a view of nodes by taxonomy id On my website, the user first fills out a questionnaire. Based on the answers given, I want to generate a view. The answers correspond to taxonomy ids. The problem is that I can't seem to find any option to filter by taxonomy id, which I am passing to my view as an argument.

Is there any way to do this? Preferably through the GUI, but code is no problem.

There was an option in drupal 6 that could do this on a regular page (taxonomy_render_nodes), but this has disappeared in drupal 7, which is why I'm looking to create a view now.

If you want to filter by taxonomy term in your view you can do this by adding a contextual filter (arguments in D6).

If you can pass the term id then you can do the following:

When adding a contextual filter choose "Content:Has taxonomy term ID".
Under "MORE" there is an option "Allow multiple values".

You can play around with these options as I never get it right on the first go.


Webform multistep form previous button asks to fill the required fields I'm working on a D8 project and I have a multistep webform. Everything works fine but when I click the previous button I'm getting errors that the required fields shouldn't be null in order to go to the previous step. Is this a configuration I need to change or is there a way to avoid it?

Thanks in advance.

For exactly this purpose the form has the #limit_validation_errors attribute. It is an array of values that will be validated instead of the whole form.

So to go back this woul mean an empty array since you do not want to valdiate anything.

But a small issue is that with empty array you will not be able to detect the button that submitted the form so you have to always include it in the list. If you have custom button #name use that, if not then use op which is the default.

Also these are the #parents values, not #array_parents so if you have a tree form you have to take that into account. Also using this will not only limit the validation, it will actually strip the submitted values, so if you want to go back but save some information(textfield) from the form, you have to include it as well.

For example:

$form['actions']['back'] = [
  '#type' => 'submit',
  '#value' => $this->t('Back'),
  '#submit' => ['::goBackSubmit'],
  '#limit_validation_errors' => [['op']]
];

or:

$form['actions']['back'] = [
  '#type' => 'submit',
  '#name' => 'go_back_submit',
  '#value' => $this->t('Back'),
  '#submit' => ['::goBackSubmit'],
  '#limit_validation_errors' => [['go_back_submit']]
];

or:

$form['#tree'] = TRUE;
$form['actions']['back'] = [
  '#type' => 'submit',
  '#name' => 'go_back_submit',
  '#value' => $this->t('Back'),
  '#submit' => ['::goBackSubmit'],
  '#limit_validation_errors' => [['actions', 'go_back_submit']]
];


How to add Breadcrumbs in views pages? I have a page which list some products in a particular category and I have passed taxonamy term as contextual filter. Here is an example of my url: www.example.com/prod_category.

I want to show breadcrumb in my page like home > prod_category where prod_category is category of product. I have used Custom Breadcrumbs module but couldn't find a solution.

You can create custom breadcrumb by adding this code :

<?php
global $base_url;
$breadcrumb[] = l('Home', null);
$breadcrumb[] .= l('Product Category', 'prod_category');
$breadcrumb[] .= l(drupal_get_title(), $base_url.$_SERVER['REQUEST_URI']);
drupal_set_breadcrumb($breadcrumb);
?>

Refer to LINK1, LINK2 & LINK3


Sub-theme of a sub-theme If you have a sub-theme of a sub-theme...

Sub-theme a
Sub-theme b (base theme = Sub-theme a)

Ideally, what I want to do is have the default theme as 'Sub theme a' and just introduce some minor theming and processing in 'Sub theme b'. Reason being, there are lots of versions of this site being deployed and some minor fixes are required that can be thrown away at the click of a button i.e. remove Sub-theme b.

Google has not been helpful in this instance ;-)

If both themes are enabled and sub-theme a is the default, how do I get sub-theme b to work? (because its not working i.e. I have added a stylesheet in the .info file and its not being added. If I make sub-theme b default then Sub-theme a doesnt work)

You always start with a base-theme.  Let us call this Theme A.  If you introduce a sub-theme (e.g. Theme B as a sub-theme of Theme A), it inherits everything from Theme A.  You can introduce minor (or major) tweaks in Theme B.

If you set Theme B as the default, then you get Theme A + Theme B.

If you set Theme A as the default, then you get Theme A (with nothing from Theme B).

In other words, if you've set Theme A as the default, then Theme B is not supposed to work.   To get Theme B to "work", you must set Theme B as the default.

This also works if you cascade with more sub-themes.

For instance, if you introduce another sub-theme (e.g. Theme C as a sub-theme of Theme B), it inherits everything from Theme A and Theme B. You can then introduce minor (or major) tweaks in Theme C.

If you set Theme C as the default, then you get Theme A + Theme B  + Theme C.

A theme need to be enabled to be set as default, but works fine as an inherited theme even when it is not enabled.


Is there a compelling reason to track sites.php with version control? I'm wondering if sites.php is a file that should be tracked?  I can see it being useful because domains tend not to change for any given site (not true for development, as I usually run a shortname.local site alias for ease).  But then again, if you're not tracking the actual site folder, then the site folder name could vary from installation to installation potentially, making tracking sites.php potentially a useless cause...

I don't know, I guess I'm looking for guidance here.  Typically I do not track the sites folder because it contains generated site files and sensitive database information, so maybe it doesn't make sense to track sites.php?

Looking for some tips from the seasoned pros out there.

We track it. You can have more than one entry in sites.php that points to the same site, so we have one for the production site and then a few more for development purposes.

The file is not sensitive itself, because if you give someone the ability to read the contents of .php files on your webserver, then you have bigger problems! I'd say try and find reasons NOT to keep it under version control.

I have to say Gisle's suggestion of manually logging changes to files seems to be a bit more effort than I'd normally want to put in, to get round a problem that's not really a problem for me to begin with!


Use email to validate post, not unlike craigslist I'd like for anonymous users to be able to post nodes to my site. By default their post is unpublished, but when they submit it, the site sends an email with a verification URL. When they revisit the site with that URL they can then publish their node.

Call this the 'craigslist model.' :-)

Restating: I want users to be able to publish their own node anonymously, by linking out of an email.

I've been unable to find a module or setting that does this, and I thought I'd ask before diving into code.

Update: Found this unmaintained Drupal 5 project: Anonymous publishing.

Similar question: How can anonymous users be allowed to post while still maintaining content integrity?

You can use the Rules module, but you'll have to write a custom rule to grab the email from the submitted node and send a verification link to the email address. You could also do this with a custom function through hook_entity_insert().

For the verification link you could do use drupal_hmac_base64() to create a url-safe hash of the content of the post or of the node + timestamp + email or something like that.

Then you can create a custom menu to fire a callback function that takes arguments from the verification link to publish the node if the verification link is correct.


Hierarchical Taxonomy list pages I'm developing a site which has 3 levels of taxonomy terms, something like:

Products -> Subcat1 -> Subcat2 -> Item

I've created a view with a page for the taxonomy vocabulary which has a contextual filter configured when a filter value is not in the URL to use the fixed value ''. This page displays the first level of taxonomy terms as expected which is great, however I would like to link the first level to the next level of terms but after 3 days of trying I'm still no closer to figuring it out.

Can anyone shed any light on how this can be achieved? I'm still learning Drupal so it's more than possible I've missed something obvious.

So essentially what I'm after is this:

Top-level page:

Fruits
Nuts
Sweets

Clicking on fruits shows:

Citrus
Non-citrus

Clicking on Citrus shows:

Lemon
Lime

The final page above is a list of actual content items, not taxonomy terms. I hope that makes sense.

So i have similar issue, and i solve this by creating 2 views.
First view show taxonomy terms and i group them by theirs parents (add relationship Taxonomy term: Parent)
Second View is override on taxonomy/term/% and i add more Context (Arguments) for each level add an argument, and finally i add into header another view, who shows only children terms of current term.

You can view my work at http://www.attorney-directory.net/practice-areas


How do I limit the number of rows affected from the query? In my custom module for Drupal 8, I am using the following code.

$query = $this->connection->select('node_field_data', 'nf_data');
$result = $query->execute();

I want to get the first 500 rows. I tried with $query->limit(50), but that gives the following error.

  Call to undefined method Drupal\Core\Database\Driver\mysql\Select::limit()

What is the correct code to get the first 500 rows?

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Select.php/class/Select/8.6.x

$query->range(0, 500);


How to set up an iTunes podcast? This question about podcasting in Drupal 7 recommends the Views RSS iTunes elements module, which hasn't had any commits on the Drupal 8 dev branch since 2014. (tutorial for D7)

The iTunes RSS tag documentation shows that the tags are not very complex, and indeed the iTunes elements module (D7) documentation shows that there are only about a dozen tags that need to be set up for an iTunes-compatible podcast.

So my question is, do any of the additional features of D8 compared to D7 provide a way to configure this with just the modules in core, or am I going to have to code something to generate an RSS feed that meets the iTunes podcasting requirements?

I was hoping to be able to use something like a Views theming template to just rewrite all the tags in the template and publish the feed that way.

Just because there hasn't been a commit for ages doesn't mean it's totally not worth investigating further - as you say the tags are not complicated so probably that hasn't changed.

I had a quick look and the first issue on the issue queue is for the 8 version and it's to do with how libraries are loaded, which I believe did change as 8 moved along. Someone's posted a patch in Dec 16 so not that long ago and it's marked as 'needs review', so best would be to try it out and report back there as to whether that works or not, if so and something else doesn't work then create another issue if you can't fix it yourself, or post another patch if you can.

If you use composer to install Drupal 8, for example using:
https://github.com/drupal-composer/drupal-project

then you can also apply the patch in the patches section of your composer.json by adding the link to the patch so it can find it:
https://www.drupal.org/files/issues/views_rss_itunes-fatal_error_call_to_undefined_function_libraries_load-2839012-3.patch

This is kinda how it works - if you wait it may never arrive, and if you can't do the above it's all googleable skills.


Unwanted / duplicated temporary css files if CSS Optimization is enabled I'm experiencing the duplicate CSS issue mentioned in drupal.org #830382: Unwanted / duplicated temporary css files if CSS Optimization is enabled. In one of my production sites I have about 335 CSS files consuming 3.2M. While this is not a big deal at the moment but certainly not saner to let it grow as such. The site is relatively small and using not more than 10 CSS file. The issue link referred above doesn't seem to have any direction. I would like to hear from the experts here to fix it. Thanks in advance.

I think your problem is about aggregate css files. The issue you give is unrelated. Each page may need a different aggregate CSS file (even in D7, it's much better than it was in D6). It results in hundreds of CSS files as you may state.

Nothing to worry about. Unused file will be deleted automatically. I can't suggest you to use Advagg module because it is only for D6 now, but take a look to have an idea about aggregate files actually work (and how they should work).


Solr Search or Views Exposed Filters I have a food recipes site and it has a search feature on home page.

My Questions are :

Once the user search for some thing, they "continue to narrow down the results" . Is it possible with views exposed filters ? or i should be looking into Solar search for  Faceted navigation and Relevancy tuning .

Another Search Interface .

Assuming that you use proper fields that keep the relevant information (either in nodes or custom entities), it is possible that this can be achieved with Views exposed filters (the slider will require some client-side programming). For more search features, you can also use the Search API without needing to get into the complications of Apache Solr.


Importing data using Feeds into dropdowns/select lists/taxonomy terms I'm importing a set of users into my website using the Feeds module. The users have various details including company name. I wanted to make the company name field on the website a dropdown list rather than a free text field. I was thinking to make the company field a taxonomy vocabulary, and then add a taxonomy term reference field to the user profile. If I did this how would I import the company data for the user profiles using feeds?

For example if Mark Twain works at Penguin how do I import correctly his company into his record?

Would it be possible to create a new field in my CSV file for the company term ID and then import this into the term reference field in the user profile?

I'm using D7 with the custom user fields and not the old D6 user profile module.

Import the same way you would if it was a textfield. The taxonomy terms will be created for you and reused for terms with the same name.


Views disappear upon logout I haven't touched any default permissions for views in my site but they disappear for anonymous and authenticated users. In permissions 'view published content' is enabled for the mentioned roles. I have even tried rebuilding the permissions but no use.

I also checked permissions in views i.e, Access option in Block Settings and tried all combinations of it's options but still no use.

All other contents (shown through print render($page['content'])) are fine and displays upon logout but it's only the views that disppear.

I'm using Drupal 7.

I don't know what seems to be the problem, and what else to try.

I solved the problem by enabling the Disable SQL Rewriting option in Query Settings in my views. This action might have some security implications so lets hope for the best for now.

You can find the discussion here.


How to have a required profile2 on user registrations, but allow admin-created users without a profile? Profile2 allows to give access to a profile based on user role. This works naturally when creating a profile is optional for privileged users with an extra role. How can you achieve what is more or less the reverse? That is,

Visitors can create a user account, and a main profile2 profile must be filled out on the user registration form (it has some required fields)
But, admins should be able to create users without this main profile (e.g. new admin users). This does not seem possible with the usual configuration options...

What is the best way to achieve this?

I'm going to guess the best option is to:

set the profile fields to not required
set the profile to show on the user registration form
then hook into the user registration form via a custom module to set the profile fields you want filled out as required (and admin-created users added via user/add will be able to skip these fields).


How can I implement OAuth based login, just like drupal.stackexchange.com offers? Possible Duplicate:
  What are the differences between the various OpenID widgets available?

I know there is the Janrain Engage module, but I don't want to depend on an external provider. Can I implement it with any Drupal module?

Stack Exchange uses OpenID for single-sign-on, which is not the same as OAuth.  The good news is, OpenID is built-in to Drupal core.  The downside of using the core module is your visitors must know the URL of their OpenID provider.  Most people already have at least one OpenID provider, but don't know it.

To solve this problem, you could try OpenID selector, which offers a login selector similar to SE.


Add additional fields in Drupal 8 node edit form With the functionality of core drupal 8 module I could view, edit nodes. But what I need is that I need to add some extra fields to the node edit  form. Is there any method to do this ? Any help?

You can add fields to nodes both utilizing the UI and programatically.

To do it over the interface, go Structure > Content Types (in the admin menu) - you will see a list of all node types currently available to your site. Find the node type you want to add fields to and hit 'manage fields' (preselected in the dropdown button to the right).

Now you can use 'add field' to add fields of any type you have enabled/downloaded from drupal. (If you don't have a whole lot of field types to select from, check if their modules are enabled under 'Extend'.)


How can I get single keys in multi-item config objects using debug:config? For example, in drush I can run

drush cget search_api.server.iges_solr backend_config.connector_config.port

and get a useful answer.

('search_api.server.iges_solr:backend_config.connector_config.port': 8988)

In Drupal Console, I've tried the same formatting as in the drush command, I've tried a colon between the main config item, and the sub item

(drupal dc search_api.server.iges_solr:backend_config.connector_config.port)

I've tried a fair number of other things, and I've read the docs to no avail.  Is it possible to do without just grepping?

No, Drupal Console doesn't support selecting a key from a configuration object. This is clear from drupal help debug:config which even mention grepping.

Using grep isn't beautiful, but it works:

drupal debug:config system.date | grep -A1 timezone

does return the timezone with the first subkey. (Changing the value after A, you get more lines/the user subkey.)

I would of course prefer to get the configuration object as proper JSON and then pipe it to jq to select a key robustly, but Drupal Console doesn't support an output format option yet - see Github issue.


Image style scale and crop not formatting right I had a scale and crop image style created, but I had to move it to code.  So, to re-create it, my code is:

function mymodule_image_default_styles() {
    $styles = array();

    $styles['mymodule_thumb'] = array(
        'label' => 'MyModule Thumbnail',
        'effects' => array(
            array(
                'name' => 'image_scale_and_crop',
                'data' => array(
                    'width' => 210,
                    'height' => 210

                ),
            )
        ),
        'name' => 'mymodule_thumb',
        'storage' => IMAGE_STORAGE_NORMAL

    );

    return $styles;
}

It's scaling to the 210px width, but it doesn't seem to be cropping right.

Am I missing something?  Before this, I tried separate scale and crop effects, but got the same result.

EDIT: If it matters, I'm calling image_style_url() and passing the style.

In addition to this code. Try using this

function mymodule_image_default_styles() {
  $styles = array();

  $styles['mymodule_thumb'] = array(
    'label' => 'MyModule Thumbnail',
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array(
          'width' => 200,
          'upscale' => 1,
          'height' => 200,
        ),
        'weight' => 0,
      ),
      array(
        'name' => 'image_crop',
        'data' => array(
          'width' => 210,
          'height' => 210
        ),
      )
    ),
    'name' => 'mymodule_thumb',
    'storage' => IMAGE_STORAGE_NORMAL
  );
  return $styles;
}

Hope it works!


Permanent Cookie Contains Sensitive Session Information I have a cookie question in regards to a security scan (via IBM Rational AppScan) conducted on a drupal(7.43) site. The security scan failed with the following error: (Permanent Cookie Contains Sensitive Session Information) is POSITIVE on: http://site-name/user/login?ModPagespeed=noscript (cookie = SESSa020b17496f7fb76f92dd28c8d8341be).

How to resolve this?

Your app scanner is alerting you that cookie session data is being sent over an insecure channel (http://site-name/user/login?ModPagespeed=noscript) and is susceptible session hijacking.

One way to resolve this is to force your website to use HTTPS only, thus preventing anyone from sniffing out session data.


No such file or directory in Drupal\Component\DependencyInjection\PhpArrayContainer->createService() I installed a fresh D8 (Drupal 8.6.15) site on my local dev and I am unable to use drush.

After I installed the site, I also did a composer install. My dev is set up on php 7.1 using AMMPS and drush 8.1.18.

  No such file or directory in
  Drupal\Component\DependencyInjection\PhpArrayContainer->createService()
  (line 79 of
  /Applications/AMPPS/www/commerce/docroot/core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php).

I needed to use drush 9.6 and updated that by composer require drush/drush:"^9.6". Thanks drugan!


Possible conflict with multiple jquery plugins I have a custom module that uses the jCarousel jquery plugin (not the Drupal module). The module code up to this point works correctly, and looks like this (only the main function included for brevity.)

function speaker_carousel_block_view($delta = '') {
 switch($delta){
    case 'speaker_carousel':
      drupal_add_js('sites/all/libraries/jcarousel/lib/jquery.jcarousel.min.js');
      drupal_add_css('sites/all/libraries/jcarousel/skins/speakers/jcarousel-speakers.css');

     drupal_add_js(
       'jQuery.noConflict();
            (function($) {
              $(document).ready(function() {
                 jQuery("#mycarousel").jcarousel({wrap: "circular"});
                });
            })(jQuery);',
       'inline'

     );

        $block_content = "";
        //Use our custom function to retrieve data.
        $result = speaker_carousel_get_data();

        //parse into html
        $block_content .= '
';
        $block_content .= speaker_carousel_create_html($result);
        $block_content .= '
';

        $block['content'] = $block_content;
  }
  return $block;
}

I'm now trying to incorporate a second plugin ([jquery tools tooltip])2 to handle a mouseover popup of some text. This is what the function looks like after additions:

function speaker_carousel_block_view($delta = '') {
 switch($delta){
    case 'speaker_carousel':
      drupal_add_js('sites/all/libraries/jcarousel/lib/jquery.jcarousel.min.js');
      drupal_add_css('sites/all/libraries/jcarousel/skins/speakers/jcarousel-speakers.css');
      drupal_add_js('http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js', 'external');

     drupal_add_js(
       'jQuery.noConflict();
            (function($) {
              $(document).ready(function() {
                 jQuery("#mycarousel").jcarousel({wrap: "circular"});
                 jQuery("#mycarousel img").tooltip();
                });
            })(jQuery);',
       'inline'

     );
        $block_content = "";
        //Use our custom function to retrieve data.
        $result = speaker_carousel_get_data();

        //parse into html
        $block_content .= '
';
        $block_content .= speaker_carousel_create_html($result);
        $block_content .= '
';

        $block['content'] = $block_content;

  }
  return $block;
}

As soon as I add the second drupal_add_js() call in (to the cdn.jquerytools.org site), everything blows up. The carousel no longer displays correctly; it just shows a single item instead of the horizontally scrolling strip of images that was there before. Any idea how I can get the two to play nicely together?

I found the JQuery Multi module, which I really thought would help. I installed and configured, and now the carousel no longer blows up, but I get an error in Firebug console:

  jQuery("#mycarousel a.speaker_trigger").tooltip is not a function
  jQuery("#mycarousel a.speaker_trigger").tooltip();

I know it's not an issue with the two plugins working together, because I copied the rendered source into a static HTML file and put it here. It works fine, but it's only using a single version of jquery.

Do you have any idea?

You can run two separate versions of jQuery, which is what your situation seems to require.

This module offers hope to an easy resolution . https://drupal.org/project/jqmulti

Otherwise this document offers more clarity: https://drupal.org/node/1058168

Generally speaking, you only need a single instance of jQuery installed on the server, which might be called from many different scripts scattered all over the place. However sometimes you'll have a requirement for jQuery more recent than your current stock-Drupal installation. This is when you want to run multiple jQuery versions (because you don't want to simply upgrade your single instance, which would break standard Drupal jQuery stuff like the admin-menu).

(function($){
    // your code here, using jQuery 1.7.1 setup w/ jqmulti module
    alert("jQuery version = " + $().jquery); //proves jquery version being used
})(jq171)


Add font to bootstrap sub-theme I use drupal 8, and Bootstrap theme.

I created a sub-theme.

I would like added one font that I downloaded, to use it in my sub-theme.

I read contradictory things to realize it. For example that it was enough to create a folder "font" in its sub-theme, and add the font in it, then add it in mytheme.libraries.yml, or that it was necessary to place this font in the folder vendor/ . I am a little lost.

How can it be done?

I followed this guide on Google Fonts to get it to work with my downloaded font. In your case that would be editing your info file to declare that you have fonts assets:

name: Subboot
description: Bootstrap Subtheme
type: theme
base theme: bootstrap
core: 8.x
libraries:
  - subboot/fonts

then edit the libraries.yml in your subtheme, ex. subboot.libraries.yml to add in the following:

fonts:
  css:
    theme:
      //your.domain.com/path/to/font {}


Views: one view for multiple pages How do i make a view that:

1)displays all the content tagged with a term in a list?

2)displays all the content tagged with a parent term in that list? (two levels up)

3)displays all the content tagged with a child-term in that list?  (only one level deep)

4)Page title=tag

5)url for that page : http:zee-online.be/tag-name

I tried it, but i couldn't get it to work.... Now i have a view for each term, and when i need to change something, that takes an hour to do it for all the terms.

in hook_preprocess_views_view you need to suggest theme hook for every page, because you want to have one view, so define one views template file. visit this question for more information.


Elysia cron and feeds being stuck - how to resume the imports? I have a bunch of Feeds imports, programmed automatically with Elysia Cron.

There is a problem with the size of the content to be loaded, as the import uses to hang, and always at about the same approx. point in a definite feed. The feed, imported manually, throws no errors and do all its stuff perfectly, only fails in automated cron, getting stuck.

After I unblock the Feed with this

 update feeds_source set state = 'b:0;';
 update feeds_source set fetcher_result='b:0;';

And reset the Elysia table with this

 UPDATE elysia_cron SET running = 0 WHERE name = :name_of_process

sometimes the Elysia Cron starts again, but, to my dismay, no Feed process is launched even if Elysia Cron says otherwise. There is a Running indication, but no feed importation is done, and the progress indicator in the Feed itself indicates that it is not working.

What can I do, someone has the same problems? I have read tons of documentation, but I find no solution, I see terrible stories on the net about updating processes enduring for weeks, shouldn't just 4.000 products (nodes, taxonomies) load in just 5 minutes?

I have discovered that the following lines had been wiped out from the code somehow in my module:

 while (FEEDS_BATCH_COMPLETE != $source->import()){
// nothing
 } // while

This piece of code keeps de feeds working after it finishes. When the resetting is done via phpMyAdmin, the cron itself (called every minute) launches again the tasks. The Elysia task when being called, but the callback did not do anything as the feed had started and the code lacked the while() construction


Primary & secondary links I tried really hard but couldn't figure out what are they (subj). Can anybody explain? I see mentions of them here and there but there just no definitions anywhere available.

Thank you.

Primary & Secondary links are the definition of the  hyperlinks often found in the main menu in Drupal 7

Menu System Documentation


Drupal 7 - Extract posts and user names New at Drupal. Trying to extract from MySql the list of the posts with body and user name. Apparently since Drupal 7, the content is stored in drupal_field_data_body. The problem is that it does not contain any user_id, so I have no clue how to join the two tables.
So far I am here:

SELECT *
FROM drupal_node node, drupal_node_revision revision, drupal_users users
WHERE 1=1 AND revision.vid=node.vid AND revision.nid=node.nid AND users.uid=node.uid

Need to JOIN drupal_field_data_body

Can I ask why you are not using views for this task?

Views 3 for drupal 7 is a powerful interactive SQL builder. And trivial tasks like this are can be easily sold without even knowing SQL or which tables to join on etc.