Subtheme: How to use the template function of a parent theme (from inside the parent theme) I have created a theme that contains several functions.

I now want to create a sub theme. That way, I can use the parent theme on all my sites (and any updates to the parent the theme can be easily applied to all the sites). The sub theme will contain all the modifications that are specific to that individual website.

I have created a sub theme following the instructions in this tutorial. When I enable the subtheme, the site breaks. Most of the content disappears and I get this error message:

  Fatal error: Call to undefined function legendary_views_field_compare_value() in /all/themes/legendary/templates/slideshow.tpl.php on line 20

legendary_views_field_compare_value() is the name of a function in my
parent theme.
legendary is the name of my parent theme.
slideshow.tpl.php is a template in my parent theme.

I don't understand why this is happening. I thought the sub theme should inherit all the functions of the parent theme (especially is the function is being called from inside the parent theme and NOT in the sub theme).

How can I fix this?

The problem

Pay attention to your first sentence:

  I have created a theme that contains several functions.

The link that you have provided warns about what type of functions hold a template.php in a theme.

  There are two main types of functions in template.php: theme function
  overrides and preprocess functions. The template system handles these
  two types in very different ways.

Is legendary_views_field_compare_value() any of these cases? OK, we agree that the anwers is No. It's a custom function that you have written.

Why should not you put your custom functions in template.php?

Because Drupal has a registry of implemented hooks and templates that have been overriden. The system only load the template.php when match the hook in the registry. So, the template.php is not always load.

The solution

First of all, you should keep separate the custom functions from the theme functions. You need to create a file called for example my_custom_functions.inc , and insert all your custom functions in that file.

How do i load a file with custom functions that i need to call in my templates?

To keep separate the logic from the theme functions, i would stored the custom functions in a module. But, it is also possible store the functions in your theme. In both cases, you have to follow the next strategy.

It's really easy. Every time that a template is rendered, a preprocess function is fired by default to let other modules to act. So, it is always fired a preprocess (and process) function before the slideshow.tpl,php. In this moment, we will load the file with our custom functions.

Here an example:

/*
 *  Implements hook_preprocess_slideshow()
 *
 *  The file will load  before rendering slideshow.tpl.php
 */
 function NAME_OF_YOUR_THEME_preprocess_slideshow(&$variables){

     include_once 'my_custom_functions.inc';
 }

Please, pay attention to the name of the template. In my simulation, i have changed the template called views-slideshow.tpl.php . So, when you implements in hook_preprocess_HOOK(&$vars) , you need to change the hyphens. The result would be NAME_OF_YOUR_THEME_preprocess_views_slideshow(&$vars)

If you have to load the same file with custom functions in lots of templates, you could implement the general hook_preprocess($vars), that it is always fired. Here an example:

 /*
 *  Implements hook_preprocess()
 *
 *  The system always load the file
 */
 function NAME_OF_YOUR_THEME_preprocess(&$variables){

     include_once 'my_function.inc';
 }


Problems with extreme slow database queries in Drupal 7 I have a problem with extreme slow database queries that make my site loading for more than a minute. I am not able to locate the source of that problem. I'm using devel to control the queries and I found out that mostly the functions saving or updating the cache or session tables are the cause. Here is one example of devel's output:

19622.34 1 _drupal_session_write P A UPDATE users SET access=:db_update_placeholder_0 WHERE (uid = :db_condition_placeholder_0)
10442.86 2 DrupalDatabaseCache::clear P A DELETE FROM cache_bootstrap WHERE (cid = :db_condition_placeholder_0)

I do not have an idea what I could do to find the cause of that problem.

When a server's I/O performance (especially its disk write performance) reaches its limit, it'll probably show first with cache queries because they're frequent and can contain some quite big chunks of serialized data.

I recommend you take a look at your disk I/O while you're waiting for a page to render, by using iotop for example.

The best way to prevent those I/O bottlenecks is to keep page requests from even reaching Drupal by putting a Varnish cache in front of the webserver. If they need to be answered by Drupal, though, at least take the cache load from the database by using Memcache.


Check if there's a content type published How can I check (via PHP code) if a content type is published?

I have a content type called 'House' and a content type called 'People'. On the 'People' content type, there's a field called 'House'. If the user didn't publish a 'House' content type yet, I want to hide this field.

I thought I could do it by using a hook_form_alter, isn't it possible? If it is, I just don't know how to check if a content type was published or not. Something like: if (isset($node->type == 'House')) ... Of course it doesn't work.

Do you have any suggestions?

Something like this?

hook_form_alter() {
  /* check that you're looking at the right form here.. */
    global $user;
    $type_to_check = 'House';

    $query = db_query("SELECT nid FROM node n JOIN users u ON n.uid = u.uid WHERE n.status = 1 AND u.uid = %d AND n.type = '%s'", $user->uid, $type_to_check);

    if(empty(db_result($query))) {
      /* kill the thing you don't want here */
    }
}


Adding alt text to a form field I know that alt text is usually used for images, to help screen readers etc. In this case my task manager wants me to add 'alternative text' to calendar items, to better satisfy 508 requirements. This would be for a custom content type called Event, which is called up in a view. The alt text would be entered by a user, and may or may not link to anything. I'm just trying to create a field that is wrapped in an alt tag, so it doesn't display but screen readers will find it.  I've tried different things, such as adding dummy text into the .tpl file for calendar item, but I can't come up with a good variable for $title that works. I've tried using a php print statement in the .tpl but again, haven't found the right code. I'm thinking I will probably have to do surgery on the custom event module itself, which has a form for people to enter in the event data.  One solution is to use hook_form_alter to add in some code, something like this:

function events_form_alter(&$form_state, $form_id) {
    if ($form_id == 'events_form') {
        <?php print $title . "text"; ?>
    }
 }

One thing is that I think the best place to find an event title variable is in an include file, where most of the module code lives. I can see #title being used in the include, but not sure what that is. A local variable?  How can I use that variable to print in my alt text?  I'm hoping I can use this variable in a hook_form_alter function that prints a statement using this title. From the include file:

    // Add an end and a date repeat form element, if needed.
if ($element ['#bundle'] == 'event') {
    if($element['#field_name'] == 'field_event_times_combined') {
        $element ['#title'] = t ( 'Date & Time' );
    }

But all this is close to exceeding my PHP skills, however. Does anybody have any general insight?

Many thanks

I don't think your approach will work, adding the new "alt" field to the edit/add form is only a small part of the task. Where and how you save the data? Instead, create a new field via the manage field section. Then you can use theme_preprocess or a tlp/twig file to change the output.


REST Services module - Access denied for user anonymous I'm Using Drupal 7, I installed Services module with all the requirements, according to this question and this video.

I'm trying to get all users with Postman where I give my credential, but I'm getting back that I'm an anonymous user.

How do I pass my credentials?
How to add a filter to that call ,for example get all users with specific role?

You need to make the user login who have the permission to view the list of user details using following Service API

http://yourdomain/endpointname/user/login

with follwing json data as arguments

{
"username":"username of the user who have the permission to view the users list",
"password":"password which matched with username"
}

After the successful login you need to get the CSRF token which will play the key role in all authenticated request. To get the token call the below mentioned API,

http://yourdomain/endpointname/user/token

You will receive a token, then add the token to your postman header for the key named X_CSRF_TOKEN. Then you can start to make the authenticated requests.


Undefined variable: node Im using

views_embed_view('view_name', 'view_block_name', $node->nid);

and im getting error Notice: Undefined variable: node in functin include()
So in D7 We cant use $node inside page.tpl.php?

If you are using drupal 7, there should already be a node object available when you are looking at a full node page. Looking at http://api.drupal.org/api/drupal/includes--theme.inc/function/template_preprocess_page/7 - the default implementation embeds it into the $variables array:

  if ($node = menu_get_object()) {
    $variables['node'] = $node;
  }

If your theme is overriding this, you can simply add it back in.

An example might be:

function YOURTHEME_preprocess_page(&$variables) {
  if ($node = menu_get_object()) {
    $variables['node'] = $node;
  }
}


Why does core update result in 'The requested page could not be found'? I have Drupal 8 rc-3 and I unzip 8.0.0 version files cause need to update. Site works fine and all external site pages shows but when I go to update.php and push Run database updates it goes to update.php/selection and displays the error:

The requested page could not be found.

Also this error appears in /admin/modules and /admin/appearance/settings and may be others don't know.

I run Drupal 8 on Nginx and think my config is wrong. What I need in this case? My config files you can read here tlito.ru/node/253

i found nginx drupal 8 host config here https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/

my config is this

server {
server_name www.EXAMPLE.COM .EXAMPLE.COM;
root /var/www/EXAMPLE.COM/www;

location = /favicon.ico {
    log_not_found off;
    access_log off;
}

location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}

# Very rarely should these ever be accessed outside of your lan
location ~* \.(txt|log)$ {
    allow 192.168.0.0/16;
    deny all;
}

location ~ \..*/.*\.php$ {
    return 403;
}

location ~ ^/sites/.*/private/ {
    return 403;
}

# Block access to "hidden" files and directories whose names begin with a
# period. This includes directories used by version control systems such
# as Subversion or Git to store control files.
location ~ (^|/)\. {
    return 403;
}

location / {
    # try_files $uri @rewrite; # For Drupal <= 6
    try_files $uri /index.php?$query_string; # For Drupal >= 7
}

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

location ~ '\.php$|^/update.php' {
    fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
    #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

    include             /etc/nginx/conf.d/fastcgi_params.conf;

    fastcgi_param       SCRIPT_FILENAME     /var/www/EXAMPLE.COM/www$fastcgi_script_name;
    fastcgi_param       DOCUMENT_ROOT       /var/www/EXAMPLE.COM/www;

    fastcgi_param       PHP_ADMIN_VALUE     upload_tmp_dir=/var/www/EXAMPLE.COM/tmp/upload;
    fastcgi_param       PHP_ADMIN_VALUE     session.save_path=/var/www/EXAMPLE.COM/tmp/sessions;
}

# Fighting with Styles? This little gem is amazing.
# location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
location ~ ^/sites/.*/files/styles/ { # For Drpal >= 7
    try_files $uri @rewrite;
}

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires max;
    log_not_found off;
}
}

