Incorrect Time showing on frontend I have installed the Date Module and added a date field to one of my content types, the widget I'm using is Popup Calendar. The problem I'm facing is that when I choose a date it seems to get stored and displayed correctly in the administration, but at the frontend the date is shown with two hours added to it.

For example if I set the fields value to 2014-12-12 10:00:00 its displayed as 2014-12-12 12:00:00 when I'm visiting a frontend page.

Like some of the comments have pointed out this might be because the frontend is displaying a visitors local time, but still I don't get why the time differance is two hours, when the differance between Findland and Sweden is only one hour.

I guess this has do do with some Regional settings or similar.

Maybe try this:

// Example: Assume we have a node with nid 1 which contains a single
// language-neutral date field named field_date.
$node = node_load(1);
$date = $node->field_date[LANGUAGE_NONE][0];

// Create a date object.
$date_object = new DateObject($date['value'], new DateTimeZone($date['timezone_db']));
// Convert from the database time zone to the user's time zone.
$date_object->setTimezone(new DateTimeZone($date['timezone']));

// Example: Print a formatted date.
print date_format_date($date_object, 'custom', 'Y m d');

Source: Convert a date field to the correct time zone


When switching themes in blocks, theme stays the same I'm trying to add a block to a specific theme (garland), but no matter what theme I switch to, I'm always shown the admin theme.

If I only have a single theme (garland) enabled, I can access the blocks I need, but there has to be a reason for this.

Edit: Discovered that this is being caused by the module "RealName" I have no idea where to look for the culprit though. Any suggestions?

Edit2: Found this explanation, but no real fix. Suggestions?

Ended up using hefox's (from Drupal comments) fix

<?php
function realname_user($op, &$edit, &$account, $category = NULL) {
    global $theme;
  if (!$theme) return; // prevent realname from overiding theme on block pages
?>

I did add in my own code as a safeguard, in the if statement, the condition that we were on the blocks page.


How to use Oracle as a remote/local database for Drupal 7? Can anyone offer any advice about the viability of using Oracle(commercial) as a remote/local database for Drupal 7?

I need to determine if this will work and convince my employer without incurring huge costs in testing.

There is a stable Oracle database driver in Contrib: http://drupal.org/project/oracle

However, if you want to use Oracle for your main Drupal database, you will need to test each contrib module that you are planning to use for Oracle compatibility. Many still have MySQL specific SQL, even though the situation has improved a lot thanks to the new database abstraction layer.

Using the Oracle driver to access data from a secondary database for imports and so on should work fine, though.


What is correct selector for radios to determine if ANY radio is selected? Using #states to change form element visibility, I would like a 2nd element to be visible only if the 1st element is filled in. The first element is a pair of radio buttons, so I tried:

  '#states' => array('visible' => array(
  ':input[name="radio-id"]' => array('value' => '0', 'value' => '1'),
    ),),

However that doesn't work, the 2nd value condition clobbers the first, so the other element only appears if the 2nd radio ('1') is checked. So then I tried:

    :input[name="radio-id"]' => array('checked' => TRUE),

Nope, that doesn't work either.

What is the correct syntax to use for this, and which documentation page is it on? (drupal.org or other site?) I've looked and looked but can't find it.

Had same problem today. A slight modification of the negated value expression proposed on this comment: "Empty Radio Selection" on drupal_process_states() API page, did the trick for me!

'#states' => array(
   'visible' => array(
     ':input[name="radios-name"]' => array('!value' => false),
   ),
 ),

I just wanted the select list with the above #states entry to be invisible while no selection has still been made on my list of five radios (sharing name "radios-name").

Radios were also '#required' => true, in my case and all 5 individual radio-buttons have non-numeric string values. No #default_value is specified in my case either.

Disclaimer: I have only tested this on Chrome!


How to access fields from node template without render within node template, i am trying to print a content type field value. usually I see the render function used to print the field value in the template e.g. render($content['field_name']). how do i just print the field value?

$content['field_name'][$lang][0]['value'] doesnt work

You can do it like this:

$lang = field_language('node', $node, 'field_name'); // gets field language

print $node->field_name[$lang][0]['value']; // prints field


Drupal 8 CKEditor dynamic internal links plugin? In Drupal 8 CKEditor WYSIWYG editor when I create a link to an internal page I use this URL path which I type manually: /parent/child/pagename

I then found a few buttons that can be added to the CKEditor interface that allow you to search for existing pages and it autoatically creates these paths.

e.g. These seem to be the best options:

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

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

The problem I have is that it inserts the link into the HTML like so which is static:

test

When I then change that page name or location to someting else the link breaks.

What I'm looking for is a plugin that inserts dynamic links, similar to this concept using that the page node ID or whatever uniquie identifier Drupal uses never changes:

test

so no matter what the page name/path/url is it will always link to the same page.

I know there is the option of setting up page redirects for old URL alias though without going into detail why that is not a solution for me in my case please leave that suggestion aside I already know of that. :)

Thank you

I'm the maintainer for Linkit module.

Linkit 8.x-5.x is solving the problem you describe with static URL:s.

The new version is using data-attributes (UUID and some other values) that calculates the URL in "run time".
That solves the issue.

Remember to also enable the Linkit filter in your text format configuration.
Also, make sure that the data attributes are added to the HTML filter allowed values if you use that filter.


How to find the ID of a webform? I am working with webform module , I have added two different forms in my website.
I have customized the forms according to my convenience, as I have changed the css. These changes are reflected in the two forms.
Now i need to get the id of these forms so i can further customize one of them.
I have added this css code for form

.form-text,
.form-textarea {
   width: 100%;
}

Try the Get Form ID module:

  By hovering over any form you will see a contextual link
  available. By expanding the link you will see the form ID. Click
  on the link and you will see a modal window with copyable form id and
  hook_form_FORM_ID_alter() hook suggestion.

Step 1: hover over the form.

Step 2: expanding the contextual link.

Step 3: Click on the link and a new window will open with copyable form id and hook_form_FORM_ID_alter() hook suggestion


Drupal Commons: Active sub theme of Commons Origins is intermittently not working (base theme is showing) I have a staging site and a production site.  The production site does not currently have a DNS record and I currently have a hosts entry for it  (134.x.x.x subdomain.example.com).

I have a subtheme of Commons Origins theme called exampletheme.   Exampletheme works fine on the staging server (which has a DNS record and no hosts file entry); but, when I migrated it over to the production server, I can only sporadically get the subtheme to show.  Sometimes it reappears if I activate random themes (including commons origins), when I re-activate exampletheme, it will show for a while.   But, eventually it goes away and I am back to looking at Commons Origins theme.

Two other factors, while the problem is existing, a drush status shows that the current theme is exampletheme.  Also I have an error_log in commons_origins_preprocess_html and exampletheme_preprocess_html.  It shows that commons_origins_preprocess_html does fire , while exampletheme_preprocess_html does not.

In addition, I have made a copy of exampletheme with a different name, activated it and it has the same problems.

I have checked the permissions on the theme files and they are the same as the commons_origins theme.

Any insight into this issue would be appreciated.

Turns out the theme_registry... entries in the cache table were not getting cleared for some reason.  I ran the following in mysql prompt:

delete from cache where cid like 'theme_%';

It's been working fine for hours now


How do I create a php page that has access to the Drupal API? I would like to create a PHP page that executes Drupal API functions.

The page would be inside my Drupal 7 website, perhaps the theme directory, but I'm not sure where it should reside.

I would like this page to run a query to the database using the Drupal's database abstraction layer. Once the query is retrieved, I would like to run some other D7 API functions and finally print out a page.

The page should not be one of the default Drupal templates, but a new page, that simply has one single  within it.

How can I achieve this?

EDIT: The correct way to do this is to implement hook_menu() inside a module. I'm trying to do this, but my approach doesn't work. This is what I'm doing:

the profileBox.info file

name = PB
description = "Creates a callback to returnuid.tpl.php"
package = SDNN
core = 7.x
files[] = profileBox.module

the profileBox.module file is installed and has the following code:

function profileBox_menu() {
  $items['returnunid'] = array(
    'title'=>'Example'
    'description'=>'examples'
    'page callback' => 'profileBoxGetit',
    'access callback'=>TRUE,
  );

  return $items;
}

function profileBoxGetit() {
  $stringit = "the string output";

  return $stringit;
}

I created a returnuid.tpl.php file with some html code in it - just to test (not functional code)
I then pointed my browser to [root]/?q=returnuid
I expected to get the content of the $stringit variable, but I instead got an "access denied" error

This module actually messes up the Administration menu, which dissapears when the module is installed.

What am I doing wrong?

The correct way to "create a PHP page that executes Drupal API functions" is to create a module.

In that module, you implement hook_menu() which allows you to tell Drupal that it should call a given php function for a specific path, for example 'yourmodule/somepath'. Inside that, you can then execute whatever PHP and Drupal API functions which you want.

See http://drupal.org/node/1074360 for more information.


Why is cache_render very big? I am having a big problem with a newly created Drupal 8 site for a theater.

After going live we discovered that the cache_render table grown extremely big, and extremely fast. After one weekend, it was already over 30 GB which makes a backup of the database impossible.

After some analysis and google search, I have stumbled upon cache_render database table growing in size. They say it is wise to use a caching service such as Memcache but honestly, that does not really solve the problem at all.

I have set the Cache maximum age to 1 hour and the cache_render page STILL sets the expiration date to infinity! Why?

What causes Drupal to fill up the database this much?

System information

Drupal version: 8.1.0

Modules in use:

