Programmatically alter custom checkout panes depending on cart quantity In a checkout process, I need to collect additional data depending on the quantity in the cart.

What is it about ?

Customers book travels
For the sake of argument, let’s say 2 couples of lovers book a week in Venice : they will add 4 "Venice trip" to the cart
During checkout, I  collect usual customer data, plus additional information (name, passport, birthday…) for each other participant in a dynamic custom pane.

My current work :

Set up a custom pane with Commerce Fieldgroup Panes, disabled by default
Add a rule with Commerce Rules Extra, which enables the pane if qty > 1 for specific product type
Then with MYMODULE_form_FORM_ID_alter, I tried 2 different ways to add the relevant fields :

First one:  duplicate the whole custom pane into the checkout page :

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

  $order = $form_state['build_info']['args'][0];
  //load line item
  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  //get quantity
  $qty = round($line_item->quantity);

  //duplicate the pane for each participant (minus the customer user)
  for($n=1; $n<$qty; $n++) {
    $form['commerce_fieldgroup_pane__group_pax_sup_'.$n] = array_merge(array(), $form['commerce_fieldgroup_pane__group_pax_sup']);
  }
}

The pane is duplicated fine, but the fields of duplicated panes are not saved, nor displayed at next step. Maybe because I have to tell the system these ARE checkout panes, + subsequent  callbacks (as incheckout_pane_example module) ?

If so, I don't find how to declare the added panes are checkout ones inside that loop.

Second one : duplicate each field of the custom pane inside the checkout pane itself :

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

  $order = $form_state['build_info']['args'][0];
  //load line item
  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  //get quantity
  $qty = round($line_item->quantity);

  //duplicate the pane for each participant (minus the customer user)
  for($n = 1; $n<$qty; $n++) {

    foreach ($form['commerce_fieldgroup_pane__group_pax_sup'] as $key => $value) {

      //searching fields into the fieldgroup array
      if(substr($key, 0, 5) == 'field') {

        //we duplicate the field
        $form['commerce_fieldgroup_pane__group_pax_sup'][$key.'_'.$n] = array_merge(array(), $form['commerce_fieldgroup_pane__group_pax_sup'][$key]);
        //rename field to have it unique
        $form['commerce_fieldgroup_pane__group_pax_sup'][$key.'_'.$n]['und'][0]['#field_name'] = $form['commerce_fieldgroup_pane__group_pax_sup'][$key.'_'.$n]['und'][0]['#field_name'].'_'.$n;
        //add it to the fieldgroup : NOT SURE WHICH IS THE RIGHT ONE OR IF I MUST LEAVE ALL
        $group_pax_sup = $form['commerce_fieldgroup_pane__group_pax_sup']['#groups']['group_pax_sup'];
        $group_pax_sup->children[] = $key.'_'.$n;
        $form['commerce_fieldgroup_pane__group_pax_sup']['#group_children'][$key.'_'.$n] = 'group_pax_sup' ;
      }
    }
  }

This is adding the fields correctly, but again nothing is saved or displayed in next steps. Here it seems that I don't manage to add the fields to the fieldgroup correctly?

How could I achieve this ? Thank you so much!

It occurred to me there may be a nice way to do this with contrib so I'll put it down, but it does require different pieces playing together nicely, which doesn't always happen (:

I see twothree clean approaches.

Using the Field API and contrib

If you want to use the Field API to create/update/delete fields, then I still think you should use custom line item products. I'm a little surprised it doesn't have the option of displaying the form at checkout built-in. Maybe a module will be built to add that, it should be relatively simple. But in the meantime this might get you there with existing contrib:

Install editablefields and Commerce Views Pane.
Create a custom line item type for the customisable product. Add the necessary fields but don't configure them to show up on the add-to-cart form. Also ensure the line items can't be combined.
Create a line item view that accepts an order ID as an argument, and add the fields you'd like to edit (and give them the editable formatter). Add a filter to ensure it only displays line items of the correct bundle. You can test the view in preview by creating a new order with a few customisable products, find the order ID (eg. from the checkout page), and pass that order ID to the Views preview. It should show you a row for each customisable line item. I wouldn't try to get the Views pane working until it works in preview.
Add that view as a checkout pane.
Make a circle of salt around the server and whisper a prayer.

Using the Field API and combined line items (involves code)

If you'd like to have a single line item have multiple customisations, then you need to set up the fields to allow that.

Create a field collection with the fields you'd like.
Add a multi-value field collection of that type to the appropriate line item type (ensure it won't show up on the add-to-cart form).
Create your own checkout pane that displays the field edit form. You'd read the quantity from the line item and display just that many fields (as it's a multi-value field it'll save ok however many there are).

Creating a custom pane and storing data serialised with the order (involves code)

This has the disadvantages that you can't use the Field API to set up, modify, or read the fields (so no Views). checkout_pane_example.module shows how to do this, adding a nickname and second email field and storing the data with the order.

Ugly method

I think you could probably do it with Commerce Fieldgroup Panes if you create a field collection with the fields you want, and then add it as a multi-value field to the order entity. You'd need some code to ensure only the correct number of field collections are shown (to match the number of line items that need customising). This method feels dirty and has two concrete drawbacks I can think of:

As you add more customisable products the order entity will get more and more fields.
You can't associate the customisations with a particular line item (what if I want a want one message on my red sweater, and a different one on my blue sweater - which message goes with which line item?).


Views aren't respecting the ?destination=xxx in the URL Using Drupal 7/Views 3, I created an admin page for a custom content type. When I click on a node edit link on a row, I'm directed to node/33/edit?destination=admin-mycontent ,where I can edit the node.

If I perform an operation like adding a field, the "destination=" in the URL is ignored, and when I save my changes, I'm directed to the node view, instead of back to my admin page.

If I cancel instead of save, I'm directed back to my view.

How can I have the expected redirect when I save the node?

It's not views, is the Drupal core. When creating/saving a node, you are automatically redirected to that node. You could create a module that hooks into node saving form and redirect you to the url destination path.

you should also check the rules modules. It seems that could do the job for you.


Commerce: retrieve coupon code used in order Using the Commerce Coupon module, how can I retrieve any coupon codes used in a particular order, given the order id? It seems that the coupons used are not actually stored in the database (as far as I can see).

If you're using 1.x version, an entity reference field is attached to the commerce order field upon installation (see function commerce_coupon_order_configuration()). This creates the field table commerce_coupon_order_reference.

To check coupons attached to an order, simply access the commerce_coupon_order_reference field, like:

if (!empty($order->commerce_coupon_order_reference)) {
  // Traverse the coupons referenced by this order.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_coupon_order_reference as $coupon_wrapper) {
    dpm($coupon_wrapper->value());
  }
}


Unset fields as required for a Form In my drupal-based project, we make a difference between laptop users and tablet users: Laptop users can skip some fields when registering, whereas tablet users have to fill in all of them. The trick is easily done by hiding or showing those fields from the signup form with jQuery and Modernizr. And I say trick, because it works, despite some of those hidden fields being marked as required, they are still allowed to signup without filling on them.

The problem comes when users forget their password and request a link to create a new one.
When they get to the screen of "Enter new password and confirm it", users who have initially signed up via laptop (i.e., not filling on some of the required fields), cannot continue because they get the error "Fields X and Y cannot be left blank", or sth similar.

I want to disable these 2 fields from being required for Drupal (not from the signup form, where I have already "hidden" them), but I am not sure how to proceed. Where should I do this?

I would suggest, you use hook_form_alter() and then check for laptop users. If laptop users are on form then make #required false for these two fields.

Example:

$form['title']['#required'] = FALSE;

Note: FYI Avoid using unset() in such type of scenario either set the #access property or #required property to FALSE. This keeps them in the form build tree, which avoids problems if other modules try to access or alter that information.


Is there a built-in "None of the above" checkbox option in webform? and how to create one? I may be mistaken but I recall seeing such option in webform somewhere before and I don't seem to find it now (in case I'm right). (please see last edit)
I have several questions with big lists of checkboxes and if there's such option buil-in webform it would be great and better than having to do it via a custom jQuery code.
Thank you
EDIT:
This is a sample question with a
  mywfq:
    '#type': checkboxes
    '#title': 'Please chcek all that applies'
    '#options':
      q1: '....'
      q2: '....'
      q3: '....'
      q4: '.....'
      q5: '.....'
    '#attributes':
      class:
        - mywfq
    '#format_items': ol
  mwwfqnota:
    '#type': checkbox
    '#title': 'None of the above'
    '#attributes':
      class:
        - nota

In the above, I created a separate single checkbox element after the multi one and tried to use jQuery to uncheck all the above if this is checked but it's not working yet.
This is my code:
 $("input.mywfq).change(function() {
 $("input.nota").not(this).prop('checked', false);
  });

$("input.nota).on('change', function() {
$("input.mywfq").not(this).prop('checked', false);
 });

I'm still wondering if no already such built-in option!
EDIT: the great Webform team seems to have added the "none of the above" option to the module (x6 but not sure about prev versions).

This code was fine but wasn't working due to iCheck enabled and then checkboxes "aren't" cleared when the "None of the above" is checked although the counting of checked ones was updating correctly (actually the checked state IS cleared but their iCheck-added class is not and that's why their apparent checked state keeps looking as checked). I'll try find a fix to keep iCheck and make it work with maybe later but for now the following works as expected.

So for anyone that may need this.
Create a single checkbox element after the one with multi checkboxes and call it "None of the above" and give it an element custom css ( I called it 'nota' ) to use in the jQuery code to toggle checked status between the 'nota' and all other checkboxes.

 $("input.mywfq).change(function() {
 $("input.nota").not(this).prop('checked', false);
  });

$("input.nota).on('change', function() {
$("input.mywfq").not(this).prop('checked', false);
 });

IMPORTANT: make sure iCheck is set to "none" for this element in case its enabled for the form by default.


State of form element based on global config I have a form_alter that adds some settings on a content type. How can I make one of these elements hidden (and cleared?) based on the value of a global config (set with variable_get)? I found the states api, but that only manipulates elements based on the values of other elements on the same form. Is there a best practice for what I am trying to do?

You can unset a form element using this code :