AND the problem disappears.


Need to ignore empty variable values for Computed Field when multiplying In my entityform, different fields appear based on choices (dependencies). Two appear at once. I'm multiplying the values using a Computed field. All works if the variables have a value. I have 8 fields I want to multiply, but ignore the empty values. Can't set field defaults to 0 (wrecks multiplication) or 1 (messes with totals).

The following warning appears for each empty field; here it's "line 1" for the 1st variable/field. No warning for those that have a value.

  Warning: array_pop() expects parameter 1 to be array, null given in eval() (line 1 of /home/content/67/10793667/html/sites/all/modules/computed_field/computed_field.module(466) : eval()'d code).

How can I instruct the computed field to ignore the empty fields?

Here is my Computed Code (PHP).

$howmany = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_how_many')));
$price1 = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_reg_price1')));
$price2 = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_sale_price2')));
$entity_field[0]['value'] = $howmany*$price1*$price2;

I tried adding this after the $price2 line, but it didn't work.

if ($price2 == null) {
    $price2 = 1;
}

I tried this too, and it didn't work.

if (!empty($price2)) {
  $price2 = 1;
}
else {
  $price2 = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_sale_price2')));
}

Both @Neo's answer and @danielesus's question shows PHP code that will throw errors. @Neo, empty() only works with variables before PHP 5.5. Both: array_pop requires a variable or something returned by a reference-returning-function which field_get_items is not.

Now let's consider what field_get_items($entity_type, $entity, 'field_how_many') returns: it returns an array indexed by delta where the values are field_column  => value. You can do

if ($all_items = field_get_items($entity_type, $entity, 'field_how_many')) {
  $item = reset($all_items);
  $value = reset($item);
}

as there's no need to actually modify the array with array_pop but also you can use your knowledge about Field API and know the actual column name which I suspect will be value here (would be tid for a taxonomy reference field for example) and that $delta is, if you have a field with cardinality 1 is actually 0:

$value = NULL;
if ($all_items = field_get_items($entity_type, $entity, 'field_how_many')) {
  $value = $all_items[0]['value'];
}

Fast and simple.


How can I create a very simple entity definition for Webform submissions? I make extensive use of the Webform module and often use Views for managing the webform submissions.

I'm fairly new to the Actions/Rules/Triggers backend of Views Bulk Operations (VBO), but I'd really like to be able to use it in my submission management views.

I've written a module that accepts submission IDs from the URL like so: mymodule/form/314/submissions/201+202+203 and generates a page with information from all the listed submissions (in this case, submissions 201, 202, and 203).

I want to use the VBO "Pass ids as arguments to a page" operation to select submissions in a my Views table, and pass their IDs to my custom page.

As far as I can tell, this isn't possible since webform submissions are not entities. So what I'm wondering is, how can I define a very simple entity type for webform submissions, so that I can use VBO on them?

I assume I should implement hook_entity_info(). I think the entity really only needs to include the submission ID in my case (the sid column in the webform_submissions db table).

I've read through the docs on defining custom entities, but can't figure out how to apply that stuff where I'm not actually wanting to create an entity type from scratch. Thanks!

Got it working. In a custom module (mymodule), I implemented hook_entity_info() like so:

function mymodule_entity_info() {
  $info = array();
  $info['mm_submission'] = array(
    'label' => t('Simple Webform Submission Entity'),
    'base table' => 'webform_submissions',
    'fieldable' => FALSE,
    'entity keys' => array(
      'id' => 'sid',
      'label' => 'sid',
    ),
  );
  return $info;
}

This very simple entity definition was sufficient for VBO to treat my submissions as entities and pass their IDs to my custom URL.

Though I didn't need to, it should be possible to override the entity class controller and its entity functions (load, save, delete, etc) should you need to. This tutorial by Ronald Ashri was useful to me and talks more about that.

After installing my custom module, I was pleasantly surprised to see a "Bulk operations: Webform submissions" field magically appear in the list of available Views fields.

I didn't make any other connection between Webform submissions and my custom entity type, nor otherwise tell VBO to treat the Views results as mm_submission entities--somebody (Views/VBO/Webform?) just automatically made it happen; which is awesome.

I presume VBO knew to process the submissions as mm_submission entities because of the entity type base table attribute? Not sure without looking more closely; perhaps someone else can shed more light on that.


How do I share data from a hook to a service/controller? I'm trying to implement a shopping cart feature that requires retrieving the data (total value of cart) from a Commerce order.  The problem is that this is only possible with a hook.  But how am I supposed to pass this data from the hook to a service/controller?  I can't find any documentation on where the return value is sent from a hook and if it exists, it's certainly not placed in a very easy to access place since I've been searching for a few days now.

Trying to implement this hook:

function commerce_cart_order_load($uid = 0) {
  // Retrieve the order ID for the specified user's current shopping cart.
  $order_id = commerce_cart_order_id($uid);

  // If a valid cart order ID exists for the user, return it now.
  if (!empty($order_id)) {
    return commerce_order_load($order_id);
  }

  return FALSE;
}

This should give me an assoc array (or some other data object) of the different elements of an order.  Not sure how I can pass this around or access it anywhere.

For those who may have the same troubles as I do...

I am trying to set a message in Drupal to show on /cart the main cart page.  The data is seemingly already there but it was a bit trickier to actually pull the data into code compared to the Views module just simply inserting a field.

So I can't say I fully understand how this is working.  But my site uses a multi-store model so it's necessary to specify store ID.  Here is my code:

This isCartNotificationController.php (I changed the route behavior of /cart by setting a default _controller method in RouteSubscriber.php and copy-pasting the CartController.php class from commerce_cart/src/Controllers/CartController.php and making edits.  Now the behavior of the route at /cart is different.

$store = \Drupal::service('commerce_store.current_store')->getStore();
$cart = \Drupal::service('commerce_cart.cart_provider')->getCart('default', $store);
$price = $cart->get('total_price')->getValue()[0]['number'];
drupal_set_message($price); //shows $19.98

So it's a rough implementation but I can successfully access the cart value using this.  I'll probably make a template or something instead since a drupal_set_message is a little bland.

Lots of Google searches will bring up hooks and extending certain hooks but it doesn't seem like you can practically use those within a service/controller.

In other words, I misunderstood what a hook was doing.


Setting menu weight for "Edit" and "View" items in a node I am trying to rearrange the order of my menu items for my custom node. Most of the menu items are created programmatically in hook_menu() so I can simply set the weights for those which works great. But I would like to move the edit menu item down the list a bit but I can't find a way to change its weight from the default of zero.

Is this possible?

I believe you can do this with hook_menu_alter().

Another option would be to leave the edit at 0 and change the weights of the items you can adjust to work around the edit.


Ajax callback of select form field not triggered when changed by javascript, only when changed manually I have a simple ajax form with select form input:

$form['children']['number_children'] = array(
  '#title' => t('Počet detí'),
  '#type' => 'select',
  '#options' => range(0, 15),
  '#default_value' => $number_children,
  '#ajax' => array(
    'callback' => 'ajax_callback_registration_children',
    'wrapper' => 'children-div',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

When the select input is changed manually it properly executes an ajax and appends new inputs into the form. But I need to trigger the ajax callback by javasrcipt code that is changing the selected option:

$('#children-div select[name="number_children"]').val('3').change();

This changes the value, but the ajax is not triggered at all. Why is it not working and is there something I could do?

EDIT: It works when this command: $('#children-div select[name="number_children"]').val('3').change(); or another way of triggering an event is typed in browser console, but not if the same code is executed from my chrome extension. Is it possible that Drupal somehow verifies what exactly triggered the event?

try to specify the event, like

$form['children']['number_children'] = array(
  '#title' => t('Počet detí'),
  '#type' => 'select',
  '#options' => range(0, 15),
  '#default_value' => $number_children,
  '#ajax' => array(
    'callback' => 'ajax_callback_registration_children',
    'wrapper' => 'children-div',
    'method' => 'replace',
    'effect' => 'fade',
    'event' => 'change',
  ),
);

this should be sufficent .. (but select uses change already as default event ..)

other things to try could be

add a custom event, like:

'event' => 'custom_change',

jQuery('select').trigger('custom_change');

See How to trigger Ajax forms machinery

or invoke the callback yourself:

Drupal.ajax['#ID'].eventResponse('#ID');


Update price via AJAX I created a content type (main prod) that is referencing a product content type (sub prod). The sub prod is also referencing another product content type called (option sets) which will be the option sets of that product, with the use of Commerce Product Bundle I was able to combine all the different prices of the sub prod and the option sets and with the use of Commerce Product Attributes I am able to change the option sets to a list text field.

I applied a patch that I saw to calculate the total price of all the chosen option sets and the sub prod on the cart and checkout page. My problem is on the product page itself I want the price of the sub prod to be calculated depending on the option sets chosen via real time of with using ajax.

Can anybody help?

This is the list of commerce modules I have currently installed on my site.

Drupal Commerce
Commerce Product Bundle
Commerce Product Attributes

The answer is that "Commerce Product Bundles" (https://www.drupal.org/project/commerce_product_bundle) is never recommended since it circumvents large portions of Drupal Commerce. You should consider using line item fields or https://www.drupal.org/project/commerce_bundle if bundling is important to you.

Note: Custom line item fields also suffer from not having ajax updates. The community effort to make this a reality can be found here: https://www.drupal.org/node/1541886 and a video that describes an interesting use case for line item fields is here: https://www.youtube.com/watch?v=j9KsyvQZaAY


How to update field after ubercart checkout completion? I have created a field (checkbox) in user profile edit form that is only visible to admin.

When the user completed their checkout process (after payment) that field which I created previously must be updated (I.e: checked).

I want to implement this functionality for letting admin know about who has purchased the subscription plan .

How could I do it by using rule or something else?

you can use the Rules module for the after checkout event then use some custom php code to update your field.

you might need to add Commerce Rules Extra module to get the checkout event in rules.


is it possible to edit default output of services module? Is it possible to edit/customize the default output we get using Services Module ?

For example I want to edit output which I get from this URL : http://example.com/api/node/39

And I want to edit output of this URL : http://example.com/api/user/39

OR is there any way to create a View for single user profile ?

Using the Services API this is possible: http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x

/**
 * Implements hook_services_request_postprocess_alter().
 */
function example_services_request_postprocess_alter($controller, $args, &$result) {
  switch ($controller['callback']) {
    case '_node_resource_retrieve':
      $result->foo = 'bar';
      break;
    case '_user_resource_retrieve':
      $result->bar = 'chew';
      break;
  }
}

You could use the Views JSON module (a sub module of the Views datasource module) to build a View with a User ID contextual filter, and then return the field(s) you want for that particular user.


What is the Drupal 6 equivalent or alternative to hook_node_load? In Drupal 7, there exists the function hook_node_load. Does anyone know how I can hook into a node being loaded from the database in Drupal 6? If not, can you suggest an alternative hook? I am simply trying to get my custom module to load my javascript file upon the user visiting a particular node page. Thanks.

I've found that hook_nodeapi fits my use case: https://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_nodeapi/6


Drupal multiple node url aliases Is it possible to take a field from my node and create a url alias from the content of that field?

Say I have a node type article. This gets its normal url via pathauto, but I also wish to be able to create a short url so I can go to example.com/LS and I will be redirected to the node.

How can this custom short url be created automatically?

When you create a node they will always use the url node/[nid].

You can use the path auto module to create an url alias for the standard node. Path auto uses the token module to create the url alias for the nodes.

What you can do, is to create a token for the value of the field, and then setup path auto to use the contents of the field when creating the url alias.

Another thing you could do is to use the ShURLy module, to actual create short urls. You could make a custom module where you created or update the short url for the node when saved, and let ShURLy handle the redirects.


BOA installation caching does not refresh I have recently migrated an existing site into a fresh BOA platform. The problem I am facing is that the cache for the anonymous users is never cleaned, when new content is added. The anonymous user can only see new content by adding ?nocache=1 at the URL. But otherwise cache is not regenerated neither by drush cc all.

Given that this happens when boost is disabled, I conclude that this is an issue with speed booster. I tried all suggested solutions to reduce the TTL to 30seconds or so, but there is no improvment. New content is not even displayed for the devel.domain.com, which is supposed to have TTL of 1 second. So I don't know what to think.

Adding ?noredis=1 helps only occasionally, most of the times it delivers older content as well.

If the anonymous user submits a comment, caching gets suspended, as it should be according the documentation.

Edit: I also noticed that drupal reports

  1 error has been encountered when purging URLs Array

and nginx gets similar errors

  Blockquote [alert] 52902#0: *65633 stalled cache updating, error:0 while closing request, client: 127.0.0.1, server: 127.0.0.1:8888

I am copying here the headers of a normal request and I would appreciate some directions on how to resolve this issue, which is actually preventing totally all my sites from working. This is a news and forum website, where content needs to be displayed immediately, the latest after a minute or so.

Response Headers

Cache-Control public, max-age=0
Connection close
Content-Encoding gzip
Content-Language el
Content-Type text/html; charset=utf-8
Date Thu, 30 Jan 2014 01:09:38 GMT
Expires Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified Thu, 30 Jan 2014 00:58:19 +0000
Server nginx
Transfer-Encoding chunked
Vary Accept-Encoding, Cookie
X-Cookie-Domain .mysite.com
X-Device normal
X-GeoIP-Country-Code DE
X-GeoIP-Country-Name Germany
X-NoCache Cache
X-Server-Name www.mysite.com
X-Speed-Cache EXPIRED
X-Speed-Cache-Key /node/4042

Request Headers

Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cache-Control max-age=0
Connection keep-alive
Cookie has_js=1; __utma=1.2022174721.1391038387.1391038387.1391038387.1; __utmb=1.49.10.1391038387; __utmc=1; __utmz=1.1391038387.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __unam=f0418e2-143e0596284-fd42fad-47
Host www.mysite.com
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:26.0) Gecko/20100101 Firefox/26.0

Response Headers From Cache

Cache-Control public, max-age=0
Connection close
Content-Encoding gzip
Content-Language el
Content-Type text/html; charset=utf-8
Date Thu, 30 Jan 2014 01:09:38 GMT
Expires Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified Thu, 30 Jan 2014 00:58:19 +0000
Server nginx
Transfer-Encoding chunked
Vary Accept-Encoding, Cookie
X-Cookie-Domain .mysite.com
X-Device normal
X-GeoIP-Country-Code DE
X-GeoIP-Country-Name Germany
X-NoCache Cache
X-Server-Name www.mysite.com
X-Speed-Cache EXPIRED
X-Speed-Cache-Key /node/4042

Please make sure you are using latest BOA stable
Make sure you have configured custom Speed Booster TTL properly (INI or code)
Note that default is just 10 seconds, so there is no way it can cause such issues
Disable Purge+Expire modules, unless you are forcing long TTL
Check the docs at: https://omega8.cc/node/108 for working code examples
Make sure it is not some other caching layer (Views?) which adds confusion

I hope this helps.


How can I get the order ID from Commerce (using Rules)? I need to call a function upon successful completion of an order, and that function needs to know the OrderID that called it.

I have setup a rule

Event:
"Completing the checkout process"

Conditions:
None

Actions:
[custom function]

I am aware of two possible ways pass the order_id.

Using a data selector (though I'm not exactly sure what this should be), and passing it through a 'value' argument -or-
Calling the function commerce_cart_order_id($uid) from within my function.

commerce_cart_order_id($uid) did not seem to return anything.

global $user;
$uid = $user->uid;
$order_id = commerce_cart_order_id($uid);
drupal_set_message(t('OrderID:  ' . $order_id), 'status');

Has anyone got any suggestions on what I might be doing wrong? Many thanks.

As you have mentioned, you want to act on completion of the order, so there is a hook of drupal_commerce, which get called on completion..

hook_commerce_checkout_complete($order)

I have used this hook for some action at the order completion in my custom module. If you call this hook in your custom module then $order variable will have all the information related to order. Check this in your custom module --

function MYMODULE_commerce_checkout_complete($order){
  dpm($order);
}


Upstream cache clear issues I'm running into issues with caching on my Drupal 7 site, where it seems that users are receiving stale pages, despite not having "cache pages" or "cache blocks" settings enabled. There is no additional server-side caching enabled. I've cleared the cache via drush cc all, as well as clearing the cache through the UI.

After clearing the cache, and with js aggregation enabled, I've pulled up pages where I receive an old version of the js. With aggregation turned off, I get the new js, as expected. Turn aggregation back on and pull up the page in an incognito window, and I get the old js.

However, even with aggregation turned off, I've also seen in our logs that we're getting "Page not found" messages for expired, aggregated js files. This indicates to me that users are getting served pages with references to these old files, though I'm open to other possibilities.

The headers for our homepage include Cache-Control: no-cache, must-revalidate and an Expires value in the past. The headers for our main.js file include Cache-Control: max-age=1209600, an ETag value, and an Expires value set to 2 weeks from now. I thought that by clearing Drupal caches, there would be an update to the ETag value that would force users to download an updated asset. Our hosting support has suggested that the settings on these assets may be impacting the upstream cache (I'm assuming they mean the cache on the homepage, for example).

So it seems like there is page caching that's happening on some level. Since I don't have server-side caching or page / block caching set through Drupal, it seems that the cache settings on the assets are impacting page cache.

Any input or thoughts on troubleshooting would be appreciated!

UPDATE: In paying more attention to the details of aggregated files and cache clearing, today after clearing the cache, I had an updated, aggregated CSS for a while, and non-aggregated JS with a cache-busting ?examplestring appended. In loading the site a few hours later, I'm being served the old aggregated CSS with the new non-aggregated JS. So it's got to be something wrong with how Drupal includes what it determines to be the newest version of the aggregated files.

I'm not familiar with the term "upstream caching / caches." I'm assuming it has something to do with edge caching... which I definitely suggest you look into; regardless of host service.  I've seen many odd occurrences because of edge caching.

Also try any of the following:

check file permissions for the ability for your web server to write the JS/CSS that it's generating.
Look in your sites/default/files or site/[site]/files directory for css and js subdirectories.  Check the permissions on those two AND delete the .css, .css.gz, .js, and .js.gz files in them.
truncate (with discretion - backup your database) all tables with a _cache at the end of them.


set referenced entity programmatically I have a view that displays a content type "offers" for a specific "task" (content type), the "task" content type has an entity reference field that reference an "offer". The view shows the title of the "offers" and in front of each title a button "Select this offer for your task"

I want that when I click the button "Select this offer for your task" set the value of the entity reference field I have in the "task" node, for reference the offer I have selected from the view

Is this possible?
Thanks for your help.

Because you are already using Views, consider using the Rules with Rules Link module.  This kind of setup could be done quite easily and even stored in a Feature so that the changes could be maintained in a git repository.


Drupal Views Search: Creating an Exposed Filter with Checkbox Options Using basic search module and Views to make a search interface.

When I create an exposed filter for a field with multiple options I only have the option to choose 'dropdown' or 'autocomplete' for the filter settings.

Is there a way to make the filter display the options to users with checkboxes rather than a dropdown menu?

Better Exposed Filters module should help you.


Security issues while using external javascript and php files to access mysql database in drupal nodes I have created a search_interface node which asks for filters and onClick event of the submit button, I have called an external search.js script. My search_interface node is of a custom content type Query(this content type has no extra fields other than the default fields created by a new content type)

This script uses getElementById() to get user input and send it to an external php script using POST method. This script uses mysqli_connect() to connect to my database and then does query on the required table(only 1 table is being queried everytime). The result of mysqli_query() is passed back to the search.js script using json_encode() and in the search.js script, I have parsed this jsonData and created a table string.  Then I have used my_table.innerHTML = "table string" to finally display the query on the drupal node.

Is this method secure?
Can some anonymous user access my .php script and get to know my
mysql admin password? ( I use admin password during mysqli_connect() )
Can my whole database be exposed easily even though I always query a
single table of the  database?
Can the .php file be edited to update or delete parts of my database
or the table in which I query every time?

Please help as I am new to drupal 6 and don't know much about security of php files and drupal nodes.

Doesn't look like any of the questions you have are directly related to Drupal. I highly suggest reading about PHP security concerns. This is a good resource to get started.

That said:

  Is this method secure?

Without looking at specific code, that is hard to say. Since you're running a database query based on user input, it's important you properly sanitize the input before running the query. I suggest using PDO instead of mysqli_* functions, since PDO is more widely used now and provides easy ways to use "prepared statements" to protect your database.

  Can some anonymous user access my .php script and get to know my mysql
  admin password? ( I use admin password during mysqli_connect() )

Not unless the .php script prints the password to the screen. Sounds like it accepts POST data and will return JSON output with data from the database. Make sure your POST data in sanitized before running a query.

  Can my whole database be exposed easily even though I always query a
  single table of the database?

See above

  Can the .php file be edited to update or delete parts of my database
  or the table in which I query every time?

Not unless a malicious user has access to your web server


Update some field values after user update own account On my Drupal 8 project, usernames are only allowed to be emails. For that, on account creation, I am setting the name field equal to the email field, and users don't have the permission to edit their own usernames.

I am writing the code to update the username when the users change email. This is the code I wrote so far.

/**
 * Implements HOOK_user_update().
 * Set Username = mail if mail has been updated by user.
 */
function hook_user_update($account) {
  $current_user = \Drupal\user\Entity\User::load($account->id());
  $original_email = $account->original->get('mail')->value;
  $updated_email = $current_user->get('mail')->value;

  if ($original_email != $updated_email) {
    $current_user->setUsername($updated_email);
    $current_user->save();
  }

}

Since the code is saving a user object, the same hook is invoked again when $current_user is saved. I also tried with hook_user_save() and hook_user_presave(), but they don't work until I include $current_user->save(); in the code.

Update:

Using hook_user_presave()

function custom_module_user_presave($account) {
  $current_user = \Drupal\user\Entity\User::load($account->id());
  $original_email = $account->original->get('mail')->value;
  $updated_email = $current_user->get('mail')->value;

  if ($original_email != $updated_email) {
    $current_user->setUsername($updated_email);
    \Drupal::messenger()->addMessage(t("if"));
  }
  else {
    \Drupal::messenger()->addMessage(t("else"));
  }

However, after updating the email and saving an existing user, I always get the message: else which means $original_email != $updated_email which is logic as the user has not been not saved yet.

any help please ?

Drupal core doesn't use any hook_ENTITY_TYPE_save() hook and hook_ENTITY_TYPE_update() is called after saving in the database an entity that has been updated.
As the documentation says, that hook implementations may not alter the stored entity data. They shouldn't call save() on the entity they receive as argument, or that will invoke those hook implementations once again; if then those hook implementations don't check if they have been already invoked (which is the case of most, if not all, the hook implementations) and save again the entity they received as argument, that would cause an infinite loop.

The only hook invoked before the entity is saved is hook_ENTITY_TYPE_presave(), which is invoked either when an entity is created or updated. It's easy to understand in which case the hook is invoked, since in the latter case $entity->original will contain the entity before the change.

As side note, the documentation reference to that hook as hook_ENTITY_TYPE_presave(); the implementation done from the mymodule module for the User entity is mymodule_user_presave(). (Replace ENTITY_TYPE with the entity type for which the hook should be invoked, such as user for the User entity and node for the Node entity.)

As for the used code, that is wrong since:

There isn't the need to load the account with \Drupal\user\Entity\User::load($account->id()) because the full User object is already passed to the hook as argument
Since the hook is invoked whenever a new user is created, or an existing user is updated, the code needs to first verify $account->original is defined
The code is setting the username for $current_user, but Drupal core is saving $account; since in PHP those are two different objects, the code isn't changing the username for the User object being saved
$original_email != $updated_email is not comparing the changed email with the original email, but it's comparing the email before the User object is edited with the original email (which is still the email before the User object is edited)

I would use the following code.

function custom_module_user_presave($account) {
  if (isset($account->original)) {
    $original_email = $account->original->get('mail')->value;
    $updated_email = $account->get('mail')->value;

    if ($original_email != $updated_email) {
      $account->setUsername($updated_email);
    }
  }
}

Even better, the code should check the value returned from $account->isNew().

function custom_module_user_presave($account) {
  if (!$account->isNew()) {
    $original_email = $account->original->get('mail')->value;
    $updated_email = $account->get('mail')->value;

    if ($original_email != $updated_email) {
      $account->setUsername($updated_email);
    }
  }
}


how can I remove registered .tpl.php file? When I remove html.tpl.php file, I get this error:

Warning: include(/home/xxxx/public_html/sites/all/themes/cgame/html.tpl.php) [function.include]: failed to open stream: No such file or directory in theme_render_template() (line 1413 of /home/xxxx/public_html/includes/theme.inc).
Warning: include() [function.include]: Failed opening '/home/xxxx/public_html/sites/all/themes/cgame/html.tpl.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in theme_render_template() (line 1413 of /home/xxxx/public_html/includes/theme.inc).

How can I remove this file to force drupal use core html.tpl.php file?

Simply clear the caches either on /admin/config/development/performance or via drush cc all if you've configured drush.


How to change the functionality of FILE_EXISTS_RENAME? I am using files_save_upload function to save the file. Here, I can use  FILE_EXISTS_RENAME this to rename the current file name if already this name existed. By default it rename by appending _indexes(0,1,2..). But I want to append some other things not the default one. So how can I achieve this? Thanks for any suggestions.

There's no way to do it without changing the core function file_create_filename. That could obviously have unwanted side-effects for other parts of the system, and make updating difficult.

If you have to do it differently for whatever reason, you should write your own function and use that instead. Once you see how much code you need to copy and maintain from file_save_upload and file_create_filename, though, you might think twice about whether it's worth it.


Integrate solr search with og group I search the method to implement apache solr search with og group and search on the content associated with group.

I want that the user can search the content of a specific group or for all group.

Thank

If you want to integrate SOLR with Organic groups,  you can use the Apache Solr Organic Groups Integration module but it is in dev mode.

Also, while searching, you can filter data, and alter queries as required.


improve workflow for multi-lingual site My client is having a terrible time managing multi-lingual content in drupal 7.  I'm using the internationalization module and drupal 7's default capabilities in managing multiple languages.  Here's an example workflow my client executes, with bold statements that indicate challenges.

Client begins to add new content of content type page.  He fills out title and selects language as English.
Client clicks on menu settings, and select Provide a menu link.  Under Parent item, client selects from the drop down tree About.
Client publishes the page.
Client clicks on Translate to translate the page.
Client clicks on add translation for French to see the add content page.
Client notices all the fields except menu settings is populated.  This irritates the client.   Client expects the CMS to know that the A Propos menu link is the french equivalent for About menu link, and to have populated accordingly.  But instead, client must go through hundreds of link.

Here's another example workflow that illustrates a big problem.

Client wants to re-structure the site map.
Client goes to an ENGLISH page in the CMS, goes to menu settings, and changes the Parent item to the Home menu link.
Client presses Save.
Client goes to FRENCH version of the same page.  Client needs to repeat the process of Parent item but find Accuiel menu link.  This irritates the client because client expects the CMS to be smart enough to know Accuiel menu link is the french version of Home menu link, and when the English page was moved from About to Home, then the French page should have moved from A Propos to Accuiel.

As it stands now, the client feels like he's managing two websites individually.  Can anyone suggest a workflow that can reduce the client's workload by about half ?  Simply having drupal reflect site map changes in english into french would reduce workload by about half.

As far as I can tell this is a problem, the menu items aren't connected so the only thing that links them is through the node they are connected to and their translation sets.

Another possibility, but I never used it like this, is to make the menu items translatable and there's a module inside i18n that redirect links to the right language.


How to use current Workflow state as a Panels selection rule How can I use a nodes current Workflow state as a selection rule in the Panels Page Manager UI?

It does not seem to be available under "Selection rules."

I added a new select list field that would update to match the current workflow state each time the workflow changed.  I was able to use this field in panels and could accomplish what I needed.

It's not perfect, but it works.


Forms : How to add elements on the client without a (ajax) round trip to the server I have been playing with the ajax examples from the examples module http://drupalexamples.info/examples/ajax_example/add_more

What i'd like to do is have elements added to the form without requiring a round trip to the server. I guess drupal requires this to rebuild the form with the new elements. But is it possible to do this without calling back drupal ?

Short of building your form with a huge amount of fields, hiding them, and then showing them dependent on the user's action, no you can't.


How to debug missing default value of managed file? I have a form with images. It also contains title and alt for 3 languages, so when I select them in one query, I get the same managed file fid 3 times. But that's not the problem.

Relevant part of code is:

kpr($image_has_language);
$first_language = reset($image_has_language);
$form['image'][$i] = array (
   '#type' => 'fieldset',
   '#collapsible' => FALSE,
   'ImageFile' => array(
     '#type' => 'managed_file',
     '#default_value' => (integer)$first_language['ImageFile'],
     '#title' => t("Image"),
     '#title_display' => 'invisible',
     // '#description' => t('Allowed extensions: gif png jpg jpeg.'),
     '#upload_validators' => array(
       'file_validate_extensions' => array('gif png jpg jpeg'),
       'file_validate_size' => array(variable_get('something_image_size', 5 * 1024 * 1024)),
     ),
     '#upload_location' => 'public://something/image',
     '#theme' => 'preview_upload',
   ),
   'id_image' => array(
     '#type' => 'value',
     '#value' => $clone?'new':$first_language['idImage'],
   )
 );
 kpr($form['image'][$i]);

Below results of that kprs:

As you can see, all is perfectly well. File is on disk, file preview work, in database it is marked as permanent and as used.

When I call var_dump on $form_state['values']['image'][0] in validation function, without changing file on the form, I get:

  array(3) {
    ["ImageFile"]=>
    int(0)
    ["id_image"]=>
    string(3) "599"
  }

Values in $_POST are OK:

  ["image"]=>
  array(4) {
    [0]=>
    array(2) {
      ["ImageFile"]=>
      array(1) {
        ["fid"]=>
        string(4) "3696"
      }

If I change file, it works as expected:

  array(3) {
    ["ImageFile"]=>
    string(4) "3698"
    ["id_image"]=>
    string(3) "599"
  }

and in $_POST:

  ["image"]=>
  array(4) {
    [0]=>
    array(2) {
      ["ImageFile"]=>
      array(1) {
        ["fid"]=>
        string(4) "3698"
      }

How can I identify where my value gets removed? I also have another image on that form, single one (so without foreach), and it works OK.

First of all can you try to remove the fieldset to a different $form[] array key? Is it really necessary to make it nested like this?

I think if you want to know if the file is added or removed then you can check in the following way.

$total_image_count = $form_state['storage']['image_elements']; // The number of image uploaded elements; just as example.
for($i = 0; $i < $total_image_count; $i++) {
  if ($form_state['values']['image'][$i] != 0) {
    // File is not deleted.
  } elseif ($form_state['values']['image'][$i] == 0) {
    //File is deleted.
  }
}

However, check with this and let me know.


Using cache for twig variables in preprocess function I implement a menu on a region using a preprocess function to get a link with an anchor for each block of it with a title.
I made a preprocess function for region, in my theme, where I test the region machine name.

I first used the $variables['elements'][XXX]['#id'] to load each block, to find out if the label was set to be display. But I quickly discover that on my server, where the cache is on, the $variables['elements'] only contain an array of cached render.

I then modify my preprocess hook to use the key of the $variables['elements'], witch is finally the block key.

use Drupal\block\Entity\Block;

/**
 * Implements hook_preprocess_region().
 */
function MYTHEME_preprocess_region(&$variables) {
  if ($variables['region'] == 'one_page') {
    $blocs_menu = array();
    foreach ($variables['elements'] as $key => $values) {
      if (substr($key, 0, 1) == '#') {
        continue;
      }
      $bloc_object = Block::load($key);
      if (is_object($bloc_object)) {
        $bloc_settings = $bloc_object->get('settings');
        if ($bloc_settings['label_display']) {
          $blocs_menu[] = array(
              'id' => $key,
              'label' => $bloc_settings['label'],
          );
        }
      }
    }
    if (count($blocs_menu)) {
      $variables['region_menu'] = $blocs_menu;
    }
  }
}

And in my override file region--one-page.html.twig

{%- if region_menu -%}

{%- for menu in region_menu -%}

{{ menu['label'] }}

{%- endfor -%}

{%- endif -%}

Everything is working well, but I would like to improve the concept :

Be able to detect if the cache is activated on the project
Include in cache my 'region_menu' variable, and generate it only when cache have to be rebuild.

If I understand well, the twig template is also cached, then it is maybe just not really necessary to declare the menu if cache is ON ?

The thing is I'm really lost in the D8 cache API.
I think I have to deal with the cache tags, because I don't have a render to cache.

I would appreciate some help, I cannot find some good (and easy) examples on the documentation or in the core modules.

Regions are not cached on their own. What you build in a region template will be part of cached pages. If most pages you deliver are cached, this might be OK.

To optimize it build the menu in a block plugin and place the block at the top of the region. The block plugin can get the blocks from  BlockRepository::getVisibleBlocksPerRegion. Use the access cache metadata this method provides for the region, add cache tags for all block entities and the tag config:block_list, so that the menu block gets invalidated when the block layout is modified.


How to get grid items to align center in Bootstrap views? I'm using Bootstrap views Drupal 7.

Live site is over here to have a look at the code:

http://xuzo.com/testing/

When a 3 column grid gets minimized, the 3 items stack 2 on top and 1 on the bottom.

But the bottom one is left aligned.

How can I have them align in the center so I get a nice triangle?

This looks easy with css, but I can't get it to work, tried:

 margin: 0 auto;

And others but can't get it working for some reason...

If you can create div tag, you can use css as show below.

Example:

html:

.....

css:
.secLayerContainer { display: inline; float: left; width: 100% }
.secLayerContent { display: block; float: none; width: 200px; margin: 0px auto}

note: 200px also can change 20%. (your preference)


Clean urls working everywhere except my custom module I'm attempting to create a custom drupal module, but I can't get clean urls to work. Clean urls have been enabled and are working everywhere else on the site.

I can access my module page using "?q=" but if I remove that and try to access it with the clean url I get a "page not found" error.

I've tried clearing the cache and rebuilding the menus using devel. I've also tried disabling and re-enabling my module.

Here's the code I have in my .module file.

/**
 * @file
 * This example demonstrates how a module can display a page at a given URL.
 */

/**
 * Implements hook_menu().
 */
function page_example_menu() {
  $items['examples/page_example/simple'] = array(
    'title' => 'Simple - no arguments',
    'page callback' => 'page_example_simple',
    'access arguments' => array('access simple page'),
  );

  return $items;
}

/**
 * Constructs a simple example page.
 *
 * @return array
 *    The render array for the simple example page.
 */
function page_example_simple() {
  return array('#markup' => '<p>' . t('Simple page: The quick brown fox jumps over the lazy dog.') . '</p>');
}

Turns out the issue was in my company's custom configuration. Certain pages are routed via Drupal while others are handled by a legacy system. All I had to do was add my module's path to our config and everything works now.


How to show view item by trimming? I'm trying to show articles by trimming. So, first I tried it by managing the display of body field to trimmed from content type. After fail to get desired results I tried it with views module by adding a contextual filter Content: Body setting character limit to 200 but did nothing.

I would like to hear the answer from this module as I also have the contextual filter: Content: Has taxonomy term ID already in this view.

  Update:

I want to add a view of taxonomy terms where I have created a view with contextual filter previously to which taxonomy term name is linked in this view:

In which taxonomy term is there:

And I tried with  Trim this field to a maximum length too but couldn't success.

You wont get anywhere triiming in a contextual filter, you need to click on the field and use the rewrite results fieldset in your fields settings.

Simply enter a maximum length, and choose extras like an ellipsis "..." to text that is cut off.

You may also need to change the format to plain text. Or choose a trimmed format.


Wrap comment replies in a collapsible fieldset I found an article about wrapping all comments (http://scito.ch/content/wrap-comments-collapsible-fieldset), but I just want to wrap comment replies in a collapsible fieldset.

How do I achieve this?

Implement hook_form_alter() or hook_form_FORM_ID_alter() and add the collapsible fieldset to the form field.  For example:

function MODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
    //Create the fieldset
    $form['custom_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('My Collapsible Fieldset'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );

    //Move the field into the fieldset
    $form['custom_fieldset']['comment_body'] = $form['comment_body'];

    //Unset the original field
    unset($form['comment_body']);
}

You can set '#collapsed' => TRUE if you want the fieldset to be closed by default.

If you're looking for a Module based approach, you may want to look into the Field group project.

I'm not sure how well this module will get along with the Comment module though.  You may need to implement hook_form_alter() in a custom module or in your theme.


Users can choose image style on content type? I want to display image style list in particular content type. Users can choose their image style from the list provided.

Is it possible to achieve this?

Hopefully I've understood you properly; I think you're looking for the Formatter Field module:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.


New to Drupal and views, how do I change the order of my fields? How do I change the order of these fields? See the image.
I want to be able to change the output order of these fields.

In the View edit page, click the little cog icon in the top-right of the "Fields" pane, there's a rearrange option there.


Fatal error: Call to undefined function lock_initialize() I am getting this error on a Drupal 7 site on Ubuntu 12.10.  I downgraded PHP from 5.4 to 5.3, but am still getting it.

Does anyone recognize this error?

  Fatal error: Call to undefined function lock_initialize() in /home/buck/drupal/cms/includes/bootstrap.inc on line 2366

The function is called using code similar to the following, from Drupal.

  // Initialize the lock system.
  require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
  lock_initialize();

_drupal_bootstrap_variables() is the only Drupal function that calls lock_initialize().

That code could fail if the file whose name is contained in lock_inc doesn't exist, but in that case I would expect another warning/error message, or it doesn't contain a function called lock_initialize().

I would check if there is code that sets $conf['lock_inc'], and which value is used. I would also check if there is code calling variable_set('lock_inc', ...).


COOKIE['session_api_session'] not working in drupal 7 I have a simple module to use the flag module base on the session api.
This was working in drupal 6 (and another section working for logged in users), i changed the syntax for drupal 7 (remove db_results wrapper), and am getting some error i dont understand.

This is my code.

  $cookieid = $_COOKIE['session_api_session'];
  $sid = db_query('SELECT sid FROM {session_api}  WHERE session_id = "' . $cookieid . '"')->fetchField();

    // Returns a value only if the anonymous user has at least one bookmark
   $result = db_query('SELECT fid FROM {flag_content}  WHERE sid = ' . $sid . '' )->fetchField();

This is the error I get:

  Notice: Undefined index: session_api_session in
  flag_here_preprocess_html() (line 19 of
  /home/dev/drupal-7.x/sites/www.site.com/modules/flag_here/flag_here.module).

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  '' in 'where clause': SELECT sid FROM {session_api} WHERE session_id =
  "";

  Array ( ) in tmc_flag_here_preprocess_html() (line 20 of
  /home/dev/drupal-7.x/sites/www.site.com/modules/flag_here/tmc_flag_here.module).

All the data exist.

I really don't understand what is going on here.

I have a feeling it is something with $_COOKIEand the session_api_session, but I could be off.

Quoting value with " characters in MySQL is wrong. The MySQL string quote is '. The " character is the character used to quote table or columns names. With an empty value in $cookieid you have an SQL query searching session-id equals to a column named empty string, this is the

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where clause': SELECT sid FROM {session_api} WHERE session_id = "";

with 'foo' as session uid you would have a query searching for rows having session_id columns equals to value of "foo" column. It would also be wrong.

Use Drupal helpers to write queries. Field and value escapes will be the right ones for the right engine:

$sid = db_query(
  'SELECT sid FROM {session_api}  WHERE session_id = %my_sid',
   array('%my_sid' => $cookieid
)->fetchField();

Or even more D7 (untested but it's something like that):

 $query= db_select('session_api','s');
 $query->fields('s','sid');
 $query->conditions('sid',$cookieid,'=');
 $sid = $query->fetchField();

now the 1st error message says there is nothing in $_COOKIE['session_api_session']. So you should enclose your code in a:

if (array_key_exists('session_api_session',$_COOKIE)
 && !empty($_COOKIE['session_api_session'])) {
   ...
}

At least you will avoid the warnings and errors.

About session api usage I would certainly better use session api functions to retrieve the current id, something like session_api_get_sid():

/**
 * Return a Session API ID corresponding to the current session.
 * The session id is a created using the same method as Drupal core
 * as defined in includes/session.inc.
 * @param boolean create set this to FALSE if you don't want to create a session
 * cookie if it doesn't already exist.
 */
function session_api_get_sid($create = TRUE) {


Save a format for a node body How do I save the format used for a node body?

I am using the following code, but it doesn't work.

$article = Node::create(array('type' => 'article'));
$article->setTitle($node->title);
$article->set('body', "My body...");
$article->setPublished(TRUE);
$article->body->format = 'full_html';
$article->save();

How can I achieve this?

EDIT:

Fixed:

Right code:

$article = Node::create(array('type' => 'article'));
$article->setTitle($node->title);
$article->body->value = $node->body;
$article->body->format = 'full_html';
$article->setPublished(TRUE);
$article->save();

// $node is supposed to be previously defined node object.

$article = Node::create(array(
  'type'     => 'article',
  'langcode' => 'en,
  'title'    => $node->title->value,
  'body'     => ['value' => $node->body->value, 'format' => 'full_html'],
  'status'   => 1,
));
$article->save();

This is the code if in case, anyone wants it.


Unable to configure SMTP authentication support module In Drupal v7.36 & 7.37, after installed and enabled SMTP Authentication Support module, I still can't find the menu function under configuration/system to config this module for all related email setting.

Try to clear cache and go to the following path: admin/config/system/smtp or Home » Administration » Configuration » System » SMTP Authentication Support


Why isn't hook_node_access() invoked when a node is created? The following code doesn't work.
function mymodule_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
    $type = $node->getType();

  if ($type == 'application' && $op == 'create' && arg(3) != "" ) {
    print_r(arg(3));
    return AccessResult::neutral();
  }
  else {
    // ...
    return AccessResult::forbidden();
  }
}

Could you tell me what is wrong in the code?

As documented in hook_ENTITY_TYPE_access(), hook_node_access() is only invoked when the users try to view, update, or delete a node. The documentation doesn't make it explicit, but when an entity is created, the invoked hooks are hook_ENTITY_TYPE_create_access() and hook_entity_create_access().
With both hook_ENTITY_TYPE_access() and hook_ENTITY_TYPE_create_access(), a single hook implementation returning AccessResult::forbidden() is sufficient to block users from acting on the entity. If you are noticing users aren't allowed to take an action on an entity when you expect them to be able to take that action, that is one of the probably causes.
I assume the code shown in the question is part of the code inside the mymodule.module file, or that a module with that machine name is installed on the site. Differently, Drupal would not consider that function a hook, and it would not invoke it (which could be a reason to say it doesn't work).
As side note, arg() is implemented in Drupal 4.6.x, 4.7.x, 5.x, 6.x, and 7.x, but not 8.x.y, nor 9.x.y. (Click on Same name and namespace in other branches in the documentation page to see the list of Drupal versions for which that function is implemented.)

The code shown in the question should thrown an error about a call to a not existing function.


Quiz results/score are over 100 points I have a quiz with 5 questions of 10 points each one. When I score them, some exams save the result of the quiz with more than 100 points.

As you can see, I have an exam with 112 but if I open:

Look that the total score is 92% (but his score is 112).

In the other hand, the user with 100 scores is right.

So, as summary of this, I've got users with right total score but some of them have a wrong final score.

The module that I'm using is Quiz drupal.org/project/quiz version 7.x-5.0-alpha9.

Any idea?

Thanks!

Thanks everyone for your answer. Finally, I've achived to solve the problem. At first, this bug comes from last versions.

If you create in this module a Long Question which max score is 0, it creates an inconsistency because you cannot divide by 0.

Some months ago, I found a patch to solve it:

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

But it's incomplete, because the module save the scores of each question in database and then it updates the total score adding the score of each one.

So, the way to solve that is changing the next lines in the same file that the patch file (../question_types/long_answer/long_answer.module):

db_update('quiz_node_results_answer')
  ->fields(array(
     'points_awarded' => $points_awarded,
     'is_correct' => $is_correct,
))

to

db_update('quiz_node_results_answer')
  ->fields(array(
     'points_awarded' => $calculated_score,
     'is_correct' => $is_correct,
))

To note the change is the variable $points_awarded for the variable calculated in the patch: $calculated_score.

With these changes, the patch is complete and everything is working.


"public" not supported or disabled in libcurl error I'm learning how to create a custom JSON migration and referring to the migrate_json_example module, I see the following code in migrate_plus.migration.product.yml.

urls:
    - 'public://migrate_json_example/products.json'
  # An xpath-like selector corresponding to the items to be imported.
  item_selector: product

Can someone please tell me how to use that public:// part of the URL?
I understand it's a path to the JSON file, but it's a relative path. I don't know how public:// is handled and how Drupal knows where to look for the files.

Both modules are installed on the same site. However, when I try using the same public:// URL in my module, I get the following error.

  Error message: cURL error 1: Protocol "public" not supported or disabled in libcurl (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) at public://migrate_stuff/resources/people1.json.

public:// is the sites public file system path. You can change it by navigation to admin/config/media/file-system.
    There you can set the public file system path, the default path is sites/default/files.


Avoid new user notification on user_save I'm currently importing a whole bunch of users to a site programmically through user_save. How can I make sure that no registration mails are sent to the users?

// Create new user
$newUser = array(
    'name' => $member->name,
    'pass' => $member->password,
    'mail' => $email,
    'field_user_fullname' => array('und' => array(array('value' => $member->navn))),
    'status' => 1,
    );
user_save(null, $newUser);

I can't find a way to do that. user_save doesn't take such an argument. I believe you have two options.

Emulate the user_register_submit() call by passing your data in as a form instead, this is preferably done with drupal_form_submit(). It just so happens that the example deals with user-registration.
Just kill outgoing e-mails while you import your users.


Links in menu with domain name When I create a link in a menu containing localhost it doesn't naturally work from outside. When I create a link with my public IP address it doesn't work from inside. Can I use some Drupal variables for this purpose containing the site name?

If you are just trying to create links to pages within your Drupal site you can use relative paths and when Drupal renders the link it will show as a complete URL.  You only need to have the domain name in the path when you are linking to an external site (not the same domain)

Example, to link to the Site Configuration admin page:

Use admin/settings instead of http://localhost/admin/settings and it will still show up in your menu as a full URL.


Suppress certain content types from taxonomy term list display (D6) I'm trying to suppress certain content types (blogs) from displaying in the taxonomy term list. (taxonomy/term/*)

I realize that a specific content type can be turned off for a vocabulary but we have hundreds of nodes that have tags defined.

use a view for taxonomy/term/* (it is created by default, you just need to enable it) and set a filter for it to exclude the blog_post node types


Change notification to different languages I have a multilingual website which has English and Chinese as the languages. I use the admin account but i have made a translator account for my chinese colleagues to make translations. Now if i make any changes to the pages in English how can they automatically get notified that they need to update the translation for that specific page. Is there any automatic way to do this ?

I believe, the module, you need is Subscriptions

The docs say:

  "This module enables users to subscribe to be notified of changes to
  nodes"

It is actively maintained and was started in 2003.


Give flagged products in search API a higher search score? I have a product catalog running on Search API and Search API SOLR Search. Now I was hoping that when a customer flags a product (with the flag module), there would be a way to boost the search score of that particular product.
So that when it is flagged as favorite it will float to the top, but only for that specific user.

How to alter Search API search scores so flagged items will have a higher score?

You could have a view that shows flagged nodes by user and a view attachment for the index filtering out nodes that the user has flagged.


How to add jQuery.LocalScroll to Drupal 7? I'm trying to add smooth scrolling within a page. I did find out it could be done using jQuery.LocalScroll.

What I've done so far:
1. I use Zen subtheme, so into my .info file I put:

scripts[] = js/jquery.scrollTo.js
scripts[] = js/jquery.localscroll.js

2. I put jquery.scrollTo.js and jquery.localscroll.js into js folder of my theme.

Unfortunately scrolling does not work properly. I don't know much about jQuery and integrating it into Drupal. If someone is kind enough to guide me step by step how to make it work, I'll be very grateful.

When you view the source are the js files you added in the head? If not you'll need to clear your cache. Changes to theme .info files do not take effect until you clear your cache.

If it's a js error then it would be helpful to have some more details.


How do I link fields of a 'user content type' to the actual logged in user? I'm using the User Content Type module (Drupal 7) in order to store some fields for each user, such as "zip code."

Now, in this node_edit page, I made a variant for a Catalog node, for a specific role. (Let's say "salesman".)

How do I link the actual logged in user with their respective User node, to show and store the "zip code" field in the Catalog node?

In Drupal 7, the simplest way to associate fields with a specific user is via Admin => Configuration => People => Account settings => Manage fields.

Because of its simplicity, I recommend this approach as a starting point. If it's not flexible enough, consider the contributed Profile 2 module.


Drupal7 user reset password link not working Hi i have created a custom hook in my own themeplate

function mytheme_theme() {
  $items = array();

  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mytheme') . '/templates',
    'template' => 'user-reset',
    'preprocess functions' => array(
      'mytheme_preprocess_user_pass'
    ),
  );
  return $items;
}

function mytheme_preprocess_user_pass(&$vars) {
  $vars['intro_text'] = t('This is my super awesome reg form');
}

This is the code in user-reset.tpl.php

<?php print render($intro_text); ?>

  <?php print drupal_render_children($form) ?>

after the user register. an activation link will send to the user email
example: http://www.mysite.com/user/reset/98/1366527945/qr6sEqrJwpWjQ11sxQPpitIHosg3_-Iv1s08yrKlnYk

Problem is:

When user trying to click the link, the page give me an error "The page isn't redirecting properly"

is there anything i missed on my own theme?

cherrs

Not sure exactly what is wrong with your code (I will check it out in a min), but if the purpose is just to add some text to the password reset form, I would do it in one of these ways:

Add a custom block with the text you want to add and assign it to the user register page.
Add a custom module and use hook_form_alter to add custom markup. Like so:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_user_pass_alter(&$form, &$form_state) {
  $form['intro_text'] = array(
    '#markup' => '
' . t('This is my super awesome reg form') . '
',
    '#weight' => -10,
  );
}


Features, Drush and Drupal 6 I'm using drush on D6 websites and i would to create and manage my features via drush.So i patched the 1.2 version like in this post :

Then i get an error when i try to create a feature for content types : https://www.drupal.org/node/2283617

  $ drush @sitebl fe --d --destination="sites/all/modules/_features"  briselames_content_type  node:page_lycee
....
Unknown option: --destination

Have you any idea about this ?

thanks

EDIT1

when i try whithout quotes (or single quotes '') this give an error

$ drush @sitebl fe --d -destination=sites/all/modules/_features  briselames_content_type  node:page_lycee
PHP Warning:  Module 'curl' already loaded in Unknown on line 0
Bootstrap to phase 0. [0 sec, 3.81 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.03 sec, 4.01 MB] [bootstrap]
Loaded alias @sitebl from file /home/xxx/.drush/aliases.drushrc.php [0.16 sec, 4.02 MB]                                             [notice]
Cache SET cid: 6.6-dev-alias-path--e9a42ca79125c2d266c093da6a27d238 [0.25 sec, 4.02 MB]                                                             [debug]
Cache HIT cid: 6.6-dev-commandfiles-0-29f4f0296708390047a2c57582fb56a8 [0.27 sec, 4.03 MB]                                                          [debug]
Bootstrap to phase 0. [1.9 sec, 9.59 MB]                                                                                [bootstrap]
Bootstrap to phase 5. [1.94 sec, 9.59 MB]                                                                                [bootstrap]
The drush command 'fe briselames_content_type node:page_lycee' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache[error]
if you have installed new extensions. [1.94 sec, 9.59 MB]
The directory 1 does not contain a valid Drupal installation [1.94 sec, 9.59 MB]                                                                [error]

Try to specify the destination part of your drush command without the quotes, like so:

  --destination=sites/all/modules/_features

Curious to see if this helps ...

Updated answer, now related to the new error after "edit1" in the question: Try running the comment again, but now with this slightly corrected command (note the "--destination" instead of "-destination"), like so:

  $ drush @sitebl fe --d --destination=sites/all/modules/_features  briselames_content_type  node:page_lycee


How do I show an image using a relative or external url? Seems like a simple issue but can't find a simple solution.

Basically I have the feeds module populating a content type from another database which has relative URLS of images. ie. /images/image1.jpg

I'm storing this value in a text field type.

Is there a way to easily translate the output of this field into <img src="$value"> ?

Sure, assuming Drupal 7, you can create your own field formatter for this in a custom module:

/**
 * Implements hook_field_formatter_info().
 */
function YOURMODULE_field_formatter_info() {

  $info = array();

  $info['image_source_formatter'] = array(
    'label' => t('Image Source Formatter'),
    'description' => t('Display the image sourced in this field.'),
    'field types' => array('text'),
  );

  return $info;

}

/**
 * Implements hook_field_formatter_view().
 */
function YOURMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'image_source_formatter':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#theme' => 'image',
          '#path' => $item['safe_value'], // you can also set '#height', '#width', '#alt', '#title' and '#attributes' here as well, see theme_image() for more details
        );
      }
      break;

  }

  return $element;

}

Clear your caches to be on the safe side, and then you can use this new field formatter for this field, eg, you can go to the Manage Display in your Content Type and select this:

for the plain text field and instead of outputting the text, it will theme the text as the path to an image.

In this field, you can have sites/default/files/foo.jpg if you want and it will source it locally, or you can have http://www.example.com/foo/bar/baz.jpg and that'll work as well, as this will call theme('image', $variables) with the path set to the value of this field.

ADDITION:  The URL Formatter and Simple Field Formatter modules appear to do this for you if you don't want to create your own custom module.


Pick which fields to use for content I have content type = CD.
As there are many fields to describe each detail (artist, publisher, performers, band, producer etc.) i want somehow to give user option which field to pick.
Of course this works by default, but i would like some kind of checkboxes in block for example when adding node, so user picks only 3 of 15 if he wants, and then

If CD is compilation or you have many artist (Opera for example), user will proly use all fields, if CD is one man band he will use far less.

I hope i gave good explanation of what i want to acchive.

I'm not aware of a simple way to provide checkboxes of what fields you want to show for a node form.

You could probably use Conditional Fields to show 1 field type you create called desired_fields it simply has checkboxes for artist, publisher, performers, band, producer, as they check those boxes you could have a condition in Conditional Fields that Shows the field in the node form.

If you're comfortable coding you could probably have a custom form that gets the choices you want and then shows the form.

Both approaches will get complicated if you have required fields.


How to send auto email for new unapproved comments? How do I config to send auto email for new unapproved comments.

I enabled the comments module and anonymous user can create comments in some content types.

But, I want to receive in an specific email acount a notification for each new comment.

Any suggestion ?

using simple_comment_email_notification

and will send email notification to the site email configured at admin/config/system/site-information without any configuration

using rules

Rules module allows you  to
Add reaction rule by going to admin/config/workflow/rules/reactions/add

  React on event > After saving new comment

And add action

  system > send email

NOTE: rules is still in alpha stage at this time so some things might not work as expected if at all (above procedure has not been tested)


How do I change a widget's markup? I need to create another widget which acts exactly like a text field, but contains a button and link next to the element. What's the best way to accomplish this?

I thought of:

Copying the Text Module (with the Field Module) and looking for the HTML.
Downloading the Autocomplete module and editing its markup.

I haven't really seen where the HTML for widgets is. Is this even possible?

In Drupal 7, to implement a new widget, you need to implement the following hooks:

hook_field_widget_info()
hook_field_widget_form()
hook_field_widget_error()

hook_field_widget_info() returns information about the type of widget implemented, such as the fields supported from the widget and for which the widget can be used. An example of implementation is image_field_widget_info().

function image_field_widget_info() {
  return array(
    'image_image' => array(
      'label' => t('Image'),
      'field types' => array('image'),
      'settings' => array(
        'progress_indicator' => 'throbber',
        'preview_image_style' => 'thumbnail',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
        'default value' => FIELD_BEHAVIOR_NONE,
      ),
    ),
  );
}

hook_field_widget_form() is the hook that returns the form field(s) necessary to get values for the field, which is what in Drupal 7 is called widget.
The reason you don't find any HTML in a module implementing a widget is that a widget is made of one or more form fields, which are defined using a form API array. If you look at file_field_widget_form(), you will notice that it uses a managed_file form field, but it also uses a theme function, and a form field process function.

  $element_info = element_info('managed_file');
  $element += array(
    '#type' => 'managed_file',
    '#upload_location' => file_field_widget_uri($field, $instance),
    '#upload_validators' => file_field_widget_upload_validators($field, $instance),
    '#value_callback' => 'file_field_widget_value',
    '#process' => array_merge($element_info['#process'], array('file_field_widget_process')),
    '#progress_indicator' => $instance['widget']['settings']['progress_indicator'],
    // Allows this field to return an array instead of a single value.
    '#extended' => TRUE,
  );

  if ($field['cardinality'] == 1) {
    // Set the default value.
    $element['#default_value'] = !empty($items) ? $items[0] : $defaults;
    // If there's only one field, return it as delta 0.
    if (empty($element['#default_value']['fid'])) {
      $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
    }
    $elements = array($element);
  }

As I said, a widget is used to get the value associated with a field; when you need to show the value associated with a field, you need to create a formatter through hook_field_formatter_view(). See Field Formatter API for more information.


views to display list and related content on same page I have created a veiws block which displays all the taxonomy terms of a particular type.
This block is in left sidebar . Now what I want is ,"when i click on any of the term all nodes related to it should be shown on the same page in the content area " ( what normally happens is it shows all nodes listing correctly but not on the content area of same page but takes me to next page) . Can someone please help me with this and any good tutorials for views

I got it solved myself! What I did is:

Create a views page to display all contents having these taxonomy terms. This page has path "views-page".
Create a block view of those taxonomy terms, now while enabling this block the setting for pages tab is under Show block on specific pages --> select radio of "Only the listed pages" and the values for this should be :

  views-page
  views-page/*

This way when you select a term all related posts appear on the page and taxonomy block is also there.


How to delete a webform submission in a custom module? I want to delete a webform submission from a custom module that I've written. I'm using webform_submission_delete(123, 76). The error I receive is:

  Notice: Trying to get property of non-object in
  webform_submission_delete() (line 141 of
  /Applications/MAMP/htdocs/mercury/sites/all/modules/webform/includes/webform.submissions.inc).
  Warning: Invalid argument supplied for foreach() in
  webform_submission_delete() (line 141 of
  /Applications/MAMP/htdocs/mercury/sites/all/modules/webform/includes/webform.submissions.inc).
  Notice: Trying to get property of non-object in
  webform_submission_delete() (line 153 of
  /Applications/MAMP/htdocs/mercury/sites/all/modules/webform/includes/webform.submissions.inc).
  Notice: Trying to get property of non-object in
  webform_submission_delete() (line 157 of
  /Applications/MAMP/htdocs/mercury/sites/all/modules/webform/includes/webform.submissions.inc).

I'm a bit new to module development. Am I missing something?

If you are calling this webform_submission_delete() function, then both the first and second parameters must be objects. At least the first parameter is a node object. Most likely you are calling this using:

$nid = 12345;
webform_submission_delete($nid, $sid);

instead of doing

$node = node_load(12345);
webform_submission_delete($node, $sid);

and as a result causing PHP to complain.

If you have doubts on how to implement webform_submissions_delete(), I suggest you take a look at the various functions that implement it for an example.


How can I place an entity content field value in header markup? I need to put an image field url into the header meta tag (open graph image). The obvious ways to put things in the header are in html.html.twig, hook_preprocess_html, and hook_page_attachments. But in any of these, how do I access the content to be rendered in order to see what the image url is?

And this is complicated by the fact that the rendered entity is a commerce product, while the desired image field is on the product_variation entity, with drupal commerce rendering the desired variation using a query string and an EntityViewBulder::alterBuild.

This means I can't use e.g. $product = \Drupal::routeMatch()->getParameter('commerce_product') because we wouldn't know what variation is being shown.

Once the variation is to be had, it would be fine to get the delta 0 image from the image field on the variation.

The essence of the problem is how to move a value from the field template preprocess to the html theme preprocess. I did this by using a one-off static variable function, provided by a helper module:

/*
 * Generates a static variable in the scope of the page request
 * to set instantiate like
 *  $var = &p2p_helpers_ogimage_function(); $var = 'my value';
 *    to read the var,
 *   instantiate without.
 */
function &p2p_helpers_ogimage_function() {
  $var = &drupal_static(__FUNCTION__);
 if (!isset($var)) {
    // generate contents of static variable
    $var = NULL;
  }
  return $var;
}

Then I can do the rest in the THEME.theme file.

In the field template preprocess hook I can do this:

/**
 * Prepares variables for blazy.html.twig templates.
 */
function p2p_bootstrap_preprocess_blazy(&$variables) {
  $url = p2p_helpers_ogimage_function();
  if (!$url) {
    $url = &p2p_helpers_ogimage_function();
    $url = $variables['url'];
  }
  ...

This will fill check if the variable is already set, so it only sets it once for the first image in the field.

Then in hook_preprocess_html:

$url = p2p_helpers_ogimage_function();
if ($url) {
  $ogimage = [
    '#tag' => 'meta',
    '#attributes' => [
      'property' => 'og:image:secure_url',
      'content' => $url,
    ],
  ];

  $variables['page']['#attached']['html_head'][] = [$ogimage, 'og:image'];
}

Does anyone see any better way to do this?


Can I skip or bypass translation when creating a form #options elements? I know I must use t() function in Drupal, but my particular task involves a great number of values in Russian, for which I do not want to enter values as
    t('Moscow')
and then manually translate strings into Russian. There are tons of Russian names and I just want to use them directly. Is it possible?

When I try, my select element options just appear blank.

...
       $form['selected'] = array(
           '#type' => 'select',
           '#title' => t('Selected'),
           '#options' => array(
              0 => 'Чебоксары',
              1 => 'Москва',
           ),
...

Using t() is considered a good practice, but it is in no way required by Form API.

Your code should work all right. Be sure your code files are properly saved as UTF-8 and transferred using "binary" mode, to prevent misinterpretation of non-ASCII characters.


Unable to print form element I am not able to get form element qty twice. I have 2 line item IDs, but I am getting 1 instead of printing qty twice. Please help me out this. This is my code.

function mol_split_delivery_form($form, &$form_state, $order_id) {

$order = arg(1);
$line_item_idds = get_total_line_item_ids($order);

if (!empty($line_item_idds)) {
  $line_items = commerce_line_item_load_multiple($line_item_idds);

}
else {
  $line_items = array();
}

foreach ($line_items as $line_item_id => $line_item) {

$form = array();
$option_first = array(1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9');
$form['line_items'][$line_item_id]['quantity'] = array(
    '#title' => 'Qty',
    '#type' => 'select',
    '#options' => $option_first,
    '#default_value' =>  $line_item->quantity,
 );

 }
return $form;
}

Take the $form = array(); line out of the foreach loop. This is clearing the $form array every time it loops around. You don't want it to do that.

foreach ($line_items as $line_item_id => $line_item) {

   $option_first = array(1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9');

   $form['line_items'][$line_item_id]['quantity'] = array(
     '#title' => 'Qty',
     '#type' => 'select',
     '#options' => $option_first,
     '#default_value' =>  $line_item->quantity,
   );
}

Also, if $order_id is a argument, you should not need to call arg(1). Consider passing the commerce order object as an argument instead, using %commerce_order as a URL parameter. Drupal will load it and pass it for you (if this function is a menu item callback).


Why is Drupal deleting my images? I have images going mysteriously missing from my Drupal site, sometimes several all at once.  There are currently only two people who have access to edit these, myself and a manager in Corporate Communications.  She just alerted me to a half a dozen disappearing all at once, and claims she did not delete them.  I have no reason to doubt her word, and I know I did not delete them.  This started happening months ago, and I had thought I may have fixed it a couple of months ago by deselecting "Delete unused files" in the One-click Upload settings.  Apparently that did not fix the problem.

Why is Drupal eating my content?  How can I stop it?

I'm not familiar with the One-Click Upload module, but you might want to check the file_usage table after adding an image to see if it's recording a usage. If it's not recording a usage, it's being deleted because on cron run, Drupal automatically deletes files from file_managed that don't have a usage recorded in file_usage.

Drupal does not detect linking from entities other than the one(s) on which a usage was originally recorded. For example, if you added a link to an image in the markup of node 5, but the image was uploaded as an attachment on node 3, the image will disappear when node 3 is deleted, and node 5 will show a broken link.

If this is your problem, you could solve it by using the File Lock module to add file usages so they aren't deleted, or you could switch to the Media module, and apply this patch that has been committed to the latest dev (and that I personally wrote some tests for) to ensure that a usage is being recorded for files uploaded via WYSIWYG.


Does Drupal 7 Entity Translation Translate? I've gone through the process of setting up Entity Translation and get the option for Translation, (for example a basic page). When editing the node, I get the translate tab, but see nothing there that actually translates. It appears that the functionality is the ability for the user or admin to supply the translation, and Entity Translation provides the link to the proper content depending on the translation option(s) specified by the user or browser, or other language selecting trigger.

I was hoping for an actual translation of content. Does that happen, or can it happen?

Modules installed and/or enabled on 7 include:

Entity Translation
Title
Entity
i18n
Variable
Localization Update

You need to edit your fields and make them translatable.

EDIT:

Ah, misunderstanding. Entity translations provides a user interface that allows you to translate entities. It doesn't translate itself.

What you are looking for in that case is Translation Management Tools*. It integrates with content translation, entity translation and more and allows to send text to a translator and save the translation in the correct place. There is a large list of supported translators, including a simple export/import, translation agencies, a local translator and Microsoft Translator, which is a machine translator and probably what you are looking for.

It's goal is to facilitate the management of a multilingual site with overviews, bulk operations, configurable review processes and a flexible, extendable architecture. It is, however, a new and large project, currently only available as an alpha and not every subsystem is finished. Notably, Microsoft Translator is currently broken because they changed their API, see http://drupal.org/node/1574516.

*Disclaimer: I am the maintainer of that project.


Drupal - Save for Later using Workbench, conditional required fields I have a node set up with a few workbench states. The first state, "Draft", should be used to allow someone to save the node without any required fields. The second state, "Submitted", should make the required fields active.
Essentially, I'd like to use default required field behavior for all states except the first "Draft". Is this something I can do programmatically with a module?

Yes, this should be fairly easy to do with hook_form_<form-id>_alter():

<?php

function MODULENAME_form_page_node_form_alter(&$form, &$form_state) {
  $target_field = "FIELDNAME";
  $workbench_state_required = "draft";

  $form[$target_field]['#states'] = array(
    'required' => array(
      ':input[name="workbench_moderation_state_new"]' => array(
        '!value' => $workbench_state_required
      ),
    )
  );
}

Just replace MODULENAME with the name of your custom module, and FIELDNAME with the field in question to toggle required or not (you can print the $form array in this function to work out the exact field name if you like).

For more information on the Form States API, visit: api.drupal.org.


Sub selection in db_select selectQuery Possible Duplicate:
  Is it possible to join dynamic tables (subqueries) using db_select()?

I have this part of a query running in drupal with db_query.

LEFT JOIN (SELECT ogmk.gid, ogmk.etid, kompas.* FROM og_membership ogmk
        INNER JOIN node kompas ON kompas.nid=ogmk.etid AND kompas.type='kompas'
        INNER JOIN publication_date pd ON pd.nid=kompas.nid
        WHERE pd.published_at > :start AND pd.published_at < :end AND kompas.status = 1
        ) ogm_kompas
        ON ogm_kompas.gid=og.gid

The left join should give records if they are available. If not the fields will be null.

How can I transform this to the db_select method with a selectQuery, so I can use the theme function for sorting and paging?

Thanks in advance for your answer.

I just found out that you can add a db_select as a table into the left join. So the solution for this will be:

$subselect = db_select('og_membership', 'ogmk');
$subselect->join('node', 'kompas', "kompas.nid=ogmk.etid AND kompas.type='kompas'");
$subselect->join('publication_date', 'pd', 'pd.nid=kompas.nid');
$subselect->condition('pd.published_at', $end, '<');
$subselect->condition('pd.published_at', $start, '>');
$subselect->condition('kompas.status', 1, '=');
$subselect->fields('ogmk', array('gid', 'etid'));

$select->leftJoin($subselect, 'ogm_kompas', 'ogm_kompas.gid=og.gid');