List item
color_field 8.x-2.0-rc1
contact_block 8.x-1.1
contact_storage 8.x-1.0-beta4
ds 8.x-2.3
embed 8.x-1.0-rc2
entity_embed 8.x-1.0-alpha1
entity_reference_revisions 8.x-1.0-rc6
field_group 8.x-1.0-rc4
file_entity 8.x-2.x-dev (2016-Apr-13)Aktuell  Ok
Google Analytics 8.x-2.0
google_map_field 8.x-1.1
imagemagick 8.x-1.0-alpha2
layout_plugin 8.x-1.0-alpha22
mailchimp 8.x-1.1
menu_link_attributes 8.x-1.0-beta1+5-dev (2016-Feb-23)
metatag 8.x-1.0-beta8
paragraphs 8.x-1.0-rc4
smtp 8.x-1.0-alpha0
token 8.x-1.0-alpha2
weight 8.x-3.0
yoast_seo 8.x-1.0-alpha2+2-dev (2016-Mai-20)

It seems like this could be related to particular blocks or other renderable objects on your site that may have many permutations. In one case, I saw 100,000+ rows for one particular views exposed filter block.

Since users were able to select many different options, the block was stored hundreds of times per page/URL in the cache_render table.

It's best to try to scan through the cid values of the table and see any patterns, e.g. with SELECT COUNT(*) FROM cache_render WHERE cid LIKE "%interesting_cid_here%";, to see if there are any major offenders.

Still trying to figure out the best way (besides periodically running drush cr) to fix this issue. For now, I opened up an issue in the Drupal Core issue queue: cache_render table becomes extremely large over time

See discussion around this issue in this Drupal Core issue: Make CACHE_PERMANENT configurable in the database cache — currently allows unlimited growth: cache DB tables of gigabytes!.


Export nodes inside Panels by their UUIDs through Features In D7, I have a panel page that uses several nodes as content. When I export the panel into a feature on my Dev using UUIDs and UUID Features, and import the feature into my Test environment, Drupal creates new nodes with the UUIDs as expected, but the Panel isn't updated to reference these new UUIDs and their respective new NIDs. Instead the Panel keeps referring to Dev's NIDs.

I've looked high and low for a solution to no avail. The closest I have come to a solution was:
https://www.drupal.org/node/827466
But it has been years and no update. Does anyone have any ideas/solutions? Thanks.

Try this module https://www.drupal.org/sandbox/danylevskyi/2399993
It will work fine, if you don't have reference fields in your node.


Is there any alternative to devel themer? I am using Theme developer module for theming. The module is pretty good, but still it is very buggy. Is there a less buggy alternative?

Not really.

Since Drupal 7.33 release there is now simple support for alternative template support and themeing function alternatives listing in Drupal (core) by adding a setting in settings.php.

  Added a "theme_hook_original" variable to templates and theme functions and an optional sitewide theme debug mode, to provide contextual information in the page's HTML to theme developers. The theme debug mode is based on the one used with Twig in Drupal 8 and can be accessed by setting the "theme_debug" variable to TRUE (API addition).

So in settings.php you set:

$conf['theme_debug'] = TRUE;

Then view the source of your page and you will see comments in your HTML as <!-- THEME DEBUG --> that list out function and template suggestions for the current Node.

Example Output for /admin/structure/views:

<!-- THEME DEBUG -->
<!-- CALL: theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--admin--structure--views.tpl.php
   * html--admin--structure.tpl.php
   * html--admin.tpl.php
   x html.tpl.php
-->
... lots of HTML ...
<!-- THEME DEBUG -->
<!-- CALL: theme('region') -->
<!-- FILE NAME SUGGESTIONS:
  * region--page-top.tpl.php
  x region.tpl.php
-->
<!-- THEME DEBUG -->
<!-- CALL: theme('toolbar') -->
<!-- BEGIN OUTPUT from 'modules/toolbar/toolbar.tpl.php' -->

This is a backport of Drupal 8 Twig helper functionality built into Drupal 8 (largely I guess because devel_theme has no Drupal 8 release).


Trying to make gallery with views in Drupal 7 I have made 2 content types one is called Series and the other is Pictures. I have made a field on Pictures that will reference to Series. Using views I made a tab menu page that will appear on only the Series content type. What I'm having trouble is having to show all the Pictures that is referenced to that series. How would I do this?

This question could use a bit of clarification.

  Using views I made a tab menu page that will appear on only the Series content type

What does the view currently display if not all the pictures associated to the series? Just every single pictures that exists in the database? Or doesn't display anything? If it displays every single picture existing, then you need to add a "Contextual filter" to the view, choose the field that you use to reference the series. And choose "Provide a default value" and choose "Content ID from URL" option.

For display I would use HTML List type of views, and use image presets (core) to display the thumbnails and use lightbox2 (contrib) module to display the large image.


How to access user account fields? When I look at $user like this

global $user
dpm($user);

I do not see the user account fields I added. How can I access them?

You need to use:

$account = user_load($user->uid);

Then, dump the $account object and you will see profile field.


What's the difference between web service (API) implementation with REST and routing? what are the real differences between these two methods of creating a webservice :