var x = variable_get("VariableName");
if(x confirmed some condition)
{
  unset($form[$ELEMENT_YOU_DESIRE_TO_HIDE]);
}


How do I delete an old node when a new node is created? When a user submits a new node, I want the Rules module to look for other nodes with the same email field, then delete the older node and keep the new node.

When a user adds a new node, there is an email field that always stays the same which can be used as field to find nodes.

Is there any way to do this?

with views rules is possible, a bit complicated, make a user view, you will need a contextual filter, "When the filter value is NOT available", "Provide default value", php code, then add something like:

global $user; // gets current logged in user object

 if (isset($user->field_user_address[LANGUAGE_NONE][0]['country'])) {
  $user_country = $user->field_user_address[LANGUAGE_NONE][0]
['country'];
return $user_country;}

instead of using & returning $user_country, use & return your email field, and that view will return only the loggedin user field-email, add a relationship on node author, then add "node title" or whatever form the relationship, then apply a rule on that view and delete (or unplubish) that content. hope it helps.

EDIT: may be is over-coded my solution, just add a user view, contextual filter, loggedin user from URL, apply filters and relationships as needed to only get the node you are looking for, then apply a rule on that view.


Creating REST service to get complex node type I'd like some advice as I don't know if I'm doing this the correct way...

I'd like to create a web service to get a specific node type. I don't need create/update/delete functionality, just being able to retreive the data is enough. It also shouldn't contain any authentication (the data is public).

This node type contains several field collections. Each field collection could occur multiple times in the node. (for example, there's the node type "Car" which contains the field collections "Audi", "BMW", "Skoda". Each of these can occur multiple times in the node).

The JSON I'd like to return should look like this:

{"cars": {
    "title": "newest cars",
    "image": "http://www.example.com/image.jpg",
    "audi": [
       {
        "title": "A1",
        "price": "expensive"
       },
       { "title": "A6",
         "price": "very expensive"
       }
    ],
   "BMW": [
       // multiple BMW's
    ],
}}

It's possible that zero cars of a specific brand are returned.

I've been looking how to do this in Drupal. I don't have much Drupal experience, so I'm sorry if this is a very easy thing.

I'm currently using the services module. I've had a look at this tutorial:
http://pingv.com/blog/an-introduction-drupal-7-restful-services

It looks pretty easy, however, the field collection module adds all fields in a different database table. With all fields I have, I'd have to join more than 20 tables in the query and the Drupal database can get pretty confusing this way.

I'm wondering if there's a much easier way to do this. I've already looked at other modules like "Services Views", but these don't seem to do the things I want:

Return specific node (and specific node id) which contains field
collections
Return image url
Return only the fields I want
Return easy, readable names
Accept certain parameters in the URL (which I'd like to define myself) to filter

Is there an easy way to do this or is the only way creating the very complex query?

Thanks!

Views Datasource is very popular module to return json, xml or any other type of data.

    Views Datasource is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML.

Install the module. Create the view that return your node. then under format select data source as json. You can only select the field you want to render in field settings.


How to tell if content has been migrated I am using drupal2drupal migration. How can I indicate that some content has been migrated as opposed to being manually added.

You could alter the incoming data and attach a taxonomy tag, like 'migrated', to indicate this.

You could also add (migrated) in the title, but you would have to ensure this does not affect users, terms, URL aliases, etc. Hence why I suggest a taxonomy term. I am not that familiar with D2D API but I know this is very easy to do with Migrate Framework.


How to add class in title div for specific block? I have created a block using Views module in website using drupal 7.
My block title's HTML structure is as bellow:

BLOCK_TITLE

I want to add a class in
.
Should I create a module for this or any other way?
Please guide me how can I do this?

Thank you in advance

function themename_preprocess_block(&$variables) {

if($variables['block']->bid == 'views-front-block') {

     $variables['classes_array'][] = 'container';
 }

}

add this function in your template.php file of your theme.


Very slow loading on localhost (via. Uniform Server) I've setup Drupal to run successfully on a Uniform Server installation on my local machine, but it's really slow.  It's taking over 30 seconds to enable/disable modules, and around 3-10 seconds on most other pages.  This is becoming time prohibitive.

Things I've observed/tested:

PhpMyAdmin (running under the same server stack) doesn't seem to take any unnecessary time to load with any operations.
As per this guide, disabling my firewall (while LAN/WAN disabled) has no effect.
Modifying php.ini and my windows hosts file (also by that guide) have no effect.
Firefox settings seem to have no effect (including the one mentioned in that guide).

My next move is simply to try a different server stack, but I'm wonder if I have to.  Advice?

Well, for when I did run Windows last time with a webserver on it, I used Xampp, and it wasn't too slow out of the box. I found I still had to change portions of my.cnf to get it to run at a decent pace.

Several installs and jumps between Linux and Windows has made me realise that most of the Windows stacks I've come across have a lot to be desired performance wise and fiddling with my.cnf yields the best improvement.

Currently I use a 9 year old pc for most dev work, running Ubuntu server. It was painfully slow, but setting up MySQL caching to be a bit more reasonable and installing APC now has it running much, much faster than my quad core (with Xampp, admittedly no apc) at a mere 3 years of age. (The server only has 768mb of RAM).

My suggestion is to dive into my.cnf, though back it up first because if you get it set up wrong it may run much slower.

Alternatively get yourself set up with an Ubuntu server, made my life much easier (Though be prepared to lose several hours, maybe more if you are adverse to using a terminal) The Ubuntu Server guide walks you through pretty much everything you will need to do though.

As a disclaimer I have never used Uniform.

Edit from here on:

Relevant settings I use for my.cnf are:

[myslqd]
key_buffer              = 16M
max_allowed_packet      = 16M
thread_stack            = 192K
thread_cache_size       = 8
# I keep this low to limit max memory usage, with 2 or less people we don't get near this
max_connections         = 50
# table_cache is quite large compared to default because of the massive amount of tables
# Drupal uses.
table_cache             = 512
# Increased for those large queries, though keep an eye on these queries exceeding this
# value on your production server/hosting.
query_cache_limit       = 3M
# Greatly increased due to the large numbers of queries Drupal does.
query_cache_size        = 32M
# Total size of InnoDB's buffer, larger is better, I keep it larger than the DB of the
# of the site I am currently working on.
innodb_buffer_pool_size = 128M
# This stops InnoDB flushing its log at every transaction, instead flushiong it once
# per second. Can be detrimental to the last 1 or 2 seconds of data in case of a crash.
# Imo provides the largest boost on desktops due to their usually limited I/O capacity.
innodb_flush_log_at_trx_commit = 2

I no longer use myisam tables so I haven't played with myisam specific settings in there.

Overall the biggest bottleneck is hard drive access time so I keep as much in memory as possible, my dev server (Which is that ancient desktop box) has PATA drives so even writing to its miserable 8MB cache is slow. If your computer is low on I/O you need more caching, APC also makes a big difference in these cases.

Just keep in mind that you should compare the production environment settings to your dev ones to make sure that you stay within the production environment capabilities, though even on shared hosting with dismal caching and no APC, the presence of RAID usually makes up for it (Granted though that the host we use currently is the fastest one we have used, and some shared hosts are going to be slow no matter what you do.).

Also look at http://www.mysqlperformanceblog.com/ but also maybe avoid it because that is more geared towards dedicated database servers with obese amounts of RAM.


How to add certificate to drupal_http_request()? I am currently setting up a payment method in my Drupal 7 site and following the API documentation for the service I could use this cURL command for testing purposes:

$ curl -s -S -i --cert
./Swish_Merchant_TestCertificate_1231181189.p12:swish --cert-type p12 --
cacert ./Swish_TLS_RootCA.pem --tlsv1.1 --header "Content-Type:
application/json"
https://mss.cpc.getswish.net/swish-cpcapi/api/v1/paymentrequests --data
'{ "payeePaymentReference" : "0123456789", "callbackUrl" :
"https://myfakehost.se/swishcallback.cfm", "payerAlias" : "4671234768",
"payeeAlias" : "1231181189", "amount" : "100", "currency" : "SEK",
"message" : "Kingston USB Flash Drive 8 GB" }'

But since I am developing this function in Drupal 7 I want to use drupal_http_request instead. But I am confused about how to include the certificates used in the cURL command. Anyone?

EDITED:
After the suggestion below I added a context parameter. I still get "connection refused by destination". Is there anything more I should do? This is how my function looks so far:

function create_payment_request(){
  // Send payment request to Swish API
  $headers =  array('Content-Type'=>'application/JSON' );
  $url = "https://mss.cpc.getswish.net/swish-cpcapi/api/v1/paymentrequests";

  $context = stream_context_create([ 'ssl' => [
  'local_cert'        => '/mypathtocertificates/TestCertificate_123456789.pem',
  'passphrase'        => 'pass' ]]);

  $json = '{
  "payeePaymentReference": "0123456789",
  "callbackUrl: "/swish_callback",
  "payerAlias": "4671234768",
  "payeeAlias: "1231181189",
  "amount": "100",
  "currency": "SEK",
  "message": "testo 925"
}
';

  $options=array(
      'headers'=>$headers,
      'context' => $context,
      'method'=>'POST',
      'data'=>$json,
    );

    $result=drupal_http_request($url, $options);
    dpm($result);
}

You need to supply a context parameter in the options for drupal_http_request. The value is a stream context created using the PHP function stream_context_create.

There are a lot of possible parameters so you may have to hunt through the parameter list to find the ones you want.


How add new tab in structure when manage it? I try to do own User Graffic Interface. That interface must help to managers do they are own form displays. By drug`n drop elements in space. Then when they push save. I will save coordinats of elements. I need to show my module in other (new one) tab when manage in structure. I have little exp. working with drupal. But deadline is coming close. I sware i will give this module for avryone. So i need help. (pls. didn't write about Display Suit.)

<?php
/**
 * Implements hook_form_FORM_ID_alter().
 */
function admt_form_node_type_form_alter(&$form, &$form_state) {
  $default_value =TRUE;// auto_nodetitle_get_setting($form['#node_type']->type);

  $type = $form['#node_type'];
  $form['#theme'] = 'admt_form_theme_function';
  $form['admt'] = array(
    '#type' => 'fieldset',
    '#title' => t('Graffic User Interface'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => false,
    '#group' => 'additional_settings',
    //'#theme' => 'admt_form_theme_function',
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
    ),
  );

    if (isset($type) && $type->has_title) {
    $title = $type->title_label;
    }
    $fields = array();
    $arrFieldsType=array(
    "number"=>"textfield",
    "text_textfield"=>"textfield",
    "options_select"=>"select",
    "taxonomy_autocomplete"=>"textfield",
    "text_textarea_with_summary"=>"textare",
    "image_image"=>"file",
    "checkboxes",
    "radios"
    );
  $instances = field_info_instances('node', $type->type);
  $extra_fields = field_info_extra_fields('node', $type->type, 'form');

  // Fields.
  foreach ($instances as $name => $instance) {
    $form['admt'][$name] = array(
    '#type' => $arrFieldsType[$instance["widget"]["type"]],
    '#title' => t($instance["label"]),
    '#default_value' => array('value' => '...'),
    //'#options' => $type2,
     );
        if($arrFieldsType[$instance["widget"]["type"]]!="select") $form['admt'][$name]['#size']= '20';
  }

  // Non-field elements.
  foreach ($extra_fields as $name => $extra_field) {
    if(!empty($extra_field["type"]))
    $typ=$arrFieldsType[$extra_field["type"]];
    else
    $typ="textfield";
    $form['admt'][$name] = array(
    '#type' => $typ,
    '#size' => '20',
    '#title' => t($extra_field["label"]),
    '#default_value' => array('value' => '...'),
    '#description' =>  t($extra_field["description"]),
    //'#options' => $type2,

     );
  }
  return $form;
}
function admt_theme($existing, $type, $theme, $path,$form)
{
  return array(
    'admt_form_theme_function' => array(
      'render element' => 'form',
      'template' => 'admt',
      'form' => $form,
    ),
  );
}

You need to create a menu with type as MENU_LOCAL_TASK. Can refer to menu 'node/%node/edit' in node.module.

Hope it helps


How do I restrict access to the install.php file In my Drupal 8 site, the install.php file is accessible.

How can I restrict the access to that file?

In apache vhost:

RedirectMatch 403     "/(install|update).php"

Or in htaccess change the part on top:

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock)|web\.config)$|cron\.php|install\.php|update\.php|^(CHANGELOG|COPYRIGHT|INSTALL.*|LICENSE|MAINTAINERS|README|UPDATE).txt$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">

Please note this htaccess also protects access to cron.php, update.php, web.config and txt files like /core/CHANGELOG.txt


Media module function overriting, user can see only own media As title says, I need to override few media module functions and add some extra conditions when selecting media. I wanted to create new module that extends media module and overrides those functions but without success.

I wanted to override function

function media_admin_list(&$parent_form)

and to add this line so media module will select media from logged in user

$query = db_select('file_managed', 'f')->extend('PagerDefault')->extend('TableSort');
$query->join('users', 'u', 'f.uid = u.uid');
$query->fields('f', array('fid'));
$query->fields('u', array('uid'));
$query->condition('f.status', FILE_STATUS_PERMANENT);
$query->condition('u.uid', $user_id, "=");
$query->limit($limit);
$query->orderByHeader($header);

As you can see in code above, we have condition for selecting media from specific user.

Please advise how to override this function in my own module.

Thanks.

The best suggestion I can come up with is to use hook_form_alter() to alter the value of $form['admin']['#files'] (inspect the form array on the /admin/content/media page) by calling your own version of media_admin_list() with an altered query.

Something like:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'media_admin') {
        $form['admin']['#files'] = custom_media_admin_list();
    }
}

This is slightly inefficient as the original function has already run but I can't see a way to alter it before the initial form array has been built.


Custom Block Content with HTML and PHP I am having a lot of trouble understanding what is wrong with my code. I am trying to create a custom Facebook block, utilizing the Facebook Graph API. My module works to the extent that I see some posts show but the following is taking place:

1) The posts duplicate. This does not happen when recreating the feed outside of a drupal module.

2) Output of Block content is outside of any region and loads at the top of the page.

Here is the code I am using:

/**
 * Implementation of hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['facebook_block'] = array(
    'info' => t('Facebook Block'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'facebook_block':
      $block['subject'] = '';
      $block['content'] = facebook_main_contents();
      break;
  }
  return $block;
}

function facebook_main_contents(){
require_once('resources/facebook-php-sdk-master/src/facebook.php');

// connect to app
$config = array();
$config['appId'] = 'MYAPPID';
$config['secret'] = 'MYSECRETID';
$config['fileUpload'] = false; // optional

// instantiate
$facebook = new Facebook($config);

// set page id
$pageid = "MYPAGEID";

// now we can access various parts of the graph, starting with the feed
$pagefeed = $facebook->api("/" . $pageid . "/feed");

echo "
";

// set counter to 0, because we only want to display 10 posts
$i = 0;
foreach($pagefeed['data'] as $post) {

    if ($post['type'] == 'link' || $post['type'] == 'photo') {

        // open up an fb-update div
        echo "
";

            // check if post type is a link
            if ($post['type'] == 'link') {
                echo "
" . $post['message'] . "
";
                echo "
";
                echo "

";
                echo "
" . $post['name'] . "
";
                echo "
";
                echo "
Posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "
";
            }

            // check if post type is a photo
            if ($post['type'] == 'photo') {
                echo "
Photo posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "
";
                if (empty($post['story']) === false) {
                    echo "

Story
" . $post['story'] . "
";
                } elseif (empty($post['message']) === false) {
                    echo "

Message
" . $post['message'] . "
";
                }
                echo "
View photo &rarr;
";
            }

        echo "
"; // close fb-update div

        $i++; // add 1 to the counter if our condition for $post['type'] is met
    }

    //  break out of the loop if counter has reached 10
    if ($i == 5) {
        break;
    }
} // end the foreach statement

echo "
";
}

I have tried placing my content code in a separate php file and including it, but that just breaks everything.

The problem is the lack of a return value in facebook_main_contents(); As you can see in the api documentation $block['content'] should contain either a Drupal render array or fully rendered html. facebook_main_contents(); is not actually returning anything but instead echoing output to the page.

You need to collect your rendered html and return it, like so:

$content = "
";
// check if post type is a link
if ($post['type'] == 'link') {
  $content .= "
" . $post['message'] . "
";
  $content .= "
";
  $content .= "

";
  $content .= "
" . $post['name'] . "
";
  $content .= "
";
  $content .= "
Posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "
";
}
...

return $content;


Is there a way to alter a node save confirmation form? I would like to add a confirmation form that is presented to a user on node update/delete operations triggered through the UI.

Specifically, I would like the form to present more than two choices for the user. i.e. instead of Submit/Cancel I would Option A/Option B/Option C.

Is this possible?

Yes. I was writing a huge response before regarding confirm_form in Drupal 7. I recommend you google and look at the examples module for confirm_form usage.

In short you probably want to:

use hook_form_alter to override the #submit or #action (or pre-pend to the list) the form will send to.
then you want to show a new form -- just like confirm_form does and do more logic in your custom confirmation form submit handler.
then redirect wherever using drupal_goto for instance or $form['#redirect'].

This may sound vague -- but the Form API can do all of this. You just have alot of learning to do. I have used confirm_form. I've made workflows for 8 Node forms to wizard through 8 Node add forms; and even made a "login" form fake login people from a login form completely overridden with a dropdown list of students on a Test server (to mock out users) using hook_form_alter().

Drupal can do all of this -- you just have to read the API and look at examples and experiment until you get what you want.


file_entity update means views now checks for public: in their uri? Since a recent update, I think Views must have changed the way it links in relationships to file fields.

Now the SQL includes a WHERE clause like this:

EXISTS (
  SELECT fm_access.fid AS fid
  FROM file_managed fm_access
  WHERE ( (fm_access.uri LIKE 'public%' ESCAPE '\\') ) AND
  (file_managed_field_data_field_file_private.fid = fm_access.fid) )

Now the files that are linked here are actually private, so this clause means my view now returns nothing.

Why is Views adding this bit, and how can I stop it from doing so?

File entity adds a tag to Views' queries called query_file_access.

This checks to see if a user has view private files privilege, and if not it denies access to any private files.

So you can get this view working again by granting this privilege to that user.

I find the privilege confusing because I do not want grant access to all files to this user, and the privilege screen warns that this has security implications.

I believe it's ok as long as the node access checks are done.


Logintoboggan- Providing the one-time login link in an admin view Logintoboggan can be configured so that users are initially assigned an unverified role and only become authenticated users when they click the link in their e-mail for the first time.

However, sometimes users have trouble clicking the link (low technical ability, old cellphones that don't recognize the link, etc.)  For this reason, sometimes the admin needs to activate a user's account on behalf of that user.

I have a view of users with the unverified role and I would like to add the one-time login links to the view so that admins can simply click them.  Logintoboggan provides a token, [user:one-time-login-url], but this token cannot be used in Views.

Is there some way I can show the link in Views?

This is not an ideal way to do this, but since I am using the Panels module to display user profiles, I created a new variant for unverified users and added a piece of custom content on the variant (with a visibility rule restricting it to admin users) that showed the validation token.

Then I added a link on the view to the user profile; this is two steps instead of one, but at least it is a working solution.


db_query for a specific titles I'm building a custom module for webform and I want to get only a title for a specific content type.

In phpMyAdmin with sql query I've managed to sort what titles I need. This is the SQL query:

SELECT title FROM `node` WHERE TYPE = 'outlets' AND uid

How can I wrap this into db_query() ?

You can read more about db_query() here.

$result = db_query("
  SELECT title
  FROM {node} n
  WHERE n.type = :type
    AND n.uid =:uid
", array(':type' => 'outlets', ':uid' => $uid));

foreach ($result as $record) {
  // Perform operations on $record->title, etc. here.
  // in this example the available data would be mapped to object properties:
  // $record->nid, $record->title, $record->created
}


Combination of multiple taxonomies I have these following 4 Taxonomies
1. New Taxonomy
2. Content Category
3. Technology Taxonomy

Applications
Gamification
Architecture
etc. Totally 170 terms

4. Vertical Taxonomy

Automotive
Banking

Have used Taxonomy term views to create listing pages for these. I want to know is it possible for me to dynamically combine multiple taxonomies ( Technology & Vertical) to display content. Eg : example.com/applications/automotive . If yes how can this be done?

Yes, you can do it with Contextual filters in Views. You can Duplicate the Taxonomy term Views and work on it, disable the original for future reference.

You need to add one Contextual filter for each of your Vocabularies. You probably have one field for each of those on your Content type, so add the Taxonomy reference fields as your Contextual filters. The alternative is to use "Has taxonomy term" twice and limit Vocabularies.

You'll need to set up a default value taken from the URL. You can find a lot of tutorials online about the details of setting it up: Add a contextual filter to a view, How to use Contextual Filter in Drupal 8.

The above approach will only work with term IDs example.com/16/35.

To have term names displayed instead of TIDs you need to add a Relationship to the Taxonomy field to your Views, then add Taxonomy term: Name in your Contextual filters and it will use that Relationship in the Taxonomy Contextual filter. Repeat for the other Vocabulary. Also see this answer: How to setup view to filter based on second URL parameter?

That is how you can get example.com/applications/automotive.


How do I produce 2 lists with one display? I'm back on this issue for me because I would to implement Responsive slideshows with thumbnails and many of those use 2  elements to display thumbs and full image.
So I know I need to edit the style output template or the row style output template but I don't know how to find values provided by views to print them inside my template.
This doesn't explain how to find variables.
I'm looking for some example and explanations to understand how to do.

So I get the style output template, and I have done as you said to print fields. I want to modify the field settings in the view.

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>

<?php foreach ($rows as $id => $row): ?>
  <li class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>

      <?php foreach ($rows as $id => $row): ?>

    <?php print ($fields['field_galerie_image_vdl_fid_1']->content); ?>

<?php endforeach; ?>

I can't find the right targeting for my desired field, and in the  I need to exclude some part of the output.

Under Advanced, Theming: Information, click on Information and you will see something like this:

For template file name you want to use the last suggested name, (which I underlined for you) that way it only affects this specific view and not others.

In the above example Row Style Output: you would use views-view--fields-shipping-cart--block.tpl.php

To print your fields, inside the template file you put

<?php print $fields["title"]->content; ?>

<?php print $fields["field_name"]->content; ?>

Title prints your node title, else if you want to print a field, you use field_name

Remember to flush the cache to see changes or you could click the Rescan template files button

If you're unsure of the name of a field, In view's click on your field, and go to re-write the output of the field, click on replacement patterns, whatever name replacement patterns uses is the one you need to use.

Alternatively, instead of working with template files, you could work with just replacement patterns if you like as my answer shows here

Else if you just want to add classes to your fields, you can do it with views like this:


Using views arguments to highlight/alter corresponding entries instead of filtering So, I am making a tree based tab style menu for a section of my site.

There are 3 content types with node references going up the tree. They are ordered: Section < Product < Package.

If I am on a package I want to display 3 tiers of tab at the top of the page, filtered by the section/product the package is in and with the section+product+package that the package is a child of highlighted.

eg: If I am looking at "SECTION1 PRODUCT2 PACKAGE3" it should display the tabs like this:

SECTION1 section2 section3

section1product1 SECTION1PRODUCT2 section1product3

section1product2package1 section1product2package2 SECTION1PRODUCT2PACKAGE3

with the capitalisation representing something akin to the "active"class in css

My URL aliases are formatted: example.com/[sectionname]/[productname]/[packagename]

Edit: Many paths have failed me thus far... Any generic advice welcome...

Ended up just manually making a menu to display the same information... Surely there should be support for one of: node path aliases as arguments OR menu generation from nodereference tree OR menu generation from url aliases (ideally from only selected nodes)
Alas i found none of the above. I feel gross for creating the menu manually but there seemed to be no other way. Thanks for checking this out...


How to add additional display (view mode) for all node types? Firstly, I've seen this question, have followed the steps in the answer by FranCarstens to no vail.

To clarify: I want to add custom views to all content types. (as a side question, would be nice to know how to target a specific node type, if possible).

I've created the modules, enabled it but it doesn't show as an option in any of my content types.

What am I missing?

Thanks!

The programm way from related quedtion should work, but it doesn't, you can try to use the following module: https://www.drupal.org/project/entity_view_mode

  The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities.


How can I get Autocomplete behave as in most of the sites out there? I have a form built with FORM Api. It has a text field, with Autocomplete.
I also have another form, with several fields, some of them with Autocomplete.

It works well, but I have to press Enter Key twice to send the form.

The first Enter key is to select an item.
The second Enter key sends the selected item for process.

The behaviour that I have seen outside, in the wild, and which is customary in thousands of millions of sites is this:

If only one field form (search form, for example), once you click or press enter with the suggested term highlighted, the form will be sent (let's call this behaviour One-Clik). Note: there are no multiple selections option, if not, this behaviour would have to be different.
In several fields form, you just select and press ENTER, and can continue filling other fields. If you want to submit the form, you press the Go button or just click Enter in the autocomplete field if that is the last one you used. This is called Two-Clicks, except that: you can write some words in the autosuggest field, and not choose anything. The desired behaviour would be that just clicking ONCE the Enter key, you would submit the form. So this behaviour is really One-Click, with the only exception that selecting an item by pressing Enter key does not qualify as a click.

In order to have it working, I had to rewrite the autocomplete.js. Is there another solution?

I cannot understand how Drupal cannot manage by default such an easy behaviour, seem in millions of sites. And I can assure that for normal users this is very frustrating and irritating and very counterintuitive.

I think this is a JQuery problem rather than a Drupal problem.

You should be able to add a JavaScript function, something like the following:

$("#searchField").select(function(event, ui) {
    $("#searchField").val(ui.item.label);
    $("#searchForm").submit();
});

It's necessary to assign the value before submitting the form because if the user clicked on a list entry with the mouse, the value won't have been assigned before the select event occurs.

I haven't actually tested this, but hopefully this will send you in the right direction.


How to overriding specific Omega_Kickstart CSS files in a subtheme? I'm using Commerce Kickstart (Version 2).

I created a new theme, which is basically a copy of the commerce_kickstart_theme. So it's a subtheme of omega_kickstart which is, itself, a subtheme of omega v3.

Even though the child theme has various css files for global, narrow, normal, it -looks- as though the theme actually reads in the css from the parent theme... ie. the OMEGA and is ignoring same-named files in my subtheme.

Eg. if I have a file global.css in my subtheme, it is ignored and the omega_kickstart/global.css is used instead.

The same goes for the various alpha files. Eg. I copied alpha-mobile.css into my theme folder. But the file being @imported is the /omega/alpha/css/alpha-mobile.css.

My understanding is that if a same-named css file was in your theme directory it -replaced- the file from the parent. But that doesn't seem to be happening.

Any ideas?

A few things you may want to check (since none of these items are incuded in the question):

make sure you cleared the cache (if not that explains what you experienced).
make sure the file permissions are correct (if not the webserver will not be aware of the newly created subtheme).
make sure you enabled the sub-theme (only creating it is not sufficient).


Register nodes seen in a view as not "new" I have a view of nodes, the only place those nodes will be seen is in the view - never as individual entities. These are short "updates". When someone has seen an update, I no longer want it marked as "new" (as in drupal's 'content: has new content' functionality).

Is it possible to trigger whatever it is that makes entities 'read', but when that node is loaded into to a view on a page the user is viewing?

The New or Updated mark is generated by a simple theme function (theme_mark) which can be overriden. Normally you would do that in your template.php but since this theme function is used in the admin theme, that's not gonna work.

A workaround for this is to add your own theme function to a custom module, like this:

/**
 * Implements hook_mark().
 */
function yourmodule_mark($variables) {
  // Always return an empty string.
  return '';
}

Now, we need to add this function to the theme registry like this:

/**
 * Implements hook_theme_registry_alter().
 */
function yourmodule_theme_registry_alter(&$theme_registry) {
  // Check if the default theme function of mark exists
  // and override it with our own theme function.
  if (isset($theme_registry['mark']['function']) {
    $theme_registry['mark']['function'] = 'yourmodule_mark';
  }
}

Clear your cache and your done.

You'll find the original theme function here in the Drupal docs.

Note that this code will permanently override the output of this function where ever it is used.


How can I use my table for Views 3 sort criteria? I am trying to create a special sort criterium.
I have a table with 2 cols: nid, and count.

How can I use this table to sort the view by count?

You can let Views know about your data using hook_views_data.

The function documentation itself contains all the information you need to use the data for sorting and other Views functions, so I'm not repeating them here.


Organic Group: Can not create group type content? I have Organic Groups installed on my website. I have a content type with OG setting as Group. I had several contents of this type. And then all of a sudden, I started getting the following error when I try to create a content of this type:

Can't save entity as group, because user admin can't be subscribed to group and become a manager.

What may be causing this error?

You should change the number of value for the group_group field to unlimited.
That field must be in the content type which you defined as group.


Secondary Tabs and views I am trying to get Secondary Tabs to work. I want to create a local tab with sub tabs.

View | Edit | Reg Report

Reg Report
       Reg Report | Pre-Registration | Post-Registartion (Secondary Tabs)

I tried this method (Menu secondary tabs) and have it showing the naviagation, however when I add the path for Photo to my second view the navigation goes away.

Here is the code:

/**
 * Implements hook_menu().
 */
function secondary_tabs_menu() {
  $items['node/%node/update'] = array(
   'title' => 'Update',
   'page callback' => 'price_callback_function',
   'access arguments' => array('access args'),
   'type' => MENU_LOCAL_TASK // This adds the 'Update' tab to the node path
 );

 $items['node/%node/update/price'] = array(
   'title' => 'Price',
   'type' => MENU_DEFAULT_LOCAL_TASK,
   'weight' => -10
 );

 $items['node/%node/update/photo'] = array(
   'title' => 'Photo',
   'page callback' => 'callback_function',
   'access arguments' => array('access args'),
   'access callback' => TRUE,
   'type' => MENU_LOCAL_TASK // This adds another tab under 'Update'
 );
  return $items;
}

/**
 * Implements hook_admin_paths().
 *
 * Show admin theme on the participants totals report.
 */
function secondary_tabs_admin_paths() {
  return array(
    'node/*/update' => TRUE,
  );
}

My goal is to create a sub-section where I can click through a few views within this secondary tab area.

Also, I was trying to add the Admin theme to the views as well.I have it in code but it doesn't seem to work.

Can someone guide me towards what I might be missing. Thanks!

So, Basically I was trying to piece together a few views under one local task tab for a content admin. I finally figure out how to write a small module to create the structure and used views path and menu to point to the sub task items. See below.

/**
 * Implements hook_menu().
 */
function secondary_tabs_menu() {
  $items['node/%node/update'] = array(
   'title' => 'Update',
   'page callback' => 'price_callback_function',
   #'access arguments' => array(2),
   'type' => MENU_LOCAL_TASK // This adds the 'Update' tab to the node path
 );

 $items['node/%node/update/price'] = array(
   'title' => 'Price',
   'type' => MENU_DEFAULT_LOCAL_TASK,
   'weight' => -10
 );

 $items['node/%node/update/test'] = array(
   'title' => 'Test',
   'page callback' => 'callback_function',
   #'access arguments' => array(2),
   'access callback' => TRUE,
   'type' => MENU_LOCAL_TASK // This adds another tab under 'Update'
 );
 $items['node/%node/update/test/test1'] = array(
   'title' => 'Test1',
   'page callback' => 'callback_function',
   #'access arguments' => array(2),
   'access callback' => TRUE,
   'type' => MENU_LOCAL_TASK // This adds another tab under 'Update'
 );
 $items['node/%node/update/test/test2'] = array(
   'title' => 'Test2',
   'page callback' => 'callback_function',
   #'access arguments' => array(2),
   'access callback' => TRUE,
   'type' => MENU_LOCAL_TASK // This adds another tab under 'Update'
 );

  return $items;
}

/**
 * Implements hook_admin_paths().
 *
 * Show admin theme on the participants totals report.
 */
function secondary_tabs_admin_paths() {
  return array(
    'node/*/update' => TRUE,
    'node/*/update/test' => TRUE,
    'node/*/update/test/test1' => TRUE,
    'node/*/update/test/test2' => TRUE,
  );
}

I also found out the best way to make those views show up within the admin theme. See hook_admin_path().


Views Accordion to be accessible by keyboard I need the Views Accordion module in Drupal 7 and what is in it to be accessible by the keyboard. When you are tabbing, it skips it completely. Also the screen reader does not recognize the closed items.

Anything I can modify to achieve this?

iput this in a block

<script type="text/javascript">
(function ($) {
  $(document).ready(function(){
$('a')

 .each(function(){ // loop through all matched elements

  $(this).removeAttr("tabindex");

});

});

})(jQuery);
</script>


remove drupal admin menu from actual site i'm using drupal 7 and i want to hide the admin toolbar from the normal sites. but in the configuration i can only find the option to disable the toolbar completely. what i want is that it is only visible on "mysite.com/admin/" and removed from the actual website.

i found some drupal modules with which you can collapse the toolbar or hide it by pressing the UP key but what i want the complete admin toolbar markup gone on my actual site.

i'm removing all the drupal system css and js anyway (using the template.php file) so even if i wanted the admin toolbar on my sites it would look messed up because of the missing styles and scripts.

any ideas?

You can remove the toolbar from the "normal" part of you're site by unsetting its entry in the $page array using hook_page_alter. You can do this in either a module or a theme.

function mymodule_page_alter(&$page) {
  unset($page['page_top']['toolbar']);
}


Module installation via web browser I've a question regarding the installation of modules via the web browser. At the moment, I can easily upload both themes and modules to my Drupal site via sftp, but when I attempt to do the same using the module 'Update Manager' (i.e., through the web server itself, to avoid the hassle of adding the theme/module manually) I get an error that reads "Your server does not support installing modules and themes from this interface..." How does one enable the fix? I've read through some documentation regarding module installation but the comments seem contradictory, with some users suggesting a chown prompt and others saying such a solution is a breach of site security and thus to be avoided. Is there any consensus on what to do in this situation? Any help would be appreciated.

You need to install the php5-ftp package and reload your webserver to load this extension.


Check if current node meets conditions, then alter a block's contents? In Drupal 7, how would I check whether the current node being viewed meets certain conditions, and then based on that check alter a block's contents?

To give a specific example, I want to check if the current node on my site is a blog post (like http://www.givingwhatwecan.org/blog/2012-10-04/giving-to-charity-%E2%80%93-a-pain-in-the-eye - the conditions here are being tagged with the 'Blog' taxonomy term, or being of type 'story'). If it is, I want to add the class 'active-trail' to the 'Blog' heading in the menu block atop the page.

If need be, I'm happy to use jQuery, though I'd be interested to know the general 'Drupal way' of doing this.

You can check the content type of current node via preprocessing functions in your theme, but there might be another (simpler) way to do what you want: Drupal adds various information about the current page in the body classes, so you have more options for theming.

To select a specific menu link on all nodes of blog content type you can use the following CSS class: body.node-type-blog and a unique menu link ID (#menu-1000-1).

Add that line to the place where you define the active state of menu items. In your case this will be (in your superfish CSS file):

body.node-type-blog #menu-1000-1 a,
a.sf-depth-1.active, .active-trail a.sf-depth-1 {

Another quick solution would be using jQuery:

if ($("body").hasClass("node-type-blog")) {
  $("#menu-1000-1").addClass("active-trail");
}

Check also Context module for more complex use cases where you need to define a section on your website and apply certain theming/functional changes.


How do I add a custom field to the image field widget in Drupal 7? I need to add a custom field (a simple text field) to the image_field widget in Drupal 7.

The structure is a standard node (called Article) which has zero or more images (related photos or graphics) attached via the image_field widget. The field I want to add is the source of the image, and is used later to figure out when it needs to be deleted.

I've tried the code from this post, but couldn't get it to work.

Attaching metadata to images and other media, is precisely the reason that prompted the creation of the media module. We use the unfortunately "unstable" version ourselves, with good results. Using Media, your images becomes entities, allowing you to attach any field you want to them through the normal means.
While the solution to manipulate the existing widget is fully valid, it will require quite a bit of understanding of the Field API, and I believe any such solution would get rather messy.


Control where a new field is stored in the database D7 I am interested in adding a field to the 'Product' content type in Ubercart 3 / Drupal 7.  I have read up on topics like field_create_field() and db_add_field() but I want my field to be stored as an additional column in the uc_products table in my database.  In addition, I want my new field (qid) to be called whenever I call up the $node value.  How would I go about doing this?

This is no longer done in D7.
You will want to use a proper field (which is stored in its own table and has many benefits over a simple column).


Display submitted data using a select field option - webform module I'm new to Drupal. I have a form that I created using Webform Module, is there a way to pull data submitted by Webform and group it by a column. To display result in a view

Hi this topic should help you out. https://drupal.org/node/1658784 I used it when i needed to achieve the same thing.


Deploying block settings as an update script? I need to add a block to an existing Drupal site and would like to if possible automate the process using hook_update_N or something similar.

Specifically I'm referring to the position and region of the block relative to adjacent and following blocks. Is there a Drupal standard method to this process or do I simply need to use SQL to achieve this.

Is there a way to force a block in between others with some trick with the weights, or will I need to actively increment the weight of blocks below this in the same region?

Thanks for any advice!

You could do this if you like, but this is an unstable and hacky way of fixing your problem. The thing is that blocks can be rearranged at any time so using an update function to sort the block weights is not the best way to deal with this.

What you could do instead is to use the context module to deal with blocks. If offers a better interface to control blocks and allow you to display the same block in different regions. It also gives you a more advanced control of when blocks should be displayed, like display on all nodes of type x, or on these views etc.

In addition to all the nice features described above, contexts can be exported as features. This mean that you can with a click of a button create a module that have your block setup stored in code, including weights etc. If those blocks were to be rearranged, you could revert the feature back to the old state.


Only show content in a View if the content has a checked field On my content type, I have a boolean field which consists of a single on/off checkbox.

I have created a view, which shows all the nodes of that content type. However, I only want the view to show nodes where the boolean field has been ticked. How can I do this?

I thought in Views I could use "Filter criteria > Content: [Name of Field]."
However, when I select this, the only option available is "Select All". If I select this, I get the following error message:

  No valid values found on filter: Content: Show on Main Navigation.

What am I doing wrong?

I tried on my test site, and it happened to me too, for the simple fact I didn't enter any value for On value, and Off value. Once I entered Show the node in the view, and Don't show the node in the view, for those fields, the filtered criteria showed those values in Options.

If you don't enter any value for On value, and Off value, the Options fields really shows three entries, but the other two are empty strings. They are there, but you cannot see them, and you don't know which value comes first. Is the first row for On value, or Off value?


Specific field tag based naming conventions (overriding views-view-field.html.twig for specific fields) I've scoured the documentation and I simply cannot find an answer to this question regarding naming convention for twig files given a tagged view with the override of a specific field.
Let me create a scenario to explain the problem.

Given Viewname with tag viewtag with a block display and a fieldname field.

I can override the theme as follows

Original file --> Overridden file name

views-view-unformatted.html.twig --> views-view-unformatted--viewtag.html.twig
views-view-field.html.twig --> views-view-field--fieldname.html.twig
views-view-field.html.twig --> views-view-field--viewname--block--fieldname.html.twig
views-view-field.html.twig --> views-view-field--block--fieldname.html.twig

I cannot figure out how to override views-view-field for a specific fieldname by specifying the viewtag. The following names do not work:

views-view-field--viewtag--fieldname
views-view-field--viewtag--block--fieldname
views-view-field--fieldname--viewtag
views-view-field--block--fieldname--viewtag
views-view-field--block--viewtag--fieldname

I've run out of possible combinations and yet I'm simply not able to get the viewtags to override the specific field. Surely there has to be a way to do this given that you can use the viewname to override the templates. I'd rather avoid having 50 versions of a view template when 1 could do the same thing.

I am able to use the tag to create template files for everything other
  than the specific field templates. – John Millnik

Your comment gave me the following thought: When you tag something, you tag the node and not the fields themselves. Fields do not have any tags, which makes me think that what you're trying to do is not possible.


How to load the current entity object (Profile 2) Problem

I'm trying to load the current entity object, in this case a profile2, profile page.

I've been using
Is there a way to load the current entity object?, to try and solve this. Where am I going wrong?

So Far

I have the following code running in a custom form inside a block. The block appears on the profile page.

function mymodule_form() {
    $node = menu_get_object('profile2', 1);
    dpm($node);
}

The path of my page is: localhost/drupal5/profile-main/154

I have two kinds of profile 2, machine names main and school, however the following doesn't work either.

$node = menu_get_object('main', 1);

I couldn't get menu_get_object to work with profile2 so instead I used a combination of profile2_load_by_user and arg suggested by Clive.

function mymodule_form() {
   //this arg gets the UID from the URL.
    $testarg = arg(1);

  //The UID is then put into a profile2 defined function which locates and opens the
  //correct profile.
    $currentprofile = profile2_load_by_user($testarg);
}


Cannot pass variable to js file I cannot pass variable to js file, from my common.module

  $max_length = 10; //variable_get('title_max_length');
      drupal_add_js(drupal_get_path('theme', 'myTHEME'). '/js/script.js');
      drupal_add_js(array('common' => array('max' => $max_length)), array('type' => 'setting'));

Javascript works fine, but i need to get **$max_length** variable from module. At the moment its not working.
here is js file:

(function($, Drupal) {
/*Character limit for news node*/

    Drupal.behaviors.common = {
        attach: function(context, settings) {
            var length = $('#edit-title').val().length;
           /* ####################################### */
           /* Does not work */
            var char_limit = Drupal.settings.common.max;
           /* ####################################### */
            if (length >= char_limit) {
                $('div.form-item-title label span.form-required').text("characters left limit exceeded for displaying on home page");
            } else {
                $('div.form-item-title label span.form-required').text(char_limit-length-1 + " characters left");
            }

            $('#edit-title:not(.edit-title-processed)', context).keyup(function () {

                $(this).addClass('edit-title-processed');
                var new_length = $('#edit-title').val().length;

                if (new_length >= char_limit) {
                    var chars = char_limit-new_length;
                    $('#edit-title').css('color','red');
                    //$('div.form-item-title label span.form-required').text("characters left limit exceeded for displaying on home page");
                    $('div.form-item-title label span.form-required').text("" + chars-1 + " characters");

                } else {
                    var chars = char_limit-new_length;
                    $('div.form-item-title label span.form-required').text(chars-1 + " characters left");
                    $('#edit-title').css('color', 'black');

                }
            });
        }
    };
})(jQuery, Drupal);

Interchange below lines that should work !!

$max_length = 10; //variable_get('title_max_length');
drupal_add_js(drupal_get_path('theme', 'myTHEME'). '/js/script.js');
drupal_add_js(array('common' => array('max' => $max_length)), array('type' => 'setting'));

to

$max_length = 10; //variable_get('title_max_length');
drupal_add_js(array('common' => array('max' => $max_length)), array('type' => 'setting'));
drupal_add_js(drupal_get_path('theme', 'myTHEME'). '/js/script.js');


How to disabled Statistics module for role or anonym users? I use Statistics module (Drupal core modules) on my site to get node's view count. How to disabled this function for role or anonym users?

Like that in template.php:

function MYTHEME_preprocess_page(&$vars) {
  if (!$logged_in) {
    // Code for disable Statistics module
  }
}

The statistics module doesn't provide that option, or an easy way to inject that logic at first glance.

If you're using the AJAX counting method, you can implement hook_js_alter() to change the settings that the module adds, specifically altering the path it sends the tracking AJAX request to. You can change that to a file controlled by your own module, and you can make the decision whether or not to save the record based on the current user in there (after copying the code from the stats module's own statistics.php file).

If you're not using the AJAX method, there are a few different ways you could attack it, but each are more of a pain than it's probably worth. If the AJAX version isn't an option, I'd recommend writing your own custom module that incorporates the existing logic from Statistics that you need, plus your new logic.

The other options are doing things like trying to remove the Stats module's implementations of hook_exit() and/or hook_node_view() from your own module, and re-implementing them. This is never a great approach as you have to re-visit your module every time there's a core update to make sure nothing's changed.

Or, you could maintain a patch to the core module. Usual caveats apply if you go down that route obviously.


How to change Display modes per node (view modes)? In Drupal 8 views modes are supported by Core, which makes entity view modes obsolete. I will like to have the ability to change my view mode per node without using Display Suite.

Does anyone know if I can do this by only using Drupal core or a lighter contribute module than Display suite for?

Ideally, I will have a select list to pick my view mode from the UI at the node level.

That's a task for hook_entity_view_mode_alter.

  Change the view mode of an entity that is being displayed.

See the following working sample that automatically lets node 123 be rendered in the teaser view mode when accessed as full page. You could simply add your own logic (type, user, datetime etc.) as well.

/**
 * Implements hook_entity_view_mode_alter().
 */
function MYMODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {

  // Change the view mode to teaser on full page view for node ID 123.
  if ($entity->getEntityTypeId() == 'node' && $entity->id() == '123' && $view_mode == 'full') {
    $view_mode = 'teaser';
  }
}

As you can maybe imagine, from $entity you can get any field value of a node. So you could add some select list field or taxonomy reference to your content type and then adjust that value node-wise. Finally you can use above code snippet to switch the view mode depending on these values. Mission accomplished.


How to remove comments from all nodes I want to remove the comment section from all my articles. Can this be done with an sql query or something so I don't have to do it manually by setting comments to disabled ?

Delete the comment fields from the Article content type and uninstall the Comment module.


Images placed in blocks do not show up on certain pages I hope this is not a silly question. I have created some links to social media using images inside custom blocks. The images show up on every single page on my local testing server, but after uploading to my production server, I notice that on pages where I use URL aliases that are not directly attached to the site url, the images don't show up. For example if I the page address is www.thebeat99.com/sandbox/competitions, the images show up just fine. If the page address is www.thebeat99.com/sandbox/profile/dami, the images don't show up. I have tried adding a base url in the settings.php file but it does not work either.

This is an example of the html I use to embed the images:

Add "/sandbox/" before sites like below
(src="/sandbox/sites/default/files/buttons/fbicon.png")

Or add "/" before sites as src="/sites/default/files/buttons/fbicon.png" and set your base url to http://www.thebeat99.com/sandbox


Where can I tell if my Drupal 7 database is using InnoDB? I have a Drupal 7 site and was wondering how can I tell if my database is using InnoDB ?

If its not using InnoDB, would I be able to just switch over easily? I just recently switched to MariaDB if that makes a difference.

To find out which tables are InnoDB and MyISAM
COUNTS
SELECT ENGINE,COUNT(1) TableCount FROM information_schema.tables
WHERE table_schema NOT IN ('information_schema','mysql','performance_schema')
GROUP BY engine;

Since MyISAM is a non-transactional storage engine, it has no foreign key referential integrity to enforce. You could change all MyISAM tables to InnoDB, but with one exception: Before MySQL 5.6, FULLTEXT indexes are only available for MyISAM tables.
Here is how to find all tables using FULLTEXT indexes.
SELECT tbl.table_schema,tbl.table_name FROM
(
    SELECT table_schema,table_name
    FROM information_schema.tables
    WHERE engine='MyISAM' AND table_schema NOT IN
    ('information_schema','mysql','performance_schema')
) tbl
INNER JOIN
(
    SELECT table_schema,table_name
    FROM information_schema.statistics
    WHERE index_type='FULLTEXT'
) ndx
USING (table_schema,table_name);

If this comes back with no rows, you can convert all MyISAM tables to InnoDB without worry. If you have any tables with FULLTEXT indexes and you do not use them, you could drop the FULLTEXT indexes then convert the tables to InnoDB.
CONVERSION SCRIPTS
Here is a script to convert all MyISAM tables that do not have FULLTEXT indexes to InnoDB:
SQLSTMT="SELECT CONCAT('ALTER TABLE ',tbl.table_schema,'.',tbl.table_name,' ENGINE=InnoDB;')"
SQLSTMT="${SQLSTMT} FROM (SELECT table_schema,table_name FROM information_schema.tables"
SQLSTMT="${SQLSTMT} WHERE engine='MyISAM' AND table_schema NOT IN"
SQLSTMT="${SQLSTMT} ('information_schema','mysql','performance_schema')) tbl"
SQLSTMT="${SQLSTMT} INNER JOIN"
SQLSTMT="${SQLSTMT} (SELECT table_schema,table_name FROM information_schema.statistics"
SQLSTMT="${SQLSTMT} WHERE index_type='FULLTEXT') ndx USING (table_schema,table_name)"
mysql -uroot -p -ANe"${SQLSTMT}" > ConvertMyISAMToInnoDB.sql
mysql -uroot -p -A < ConvertMyISAMToInnoDB.sql

If you know for a certainty that there are no FULLTEXT indexes in use, you can do this:
MYSQL_CONN="-uroot -prootpassword"
SQLSTMT="SELECT CONCAT('ALTER TABLE ',table_schema,'.',"
SQLSTMT="${SQLSTMT} table_name,' ENGINE=InnoDB;') InnoDBConversionSQL"
SQLSTMT="${SQLSTMT} FROM information_schema.tables WHERE engine='MyISAM' AND"
SQLSTMT="${SQLSTMT} table_schema NOT IN ('information_schema','mysql','performance_schema')"
SQLSTMT="${SQLSTMT} ORDER BY (data_length+index_length)"
MYSQL_OPTIONS="-AN"
mysql ${MYSQL_CONN} ${MYSQL_OPTIONS} -e"${SQLSTMT}" > ConvertMyISAMToInnoDB.sql
mysql ${MYSQL_CONN} ${MYSQL_OPTIONS} < ConvertMyISAMToInnoDB.sql

I have suggested this in the past : How do I convert a database from MyISAM to InnoDB?
CAVEAT
Changing all tables to InnoDB will change the needs for MySQL's memory usage. Why?

MyISAM only caches indexes (via MyISAM .MYI files) into the key buffer. Data is never cached, but always reread from disk (via the .MYD of a MyISAM table) or OS caches
InnoDB caches data and index pages in the InnoDB Buffer Pool
You will have to compute and resize both the MyISAM key buffer and InnoDB Buffer Pool


CKEditor not displaying in latest 8.0.x-dev version After updating Drupal from version 8.0.0-beta7 to version 8.0.x-dev — to fix text_format fields not submitting their value due to a missing name attribute —, my field is now displaying as a basic input field with the format bar under it.

Here's the code that defines the content field of my entity (inside the baseFieldDefinitions method):

$fields['content'] = BaseFieldDefinition::create('text')
  ->setLabel(t('Content'))
  ->setDescription(t('The content of the block'))
  ->setSettings(array(
    'max_length'  => 1024
  ))
  ->setDisplayOptions('form', array(
    'type'   => 'text_format',
    'weight' => -6
  ))
  ->setRequired(TRUE)
  ->setDisplayConfigurable('form', TRUE);

As said above, this code works fine on the latest beta but breaks on the latest version from GitHub.

Expected result (8.0.0-beta7):

Obtained result (8.0.x-dev):

I had submitted a bug report, thinking this was a bug, but apparently it isn't. I was told I need to use a textarea for the editor to show up. The thing is... text_format defaults to a textarea.

I'm guessing there's something I'm not doing right here, but after hours of searching, I just can't seem to understand what. I've tried changing the type passed to BaseFieldDefinition::create() to string_long, too, but then I just get a textarea with no format.

Here is the correct code to create a WYSIWYG field:

$fields['title'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('Content'))
  ->setDescription(t('The content of the block'))
  ->setDisplayOptions('form', [
      'type' => 'text_textarea',
    ])
  ->setDisplayOptions('view', [
      'type' => 'text_default',
    ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);


Where 'target_id' of field_data_field... tables points? I'm extracting database information from a Drupal site that I have using SQL queries.
I have seen that, in the field_data_field... tables can be three type of information storage:

field...value: stores the value of the field directly.
field...val_tid: stores the id number of taxonomy_term_data value.
field...val_target_id: stores an integer id.

I'm interested in the third field, my question is: where is this field value pointing?

If you look in the field_data_field_{field_name} table, you will see these columns:

entity_type: tells which type of object the target is.
entity_id: which one in the entity table

For entityforms, you can go to the URL /admin/structure/entityform_types/manage/{entity_type}/fields, and you can see what the {field_name} refers to by finding {name} in the list.

So if you know what type of object it is, hopefully you know how to find the list of fields.

If not, go to /admin/reports/fields and search the full list for your field.


Drupal - Update Statistics label from "read" to "view" and "reads" to "views" As the subject suggests I'm attempting to update the statistics title via a theme_preprocess_node function to read 'views' instead of 'reads':

function mytheme_preprocess_node($variables) {

  $content = $variables['content'];
  // Check the node  type to make sure
  // we have the one we want

  $content['links']['statistics']['#links']['statistics_counter']['title'] = str_replace('reads', 'views', $content['links']['statistics']['#links']['statistics_counter']['title']);
}

This isn't working but I cannot see why.
I also don't want to use the stringoverrides module as I use 'read' and 'reads' elsewhere on the site.

Thanks

It's because you aren't accepting $variables by reference, so you're just changing a local variable. This will probably do what you want:

function mytheme_preprocess_node(&$variables) {
  $content = &$variables['content'];

  // Check the node  type to make sure
  // we have the one we want

  $content['links']['statistics']['#links']['statistics_counter']['title'] = str_replace('reads', 'views', $content['links']['statistics']['#links']['statistics_counter']['title']);
}


drupal removes language key from variables in templates I have a multilingual website using Drupal 7. The 1st développer didn't use Views.

I installed i18n modules (entity translation, etc )
Un templates I have been using variables like $vars['und' ] (for undefined)

I think drupal ran update and now the template system uses $var without the language as key..
I think I activated block translation..
Other thing : (I purged caches) template still work as disconnected user but doesn't work as administrator.

Do you know what's happend ?

Thanks for your help
Mario

Once you are logged in, another language is requested and the 'und' key no longer works:
https://www.deeson.co.uk/labs/programatically-access-field-data-using-entitymetadatawrapper-drupal
Try replacing your use of $vars['und'][0]['value'] with Entity metadata wrappers. More examples here: https://www.drupal.org/documentation/entity-metadata-wrappers


Does Drupal cache db_query results for multiple users? I am running into something strange and perhaps someone here can help me. I am trying to prevent two things from happening at once because the second attempt might be influenced by the first attempt.

The (simplified) code:

function save_my_thing($thing) {
  module_invoke_all('my_thing_presave');
    >>> INVOCATION

      if (!lock_acquire('mything_lock')) {
        // If  we cannot obtain a lock, wait.
        lock_wait('mything_lock');
      }

      $sql = "SELECT COUNT(*) FROM {my_things}";
      $count = db_query($sql, array())->fetchField();

      if($count >= 1) {
        drupal_set_message('already there','error');
        drupal_goto(drupal_get_destination());
      }

    >>> END INVOCATION

  drupal_write_record('my_things', $thing, array('tid'));
  dpm(db_query('SELECT * FROM {my_things} WHERE `tid` = ' . $thing->tid)->fetchAssoc());

  module_invoke_all('my_thing_save');
    >>> INVOCATION

      lock_release('mything_lock');

    >>> END INVOCATION

}

Above code works perfect if I request the function, wait for it to complete and then call it again. I end up on the page I came from with a visible error.

However if I call this function from two different windows before either of them is finished (as can occur in real life), the sql count returns 0 in both cases. The lock works, and using microtime() I can see the second call starts right after the first call releases the lock. The dpm() returns the inserted row, so the record is written before the lock is released. But SELECT COUNT(*) FROM {my_things} keeps returning 0.

The only thing I can think of now is some kind of fancy SQL caching layer that presents '0' to the second call for some reason, however I could find no such thing in the Drupal database code.

One more interesting thing is that when I move my lock from the custom invoking module to the main module, right before _presave and right after _save. It does work as expected. But then why doesn't this implementation work?

You need to put in an else {...} after using lock_acquire(); or have it return right after calling  lock_wait().

Also, db_query is not cached in any way


Override module javascript file in theme or custom module Is it possible to override a single javascript file from a module within a theme or custom module? My specific use would be for Views/js/ajax_view.js - I've had to apply multiple patches to get ajax views to work properly with BEF and panels, and though I'm including documentation for future developers, it seems more foolproof to override within the theme or a custom module.

hook_js_alter() allows you to modify any JS before it is written to the page.
The documentation includes a snippet to replace a core file with an alternate from a module:

function hook_js_alter(&$javascript) {
  // Swap out jQuery to use an updated version of the library.
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';
}


Class not found for a new module/service I am building. I am not sure how to debug I am building a new service, an event subscriber in a custom module. My class which extends EventSubscriberInterface is not being found.

  [error]  Class
  Drupal\fivewire_commerce\EventSubscriber\fivewire_commerce_orderStateSubscriber
  does not exist

I am not sure why and am struggling to debug what I have done wrong.

My module is 'fivewire_commerce'.

/modules/custom/fivewire_commerce

I have created a file to delare my service.

/modules/custom/fivewire_commerce/fivewire_commerce.services.yml

services:
  fivewire_commerce.order_subscriber:
    class: Drupal\fivewire_commerce\EventSubscriber\fivewire_commerce_orderStateSubscriber
    tags:
      - { name: 'event_subscriber' }

And this is my class

/modules/custom/fivewire_commerce/EventSubscriber/fivewire_commerce_orderStateSubscriber.php

<?php

/**
 * @file
 * Contains \Drupal\fivewire_commerce\EventSubscriber\fivewire_commerce_orderStateSubscriber
 */

namespace Drupal\fivewire_commerce\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;

/**
 * Event Subscriber MyEventSubscriber.
 */
class fivewire_commerce_orderStateSubscriber implements EventSubscriberInterface {

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        // Trigger after an order is made
        $events['commerce_order.place.post_transition'][] = ['onCompletedOrders'];
        return $events;
    }

    /**
     * Code that should be triggered when an order is placed.
     * This is the order state 'validation' according to our chosen workflow.
     */
    public function onCompletedOrders(WorkflowTransitionEvent $event) {
        $test =true;
//        if ($event->getToState()->getId() == 'validation') {
//
//        }
    }

}

And if I try to rebuild my cache I get:

  [error]  Class
  Drupal\fivewire_commerce\EventSubscriber\fivewire_commerce_orderStateSubscriber
  does not exist

And this is my class
/modules/custom/fivewire_commerce/EventSubscriber/fivewire_commerce_orderStateSubscriber.php

Autoloading relies on your classes being in a root /src folder for the module.
So move the file to

/modules/custom/fivewire_commerce/src/EventSubscriber/fivewire_commerce_orderStateSubscriber.php

And PHP will be able to find it.


CkEditor Toolbar not available/visible to Administrator when creating content I am having a strange problem on my local dev site install. When either Basic HTML or Full HTML mode is selected in CkEditor, the toolbar and the whole area where text would be typed, are not available or visible. Yet when selecting Restricted HTML, the area for text and toolbar are visible and available.

This is the only user I have on my site so I am assuming it has full administrative privileges correct?

Where else do I need to change any settings for this user to have access and use Full or Basic HTML along with the toolbar?

The Text formats and editors section have Administrator under the Rolescolumn for Full HTML

Any ideas or suggestions of where I am going wrong?

Brand new Drupal user here, obviously.

Semi Reolved..
Found the issue for a temporary fix..
Status Report showed an error for a CodeTag module that was not loaded for some reason.
Even though it was installed and enabled with drush.
Even showed up in list from
drush pm-list
command so not sure what the deal is with it.
Uninstalled it in UI on-site instead of with drush and the editor issues are no more. For what I originally posted.

Sounds like you have a ckeditor plugin conflict.

Your symptoms are typical what happens if there are for example a js error on a added ckeditor plugin.

Quick way to confirm is using Firefox Console, it will in most cases flag the offending js for you. Armed with that you can google for a fix or patch.

Alternatively you can turn of the plugins off one by one, but you need to remember to clear your cache, else the offending js could still be there.

So try FF console first and post any extra info you get.


How do I send a drupal_http_request() with GET method? Following examples found here and in API, I tried 2 methods, both return a bad request status message.

First method

$data = 'name=value&name1=value1';

$options = array(
  'method' => 'GET',
  'data' => $data,
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$result = drupal_http_request('http://example.com/foo', $options);

dpm($result);

Second method

$data = array(
  'key1' => $value1,
  'key2' => $value2,
);

$full_url = url('http://example.com/foo', array('query' => $data));

$options = array(
  'method' => 'GET',
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);
$result = drupal_http_request($full_url, $options);

dpm($result);

Which one is the good one and what's wrong ? Thank you

Edit

This is dpm($result)

The first method is correct; you don't use url() to pass the data. Also, application/x-www-form-urlencoded is the content type used when POSTing data.

You could also use drupal_http_build_query() to build the data to pass.

$data = array('name' => 'value', 'name1' => 'value1');

$options = array(
  'method' => 'GET',
  'data' => drupal_http_build_query($data),
  'timeout' => 15,
);

$result = drupal_http_request('http://example.com/foo', $options);


Memcache not being cleared on cache flush When clearing the cache, either through /admin_menu/flush-cache or drush cc all, the cache isn't cleared, without errors. I've tried doing it directly through telnet, on memcache, getting "OK" as result, but old pages are still being presented to users.

I am using the Memcache module 1.10; in the settings.php file, I added the following.

$conf['cache_inc'] ='sites/all/modules/memcache/memcache.inc';
$conf['memcache_servers'] = array(
  '127.0.0.1:11211' => 'sessions',
  '127.0.0.1:11212' => 'cache',
);
$conf['memcache_bins'] = array(
  'cache' => 'cache',
  'cache_form' => 'database',
);

Although the session bin is configured, it's not in use. I also have http://livebookmark.net/journal/2008/05/21/memcachephp-stats-like-apcphp/ set up, tried using the "Flush this server" option, and get OK as result.

Turns out it wasn't a memcache problem but a LESS preprocessor issue.


How to trigger rules action if cart is empty? We have a field in our user profiles that is checkmarked when a user adds a product to their shopping cart (with Drupal Commerce). This is used to display a message reminding them to checkout if they have items in their cart. I have successfully set up rules to check the field when they add a product, and uncheck it when they make it through checkout.

However, I also need to uncheck the field if a user removes all products from their cart. I can't seem to figure out what conditions to add to check if the user's cart is empty after a product has been removed.

Any suggestions?

You could try adding a rule that looks at the total number of items in the cart. Just get the count of the line items list within rules.


How to send emails to 20,000 + registered members efficiently? I have a Drupal 7 site with about 20,000 members.  Sometimes I need to email them all at once.  Thus far, I have been adding a rules component (Condition: Make sure user has not opted out of emails, Action: Send email, translated as appropriate for each language) and then used VBO and a view to select all the users on the site.

Unfortunately, with such a large number of users, even when VBO is queued to send emails 10 at a time the batch often encounters some error every few thousand users, so I need to find which user was last e-mailed when the batch error occurred and restart the batch manually.

Is there a more robust (i.e., automatic way that will not break and require manual intervention on my part) to email all the user accounts on the site when the number of users is large?

Below is a summary of how you can improve what you already have in place ...

Part 1 - Use a flag to keep track of the progress

Introduce an additional flag to allow "flagging" of some new or updated "entity" (eg "nodes") by all users "which you need to email all at once" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).

This of course assumes your eMails are to be triggered by such new or updated entities. But if you don't have such entities (= you have another reason to send such eMails), you could introduce a dedicated content type and use it as a kind of eMail template (with fields up to your own imagination). And each time you have a new eMail to be delivered, just create an appropriate node (of this dedicated content type) for it.
Create a rule to flag the newly saved (or updated) content, using the new flag (from step 1) for each of the users you already have in your existing "a view to select all the users on the site".
Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged nodes (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first X users only (pick a value for X that fits your needs).
Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

eMail each of the users in that VBO list (you can probably reuse the Rule to "send an eMail" that you already have).
unflag (using flag from step 1) the node (for the user for which you just produced an eMail). This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the execution of the same rule within Y minutes or hours  (pick a value for Y that fits your needs).
Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every Y minutes (or hours), Rules will eMail X users "as requested".

Part 2 - Recovering from an error

Sooner or later, Mr. Murphy will come along again, and it might cause some error again (eg after a few thousand users). If that happens, all that's needed is to repeat Step 5 ... And even if you didn't realize the error at first (only after X hours or days or so), all that's needed is to repeat step 5 as soon as the error got noticed.


Get IP address of submitter I'm actually testing a website with Drupal 7.

I am searching a way to get the visitors' IP, when they submit a new node; the users can also be not logged-in, as anonymous users are allowed to submit new content.

I can't find a module to do that, and I don't know how to use hooks or PHP to achieve this.

What should I do?

I haven't found a module which does this yet.  You can do these steps:

Create a text field named ip_address
Manage display: make the field hidden
Use Display Suite or a custom hook (or even CSS) to hide the field when filling out the form
Create a Rule on event "Before saving content"
Set a condition of content type: your content type
Set a condition of Data comparison: [node:is-new], Data value: True (check the checkbox)
Set an action of Set a data value, and set the field to be:

PHP Code

<?php
  print ip_address();
?>

That should do it.

You could also accomplish this by creating a module and using some hooks


How can I show a block on a specific page if a custom PHP function evaluates to be true? Follow-up to the question "How can I show a single block only if the user is on iOS?".

I am using D7 and trying to show a message to iOS users that their devices of choice do not support basic upload functionality.  I have a block that I would like to show only on the following path: node/add/profile-picture if the function mymodule_is_iOS() returns TRUE.

On the block configuration screen, I can easily limit it to a given path by adding the path to Show block on specific pages.  However, if I do that, I cannot select Pages on which this PHP code returns TRUE to limit it to users for which the function mymodule_is_iOS() returns true.

I found some documentation on Drupal.org here (Combining PHP visibility control with specific page visibility) but it isn't relevant to my case.

Is there a way to do this by adding another function to my custom module for the site or theme?  I'm not an expert in PHP but I do have custom functions in a custom module and in my theme.

By enabling core PHP Filter module, you will see another option "Pages on which this PHP code returns TRUE (experts only)" under Show block on specific pages of the block configuration page. Select the option and write the following code in the box.

<?php
  if (mymodule_is_iOS()) {
    if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'profile-picture') {
      return TRUE;
    }
  }
  return FALSE;
?>

Your module must have a lower weight than the core PHP filter module to allow this code snippet to call mymodule_is_iOS().


How to theme all pages after a certain url I'm using Drupal 8.7.8

I would like to create a new twig theme file for all pages that are after a certain URL.
For example: example.com/example/this-page

"This-page" is what I want to create my twig file for. But there doesn't seem to be an option in the theme debugging for anything after example.com/example.

Another example...The twig file would be named page--example.html.twig ... Is there no way to say page--example/*.html.twig ?

You can use THEME_NAME_theme_suggestions_page_alter to create your own template suggestions!

In your theme:

File: my_theme/my_theme.theme

/**
 * Implements hook_theme_suggestions_HOOK_alter.
 */
function my_theme_suggestions_page_alter(&$suggestions, $variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $current_path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

  if (strpos($current_path, 'this-page') !== false) {
    $suggestions[] = 'page__this_page';
  }
}

File: my_theme/templates/page--this-page.html.twig

// Output html and stuff

Obviously replace "my_theme" with the name of your custom theme.

Here is a nice tutorial that expands more on it.


How to display the user's url in a template? I created a template user-comment.html.twig to customize the rendering of the comments author.

I can not display the user account url:

user.url

does not work.

How to display the user's url in a template?

{#
/**
 * @file
 * Default theme implementation to present all user data.
 *
 * This template is used when viewing a registered user's page,
 * e.g., example.com/user/123. 123 being the user's ID.
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 *   print a subset such as 'content.field_example'. Fields attached to a user
 *   such as 'user_picture' are available as 'content.user_picture'.
 * - attributes: HTML attributes for the container element.
 * - user: A Drupal User entity.
 *
 * @see template_preprocess_user()
 *
 * @ingroup themeable
 */
#}

  {{ content.user_picture }}
  {{ user.label }}

    {{ content.utilisateur_statut_entity_view_1 }}
    {{ content.utilisateur_statut_entity_view_2 }}
    {{ content.utilisateur_statut_entity_view_3 }}

You can use the path function in a Twig template:

{{ 'View user profile'|t }}

I don't know if user.url is a thing.


Clearing cached CSS when updating live web page I'm responsible for my company's webpage, and I'm having caching issues when updating it with the new CSS files. The CSS files are collected and minified as they should be, but when I update them, they should be cleared, so the page looks like it should.

How do I clear the cached CSS files in Drupal 7?

Navigate to http://mysite.com/admin/config/development/performance and click the "Clear all caches" button :)

Or if it's an option, install drush on your server and use drush cc css-js, it will only clear CSS/JS cache so won't slow the site down while all the caches are rebuilt.


how to setting drupal i18n translation module not to translate system menu I don't want? In my site I am using drupal7 i18n module to translate to Burmese language. But my problem is I don't like drupal to translate system fields that does not need to translate because translation is totally wrong and might confuse for user, so it is better for user to leave these as English such as system field and something like that. When I click Burmese language in language switcher block, all for content fields, sitemap navigation, content types fields and product fields are changed to burmese, but translation is really really confusing for me and also for customer. So I am thinking that it is easy for me and customer if not system translated, and I will have to manually interpret the fields and taxonomy that I want to local user to understand.

Any suggestion is greatly appreciated.

Thanks

Highlights in above two images are really misunderstanding and that doesn't need for i18n module to interpret.

You can try Administration Language module.

  This module lets the administrator see all administration pages in her preferred language.

  You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).

  You can use the standard Languages page to choose the language of the admin pages.