Routing + Controller (https://www.chapterthree.com/blog/custom-restful-api-drupal-8)
REST plugin (https://www.drupal.org/docs/8/api/restful-web-services-api/custom-rest-resources)

advantages/disadvantages of both?

I think we can create a restfull API with one as with the other, isn't it?

Thanks

actually to create a wbesrvice endpoitns  in Drupal 8 we need to activate  one of or both of this 2 modules :

JSON:API module (best one):

after the activation of this module you can
       access to all Drupal entities (user , node , taxonomy ) throw a dynamic endpoints that have this structure http://{host}/json_api/{entity_type}/{bundle}?Parameters, with the ability to fitter the result + built in pagination + sorting ex of endpoints :

/jsonapi/node/article : get a json contains all node article.
/jsonapi/node/article,sort=-created : get a json contains all node article and order them with e created field in DESC
order.article.
/jsonapi/taxojomy_term/article : get a json contains all taxnomy term category.

  understand the Drupal entity type first will be better :
  https://www.youtube.com/watch?v=FrSjwe8bh7I

  then use the  JSON:api using this videos :
  https://www.youtube.com/watch?v=--ZL3EAhnwc&list=PLZOQ_ZMpYrZsyO-3IstImK1okrpfAjuMZ

RESTful Web Services

Exposing Views using the RESTful Web Services module( Do you need an easy configuration from backoffice to set up and endpoint ?) https://www.youtube.com/watch?v=TMvNwRVJSEQ.
Creating a Custom REST Resources to expose data that can’t be exposed by the previous solution - when to use  this solution when none of the previous solution can expose this data (Does JSON:API  and View exposing can't expose this type of data ?)

note : the methos in this url https://www.chapterthree.com/blog/custom-restful-api-drupal-8 never use it because we get out of the context of drupal, and you waon't be able to use a hiddne power of Rest module ex  :l by default any custom rest endpoint will display i if rest ui (https://www.drupal.org/project/restui) module installed .


Disable the submission of a form I need to make a form read-only under certains conditions : what I did is to not add the $form['submit'] button.

This way I can't submit the form. But I wonder if it is enough ...

Do you know if I ca be 100% sure that nobody could find a way to submit the form ?

Thanks !

To make sure nobody submit the form create a custom validate function that always set error on form ,(using form_set_error).

In that validate function you have to check for the circunstnaces that makes the form available to submission or not.


Multiple URLs for same node anyone know how to create a URL alias and not redirect the user? I have a node with its alias set to /sign-up, but I also want it accessible via /caregiver/sign-up. I created a URL alias, but it seems to just do a redirect to /sign-up.

I checked the current redirects list and the only redirect for sign-up I am seeing as for an old page that redirects from /activate to /sign-up

Get the node id that have /sign-up as alias (lets say it's node/42)
Go to /admin/config/search/path/add
Fill the form as mentioned in the description :
Existing system path : /node/42
Path alias : /caregiver/sign-up
Save the form
you can now access the node with /caregiver/sign-up alias :)


multiple (two at least) user registration forms I have built a registration form with a few custom fields, works fine. Now I need to another registration form, but with a dozen or so more fields. Both need to force drupal into its user registration/validation process.

it has to be done this way, I cannot just redirect a user to register first then fill out a survey.

Alex

You can achieve this using Profile 2 and Profile2 Registration Path module.

Profile 2

  Multiple profile types may be created via the UI (e.g. a general
  profile + a customer profile), whereas the module provides separated
  permissions for those

Profile2 Registration Path

  This module enables administrators to set unique registration paths
  per Profile2 profile type


Conditional image style in Views How can I apply different image style to an image field in Views, based on the condition of some other field of the same content type? I need to print the image with some frame, if some field (checkbox) is true, and with other style if the field is false. Any ideas?

Thanks

Add the image field twice(!) to the fields list. Use the frame style on the first image and the no-frame style on the second. Exclude both fields from display and place them before the checkbox.

Next, rewrite the output of the checkbox field to use [field_image] if the checkbox is checked (normal rewrite) and [field_image_1] if it is not (no result behaviour, Treat 0 as empty).


How to add class to the options for type radio present under radios? function template_preprocess_bef_radios(&$variables) {
  $variables['children'] = Element::children($variables['element']);
  _bef_preprocess_nested_elements($variables);
    foreach($variables['element'] as $tid => $value) {
        if (is_numeric($tid) || $tid === 'All') {
            $value['#attributes']['class'][] = Html::cleanCssIdentifier($value['#title']);
        }
    }
 }

While trying the above does not add class to radio button under radios(which has multiple options)
How can I add class to the options ?

You are almost there just you should change $variables['element'][$tid]['#attributes']['class'] instead of $value['#attributes']['class'] try with:

/**
 * Implements hook_preprocess_HOOK().
 */
function template_preprocess_bef_radios(&$variables) {
  // No need to this two lines
//  $variables['children'] = Element::children($variables['element']);
//  _bef_preprocess_nested_elements($variables);
  foreach($variables['element'] as $tid => $value) {
    if (is_numeric($tid) || $tid === 'All') {
      $variables['element'][$tid]['#attributes']['class'][] = Html::cleanCssIdentifier($value['#title']);
    }
  }
}


How do I load a field of a product in a custom module? A customer want to have the possibility to use different discounts on products. I'm working with the price resolver and I'll give the possibility to manage different discounts with taxonomy terms. I added an entity reference field (field_discount) to the product.

I'm writing the module that should look which discount is given to the product and then calculate the price based on the discount.

How can I load the value of field_discount in my module?

I made now a lot of research and I tried many different things, but nothing worked.

Have you tried?

$product->get('field_discount')->entity


When does Drupal load variables from the database? I am writing a report module so that users can flag posts and write a description. This module has a block that shows the unwatched reports; every time this block is shown it gets the number of unread reports from a table.

Is it better to use the Drupal variable system to set the number of unread reports?
When does Drupal load the variables from the database? Does it load them when I call variable_get()?

If the values need to be continuously updated, then it is better not to use variable_get()/variable_set() for storing it. This is because every time variable_set() is called, it clears the cache containing the values of the variables, which means that the next time a page is required, the Drupal variables will be loaded from the database, and not from the cache, with consequent lose of performance.

In such case, it is better to count the number of unread reports when reading from the database table containing the report data. This means the database table should contain a unread field that is set to TRUE when the report has not been read.

The values of the Drupal variables are loaded from the database, or the cache, when Drupal is bootstraping; the called function is variable_init(), which first checks the cache, and loads the values from the database, if the cache is empty.

  if ($cached = cache_get('variables', 'cache')) {
    $variables = $cached->data;
  }
  else {
    $result = db_query('SELECT * FROM {variable}');
    while ($variable = db_fetch_object($result)) {
      $variables[$variable->name] = unserialize($variable->value);
    }
    cache_set('variables', $variables);
  }


Views- how can I hide one specific value of a series of checkboxes displayed in views? On my user profile, I am displaying a field that looks like this:

Choose your favorite fruits:

Apples
Strawberries
Bananas
Grapes
Click to enter your own

Using the Conditional Fields module, clicking "Click to enter your own" displays a text field where the user can input whatever they like.  This all works great.

However, if a user chooses "Apples", "Strawberries", and "Click to enter your own", when I display the user profile in views by adding the "favorite fruits" field, it looks like this:

Fruits I like: Apples, Strawberries, Click to enter your own

Needless to say this is very ugly and I want to hide "Click to enter your own"-- and that's all I want to do, hide that text.  Is there an easy way to do that?

EDIT: I'm attempting to find the values for my site for ($view->field['my-field-name']['my-field-value'].  Using print_r, it appears that the value I want to remove is: [field_purpose]['und'][0]['o']; "o" is the value of the checkbox for other in the field_purpose field.  However, when I use this code: ($view->field['field_purpose']['und'][0]['o'], I get this error: Fatal error: Cannot use object of type views_handler_field_field as array mymodule on line 325

Perhaps I have the value wrong?  When I use dpm instead of print_r (dpm($view->field['field_purpose']); I don't see the values of the checkboxes stored anywhere...

The dpm output is as follows:

You can remove it with jQuery. Find that element by the value and just do .remove().

Even though this is not the perfect solution, it needs least amount of time and you can use it in the short term.

[EDIT]

Check Views selective filters. They can limit the options only to the ones available in the results; all others will be hidden.


Get field definitions across bundles, including base fields In Drupal 8 there are two types of fields: "base fields" like node.uid, and user-defined fields like 'node.body'.

All of the field names for one entity type can be found with EntityFieldManagerInterface->getFieldMap(). However this only contains the field type (as string) and a list of bundles.

For the base fields like 'uid', there is EntityFieldManagerInterface->getbaseFieldDefinitions($entity_type_id). But this omits the user-defined fields.

For user-defined fields, there is EntityTypeManagerInterface->getStorage('field_storage_config')->load($entity_type_id . $field_name);. But this does not include base fields like 'node.uid'.

There is also EntityFieldManagerInterface->getFieldDefinitions($entity_type_id, $bundle_name). But this has to be called per bundle.

There is more in FieldTypePluginmanager, EntityAdapter, and EntityDataDefinition. The more I look, the more confusing and complex this entire architecture looks to me..

Background

I would like to show a select element where a user can choose a field.
Entity type is given, but bundle is not.
Options are filtered by various criteria. E.g. maybe I want to show all fields where the item type extends EntityReferenceItem, and the reference target type is 'node'.
For this I need to inspect the definition of each field.

All of this is for D8 version of https://drupal.org/project/renderkit.

The more I look, the more confusing and complex this entire architecture looks to me.

The architecture is actually very similar to 7.x, just renamed. 7.x had fields and field instances, 8.x has field storages (= 7.x fields) and fields. Base fields are exposed as both by default, while configurable fields have a separate entity type for each.

Field storages exist per entity type and fields per entity_type/bundle. (in 7.x, fields were global, otherwise it is the same).

To get all field storages of an entity type, you can use \Drupal\Core\Entity\EntityFieldManager::getFieldStorageDefinitions(). Note that a field storage has no label, only the field (and the label can be different per bundle), so you will need to consider all bundles anyway if you don't want to just show a machine name. token and views have helper functions for that, e.g. _token_field_label().

Another useful reference is how the entity selection plugin build the list of fields to sort by: \Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection::buildConfigurationForm()


Set blank vale as default for a select box using Drupal form API? I'm building a form in a module using the Drupal Form API (Drupal 6) and have it mostly working, however I have a few required fields but don't know how to set a blank or null first selection option so the user will be forced to select an option.  Here's an example of my code using my country select box:

$form['address']['country'] = array(
    '#type' => 'select',
    '#title' => 'Country of Residence',
    '#options' => get_country_form_array(),
    '#required' => true
);

Here's the get_country_form_array() function:

function get_country_form_array() {

    $countries = variable_get('form_countries');

    $output[0] = 'Select a Country';

    foreach ($countries as $country) {

        $output[$country[0]] = $country[1];

    }

    return $output;

}

How do I add a blank first option to force a selection by the user?

In Drupal 7, you could use the #empty_option property, for which the default value is "- Select -" for a required field, and "- None -" for an optional field. The property adds the additional label as per the following cases:

If #required is TRUE and there is no #default_value, an empty option is added to the select control to force the user to make an active choice.
If #empty_value or #empty_option is set and #required is FALSE (default), an empty option is added to the select control, allowing the user to choose nothing.
If none of #required, #empty_value, #empty_option, and #default_value are set, then no empty option is added to the select control. This leaves the control in a slightly illogical state, since all user agents automatically preselect the first available option. There's no way for the user to select nothing, and the user is also not forced to make an active decision.

The property is used only for "select" form fields.


Alternatives to themekey? I need to show my website with a "theme" when in header's requests is present a particular key/value.

In Drupal 7 I do this via themekey, but this module does not exist in Drupal 8.

Are there alternatives, or other ways to do this?

You can easily recreate your required feature by implementing a custom theme negotiator. This requires a little custom programming.

First, create an own module (in the following example, we'll call it mymodule). Within that module, create a mymodule.services.yml file, that lets Drupal know about your theme negotiator service:

services:
  mymodule.theme_negotiator:
    class: Drupal\mymodule\Theme\MyModuleThemeNegotiator
    arguments: ['@request_stack']
    tags:
      - { name: theme_negotiator, priority: 1000 }

The important parts here are the service tag theme_negotiator and a high enough priority, that ensures the negotiator will be called before any other negotiators. If you want to just change the default theme dynamically but let route specific theme negotiators still apply, use a priority < 0.

As you can see, we also mentioned your custom theme negotiator service class MyModuleThemeNegotiator located in the namespace Drupal\mymodule\Theme, and as argument the current request stack (as we can use it to get the request headers).

So let's create a folder src/Theme in your module and add a MyModuleThemeNegotiator.php like this:

namespace Drupal\mymodule\Theme;

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Theme\ThemeNegotiatorInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * My Custom Theme Negotiator.
 */
class MyModuleThemeNegotiator implements ThemeNegotiatorInterface {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a MyModuleThemeNegotiator object.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    // This method must return TRUE, if your headers
    // fulfill the desired requirements.
    if (
      $this->requestStack->getCurrentRequest()->headers->has('myheader')
      && $value = $this->requestStack->getCurrentRequest()->headers->get('myheader')
      && $value == 'myvalue'
    ) {
      return TRUE;
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function determineActiveTheme(RouteMatchInterface $route_match) {
    // This method returns the ID of the theme that shall be
    // used, if your theme negotiator applies.
    return 'mytheme';
  }
}

Alter the header/values to match your requirements, clear your caches, and your theme should be applied.


How to limit the quantity of a product to 1? Some stores sell products that can only be purchased once (for example, on iTunes, you can only buy a song for yourself once, or on Steam, you can only buy a game for yourself once).

So for products like this, how can I limit the quantity to 1 in Commerce?  (Users should never be able to order 2+ of any individual product of type myproducttype.)

There are some answers for doing this in Drupal 7:

Using rules to restrict anonymous users to quantity of 1
Limiting order quantity

Unfortunately, these solutions use Rules, which is still in alpha for D8.

So how can I programatically restrict the product quantity to 1 for a given product type?

For me, simply skipping to checkout does not address my desired workflow. I still want users to be able to shop around and use a cart.

But some of my products are subscriptions, for which it doesn't make any sense to have multiple. For this purpose, I'm using https://www.drupal.org/project/commerce_xquantity module.


How to display node image in page header for custom theme? I'm extending the Tweme theme (a Bootstrap subtheme) and I want the "banner_image" field on the node page to be displayed in the header.

The page.tpl.html template from Tweme has the markup for the header, but this doesn't work because (I believe...) that template doesn't have access to the $content variable:

print render($content['field_review_nationality']);

The node.tpl.html template does have access to $content, but the header isn't present in that template.

Where/how do I render my "banner_image" field?

You can find @var $node on page.tpl.php. you can display your field using this code.

<?php
if(isset($node->field_review_nationality) && !empty($node->field_review_nationality['und'][0]['uri'])) {
   <img src="<?php print file_create_url($node->field_review_nationality['und'][0]['uri']); ?>"/>
}
?>

If you have a style of the image then you can display using below code.

<?php print theme('image_style', array('path' => $node->field_review_nationality['und'][0]['uri'], 'style_name' => [STYLE NAME])); ?>


An AJAX autocomplete textfield in Drupal 7 doesn't work in Chrome An AJAX autocomplete textfield in Drupal 7 works in Firefox, but doesn't work in IE and Chrome. The following error appears:

An AJAX HTTP error occured. HTTP Result Code: 200 Debugging information follows.
Path: http://localhost/drupal/en/example/autocomplete
StatusText: OK
ResponseText: {"admin":"admin","alex":"alex","apple":"apple"}

function clubform_menu() {
  $items['example/autocomplete'] = array(
    'page callback' => '_module_name_autocomplete',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function _module_name_autocomplete($string) {
$matches = array();
$return = db_query("SELECT name FROM users where lower(name) like '".$string."%' LIMIT 10");
  // add matches to $matches
  foreach ($return as $row) {
    $matches[$row->name] = check_plain($row->name);
  }
  // return for JS
  drupal_json_output($matches);
}

...
        $form['editclub']['club_name'] = array(
          '#title' => t(''),
          '#type' => 'textfield',
          '#description' => t(''),
          '#autocomplete_path' => 'example/autocomplete',
          '#weight' =>15,
          '#size' => 30,
         );
...

The output in Firefox is the following:

I found out what causes AJAX error! When I turn on any module with UTF-8 encoding, it causes the error; when I change the encoding to ANSI or to UTF-8 without BOM, everything works. This encoding problem happened only in Google Chrome; in Firefox all encodings work well.


Composer package is updated, but core still asks to update I am using Drupal 8.5.5. On admin/modules/update I red the following message.

Bootstrap (Theme)
Bootstrap (Theme) 8.x-3.11 update to 8.x-3.12 (Release notes)

The composer.json contains the following text.

"require": {
    ...
    "drush/drush": "^9.3",
    "drupal/core": "~8.5.3",
    "drupal/bootstrap": "^3.12"
},

I then ran composer install and installed Bootstrap 8.x-3.12. When I run composer show drupal/bootstrap it outputs the following.

name     : drupal/bootstrap
descrip. : Built to use Bootstrap, a sleek, intuitive, and powerful front-
end framework for faster and easier web development.
keywords :
versions : * 3.12.0
type     : drupal-theme
license  : GNU General Public License v2.0 only (GPL-2.0) (OSI approved)
https://spdx.org/licenses/GPL-2.0.html#licenseText
source   : [git] https://git.drupal.org/project/bootstrap 8.x-3.12
dist     : [zip] https://ftp.drupal.org/files/projects/bootstrap-8.x-3.12.zip 8.x-3.12
names    : drupal/bootstrap

requires
drupal/core ~8.0

When I go back to admin/modules/update Drupal still says Bootstrap 8.x-3.11 is installed. I have ran drush updb and drush cr to no avail. I am confused as to why it is not running composer's version of Bootstrap.

Why?

EDIT:
When I run drush pm:list --package bootstrap the command line returns:

Bootstrap (bootstrap)  Enabled    8.x-3.11 . Yet composer's version is on 8.x-3.12.

CREDIT TO @CGMonroe

I had started since early stages of Drupal 8, so my themes folder was in

sites/default/theme/bootstrap
sites/default/theme/bootstrap_subtheme

but in composer.json, it updates in directory:

"installer-paths": {
  ...
  "themes/contrib/{$name}": ["type:drupal-theme"],

so what I needed to do was, move my /bootstrap_subtheme from sites/default/theme to theme/
you should end up with:

theme/contrib/bootstrap
theme/custom/bootstrap_subtheme

and here is the correct way of configuring a theme/subtheme: https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme


Having trouble making Views treat external content as nodes/entities I have created a module by customizing FlyViews module to fetch data from a third party API and render via a View. I have been successful in showing the data on a page but the data has merely one style, that is, fields. Now I want to render that content as nodes of a specific content type. That content type will be configured in the module's configuration page. Once I mention a content type, the content should be rendered as nodes of that type.

Even a hardcoded solution will work for me, but it would be nice if I could select the Show option (on Views configuration page) as Content, just as I can do for a regular View.

Edit

I have implemented the custom row plugin which is now visible in Views UI as Show option under Format. Selecting the option and saving shows the output from my plugin's render() method. This is as far as I could get without help. Any ideas how can I manipulate render() to actually render the external content as nodes/entities?

I would probably not go down the the road of using Views (or Ctools) plugins at all here. (And I'm a big fan as well as proponent of Ctools and it's plugin architecture.)

I would create a new entity type, or a dummy content type of a node, and then take over the loading of said entity/content type with hook_entity_load.

Why integrate with Views only, when you can integrate with Core instead, possibly even with less effort?


add site language to XML i'm trying to get a extra element in our XML that show the site langues where te customer is working in. However i can not get is to work....

Here is the code:

if ($submission->nid == 315) {
$destination['path'] = 'private://export/account/';
$destination['filename'] = 'request_password_' . $submission->sid . '.xml';
$wrapper = 'request_password';

// when content is supplied, generate XML file
if (isset($destination['path'], $destination['filename'], $wrapper)) {
$source = array();
$source['data'] = $submission->data;
$source['node'] = $node->webform['components'];

$xml = new XmlWebformGenerate();
$xml->setXmlHeader('1.0', 'utf-8');
$xml->setXmlWrapper($wrapper);
$xml->source = (new XmlSource($source))->getSource();

What this does is; create a XML from a webform.
When the user submit the webform then it will create a XML file with te field of the webform. However what i would like to add is a  tag that displays the language the user is viewing. however i cannot find a way to insert it to the XML, because it's already receiving the source from the node.

Could some one help me out with this? Many thanks! :)

You can get the current language through the global $language var:

$current_lang_code = $GLOBALS['language']->language;

With that in mind you just need to make whatever changes are necessary to your PHP classes (XmlWebformGenerate/XmlSource/etc), to add that data to the document.


Sum of integer vaules of a multi value field using Computed Field Module I have a field that is configured to have unlimited values.  (field_a)

How can i use Computed field to add all of the integer values of A?

A: 10, 5, 2

The computed field would then spit out 17

This code will add the last values of field_a and field_b together:

$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_calories'))) + array_pop(array_pop(field_get_items($entity_type, $entity, 'field_calories')));

I just need to add all the values of A together.  Anyone know how?

I don't have computed field installed anywhere so I can't test this, but the logic should be something along the lines of:

$field_items = field_get_items($entity_type, $entity, 'field_calories');

$total = 0;
foreach ($field_items as $item) {
  $total += $item['value'];
}

$entity_field[0]['value'] = $total;

Or if you absolutely need a one-liner:

$entity_field[0]['value'] = array_sum(array_map(function($a) { return $a['value']; }, field_get_items($entity_type, $entity, 'field_calories')));


Which other methods for building html content are out there? I am searching for opinions about the construction of static pages in Drupal.

Imagine this page as a PSD or PNG:
https://www.paypal.com/br/webapps/mpp/quanto-custa-empresa

It's a static page, but it's not just text, it has a somewhat rich layout. I don't think a regular node with WYSIWYG is the right way to do a page like this.

So, imagine you already have the template built, the side menu, the header, footer, etc, but you want more control over the content (middle) layout.

These are the ways I know for building this kind of "rich content":

Create the HTML page in a decent editor, then paste the HTML on the node body when you're finished.

Pros:

Practical for extremely simple pages

Cons:

Lose version control
If you do node-specific CSS, which is pretty much necessary for this kind of page, you might get into trouble if you can't maintain the node id between installations
Needs php input format in order to print images relatively
Requires back and forth from IDE every time something changes

Node-[id].tpl.php template

Pros:

Version control
Allows you to keep working on the IDE

Cons:

When doing node-specific CSS, which is pretty much necessary for this kind of page, you might get into trouble if you don't have a way to maintain the node id between installations
Same thing for the whole page. It will go blank if you don't keep track of the node ID.

hook_menu + hook_theme invoking a custom template for the wanted path

Pros:

Version control
Allows you to keep working on the IDE

Cons:

Requires custom module and a little more effort
Does not provide caching by default like a node does (performance hit wouldn't be that great for this, however)
You lose some node juicy stuff (can't remember an example right now)

So, are there any methods people are using I'm not aware of?
Maybe with panels? Context? Please let me know!

If this is a one off landing page, I'd go with option 1.

I would never do 2 because I also deal with different installs (dev/stage/prod) and that would break on me.

For option 3 I usually use a different flag in the data other than URL, but I've occasionally used this method. Usually I have a 'Use Template' field that points at a taxonomy, and I can make various theming decisions off of that (including but not limited to the tpl I use)

If this is a layout you think you'll see again, I'd use Panels. Especially if you want this to be editable by people who don't know code.

You can specify very generic to very complex layouts. You basically specify a layout in a tpl file with regions that can get content added to them. The content can be nodes, blocks, views whatevs.

It has a bit of a learning curve on the dev and the content editor side, but it's pretty good.

With your node specific CSS, I would recommend adding a "Custom CSS" field to content types that are going to have special layouts. You could do this to what I call a "Custom Page" content type which I use to simply paste in HTML, or add it to Panel Nodes or other customizable node types.

In the theme you'll need to hide($content['field_custom_css']); in the node preprocessor and then retrieve the value of the field and run drupal_add_css() on the sucker.

You can use file field to allow people to upload CSS, or what I do is specify the URL of the file so I can just re-up the file while I'm working with FTP and don't have to re-up through the drupal interface every time I have a change.

By default drupal_add_css doesn't let you add CSS files that aren't on your domain so if you make the user specify a URL (meaning they'd have to have FTP access to get something in there) it's a fairly secure implementation.

Pretty sure there's a way to allow css that's not on your domain, but you'd want to make sure that nefarious parties aren't able to do damage with that field if you decide to go that route.

Custom CSS has been HUGE in doing one off pages like this for all of the promotional pages my group does at work.

Hope that helps!


PDOException : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'registration Using: commerce+entity registration+commerce registration

During the checkout sequence, after completing the registration step, I get this fatal error:

  PDOException : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'registration-144-0-0-und' for key 'PRIMARY': INSERT INTO {field_data_field_nom} (entity_type, entity_id, revision_id, bundle, delta, language, field_nom_value, field_nom_format) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => registration [:db_insert_placeholder_1] => 144 [:db_insert_placeholder_2] => 144 [:db_insert_placeholder_3] => formulaire_inscription [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => dfgh [:db_insert_placeholder_7] => ) in field_sql_storage_field_storage_write() (line 514 in /home//public_html///modules/field/modules/field_sql_storage/field_sql_storage.module).

I have tried to disable some rules that could be problematic, to disable multilanguage (entity registration have some problem whit multilang)... nothing.

What can be the cause of this error?

Thx

If anyone stumble on this error again, note that it is due to corruption in the database. In this case, the registration tables got corrupted at some point.

Just unninstall everything registration related, and start anew.

Thx.


How to hide not translated menu items I have a multilanguage site. Now i'm running in the issue that some pages don't have translations. So i would like to hide that from the navigation.

I already tried to manipulate it with that hook:

mytheme_preprocess_menu_local_task

But it seems that it does not have an affect. I also don't find any other hook which i could use for that.

Any suggestion?

Use hook_node_access() to deny access to the not translated nodes and this will automatically hide the corresponding menu items:

mymodule.module:

use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;

  /**
   * Implements hook_node_access().
   */
  function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
    $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
    if (!$node->hasTranslation($langcode)) {
      $access = AccessResult::forbidden();
    }
    else {
      $access = AccessResult::neutral();
    }
    $access->addCacheableDependency($node);
    return $access;
  }

You can be more specific, hide not translated nodes of specific content types. Or for specific user roles, which you probably need to do if other users than the admin wants to edit the nodes. Or you have to be specific about the operation $op. And test this with different user roles, as admin you won't see a difference, because this account passes all access checks.


Is Drupal ready for GDPR compliance? Is Drupal is ready for GDPR compliance?

Is there any patch or extension they need to apply for GDPR ready for all EU countries as this is the law for EU countries the come in effect on may 25, 2018.

I'm one of the maintainers of the GDPR module.

First of all I'd like to call your attention to the fact that GDPR is not an IT-related question solely. Personally I'd suggest stop considering "adding an extension to my CMS will make me legally good". That's not that easy. You, or the owner of the Drupal website you maintain/develop on their behalf should transform their organization/company's inner workflow of dealing with personal data.

However, the GDPR module indeed can be a perfect starting point to install, go through on its checklist points and after you read them carefully, hopefully will realize that you're just stepped on the path of becoming GDPR-compliant, but a big portion of tasks ahead probably falls out of the scope of configuring Drupal.


Showing all Sibling nodes that share the same Taxonomy term in Drupal 7 I made a Taxonomy named Category which has terms as following:-

Term 1
Term 2
Term 3
Term 4

As a requirement, any node that I create has to select one term mentioned above.

Now, what I wanna do is; that when I visit any node page, it should show me all the node titles that share the common term.

As an example, if I selected Term 2 as a category when creating following nodes:-

Node 1
Node 2
Node 3
Node 4
Node 5
Node 6

I want the list of all these nodes when I visit any of these nodes.

My URL, when I visit any of these nodes is:-

http://www.mysite.com/term_name/node_name

Thanks.

P.S.

I tried Views arg parent term within a view and followed instructions here (https://www.drupal.org/project/views_arg_parent_term), but it seems it works with a Taxonomy Term ID and I guess my URL has Taxonomy Name in it.

Any help would be highly appreciated.

Best.

Try to add validator when filter value is AVAILABLE or Default is provided:


Possible to use default user picture in rewritten views field? I have a view which displays fields and one of them is a rewritten field to display the user picture along with some other information. There is no issue if the user picture is uploaded, but if the user does not, this field does not show the default user picture. Is there anything I need to do to allow the default user image to display in this rewritten views field?

I tried unchecking the hide field if empty option under no results behaviour, but realised that since I already rewrote the field, this does not seem to apply, because my rewrite renders other fields that always have values in them.

You can use no result behavior option to show the default picture for the user's image.

Here is my screenshot :

If you want to combine two fields then you have to take two field firstly in view fields and shown their output in diffrent-2 field after that you can combine both fields in new field using rewrite option. The first two field output is hidden who's value you want to combine.


Purging session data on devel user switch If you have used the devel module, you'd probably know about the nifty Switch user tool that is available as a block for use in a site. It allows users with the required permission to switch from the block as any other user.

This is the API doc for the devel_switch_user method.

I notice that while switching between users, the session ID of the user as whom you initially logged in to the Drupal site for the first time is re-used for all switched users i.e. In {sessions}, the uid column is simply changed while {sessions}.sid or {sessions}.ssid persists.

A problem with this approach is that the session data ({sessions}.data) (saved using the $_SESSION superglobal) remains the same even for switched users which isn't good to test the application logic sometimes (at least not in my case).

Is there an elegant way to clear the session data of the old user on switch? If not, how can this be solved?

Problem is - $_SESSION was never really meant as temporary data storage. Proper and safe way is to use cache_set() to store data.

First argument, $cid is customary used as a string with sections separated with :, so in your case it should look about like that:

global $user;
// ...
cache_set('mymodule:' . $user->uid . ':' . $user->sid . ':kind_of_data',
          $data, 'cache', CACHE_TEMPORARY);
// ...
$data = cache_get('mymodule:' . $user->uid . ':' . $user->sid . ':kind_of_data',
                  'cache');

That way you will allow Drupal to benefit from database permanency, memcached speed, whatever you please. And by including uid of current user, you are sure data is well separated and no collisions will occur. Including session ID allows proper anonymous user handling. For logged in part $user->sid might be safe to ignore, depends if you want data to be shared between logged in seats or not.

If you use session id as a part of cache key, like above, entries will be only valid for one session. If your site has few users, obsolete cache entries are not a problem. And if you have many, you should store both sessions and cache in memcached, apc or similar technology anyway. Database is simply to slow for this. Memory based cache engines are very good at automatically destroying unused entries when needed, destroying them from code is a waste of time and effort.


How to have a secure HTTPS login form? I have Drupal site with a login form on my home page.

How do I go about posting to a HTTPS url, and then after a successful authentication, redirect back to HTTP admin page?

Given the way things are heading on the internet now, and Google making statements about weighing HTTPS sites higher than HTTP in the past couple of months, you might as well make it totally HTTPS.

You don't want to log in on HTTPS then redirect back to HTTP, you'll have issues with people being logged in and out intermittently. People have tried to address this issue over the years, but I don't think it has ever been solved.

I would set HTTPS always on and handle it in .htaccess, redirecting any non HTTPS traffic to HTTP. (to clarify, you do not need a module to do any of this - just follow the instructions in .htaccess and work with your hosting provider to provide an SSL cert).


How to get the count of referenced entity (by views entityreference result)? For example, a student can register a class. The class node has a date field indicating whether the class is active for registering. The registration node has an entityreference field referencing to the class node. I get the referencing class nodes by using "Views: Filter by an entity reference view" option. This view has a filter of "current date is between the start and the end date". Now, if the count of the reference view result rows is 0, the student should be redirected from the node/add/registration page to an explanation page which tells students there is currently no active classes for registering.
On the module entityreference_count page, it says,

  Currently this module only works with entityreference fields
  configured to use the "Simple (with optional filter by bundle)"
  option. It does not work with the "Views: Filter by an entity
  reference view" option. This may be addressed in a future release.

How can I make it?

Entity Reference Count

  This Entity Reference Count is in-and-of itself, just another field
  type (called "entityreference_count" in the code) that may be attached
  to any Drupal entity. The field may be configured to select which
  referencing entity types and fields you want to aggregate in the
  count. The counter field is automatically re-calculated when the
  referencing or referenced entity get inserted, updated or deleted. The
  Entity Reference Count's numeric field value may be enabled, displayed
  and manipulated via view modes, through the "Manage Fields" interface
  provided by Drupal core's Field UI, and has built-in Views
  integration.

OR

Make sure Child has an entity reference to Parent.
Create a new view
In Filter Criteria, add a new Type (= Parent)
In Advanced>Other, set Aggregation to YES
In Advanced>Relationships, add a new relationship
for "A bridge to the Content entity that is referencing Content via
field_parent" where field_parent is your entity reference. Call this
"Parents"
In Fields, add Content: Title and when prompted set its
Aggregation type to Group results together
In Fields, add Field:
Parents and when prompted set its Aggregation type to COUNT
(Distinct)


Compile LESS files to CSS How can i preprocessor or compile at runtime the LESS files in the latest version of Drupal 8?

I am using the LESS starterkit theme of Bootstrap. The Less CSS Preprocessor is currently not ported to Drupal 8.

The next two guides says that i need NodeJS and the less package to compile it, but it is not at the runtime of Drupal:

lessc less/style.less > css/style.css

Creating a Bootstrap subtheme for Drupal 8
How to build your Drupal 8 theme using Bootstrap & Less

If you don't want to wait for the port of the Less CSS Preprocessor module to run the less compiler at run time, you can execute the command line tool from settings.php

exec('lessc themes/mytheme/less/style.less themes/mytheme/css/style.css > /tmp/less-debug 2>&1');

This is only for development, remove this from the production settings.php.


Drupal custom coding checkout redirect not working I have used custom coding to add a product into a cart.

 $items['buynow/%'] = array(
    'title' => t('buynow'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_module_my_form3',1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
function custom_module_my_form3($form, &$form_state,$id) {
global $user;
$product_id=$id;
$product = commerce_product_load($product_id);
$quantity=1;
$line_item = commerce_product_line_item_new($product, $quantity);
$line_item_added = commerce_cart_product_add($user->uid, $line_item);
$order_id=$line_item_added->order_id;
drupal_goto('checkout/'.$order_id);
}

Product added succesfully in the cart but redirecting into checkout page doesn't work.It redirecting into home page.

I have created link for each product like buynow/product_id. I have also created a custom menu path like buynow/%.

After that put the above code in the callback by passing argument.

Your fault is want using drupal_goto in form builder!!!

Change your code to this

 $items['buynow/%'] = array(
    'title' => t('buynow'),
    'page callback' => 'custom_module_my_form3',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

function custom_module_my_form3() {
   global $user;
   $id=arg(1);
   $product_id=$id;
   $product = commerce_product_load($product_id);
   $quantity=1;
   $line_item = commerce_product_line_item_new($product, $quantity);
   $line_item_added = commerce_cart_product_add($user->uid, $line_item);
   $order_id=$line_item_added->order_id;
   drupal_goto('checkout/'.$order_id);
}


How can I add a custom price to a cart as an attribute of product type in Drupal Commerce? How can I add custom price to cart as an attribute of product type in Drupal Commerce?

In detail am creating a custom tshirt design UI where user have the options to design a tshirt(add image,text etc) and add to cart. I have loaded all the products in the site to the UI and user have the option to add  product to cart after designing. User is charged with an extra amount for designing like adding each images to tshirt which increases the base price of tshirt. But my issue is that the products get added to cart with the base price. I have used the folowing code to add the product to cart.

commerce_cart_product_add_by_id($pid, $quan, $combine = TRUE, $uid);

When I searched and found that there is no way to add the custom price as parameter of the above function so that the altered price gets added to cart. But found another solution that it can be done by adding as an attribute of the product.

How can I  map the custom price I have created as an attribute of the product and add to cart for altering the price section?

Below these modules will help you with bit of customization or addons

Commerce Product Attributes

  This module provides some enhancements to the Drupal Commerce
  attribute handling.

Commerce Product Option

  This module allows you to add user-customizable options to the
  commerce "add to cart" form. You do this by defining "option sets", to
  which you can attach any field of your choosing. These option sets can
  then be added to your commerce products using entity reference, after
  which the fields in your option set will show up in the add to cart
  form.

Commerce Pricing Attributes

  This module provides some enhancements to the Commerce Product Option
  and Commerce Product Attributes handling by applying pricing rules to
  custom product attributes. So, you can add attributes to products that
  affect the final product price.


Displaying content from an entity reference in a view I have a node type, Medical Group, that has an entity reference field (field_accreditation) to another node type, Accreditation.

I would like to create a block to display on each Medical Group page that displays the Accreditation for that particular Medical Group.

I also need to provide a default value when the block is placed on a page that does not have an Accreditation field.

I've tried adding a relationship and then using that as a contextual filter, but that doesn't seem to work. Any advice or steps to go about this?

Remove current contextual filter and relationship
In contextual filter add nid.
In its configuration select raw value from URL, then select argument number which is your nid form url
Now you can also set default value in this configuration
In block display setting show your block on your content type.


Is it possible to give users different roles/profiles on different part of the website? For example, is it possible to give userA full read/write access on some part but read-only access on others?

Most importantly, is this possible without too much hassle? I mean what I'm  looking for is some sort of "inheritance", i.e.  if I give userA full read/write access on nodeA, I'd like those exact same rights are granted to userA on every child node of nodeA, recursively.

I've seen Flexi Access but this module does not seem to satisfy my "inheritance" constraint.

A widely accepted solution for this would be using the Organic Groups module.

With this module, you can define different access settings and local roles for a given group type, and for all the nodes associated to it (this would be the "inheritance" you are looking for).

It is not the simplest module to use, though. You can find some "getting started" documentation here: https://www.drupal.org/node/861418


Output an empty alt tag for an image in with views? I have an image field in a view. How can I output empty alt text for the image.

(For decorative images this is the correct markup
http://www.w3schools.com/tags/att_img_alt.asp )

If you have disallowed the "alt" text in your field configuration, the system will output and empty value as you want. But if the field has a value in the attribute, you could modify it with hook_preprocces_field().


Many views for many taxonomy terms I need some help with the taxonomy view.
How can I create many views for many terms ?
I want that many terms from different taxonomies terms point to different views or at least to different structures of the same view.
The problem is that drupal translate each link of all taxonomy term to the model taxonomy/term/% that makes that all taxonomy term point to the same view. and I want that each taxonomy term point to a different views.
I hope i expressed myself well !
Thank you very much!

The way I would go would be to first create the desired views, then create custom "page–taxonomy–term–[tid].tpl.php" files, and in their code use the views_embed_view invoking the desire per-page view. I'm not sure though if this is the most effective way.


Views Contextual Filter on date range Drupal 7.23, Views 7.x-3.7
I have a Calendar Event content type, with a date field.
In my view, I need to pass a date range as a contextual filter such that if the event's date falls within the specified range, the events is returned.
In other words, something like /events-calendar/2013-09-04/2013-09-30 should return any events happening for the rest of this month.
So far I'm only able to match a single date, not a range.
Any ideas appreciated.

Assuming that you have set up your contextual filters properly, all you need to do is change the format of the date you pass.

/events-calendar/20130904--20130930

That above format should do the trick.


How do I redirect to an external URL without caching it? I can't use a normal RedirectResponse - Drupal prevent's it when it detects I'm redirecting to an external site. Instead I need to use a TrustedRedirectResponse, but this is a cacheable response - which I don't want.

Disable caching in responses

You can build the cacheable metadata and put max-age = 0 in it:

$build = [
  '#cache' => [
    'max-age' => 0,
  ],
];
$cache_metadata = \Drupal\Core\Cache\CacheableMetadata::createFromRenderArray($build);
$response->addCacheableDependency($cache_metadata);

If you want to put this in one line:

$response
 ->addCacheableDependency((new \Drupal\Core\Cache\CacheableMetadata())->setCacheMaxAge(0));

Disable caching for anonymous requests

Also you have to disable the page cache for anonymous requests

\Drupal::service('page_cache_kill_switch')->trigger();

This is necessary no matter if you use a normal redirect response or one with drupal caching.


Assign anonymous node to user Id What I want to try and achieve.

An authenticated user creates a node of type 'listing' (this node obviously belongs to this user via his uid). On this node will be a link to create a new node of a different content type 'booking-request' (this link the author can't control).

Now an anonymous user can view this created 'listing' node and then they can click on the link and create a 'booking-request' node. So obviously the 'booking-request' node will belong to the anonymous user.

My question is. How can I assign this 'booking-request' node to the author of the 'listing' node after the anonymous user saves it?

Can I do this with a module or will this need custom php or both and how will I do this?

You can use Entity Reference Prepopulate.

  Allow prepopulating any Entity reference field via URL

In your booking-request set up an entity reference field pointing to user entities. Then, create a link in the listing node to booking-request node add form with the right parameter to prepopulate that entity reference field.

See README in the module:

  In order to pre-populate an entity reference field you have to supply
  the parameter in the URL.

  The structure is node/add/article?[field_ref]=[id]

  Where [field_ref] is the name of the entity reference field and [id]
  is the id of the entity being referenced.

  Examples: node/add/article?field_foo=1 node/add/page?field_bar=1,2,3


How to put a view generated slideshow as a page background? I need to create a homepage with a slideshow as a background.
The slideshow shows images and texts. Similar to this one: enter link description here

What I've done:

1) I created a slideshow block with views

2) I put that block in the homepage

Now I spent some hours playing with css to put it in the background and making it fill the entire page. But with no results at all..

I'd like to know if is there module to make easier to accomplish this.

I'd recommend the Backgroundfield module with Views Slideshow. Create a View with display option Slideshow and the only field to display as your background field. Violá, no coding required.


How can I make entityQuery('commerce_order') return completed orders? Under Drupal Commerce 8.x-2.13 I find that the query

Drupal::entityQuery('commerce_order')

with no conditions attached returns ONLY incomplete orders (when called in the context of an API endpoint) - and if I apply any parameters exclusive of incomplete orders such as

$query->condition('state', 'completed');

it returns nothing. How can entityQuery be made to retrieve data on completed orders?

The solution is apparently to add $query->accessCheck(FALSE);.


Get the title of the active tab Is it possible to get the title of the currently active secondary tab?

I'd like to re-use the the title of this tab later on in the content.  I found menu_local_tasks(1) which comes close, but this returns full themed output.  I just want the title as I've defined it in hook_menu().

Edit:
My hook_menu structure (trimmed to just the elements in ,not including sibling elements):

$items['events/%node'] = array(
    'title' => 'Events',
    'page callback' => 'page_events',
    'page arguments' => array(1),
    'type' => MENU_NORMAL_ITEM,
);

$items['events/%node/stats'] = array(
  'title' => 'Stats',
  'access callback' => TRUE,
  'page callback' => 'page_stats',
  'page arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'weight' => 3,
);

$items['events/%node/stats/year'] = array(
  'title' => 'This Year',
  'access callback' => TRUE,
  'type' => MENU_DEFAULT_LOCAL_TASK,
  'weight' => 0,
);

$items['events/%node/stats/lastyear'] = array(
  'title' => 'Last Year',
  'access callback' => TRUE,
  'page callback' => 'page_stats',
  'page arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'weight' => 1,
);

For example, when at the page events/%node/stats/year, I'd like to get 'This Year'.

menu_get_active_title() should be the function you are looking for.

function menu_get_active_title() {
  $active_trail = menu_get_active_trail();

  foreach (array_reverse($active_trail) as $item) {
    if (!(bool) ($item['type'] & MENU_IS_LOCAL_TASK)) {
      return $item['title'];
    }
  }
}

It should work for menus for which the menu type contains the flag MENU_LOCAL_TASK (which includes also the MENU_DEFAULT_LOCAL_TASK menu type).

The function is also defined in Drupal 7.

Update: I noticed that for menus like /node/%node/view, menu_get_active_title() returns the title for /node/%node.
The following code should return the correct title also in those cases, including in the case the title is given by a title callback. I just tested on Drupal 7; I don't actually have Drupal 6 on the test site I use.

$item = end(menu_get_active_trail());

if (!empty($item['title_callback'])) {
  $args = array();
  if (!empty($item['title_arguments'])) {
    foreach ($item['title_arguments'] as $value) {
      if (is_int($value)) {
        // Get the value from the menu item map.
        if (!empty($item['map'])) {
          $args[] = $item['map'][$value];
        }
      }
      else {
        $args[] = $value;
      }
    }
  }

  $title = call_user_func_array($item['title_callback'], $args);
}
 else {
   $title = $item['title'];
 }


Content in website does not show under the right website name I have created the contents,

And I want the content should be display like www.kvamsdanl.no.

But It was displaying like www.kvamsdanl.no/node/3(or with one of these numbers 1 , 2 or 5).

How do I achieve this thing ?

Please anyone help me to sort out this issue?

Looks like you have removed the default front page settings. Please head over to /admin/config/system/site-information and add node/3 as default front page. Let me know how you go.


Filter for all terms in a "dynamic vocabulary" I would like to add a filter in a view to search only nodes related to terms in a specific vocabulary. The problem is that the editors continuously add terms to the vocabulary and consequently I cannot select once and for ever which are the possible terms.

I would need a filter like this:
positive if the term searched, or its translation, is in the vocabulary "myVocabulary".

I believe contextual filters under the advanced options in your view is what you are looking for. You can add the term reference field there and then dynamically filter the view from the url with either the term name or term id or both depending on the options you select.


Remove RSS feed icon and create custom RSS feed I want to disable the default Drupal 7 RSS feeds located at /rss.xml.
Can this be achieved?
I want to create my own custom RSS feeds.
I have tried with the Views module, but I can't define my own fields, and default feed contains a lot of HTML etc. I just want to create a clean RSS feed with title and body summarized to 150 chars, but without HTML, like in this feed: b.dk/seneste/rss.

For your first question, I found the RSS Permissions module, which allow you to disable the RSS feeds based on roles. I haven't tested this out, but it seems to be actively developed. (NOTE: This is for Drupal 7.)


Multisite, shared users, own databases, own files, how to deal with profile picture? I'm in the middle of implementing a multisite setup. Each site will have it's own database, and files directory, but they will share the user table from the default database.

Because the profile picture field in the user table is set to a fid, am I right in thinking this will break a user picture if they look at their profile on a different site?

fid 26 might be their picture on the main site, but fid 26 in another site might be for a completely different image, or not even an image at all.

How do you normally address this issue?

Cheers

You need a single sign on approach.
You could implement your own approach just like this one https://drupal.org/node/1043724 or try to find some contribute module to handle it.
Hope this help.
Regards


Unable to Edit Main Navigation Drupal 8 I installed a custom theme called StartupGrowth. At the moment, I am trying to edit the main navigation. When I go to Structure->Menus->Main Navigation and disable the unneeded entries, they do not disappear from the navigation. However, if I add a new entry to the menu, it does appear. What's more, when I attempt to delete the entry added by me, it persists in the navigation just like the other ones.

What am I missing? Is there another place for editing this menu? Or does this sound like a bug in the theme itself?

It's kinda hard to test for the ones not having this theme.

Looking at the demo for the theme I can see it is using Superfish module to display this menu.

So, after removing the menu element try to flush the cache (from /admin/config/development/performance). If still doesn't work, go check on Structure->Blocks and see the superfish block... click on configure and be sure it is using the same menu. You have more settings in there, and you can look into the module (Superfish) settings, too.


View all subscribed events? I have a feature where if a user navigates to a specific url (www.mysite.com/special-content) they are redirected to the login page, where we've appended a destination to the request (www.mysite.com/user/login?destination=special-content).

We created a custom module using a checkAuthStatus event subscriber to detect anonymous users and redirect them appropriately:

$ cat src/EventSubscriber/RedirectAnonymousSubscriber.php
<?php

namespace Drupal\anon_redirect\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {
    $paths = [
      '/special-content',
      '/more-special-content'
    ];

    if ($this->account->isAnonymous()) {
      foreach ( $paths as $path ) {
        if ( substr($_SERVER['REQUEST_URI'], 0, strlen($path)) === $path ) {
          $url = \Drupal\Core\Url::fromUri('internal:/user/login',[
            'query'=>['destination'=>$_SERVER['REQUEST_URI']],
          ]);
          $response = new RedirectResponse('/user/login?destination='.$_SERVER['REQUEST_URI'], 302);
          $response->send();
          return;
        }
      }
    }

  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkAuthStatus'];
    return $events;
  }
}

This has been working fine for a few months, but recently I got complains that people were not getting redirected. Upon investigation, I saw that they were getting 'access denied', as evidenced by the watchdog log. That is, when they are not logged in, they see our 301 page, instead of getting redirected.

Frustratingly, I've only been able to intermittently reproduce this problem. Sometimes I get the 301 page, sometimes I get the login page with the proper redirect query appended. I've tried both Firefox and Chrome, private sessions, clearing cookies, etc.

I suspect that whatever decides access also is listening to checkAuthStatus and sometimes having the final word about what page is ultimately sent to the end-user, and our module's behavior is not implemented, while other times, our event listener is invoked.

My question is if there is any way I can see what event listeners are subscribed to the checkAuthStatus event, and ideally, which one is having the final word as to the ultimate response from Drupal. I suspect another one is somehow getting prioritized over mine, and would like to confirm or deny that theory.

In the above code example the event is KernelEvents::Request and checkAuthStatus is the method called when the Request event is dispatched.

You can use Drupal Console debug:event command to list all subscribers for a given event:

vendor/bin/drupal debug:event kernel.request

And that will give you something like:

  Drupal\Core\EventSubscriber\OptionsRequestSubscriber                   onRequest: 1000
  Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber           redirect: 1000
  Drupal\Core\EventSubscriber\AuthenticationSubscriber                   onKernelRequestAuthenticate: 300
  Drupal\language\EventSubscriber\LanguageRequestSubscriber              onKernelRequestLanguage: 255
  Drupal\Core\EventSubscriber\RedirectResponseSubscriber                 sanitizeDestination: 100
  Drupal\Core\EventSubscriber\AjaxResponseSubscriber                     onRequest: 50
  Symfony\Component\HttpKernel\EventListener\RouterListener              onKernelRequest: 32
  Drupal\Core\EventSubscriber\AuthenticationSubscriber                   onKernelRequestFilterProvider: 31
  Drupal\user\EventSubscriber\MaintenanceModeSubscriber                  onKernelRequestMaintenance: 31
  Drupal\Core\EventSubscriber\MaintenanceModeSubscriber                  onKernelRequestMaintenance: 30
  Drupal\Core\Routing\RoutePreloader                                     onRequest: 0
  Drupal\Core\EventSubscriber\ReplicaDatabaseIgnoreSubscriber            checkReplicaServer: 0

If you use Drush and have the devel module installed, you can do:

vendor/bin/drush devel-event kernel.request


Programmatically create user in another Drupal site How can I programmatically create user in another Drupal site?

The setup: multisite installation, userbase should be partially shared. Both websites have DB credentials setup in the settings.php file so I can query all tables from either site.

The problem: if I use db_set_active() to switch the database to the second site, calling user_save() will invoke all hooks of modules that are installed on the first site, not on the second one. This causes errors if the sites have different modules.

How can I avoid this problem? Any thoughts on workarounds?

Thanks!

One clean way to do this is using a web service with the services module. You could then expand to being able to create users through javascript or another server without direct access to that database.

It's easy to make your own resources to do exactly what you want.

It comes with native support for core functions, including registering users using the user resource. It's worth mentioning that the maintainers are happing to add new resources that support handling core functionality.

There's also other modules that extend services to provide single sign-on for example.


Drupal 7 with front-end in Spanish/English; Back-end in English only I installed Drupal in English and also installed the i18n and Locale modules for translation. I then enabled Spanish as a language and set it as default. My aim is to have the site default to Spanish (www.mysite.com/spanish-page), and to allow users to choose English if they wish (www.mysite.com/en/english-page).

My site is still defaulting to English... for example, in "admin/config/system/site-information", my Default front page setting is defaulting the the "en" (English) url prefix. I cannot delete that prefix on that page; it is listed in the non-editable text just in front of that field. Likewise, when I click the "Home" button on my admin menu, it takes me to "www.mysite.com/en" (the English home page) instead of "www.mysite.com" (which would be the Spanish home page). I'm sure it must be a default setting somewhere, but I cannot find it. Can anyone provide guidance on how to properly set up this type of language scenario?

Thanks!

I just found what I suppose is my "fix"... in "admin/config/regional/language/configure", I unchecked "Session", "User", and "Browser" in the "User interface text language detection" section, leaving only "URL" and "Default" checked. This seems to have fixed my issue.


how do I load a single page in a sub theme? I am creating a page in a Drupal website of mine so that I can use it for a custom iframe in a Facebook app. The reason for this is that Facebook uses 520 instead of 960, and I was wondering if there is a way to create a separate sub theme that would be used for a single page on my Drupal site.

Take a look at the ThemeKey module.  From the project page:

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties.


How do I query a MySQL view in Drupal 7? I have created a database view and I would like to show the results in a Drupal Page. The view has some pretty complex SQL behind it, so trying to use the Views module isn't possible.

I just want to do SELECT * FROM VIEW_X and display the results on a page in PHP.

I know how to do this in Drupal 6, but how is it done in Drupal 7?

I don't think it's possible to query views using the DBTNG query builder: if you try to use db_select() with a view, it raises a PDOException complaining that the table doesn't exist.

Instead, you'll want to use db_query(). Let's assume you created a view named test:

CREATE VIEW test AS SELECT * FROM variable;

To get the value of cron_key, you'd do:

$name = 'cron_key';
$result = db_query('SELECT * FROM test t WHERE t.name = :name', array(':name' => $name));
$value = $result->fetchColumn(1);

The comment by drclaw on the db_query() API entry gives a number of examples which should help you out with figuring out how to manipulate a SELECT query using db_query().


Display last 3 articles in 3 columns layout in Homepage I would like to erase the welcome message on my homepage and to do that I need to add the last 3 articles created which will be stored in 3 columns like : [article1][article2][article3]

Any ideas to do that? Maybe with Display suite or Mini Panels something like that?

Thanks!

Why not use views with a descending sort on create date and limit the number of displayed items to 3. For the layout you can define css for the .views-row class (ex. width: 33%), for the styling you can use Display Suite or use views fields display mode.


mapping of menu Name "Main Menu" with variable name: primary_nav I am new to Drupal and would like to  know the details of constant/global variable:  $primary_nav
 Observed this variable is pulling list of links from a Menu with Title : "Main Menu" .
 I try to see the mapping of these in UI and DB, but could not find.
Can you please help me to find out the mapping of this menu Name (  "Main Menu" )  with variable name : primary_nav  and where is it defined.

$primary_nav is template variable in Garland's template.php file. It's a variable specific to this Drupal core theme. The HTML markup is rendered by the theme_links().

The main argument to the theme function is page template variable $main_menu, which is defined in theme.inc. This variable is set by menu_main_menu(), which will retrieve a menu id setting then use that to look up data in the menu_links table (noted by menu_name column).


Drupal 8 webform 8.x-5.8 - how to show the previous step value in next step? I have created a multistep webform and it has 5 steps. is it possible to get the previous step field value/data in the next step?
for example, I have a field select list field (key = select_your_data_type) in step 4 and on step 5 show the selected field value?

Use

HOOK_form_alter(array $form,FormStateInterface $form_state, $form_id)

check if $form_id equals your specific form (form's machine name) and validate if current page is page where you want to display data ('step_5' is wizard's page machine_name).

if ($form['progress']['#current_page'] === 'step_5')

get values from $form_state

$form_state->getValue('select_your_data_type')

and you can set form elements via

$form['elements']['page_5']['field_i_want_to_set_in_page_5']

or via

$form_state->set('field_i_want_to_set_in_page_5', $my_value);

or course do not forget to print field_i_want_to_set_in_page_5 somewhere on page 5.


Can I control Input Type by Field? I have a node type with multiple text fields. The majority of these are designed to fit very specific templates, and have fixed height and width, and are generally quite small.  The full CKE interface is too much of a good thing for these fields, so I made a different "Text Format," and tied it to a distinct Wysiwyg profile, "Full HTML (Simple)"

All of this is super, except that the default is still the default, and unless the user CHOOSES the other profile... it serves no purpose whatsoever.  These same users have access to multiple filters, so the obvious option is out.

I understand limiting the profiles by roles... and I half understand Filtering by Node Type... but I don't understand not limiting them by field.

I checked modules and it looks like Better Formats is on the way to doing it for 7, but I can't see any modules out there that ready for prime time.

I can't be the first person who has desired this.  Is there a hiccup in my logic, or a methodology I should be considering?

@Clive was spot on... Better Formats does exactly what I wanted.


Can I delete nodes of a given content type with Drush? Just wondering if Drush is capable of deleting nodes of a given content type.

Something like: $ drush delete-node --type=MyContentType

If not possible, can I create a method like that?

Install the devel module, and use drush to delete all the nodes,

$  drush genc --kill 0 0

You can also give a type option,

$  drush genc --kill --types=article 0 0


Feeds: How to import images using Xpath Parser for XML? I am using the Feeds module for XML import. I have created entity type with the Image as a text field. I need to import an image from XML and have it shown on the page.
My XML is like this:

<Auditor>
      <Ref>RIP.jpg</Ref>
</Auditor>

I imported the name from XML using Xpath Parser, but I'm unable to display it on the page because of a path that is not mentioned.

How should I set absolute path or display image on the front?

Thanks in advance.

Importing images into a multi-valued image field using image URLs from an XML file is not working for me. The debug output shows the image URLs being parsed correctly, but the images don't get imported.

The XML structure is:

             http://www.example.com/files/content/villa-102-1.jpg

             http://www.example.com/files/content/villa-102-2.jpg

The context is: //unit
The Xpath query for the image field is: unit_details/images/image/uri

I played around with the image grabber module for feeds, but it failed also.

I was able to import images using the CSV importer and the image URL, so this appears to be a problem with Xpath Parser, not Feeds.


Unable to run update.php or update modules from web interface I would really like to be able to install module updates through the web interface or run update.php when needed without changing settings.php, but something seems to be broken in my setup because it tells me I am not authorized to do so when I try.

In all attempts to make this work, I am using UID1, which besides any special properties that user has, it is an administrator which has the "Administer software updates" permission. In settings.php I have: $settings['allow_authorize_operations'] = TRUE; set explicitly, but I have also tried it in the default, not set, state which is also TRUE.

If I set $settings['update_free_access'] = TRUE; then I can run update.php, but that doesn't seem to help with the module updates and I would rather not have to change that setting every time I need to do an update.

I have tried all of the usual things I have seen mentioned including:
- Rebuild the user permissions
- Cleared the session table in the db
- Verified correct permissions on relevant files/directories
- Looked through various server logs for any obvious failures

My first real clue came from looking at the log an noticing that the "access denied" entry is tied to the anonymous user instead of the user I was logged in as. I have tried digging through the code a bit to see if I could track down where it is losing track of my user, but I am in a little over my head at that point. Obviously, the authentication is working in general because I am able to log in the admin site and do most things.

Has anyone had any idea why Drupal would lose knowledge of the logged in user just while trying to do update type operations?

Version: Drupal 8.7.6

Update:
I have looked a little more into the code to try to track down my problem. As seen from the logs, the problem is not that my user doesn't have permission but rather that when I run those specific actions, drupal momentarily doesn't see me as being logged in. In the file core\authorize.php there is a method that gets called: authorize_access_allowed(Request) which is mostly checking to see if the logged in user has the 'administer software updates' permission. In that method, it doesn't believe I am logged in. As far as I can tell, there are two ways it might pull the user out of that passed in Request (reading PHP_AUTH_USER out of the get headers or getting the UID out of a cookie). The get headers are definitely not there, and while there is a session cookie, it doesn't seem to be able to pull a UID out of it. I have not been able to find the code that parses the Session string.

update.php does not update modules. It updates the database state if needed (after installing module updates, aka db-update).

Did you check the permissions of your /modules/contrib/* filesystem? When you update your modules with the admin UI, your webserver's user (apache or www-run...) needs to have write permission there.

Did you install your instance with composer? If so, do not use the admin UI.

Maybe, check the docs again: https://www.drupal.org/docs/user_guide/en/security-update-module.html


CKEditor buttons not showing I'm using Drupal CKEditor module 7.x-1.13 and CKEditor 4.3.2.
Everything is installed and appears to work fine... except that there are some buttons that don't appear despite being configured to do so, notably "Select All" and the justify left/right/centre/justified buttons.
Here are the buttons as configured:

And here are the buttons as they appear:

You'll need to get and install the Full Package here: http://ckeditor.com/download

Then the missing buttons will show up.


Disable Node's Show summary in full view in D6 In https://drupal.org/node/514318 it talks about how to disable showing the summary/teaser in full view mode but only for D7 it seems.

In my D6 based site, I've filled in meta-description in the node teaser as required by Nodewords module.

The problem is that in full view mode it is clubbing this node teaser with the node's body text. Is there any option to avoid it adding with the body content?

In the picture from dsm($form) in hook_form_alter when editing node we can see there is teaser_include array key with #default_value = TRUE. I'm wondering where in the Admin interface we can specify this setting.

I've written a form_alter function for node edit form that has solved my problem:

function my_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'page_node_form') {
        $form['body_field']['teaser_include']['#default_value'] = FALSE;

        $prefix = $form['#node']->teaser;
        $str = $form['body_field']['body']['#default_value'];

        if (substr($str, 0, strlen($prefix)) == $prefix) {
            $form['body_field']['body']['#default_value'] = substr($str, strlen($prefix));
        }

    }
}

Also the teaser_include as in the question is from the node edit form which is accessible from this checkbox:


Sorting rows and return the value as a simple array using EntityFieldQuery I have a drupal custom entity_type. I am trying to do to things, find the row that is the oldest and return with a simple array. I currently have the following:

function oldestTicket(){
   $query = new EntityFieldQuery;
   $ticketTime = $query
  ->entityCondition('entity_type', 'as_ticket')
  ->propertyCondition('status','new')
  ->fieldOrderBy('updated', 'value', 'ASC')
  ->pager(1)
  ->execute();
  $entities = entity_load('as_ticket', array_keys($ticketTime['as_ticket']));
  return $entities;
}

This results with an error saying that updated is not a valid column field (it is in the db) and the return array is a complex multidimensional array. I would prefer something a little simple. In fact I would prefer that the returning result was just a string with updated timestamp value.

fieldOrderBy is for ordering by a Field API field.
You want propertyOrderBy('updated' 'ASC').

And the return structure can't be changed, it's always the same (a stub entity in technical terms). You use the id from that return structure to load your entity and get the data you want. I see you've already figured that one out, judging by your code.


How to make an nid replacement in a Text area inside Footer? I want to generate an nid of the current page in the Text area inside the footer of a view. I cannot add the ID (node id) in the Footer. What is the proper way for doing this? Any hint?

Thank you.

For the current node ID try this token:

[current-page:url:unaliased:args:value:1]

See http://www.drupal.org/node/1360922


Arranging tab menus created by views module I've created 3 different view and added them to a tab menu.

now these 3 menu items are sorted alphabetically and the default tab menu is printed as middle item .

I wanted to sort them using menus but tab items doesn't exist there .

  How can I reorder tab items created by views module?

You can provide a weight while editing the Views tab:
. Higher weights will be moved to the back of the order. But since you cannot see the weights of the other tabs this can take quite a while to get right.

Better is to have a look at Tab Tamer

  Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.