Cron failed with drush: Segmentation fault In Drupal 6, whenever I run cron from web interface I get an Internal server error and when I run

drush cron

I just get

Segmentation fault

What can be wrong here and how can I fix it?

It sounds like a resource problem.  Memory limits tend to be the culprit.

Check to see that drush is using the same php.ini file your site is.

drush status

Tells you what php you are using for drush.

Running the following will give you memory output information when running cron

drush cron -d

if that memory stack is near what your php.ini limit is.. raise it up an integer of 32Mb. (i.e. 128mb to 160mb)  and then test again.


How do I wrap classes around taxonomy terms? I need to add CSS to individual terms for a taxonomy field.  Where is the best place to do that?

You're looking for taxonomy-term.tpl.php.

This will allow you to customize the output of your term page.


Use Ajax in a view outside Its path I am using a view that I get from views_get_view('') and I put it inside a node page.
The problem is that the view normally uses AJAX (to filter,pagination,etc...) only when called through Its path.
This is not my case here because the view is calling from the node page.

Do you know how to handle this?
note that I retrieve a page view using views_get_view('MYVIEW').
Thanks a lot

I have solved my issue.
Changed the type to view block and then I did views_embed_view()

Works fine


What is the correct way to use a Symfony bundle? I want to use https://github.com/KnpLabs/KnpSnappyBundle in a Drupal 8 project. How do I correctly use it?

Drupal 8 isn't using Symfony bundles, only some Symfony components. Therefore you should use https://github.com/KnpLabs/snappy instead of bundle you've mentioned. You should install it using composer and then use available classes in your Drupal code. If you want to create PDF-generation service, you should follow official Drupal documentation.


How can i populate data from a reference node into another content type? I have two content types. hospitals and referral form. I would like to pull data from the hospital form automatically, example hospital name, address, contact etc when the user fills in the name of the hospital in the referral form.

I have used entity reference but i cant get it to work. It only gets the URL of the node but not the other fields. And also i have used autofill but it only works for a single content type.
If any one has done this before or if anyone has an idea, please do help. looking forward to your responses.

Take a look at entityreference_autofill

  The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.


Perform action when new user verifies email link I am looking to catch the event when new user updates password after clicking on link in the email, right after one time login.

I actually want to perform an action right after user sets password after validating/clicking on one time login link in welcome email.

I have gone through this: Is there a hook after user confirmation?

However, it does not solve my problem as explained below:

I used this condition to check if user is just created:

if ($account->uid // user is not new && $account->status === "0" && $edit['status']==1)

The issue with this is it holds usable for me in case if admin approves pending creation. In my case I don't want admin to approve, i want drupal to send email to user for confirmation. According to my workout, when admin approves, then above condition works, because status is changed from 0 to 1 so i can do some work at this change. But without admin, when user creates account, it is automatically activtaed, so I can't grab with this condition to perform my work at this event.

I also updated the link your posted to.

If you're using the LoginToboggan module for e-mail validation and you don't wish to use the rules module you can simply mimic the module's validation response (exploiting a temporary logintoboggan_email_validated = TRUE account property that's pushed to hook_user_update) yourself in code:

 /**
 * Implement hook_user_update()
 *
 */
function yourcustommodule_user_update(&$edit, $account) {
  if (!empty($account->logintoboggan_email_validated) && !isset($account->your_custom_action)) {
        $account->your_custom_action = TRUE;

        // Do what you want here

  }
}

Since core and other modules will also invoke hook_user_update you'd want to implement something to avoid repeated actions. In this example I set another property on the $account once the action is initiated but you can impose finer control if necessary.


Taxonomy terms with numeric names and views filtering within range I have a very large taxonomy vocabulary with numeric taxonomy term names like: 10123,10124,10125,... etc. My node have a min value field and max value field. Both fields are taxonomy referenced fields with this vocabulary.
How I can create views filter to find a nodes, where exposed filter value is between these two fields?

Example 1.

Node field min: Taxonomy term with name "10500"
Node field max:Taxonomy term with name "11000"
Exposed filter value: 10800

This is TRUE, so this node must be in views result.

Example 1.

Node field min: Taxonomy term with name "10500"
Node field max: Taxonomy term with name "11000"
Exposed filter value: 11500

This is FALSE, so this node should not be in views result.

Exposed filter value can be as taxonomy term autocomplete widget.

Any ideas, how it can realize?

I'm looking a solution in _views_query_alter, but I still can not understand is this right way?..

I believe a numeric range can be filtered using regular expression.

The following regex can effectively filter values within the range 10500 - 11000 (both ends inclusive)

(10[5-8][0-9]{2}|109[0-8][0-9]|1099[0-9]|11000)

Here is a sample view that works as expected with the above regular expression

You can create any numeric range as a regex using this generator http://gamon.webfactional.com/regexnumericrangegenerator/

Alternativelly what you can do is to add an extra numeric field to populate with term name (as a number) and than using that field to filter the view OR create a more complex function using hook_views_query_alter as you mentioned


Why would some images be saved to field_image / some maintain href after on import from Blogger? Using Blogger Importer, I pulled content from Blogger. The posts include images embedded in the text and a small image gallery at the base of the post that was built (rather painfully) using tables.

Reading this Cheeky Monkey post, I saw that they had modified the module to aid with image import since the standard module didn't handle that well. I got very mixed results.

For some posts, the images are correctly identified and added to "field_image" as specified. For others, the images remain embedded in the text with a URL reference back to blogger.

Cheeky Monkey updated code:

      // Image downloaded successfully.
          if ($response->code == 200) {
            // Save it.
            $file = file_save_data($response->data, $filepath, FILE_EXISTS_REPLACE);

            // Save the image to the field_image now
            $node->field_image[LANGUAGE_NONE][] = array('fid' => $file->fid, 'display' => 1);
          }
        }

I would like to head in this direction, so that I can have better controls over the image gallery views / template. That said, I also see that the embedded images look much sharper than the images that have been saved in field_image. (Might fix that if with color box, but am not sure.)

This particular post came in with a mix of how the images were handled. The images at the top of the post are saved in field_image, while the image midway in the text and thumbnail at the bottom reference the blogger href. Here's the original post in blogger.

The issue you described with some images not importing (keeping the blogger URL) is caused by the regex not identifying the image URLs as blogger hosted images. This regex can currently be found in the same file batch.nodes.inc on line 213 :

      if (preg_match_all('/(href|src)="(http:\/\/.*?\.blogspot\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)
      || preg_match_all('/(href|src)="(http:\/\/.*?\.blogger\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)) {

The code that worked for me is follows :

      if (preg_match_all('/(href|src)="(https?:\/\/[0-9a-z\.]+blogspot\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)
      || preg_match_all('/(href|src)="(https?:\/\/[0-9a-z\.]+blogger\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)) {

This could be improved but worked for me.  It allows for http and https.  And the .* was grabbing too much text before an image if there was a link above the image.

For the image quality, note that blogger uses different quality of image for displaying within the post and when clicking on the image.  Note the number contained within the URL s200 is low resolution, s1600 is high resolution.  Other numbers could be used for different size image.  You will have to decide which image to save or create a field to save two versions of each image.


Drupal Views overflow I have a Drupal 7 / Views question... I have a site with some data reports displaying in various graphs/ gauges etc. I also have a "Data" page that shows all of the data used so the user can look through it and/or even download it. My problem stems from the views table overflows past the screen on the right with data. This in itself is not a big issue, but I was wondering if there was a way to contain the view inside a fixed size box/container that is scrollable. Much like a text box.

Again, not that it would help the functionality but sure would make it look nice and clean.

Thank you in advance.

If you are focusing on the problem of data overflow from the views table, CSS could solve the issue.

For example if you write a code similar to this:

...

...

The only factor that is missing and could prevent the overflow is:

width: 100%;

Often you need to set the height of Content as well. If the height attribute is not set, the div will grow vertically as tall as it needs to. You may also try using a FixedHeightContainer


What am I doing wrong when trying to set the default value for this radio button form element? $options = array(
    'yes' => t('Yes'),
    'no' => t('No'),
    'maybe' => t('Maybe'),
  );

  $form['infx2670selig_kangaroo_eating'] = array(
    '#type' => 'radios',
    '#title' => 'Would you eat a kangaroo?',
    '#default_value' => t('No'),
    '#options' => $options,
    '#required' => TRUE,
  );

I don't see what's going wrong. By default, none are selected.

The #default_value is the key in the $options array. you want:

'#default_value' => 'no',


Drupal 7 check logged in user has both roles in tpl file? I want to print in a page--node--17.tpl.php a code to check for roles from the logged in user and then determine what should be shown, so basically a user must have BOTH roles A and C and if they do i print xxx
If they have roles A and B i write yyy
if they have roles B and C i print zzz

So the code below can check for one role, but how do i do both.. its important that BOTH roles need to be there, a user with just one of the roles will not qualify.

thank u

<?php
  global $user;
  // Check to see if $user has the administrator user role.
  if (in_array('administrator', array_values($user->roles))) {
    // Do something.
  }
?>

also i have this code but i think this is only checking one of the roles, so it checks for either A or B

<?php
global $user;
$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
    if (empty($check) ? FALSE : TRUE) {
    // is admin
    } else {
    // is not admin
    }
?>

It would be simple as:

global $user;

if (in_array('administrator', array_values($user->roles)) &&  in_array('moderator', array_values($user->roles))) {
    // is admin
} else {
    // is not admin
}


CKEditor does not work The ckeditor on my site suddenly stopped working without changing anything.

This is what I tried up to now:

update all other modules and drupal core
remove ckeditor
clear caches of drupal and browser
download the latest drupal ckeditor module
download the latest ckeditor full version and copy it in ckeditor/ckeditor
copy all to modules/ckeditor
check if ckeditor.config.js is their.
turn module on
check status report -> no error
set permission -> admin -> full html

PROBLEM: ckeditor is not showing nor is its configuration (admin/config/content/ckeditor).

**extra info*
jquery version 1.7
using the default
compression level production
jQuery and jQuery UI CDN none*

Non of the answers found on this site concerning this subject has been of help yet.
I tried using firefox and chrome.

Thanks in advance.

You have done everything I would have done.

Try a different path to ckeditor library. Install the libraries module and put the ckeditor library under libraries/ckeditor/ckeditor.js.

Try uninstalling the Drupal CKEditor module and go with the WYSIWYG module and see if that helps.

Also, try with different versions of jQuery. Sometimes the newer versions (1.9+) conflict with a lot of modules, though 1.7 which you are using is the sweet spot I have found.

And lastly try with an older version of CKEditor plugin.


How can I return a different number of results per page for a view if a user is accessing the site with a mobile device? I have a large number of views that show member profiles.  Right now, I only show 8 members per page, because on a mobile device it takes a very long time to scroll.

However, for the desktop, I could easily show 20 members per page.

Since there are a large number of views, I don't want to do this if I have to duplicate all of them and change the pager settings.  Is there another way to return a different number of results per page if the user is on a mobile device?

You could use Browscap module along with Browscap Block which would add the visibility of blocks depending on device. Next you could add two blocks one for Normal screen and one for mobile devices.

  Browscap Block

  Browscap Block adds visibility options to block configuration settings
  to allow you hide or show blocks in mobile devices.

If you do not want to create multiple views then you could use the browscap function in your template file to detect the browser and then restrict the number of items displayed. The function would be browscap_get_browser()

This could either be done in hook_views_pre_build function or with in the Style output template file where it loops through the $rows array. you could restrict it the number to 8 depending on the device by exiting the loop once you reach the required count.


Move views pager into row data? I'm working with Drupal 7 and Views 3 to build a simple video player. The view is fields-based, and is set to display one result (video) at a time. I'd like to provide a "Next" link as shown in the attached image, to allow navigation to the next video. Ideally, the Next link would be available in the row with the other field data.

Normally, pager info is at the bottom of a view. I could use CSS and absolute positioning to move the Next link, but the site is responsive, so it would be a lot cleaner to have the Next link appear with other field data.

Is there a straightforward way to do this?

You best bet is to write a small JS script where it will clone the pager's element content into an empty element within that field.

Rewrite the field you wish to insert the pager into. Add a span element or whatever you choose.
Write a small js script to copy one elemen'ts content to another. Use this as an example: https://stackoverflow.com/questions/3475727/how-to-copy-text-from-one-div-to-another-in-javascript


Display values from exposed field in Views as a Dropdown I am building an events website - so I have a taxonomy term Venue - and this, in turn, has a field Address, which is an instance of addressfield.

I need to expose the Locality field of the address to users.  I have this working fine, but it's displaying as a text field, since the original field is a text field.
http://journalofmusic.com/listings/test

I want the field displayed to users as a dropdown of all possible locality fields.

I have taken a look at this thread, and this specific comment:
http://drupal.org/node/1549250#comment-6653514

But I can't quite get it to work.  I've updated the example code to refer to taxonomy_term, and not node, and the locality field...

Below is the code. Can anyone suggest what I'm doing wrong here?

Thanks!

<?php
function dd_locality_form_views_exposed_form_alter(&$form, &$form_state) {
$field_id = 'field_address'; // change for the field in question

// Only alter forms with the necessary field
if (isset($form[$field_id .'_locality'])) {

// Build a query to get all term ids having the specified field
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'taxonomy_term')
->fieldCondition($field_id, 'locality', '', '!=')
->fieldOrderBy($field_id, 'locality', 'ASC')
->execute();

// Attach the field values to the terms
$terms = $results['taxonomy_term'];
field_attach_load('taxonomy_term', $terms, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

// Add a default so the filter is optional
$options = array('' => '---');

// Buld the options array based on the query results, overwriting duplicate entries
foreach($terms as $nid => $term) {
  $value = $node->{$field_id}['und'][0]['locality'];
  $options[$value] = $value;
}

// Alter the field
$form[$field_id .'_locality']['#type'] = 'select';
$form[$field_id .'_locality']['#options'] = $options;
$form[$field_id .'_locality']['#size'] = 1;
  }
}
?>

There is a small mistake in the code

$value = $node->{$field_id}['und'][0]['locality'];

should be

$value = $term->{$field_id}['und'][0]['locality'];


Removing link from slideshow images Hello I Have Created A Slideshow Using Views  but in slideshow if anyone is clicking The link was opening node/8 I Don't Want To Show Link In When Anyone Clicks on slideshow here is my website link Windowhelpdesk.com

Without knowing how your view looks like (or what slideshow module you use, if any) it is hard to give a definite answer - but check the image field in your view. If you edit the field there should be an dropdown titled 'link this image with' and right now it is probably set to 'content'. Set it to 'nothing' to remove the link.

Note: I am not sure about the exact labels as I work with a german drupal instance right now, but they should come close. The dropdown is right above the Design Settings fieldset.


CSS3pie - styles not being picked up in IE. How to reference the path? I've downloaded and enabled the css3pie and libraries modules, and downloaded and extracted the PIE Library to sites/all/libraries/PIE
I initially tried adding the css selectors to admin/config/user-interface/css3pie but because that wasn't working I've now added them in my mysite.info:
settings[css3pie][selectors][] = "#block-block-1"
settings[css3pie][selectors][] = "#block-block-8"
In my css file C:\Projects\mysite\sites\all\themes\mysite\css\layout.css
I've put the following:
block-block-1, #block-block-8 {
background: red;
padding: 2em;
-moz-border-radius: 1em;
-webkit-border-radius: 1em;
border-radius: 1em;
behavior: url(C:/Projects/mysite/sites/all/libraries/PIE/PIE.htc);

}
The PIE libraries is here:
C:\Projects\mysite\sites\all\libraries\PIE\PIE.htc
What am I missing and doing wrong?
I have a feeling I've got the path wrong :(
Of course you will need to adjust the path to match where you uploaded PIE.htc in step 2. Note: this path is relative to the HTML file being viewed, not the CSS file it is called from.
How do I reference the path correctly?

The PIE Drupal module should add the behaviour where necessary, you don't do that yourself. This would defeat the point of the Drupal module, and in using the Drupal module you don't need to specify the path yourself. (Though your current path there is incorrect, but I'm not sure on the correct way right now.)

css3pie can seem very touchy, there is a long list of known issues, some of which could be causing your problem. Also ensure that your files directory is writable, and that there are no errors on your sites status page. File permission problems can prevent the css3pie module from creating it's stylesheet. Each setting in the themes .info file should also be on a new line.


How can I create a relation between a number of related pages and a main event? I need to create mini-site within existing website. I have new content type called Events.

Single event will be number of pages related to that event. Some of the pages that will be under single event are:

Registration
Scheadule
Sessions
Resources
Travel

All of this pages needs to be on their unique url like mysite.com/event-name/registration. My first guess is to create all these as different content types and create some relation to single Event.

So my question is: How to create a relation between these pages and a main event? Since this mini-site needs to have its own navigation menu, can I automatise this menu creation somehow or should I create a separate menu for every event.

Method 1.

I would create a content type to act as a parent node for each event.

Then for each other content type, add an Entity Reference field, with only that parent content type available. (If you need to restrict the available parent nodes to certain users, you can use a view to get the results of the entity reference field and only allow the node author to select that node).

You can then start adding views to that parent content type for things like "Child nodes" with a reverse relationship to act as an automatically generated menu.

Method 2.

Everything goes into one content type, but use the Field Group menu to create horizontal tabs, and place those fields in those tabs. This will make editing the pages easier as they are all in one place, but depending on the amount of content in each of these mini sites, might have a slow load. There could be a good SEO argument for this method, as your content count would be good for each mini site all on one page.

I would probably choose method 1, unless the "mini site" is small enough to manage with field groups. The benefit of Method 1, is that you can use Rules to automatically add the other pages, and fill in the Entity Reference fields once the initial "parent" node is created.


customize destination for user_login with modal_forms link? I am using the Login Destination module to form rules for login customization. But they seem to be failing when modal_form is opened for the user login.
Can any one suggest something ?

You can checkout the following for ctools modal_form issues https://drupal.org/node/1329040 there is some code there that should allow you to set the redirect url using PHP to where you need it to go.

You should also double check that your modules are both up to date, there did not seem to be any open issues about computability between the two modules.


How do I unset hook_field_storage_load()? I'm trying to unset hook_field_storage_load() and hook_field_storage_write() in hook_module_implements_alter() without success. Is there any other way to turn off those hooks?

TL;DR hook_module_implements_alter() is not invoked when mongodb_field_storage_field_storage_load() is needed. You cannot achieve what you are trying.

The function that invokes hook_field_storage_load() is field_attach_load(), which contains the following code.

// Invoke hook_field_storage_load() on the relevant storage backends.
foreach ($storages as $storage => $fields) {
  $storage_info = field_info_storage_types($storage);
  module_invoke($storage_info['module'], 'field_storage_load', $entity_type, $queried_entities, $age, $fields, $options);
}

module_invoke() calls module_hook(), which contains the following code.

  $function = $module . '_' . $hook;
  if (function_exists($function)) {
    return TRUE;
  }
  // A
  // If the hook implementation does not exist, check whether it may live in an
  // optional include file registered via hook_hook_info().
  $hook_info = module_hook_info();
  if (isset($hook_info[$hook]['group'])) {
    module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
    if (function_exists($function)) {
      return TRUE;
    }
  }

Since mongodb_field_storage_field_storage_load() is contained in mongodb_field_storage.module, your implementation of hook_module_implements_alter() will not be called. In fact function_exists($function) returns TRUE when $function is equal to 'mongodb_field_storage_field_storage_load', and the part of the code after the line marked with // A will not be executed.


Can't access date field in fieldset I am using rules and I'm trying to retrieve a field inside a field collection for my scheduled component.

I have the conditions "Entity has field" and have selected my field, but I still can't access it in the data selection for my component.

I am using Drupal 7.52, Rules 7-2.9, & Rules Scheduler 7-2.9.

Update I have discovered that I can access other fields in the fieldset, but I just can't access the date fields.

Okay, solved it.

I wasn't suppose to add the action under Components, rather I was suppose to add the action under Rules Scheduler > Schedule component evaluation.


How to render a node image separately from the rest of the node content I want to know the variable name for the image which renders with content; being more specific when I render my content with the following code:

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

It renders my node image, title, body, and tags. I want to put a <div> around my image, but I don't know how to specifically do it in my node.tpl.php. I found out how to render my tags, but I have no luck with images.

What you need is the machine name for your field. This can be found by browsing to the content type in the admin, and seeing the value in the machine name column in the table. Within your node.tpl.php you can then access it using:

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

By way of a more comprehensive description of how to render different elements of your node within the node.tpl.php, please see the rest of this answer.

You can implement this in a corresponding node template for your theme: In your theme directory, copy the default node.tpl.php from Drupal itself (resides in root_directory/modules/node/node.tpl.php, then make a second copy, node--content_machine_name.tpl.php. The variable you're interested in is an array which contains all the contents of the node you're about to display (from the Drupal API docs):

  $content: An array of node items. Use render($content) to print them
  all, or print a subset such as render($content['field_example']).

Using the $content array within this template then allows you to print either sections of the array (field by field for example), or to print the whole array, or to hide sections in the print of the whole array to display later.

By way of a couple of examples:

To print a specific field output:

<div class="example_field">
    <?php print render($content['field_name']); ?>
</div>

Or to delay the printing of a field until after you've printed the rest of the content. (This is used in the default node.tpl.php to print comments after the article content .

<?php
    // Don't print the comments during the main content run
    hide($content['comments']);

    // Render the main content array
    print render($content);

    // Then render the comments last
    print render($content['comments']);
?>

Which will print the field after the main content block. For more information check out the node.tpl.php docs.


How to combine 3 line charts in a single chart, using the Views integration of the Charts module? I want to create a line graph using the  Highcharts library which shows 3 series in a single chart. I have visualization API, views, highcharts library etc. installed in my Drupal website.

I succeeded already in creating a chart which shows only 1 serie, but couldn't get it to work with 3 series yet.

The X-axis is taxonomy terms and Y-axis is the value of nodes on this term (relationship: Taxonomy terms on node).

The view I created has a filter and it filters the views with 3 content types I wanted. So I want to show these 3 content types as 3 different series (line charts), instead of just 1 line chart with everything together.

Here are some relevant details of the view I created:

This is the line chart I was able to create so far:

Here is what I want to achieve (using data that are different though):

How can I visualize my 3 series (for 3 different content types) in a chart similar to the above one?

After diving into deep on visualization with Drupal, Charts module gives us the opportunity to do this, either by using the Views integration of Charts (to create charts without coding PHP snippets), or by using the Charts API (used as a developer module that provides a unified API for the integration of various charting solutions into Drupal).

This is from the Readme.txt file, incuded with the Charts module:

  Creating Multiple Series and Combo Charts in the UI

  When using Views to build your charts, you may find it difficult to
  retrieve more than a single set of data generated by a COUNT() query.
  For example if you wanted to retrieve the age of all your site users,
  but display "Male" and "Female" values in a column chart at the same
  time, constructing the underlying table of data is quite difficult.

  To solve this problem, you can combine multiple charts on top of each
  other. The "parent" chart provides the global information, such as the
  height, width, title, and other properties. Charts that are "children"
  provide only data and (optionally) a secondary axis. After you've
  assembled the first series of data in your chart according to the
  instructions in the "Creating Charts in the UI" section, add a new
  display to the same view of the type "Chart Add-on". The "Chart
  Add-on" type is added the same way you would add a new Page or Block
  display, from the "+ Add" menu at the top of the view configuration.

  After this new display has been added, find the setting for "Combine
  with parent chart" and change this value to point at the parent chart
  you have already assembled. Then adjust the settings for the child
  chart to pull in different data (often by overriding the filter
  settings). Now you can go back to your parent display, and see that
  the results from the child chart have been merged into the results
  from the parent chart. You can even use this approach to combine
  different types of charts, such as a line chart over the top of a
  column chart. Note that not all chart types can be combined together
  and invalid combinations may cause your chart to throw errors.


"Content manager: broken/missing" After upgrading to Drupal 7, all the pictures of the items have disappeared.
In the View UI editor, I cannot add an image content and it says "Content manager: broken/missing".

Help?

"broken/missing" means that Views can't find the field. If you hover over the "broken/missing" link you can look at the address and get a hint of which field it's supposed to be. Once you know which field it is you can remove the broken handler and re-add it to the views output. If it's not available something has gone wrong with the field migration (I assume you did migrate the fields).


Redirection should not lose the URL parameters I have a rule and in condition I'm checking a path that if the current path is some path then in action I'm redirecting it to new url.

But the problem is that url has some parameters but in redirection it loses the parameters.

For example I have the following url:

first-url?param1=value1&param2=value2

and I want to redirect it to another url. But the url parameters should be append to the new url.

Is it possible in rules?

To make the value of the URL argument available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


'Create new book' in Drupal 6 won't create, only shows loading icon Through the admin, Anytime I try to create a new book in Drupal via 'Create Content' > Book page and select '', the loading icon hangs there. When I save the entire page, it creates the page but it doesn't add it to the new book. Going to the list of books does not show the new book either. So, the object isn't being created.

I have feeling this could be a frontend error, but I'm not really sure where to start. I checked the Javascript error console and no errors there, so...

I've attached a screenshot for more context.

I am not going to upgrade to Drupal 7, if someone suggests this.

Maybe there is a way to programmatically create a new book until I figure out what the problem is.

I found the problem. We had to disable the jQuery update module, but it breaks stuff on the frontpage.


How to change the look of second article at front page I generate articles with the help of VIEWS at front-page. But I want that the second article has a different look. So I want to add div-Tags and additional css-classes to that second article.
I have tried to do this with a boolean field but the teaser does not have the possibility to check whether boolean field is true or false.
Any idea how I can realize it??

One approach to do this is to use multiple views. One that displays only one node and a second one that displays the others, with an offset of one. Then it's easy to configure those views to use different view modes then. You can do that using Page Manager/Panels, Views attachments or possibly also core blocks.

One thing that can be a challenge to figure out is paging, depends on what you expect to see on the second page exactly. If you have paging, then a different approach might be necessary, for example by changing the view mode of the first view through code, through a preprocess hook or so.


How to call functions from another module in hook_language_negotiation_info()? I am writing a new custom module which is dependent on geoip module. I'm trying to add another language negotiation in the language detection configurations which would trigger a callback function defined in the module. Now How do I call the function defined in geoip.module file? I tried calling the function directly and after a module_load_include and both do not work.

/**
 * Implement hook_language_negotiation_info
 */
function my_module_language_negotiation_info() {
  return array(
      'geoip_language_provider' => array(
          'callbacks' => array(
              'language' => '_my_module_language_callback',
          ),
          'file' => drupal_get_path( 'module', 'my_module' ) . '/my_module.module',
          'weight' => -4,
          'name' => t( 'My Module GeoIP Negotiation Provider' ),
          'description'=> t( 'This redirects the user to correct language based on their IP.' ),
          'cache' => 0,
      ),
  );
}

function _my_module_language_callback() {
  module_load_include( 'module', 'geoip' );

  //Returns array of languages based on country code. Eg. array( 'CN' => 'zh-hans',)
  $languages = _my_module_language_mapping();
  $country_code = geoip_country_code();
  $default_langcode = language_default( 'language' );

  if( !isset( $languages[$country_code] ) ) {
    watchdog( 'geoip_language', 'The country code is not in the language mapping.' );
    return $default_langcode;
  }

  return $languages[$country_code];
}

Not sure if this is the correct reason for this behaviour or not but it seems like the language negotiation process runs before the modules and the themes are bootstrapped in Drupal which would explain why the function is not available by default.

Changed the module_load_include to actually include the file directly by calling drupal_get_filename and requiring the file and it worked.

function _my_module_language_callback() {
  $geoip_file = drupal_get_filename('module', 'geoip');
  if( file_exists( $geoip_file ) ) {
    require_once DRUPAL_ROOT . DIRECTORY_SEPARATOR . $geoip_file;
  }

  $languages = _my_module_language_mapping();
  if( function_exists( 'geoip_country_code' ) ) {
    $country_code = geoip_country_code();
  }
  $default_langcode = language_default( 'language' );

  if( !isset( $country_code ) ) {
    watchdog( 'geoip_language', 'Country Code could not be identified by IP.' );
    return $default_langcode;
  }

  if( !isset( $languages[$country_code] ) ) {
    watchdog( 'geoip_language', 'The country code is not in the language mapping.' );
    return $default_langcode;
  }

  return $languages[$country_code];
}


Displaying Taxonomy Terms which are used by a Content Type I have created a taxonomy named Category which has a number of terms like Agriculture, Business, Computers, etc.

I have created three content types viz. Products, Suppliers and Buyers. All of these types use the terms from the Category taxonomy.

What I am trying to do is create a block named Supplier Categories which as the name suggests, displays a list of terms from the Category taxonomy which are associated to Suppliers. So say if you have Suppliers associated to the Agriculture and Business categories then this Block should show them. It shouldn't show Computers though because no Supplier uses this term.

I am not sure whether this is possible or not but I have spent a lot of time playing with blocks but I couldn't get it to work.

By the way, I am trying to do this using Drupal 7.

You should use Views. Here are the steps to do to achieve what you would like to do:

Create vocab. "Category":

Create content type "Suppliers" with a "Term reference" field to "Category" vocabulary:

Create three "Suppliers" contents in "Agriculture", "Business" and "Blabla" categories - so these 3 should be listed in your block.
Add a new view at admin/structure/views/add with these settings:

Add a new field "Content: Category":

(here are the settings)
Remove "Content: Title" field (1 , 2)
Set some descriptive names (like machine name, block name, display name, etc.), AND set Sort Criteria to "Content: Category (asc)":

Save
Go to admin/structure/block, set "Supplier Categories block" to be displayed in the "First sidebar" (or "Sidebar first" in Bartik) or any other, then hit "Save blocks":

You are ready.


Add JavaScript and css to page with nodes only if there is no tag in any of the nodes I wrote a module that adds javascript and css to a page with nodes of type 'rower', now I need to add javascript and css to the page only if there is no tag with id == 1503 in any of the nodes. I tried to do it myself but it does not work because the variable $containsOutletTag == TRUE only at last node. Can you please tell me how I can do this? Here's what I have for now:

<?php
function countdown_preprocess_node(&$vars)
{
  if ($vars['type'] === 'rower') {
    $containsOutletTag = false;

    foreach ($vars['field_product_tags']['und'] as $tag) {
      if ($tag['tid'] == 1503) {
        $containsOutletTag = true;
      }
    }

    if (!$containsOutletTag) {
      drupal_add_css(drupal_get_path('module', 'countdown') . '/src/countdown.css');
      drupal_add_js(drupal_get_path('module', 'countdown') . '/src/countdown.js');
    }
  }
}

you shouldn't have use hook_preprocess_node as it gets fired on each node separately, so if only one of the node doesn't have that specific tag the css and javascript will be added to the page unless other nodes have, so rather than hook_preprocess_node use hook_preprocess_page and there you can find an array of nodes (use dsm function with devel module enabled to see variable structure) and you can iterate over that array and check for condition


CSS is broken only certain admin pages Drupal 8.2.7:
Similar to this question: Why does my Site have a broken theme/style?

In my case only certain admin pages css are broken and this seems to only affect admin, not unauthenticated users. For example /node/add/article. In the head tag, I see the correct aggregated css listed a few times:
/sites/default/files/css/css_Va4zLdYXDM0x79wYfYIi_RSorpNS_xtrTcNUqq0psQA.css?onn5ym

But some stylesheets are not aggregated:
/?onn5ym

The common consensus is that the files where css are stored are not writable by Drupal, but I'm not sure this is the case because some stylesheets get aggregated. Or they are coming from another directory I do not know about? I've also tried clearing cache, no luck. Any other suggestions?

Turns out this was a permissions thing after all. The entire web/modules directory needs to be read/writeable by Drupal.


Removing line breaks in Twig My twig file is adding line breaks in the HTML which results in white spaces, as shown in this picture:

In the browser inspector:

When I remove the line breaks in the inspector, the white spaces disappear.
The default code in the file views-view-field.html.twig is:
{{ output -}}

I have researched the problem quite a bit and tried the following already, without success:
{{ output|replace({"\n":''}) }}
{{ output|trim }}
{% spaceless %}{{ output }}{% endspaceless %}
{% spaceless %}{{ output|render|trim }}{% endspaceless %}

I'm working on Drupal 8.7.6.
Any help would be appreciated.

The cause of the problem is probably not the template but how the field is configured in Views. You should be able to find a solution there, even if it means you need to rewrite the field output.
If you want to try solving it in this template you have to check what is inside of output. Views usually puts the field output in a markup object. Then you have to render it first before applying twig filters:
{{ output|render|striptags|trim }}

I've also added |striptags, otherwise you would see HTML tags in plain text on the screen because they are escaped by trim.


Drupal custom page with wildcards in url not working I have created a custom page at admin/structure/pages and have set the path to be

course-details/%id/%name

My intention is that there will be a custom block appearing on this page and the id and the name, in the URI, will pass data to the custom block. I have the block working fine and it is pulling data from a test page URI as expected. I now need to embed this block onto the course-details page, which contains content that must appear for any hit on this page regardless of the id and name.

In the settings => arguments for this page I have set the two arguments to be strings

In settings => access I have set "all criteria must pass"

When I hit the page with no id or name I see the course-details page, at this stage I do not have the custom block enabled, and I am seeing the content that must appear on all course-details pages.

However when I add the id and name, an example is as follows

course-details/ACM20110-01V03/certificate-ii-in-animal-studies

I am getting a 404 error. It seems the id and name are causing me trouble.

I have spent hours hunting on Google for trying to get my head around why this is not working. I am probably doing something silly.

Could anyone please help with this issue.

By using the named wildcards %id and %name as wildcards, Drupal will look for functions named id_load() and name_load(). It will pass the values of these wildcards to those functions, and use the return values as the arguments passed to the page callback. If the _load functions are not found, or if a FALSE value is returned, or no value is returned, you will get the error you are seeing.

I'm suspecting you want your path to be:

course-details/%/%


How can I change page title in node with some options? how can I change page title drupal 8 in node with some options?
I want change my title on "test" if node have field "field_section" is "dogs".
Just in this page I want showing in "field--node--title.html.twig" 'test'.

I tried
function test_theme_preprocess_field(&$variables, $hook) {
if($variables['field_name']=='title'){
   $variables['items']['changetitle']=true;
      // kint($variables);
   }
}

But I don't know how to search from preprocess field other paramters other fields like my field in node 'field_section'.

I want mix in preproccesing_field 'if field_section have value 'dogs' then showing page_title is 'test'.

You can fix all the things with
RouteSubscriberBase
https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones...

...

/** @var Route $entityUserEditForm */
$entityUserEditFormRoute = $collection->get('entity.user.edit_form');

// Change default user details entity form and title.
if ($entityUserEditFormRoute) {
  $entityUserEditFormRoute->setDefaults([
    '_entity_form' => 'user.complete_registration_form',
    '_title' => 'Complete Registration Form',
  ]);
}


How do I dump variables to the screen when running PHPUnit tests? I'm trying to put together some PHPUnit tests in Drupal 8. I'm running the tests from the command line, using /vendor/bin/phpunit, but I'm having troubles figuring out how to dump a variable to the screen for debugging purposes.

For that matter, I'm using this:

$this->assertEquals(2, $this->currentUser->id(), 'ID is correct');

And when it passes, the message 'ID is correct' is not shown in the console. Does anyone know how to make the error messages properly show?

Recent versions of PHPUnit swallow output.  To get around this, you need to run with the --debug flag, eg

$ ../vendor/bin/phpunit --debug modules/migrate/tests/src/Unit/process/FormatDateTest.php

Then you can see printed output.

Also note that PHPUnit will skip tests with output in them with the default phpunit.xml file, because it will deem them risky.   To avoid this update the beStrictAboutOutputDuringTests="false" setting and your tests will run.

You can also use the $message parameter to output something when an assertion fails.


Is it possible to add a class to an image field of a node wise I have a content type that has title, body, image etc. I am displaying the Title, image with caption and body using Manage Display. But here there is no option to align (Left, Right, Center) the image. How to align the image node wise.

OR

Is it possible to add a class to an image field of a node wise.

Have you checked the already built-in classes drupal adds to fields in the HTML? That is the way I style a single content view.
Is this https://drupal.org/node/1795294 the module? In the description they explain how to add a class.

PD: I wanted to leave a comment but do not have enough reputation to do so.


Services, OAuth and a mobile app I'm struggling with Drupal, OAuth and a (Cordova) mobile app I'm developing. I've made a custom module and it exposes data to the Services module. What I want to do now is get that data into my mobile app.

I've set up my endpoint, but I need authentication of course.

I've read the tutorials on 3-legged and 2-legged authentication, but from what I've read, I (think I) want the Client-flow. This is the flow where the user enters his/her username and password in the app.

Can anyone get me started on this flow? Is it even possible with Services and OAuth?

Tell me if you need any more info. I'm a developer, but mainly in the .NET space. I've managed with Drupal modules so far, but I find OAuth quite complicated.

First, this is a poorly worded question, so I'm answering the questions you asked, probably not what you really want though..

Both 3-legged and 2 legged work in Services with the OAuth module and the Services_oauth module enabled. I wrote a lengthy article on how to set this up here, and documentation here

But that doesn't really answer your question in terms of If I can help you get started with your flow. I suggest you ask a new question with the problems you're currently having rather than asking if we can help you get started on a solution we know nothing about.

This may help you understand why this is an extremely tough question to answer. Asking smart questions


How to upload static files to a remote server in Drupal 7 instead of local filesystem? I've recently had to migrate from Django to Drupal 7 due to web server constraints. One of the aspects of my old Django setup that I would like to preserve is hosting static content like images and other media on a remote server as I have free access to a massive server for this purpose.

With Django, this was as simple as editing a line or two in the settings.py file. My search for how to do this in Drupal has so far been pretty fruitless. Can someone please suggest a relatively simple way of doing this automatically?

The website in question will have multiple contributors, most of whom will be non-technical, so this should be something that is handled automatically.

You should look into the CDN project.
I am think of implementing it myself, but have no practical experience to impart.


Best practice to alter the attributes variable in a Drupal 8 Twig template I'm creating a custom Drupal 8 theme based on Bootstrap. (NOTE. I'm aware of https://www.drupal.org/project/bootstrap, I just want some practice.)

More often than not, I find myself adding Bootstrap classes to the existing Drupal classes via the Attribute object already available in the template.

For instance, in Bootstrap, the main navigation menu looks like this:

...

What is the best practice is to add the nav navbar-nav classes to Drupal's menu.html.twig template? This template already contains the following line:

1) Add the classes with a preprocess function?

I could add the following function to my MYTHEME.theme file to alter the attributes variable before it's passed to the template:

function MYTHEME_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    $variables['attributes']['class'][] = 'nav';
    $variables['attributes']['class'][] = 'navbar-nav';
  }
}

2) Add the classes directly inside the Twig template?

First, I'd create a template named menu--main.html.twig to override only Drupal's main menu.

Then, I'd alter the line with the
 to:

I find #2 a little less clean but it keeps all the markup in the same place.

What do you think?

If it is your theme then I would do it in a template. Drupal Core converted a lot of preprocess/template to work like that, e.g. the node template.

The advantage is that everything is together as you said and it's a lot easier change it later.

Also if you're a module that defines a template, then someone can just copy that, adjust it and have full control over the classes.


How to hide empty 'Content Zone' div in Omega? I'm using Omega and I have "Force this zone to be rendered" unchecked in the Content Zone settings, and "Force this region to be rendered" unchecked in the Regions settings.

Any idea what would force this zone to be rendered even if there's no content? The zone is outputting this:

<div id="zone-content" class="zone zone-content clearfix container-24">

Probably because you have the debug placeholders blocks activated?
There is a checkbox "Enable the debugging (placeholder) blocks" in Appereance > subtheme > settings > debugging tab.

The zones are rendered even if empty.
I suggest you try with this option turned off.


How to create a product class programmatically in D7 / Ubercart 3 I'm looking to create a new module that when enabled will create a new content type and create an ubercart product class for it automatically.

I've tried googling and searching stackexchange for a few days but couldn't find much that is current or applicable to D7/U3 (or so I think).

There's plenty of info on creating a node programmatically.

My question is: Once I have created the node, how do I programmatically "productize it"?

Thanks to Clive for pointing me in the right direction. As requested here is a code snippet I used in my module. I was able to take the code found in uc_product_class_form_submit() and make minor changes to make it work for my situation.

Essentially, in my module, I'm using hook_enable to call a helper function which checks for an existing product class. If it doesn't exist, then it creates it (as well as the node type). My module will go on to do more, but this is the relevant piece. (more specifically the function uc_suggested_donation_levels_add_product_class).

<?php

/**
 * @file uc_suggested_donation_levels.module
 * Adds up to 4 donation levels including a "you choose" amount.
 */
// Constants
define('DONATION_PRODUCT_TYPE_MACHINE_NAME', 'giving_project');
define('DONATION_PRODUCT_TYPE_READABLE_NAME', 'Giving Project');
define('DONATION_PRODUCT_TYPE_DESCRIPTION', 'Adds up to 4 donation levels including a [you choose] amount.');
define('DONATION_PRODUCT_TYPE_ERROR', 'Content type already exists in database. No need to re-create.');

/**
 * Implements hook_enable.
 * When this module is enabled it will check if the product type exists,
 * if not, then it will create it and productize it.
 */
function uc_suggested_donation_levels_enable() {
  uc_suggested_donation_levels_add_product_class();
}

function uc_suggested_donation_levels_add_product_class() {
  // first check to see if this product already exists.
  if (in_array(DONATION_PRODUCT_TYPE_MACHINE_NAME, uc_product_types())) {
    // The product type already exists, abort.
    watchdog('uc_suggested_donation_levels', DONATION_PRODUCT_TYPE_ERROR, array(), WATCHDOG_INFO);
    drupal_set_message(DONATION_PRODUCT_TYPE_ERROR, 'status');
    return;
  }

  $pcid = DONATION_PRODUCT_TYPE_MACHINE_NAME;

  $result = db_merge('uc_product_classes')
    ->key(array('pcid' => $pcid))
    ->fields(array(
      'name' => DONATION_PRODUCT_TYPE_READABLE_NAME,
      'description' => DONATION_PRODUCT_TYPE_DESCRIPTION,
    ))
    ->execute();

  db_update('node_type')
    ->fields(array(
      'name' => DONATION_PRODUCT_TYPE_READABLE_NAME,
      'description' => DONATION_PRODUCT_TYPE_DESCRIPTION,
    ))
    ->condition('type', $pcid)
    ->execute();

  uc_product_node_info(TRUE);

  if ($result == MergeQuery::STATUS_INSERT) {
    variable_set('node_options_' . $pcid, variable_get('node_options_product', array('status', 'promote')));

    if (module_exists('comment')) {
      variable_set('comment_' . $pcid, variable_get('comment_product', COMMENT_NODE_OPEN));
    }

    module_invoke_all('uc_product_class', $pcid, 'insert');
  }
  else {
    module_invoke_all('uc_product_class', $pcid, 'update');
  }

  node_types_rebuild();

  $type = node_type_get_type($pcid);
  node_add_body_field($type, t('Description'));
  uc_product_add_default_image_field($pcid);

  menu_rebuild();

  drupal_set_message(t('New donation content type and product class has been created.'));
}


How to alias views url with argument I set up a view with taxonomy id as the argument and am trying to figure out how to alias the term id with its name.

Trying to turn url.com/discussion/8 -> url.com/discussion/term but the argument must still be the id b/c I need to to pass it by URL to a node edit form from a link on the view display.

In your View, check the taxonomy argument and set the validator to Taxonomy Term. From there you can specify the argument type (and vocabulary where the term is expected to come from). Set the argument type to "Term name/synonym converted to Term ID" and that should help.


Load a variable displayed in devel I'm using devel to find specific fields I'd like to be able to access in a template I have for a user profile page (user-profile.tpl.php)

The field values are present in devel just fine however I'm not sure what to do with the path it gives me.

I see the info I need, (created = 1349810890)
and I see a path that devel has given me $...->created but I'm not sure what to replace $... with to get access to that field.

I've attempted the following

$node->created;
$page->created;
$user->created;
$node['created'];
$content->created;
$variables->created;
$variables->node->created;

And several others with no luck

Are you operating on the user account object?

If so, it should be:

$variables['account']['user']->created;

Which would be used at the template_preprocess function level. From the actual template itself, unless you have intimate knowledge of what was passed to $variables, you will sit there and guess all day long and not get far. Even I am guessing. The only way to know exactly what you have to work with is by using a real debugger.

The best option is implementing a debugger like xdebug so you can get a better idea of whats going on.

Atom has a package: https://atom.io/packages/php-debug
PHPStorm is
simple to setup: https://www.youtube.com/watch?v=jkv0dzW3IM4

It will save a lot of time if you leverage it over devel. You can then set a breakpoint in your template_preprocess function in template.php, inspect all the variables being passed to that appropriate template, and print or modify as you need.


How to host and play videos in a drupal site? Just that, I need to host and play videos in a drupal site. I mean not using vimeo, youtube...

Something along the lines of the Video module?

  Video module allows you to upload video in any format, play video in
  any format, transcode video to H.246, Theora, VP8 using Zencoder or
  FFMPEG automatically creates video thumbnails, stream videos from
  cloud, HTML5 videos with mobile device playback compatibility. Very
  reliable API for converting videos and auto thumbnail, embed video to
  node body using WYSIWYG module (D7 only) and many more.


How to print the file description to my twig template? I'm trying to figure how I can obtain or print the file description that is uploaded on my node and display on my twig template

So far I have tried {{ file.entity.label }} which only prints the name of the file. I even tried {{ file.entity.value }} or {{ file.entity.title }}.

Here is a sample of the code I have been working on

{% for file in object.entity.field_file %}

    <li>{{ file.entity.label }}  {{ file_url(file.entity.uri.value) }}</li>

{% endfor %}

The node variable is available in both page.html.twig and node.html.twig, so you can get your file description with

{% for file in node.field_myfile %}
  {{ file.description }}
{% endfor %}

Replace field_myfile with the machine name of your file field.


list users informations who flagged an entityform with views I'm using drupal 7 with entityform, views, rules

All is in the title, i need to list some profils fields (name, mail etc..) of users who flagged an entityform.

Exemple : User X send an entityform. User Y and Z are interested and click on a button(flag) "TAKE".
When user x come in his list of entityforms submitted he can click on one of them and then he got all informations of users who clicked on "TAKE" flag.

So for each entity form the result can be different.

**Edit : More informations :
For now i have a view who list all the entityforms of my user X, on each of these items i have a link called "access folder" who show the entityform details page.

What i try to do in the entityform details page is to add a block  who list all Users who clicked on the "TAKE" Button.**

** Edit 2 : What i did for now,
- i created a view block of type "entityform type"
- I gave a name for the block and added it in my left sidebar
- in the option of the block i specified "entityform/*" in "only in this pages list"

comming back in view i added a relationship with "Entityform Type: Entityform Submission" who is the entityform i'm using, and "(Entityform Submission) Flags: TAKE (by any user)"
in contextual filters i added : "(Entityform Submission) Entityform Submission: Entityform submission ID" and specified "Provide default value" : "Content ID from URL"

I don't rly know whats wrong if someone can tell me
**

Edit 3 : i think, in contextual filter, the "content ID from URL" does not work with entity forms. Am i right ?

Thanks in advance guys !

You're on a good track with creating the Entityform type of View. When you first created this View you chose which Entityform this is about, you can see it (change it) under Filter criteria. This view is now listing all submissions for that form.

You have also setup a Flag "Take" that users can use on Submissions of that form. And you want to show a list of all users who flagged a submission, on the submissions page.

When you create a fresh Entityform view you'll have only the field "Entityform: Entityform ID" and the Filter "Entityform: Entityform Type".

If you create a Page in that view you can list all the flags for all submissions for that Entityform. You can maybe use this page as a test, to see the user info correctly listed on submission, and delete it later.

You'll have to create a Block display to be added to submissions pages, this is what you're after.

Here is what you have to do to your Entityform view to show info about users who flagged a submission:

Add Relationship Flags: flag_take (or however your flag is called). Configure that Relationship to show Any user, and not Current user. This will list flags from all users who flagged it, not only the flags from the user currently looking at the page.
Add a new Relationship Flags: User that uses the previous Relationship flag. This introduces info about users who flagged the submission with "take" to be available in this Views.
To actually display the user info Add a new Field User: Name and set it to use the Relationship Flag user. This will show the name of the user who flagged the submission. To show other user info add different user fields and make them use the Relationship Flag user (otherwise you'll show info for the user who submitted the form, and not the one who flagged the submission).
Add a new Contextual filter Entityform: Entityform ID and configure it so that

When the filter value is NOT available:
Provide default value
Type: Raw value from URL
Path component: 2

When the filter value IS available or a default is provided:
Specify validation criteria
** - Basic validation - **
Hide view (or whatever makes sense to you)

And set that Contextual filter to This block (override) because it doesn't make sense to have it on a page display, for example.
Save the view and place the block in a region you want, you can specify the path where to show the block, like you mention in your question, this is good for performance. The Contextual filter that will make sure to only list results relevant to the particular entityform submission.

If you need to check the Block while working on it in Views enter an ID number of one submission that got flagged, to preview the result.


Can theme function be implemented in a module file? For example, in bartik theme, it has

/**
 * Implements theme_menu_tree().
 */
function bartik_menu_tree($variables) {
  return '
' . $variables['tree'] . '
';
}

Is there a way to override it via .module file?

Modules can create the initial implementation of a theme function but they can't override existing theme functions.

Modules do have one option available which should be used as a last resort: hook_theme_registry_alter. I would advise against every using this, since it will lead to code that's harder to maintain, and make it hard on those needing to theme the site. Also modules should be design never worry about theme functions of other modules, that is why we have themes. With that being said, if you change the theme registry you can change which function will be used regardless of what is normal practice, meaning that you will overwrite functions defined in themes. You can however use logic to prevent that from happening, but it can easily lead to many WTF moments, especially 6-12 months from now when you or some one else need to maintain the site.


How to create a render array for a location CCK field? The situation should be common: I have a content class with one location field; in the page view of the class I show the location on map. But, at the top of the page, I want to print the address too.

In the 'manage display' of my content type, I can choose for 'map only' (formatter location_map); which is perfect for the map, or for 'default (address only)' (formatter location_default), which is perfect for the top of the page.

It is probably as easy as, something like, in the node.tpl.php, saying

// address here
$content['field_location']['#formatter']="location_default";
drupal_render($content['field_location']);

// google map here
$content['field_location']['#formatter']="location_map";
drupal_render($content['field_location']);

but that doesnt work. I also notice Location has a theming hook, described here

http://drupal.org/node/62486

unfortunately they forget to mention what goes in there. whatever i put in there, it doesnt pass to location.tpl.php (allthough it does pass that template in vain).

I have a workaround thats so ugly I'm not even going to post it here :-)
Does anyone know how to do this properly ?

*-pike

Ah, ..in my node.tpl.php

// address here
$fvf = field_view_field('node', $node, 'field_location', array(
    'type'=>'location_default')
);
print render($fvf);

// google map here
print render($content['field_location']);

Great article: http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

pfew,
*-pike


Find all pdf links using a module Is there a way to find certain types of links and edit them from a custom module in Drupal 7? I want to add an attribute to all pdf links throughout my site. I tried the following:

function my_module_preprocess_link(&$link){
  if( substr($link['path'], 4) === '.php' ) {
    var_dump($link);
  }
}

But I suppose since the pdf links are contained in the node content of my pages, they aren't included here.

I'd like to add a custom class to all pdf links or maybe an inline onclick javascript event. Is there a way to do that?

It depends how the links have been created.

If the links were added using a field, eg using the file module, then you could look to that module for it's theme functions, and create your own replacement theme function in your module or theme.

If (just reread your question) the links are included in the body (or other textarea field) of your site's nodes, then you would have to rely on an input filter to alter them before displaying the field. You could look to a module like ELF, for how this can be accomplished using an input filter, or 'External Links' for an example using javascript.


Block certain IP addresses How to block certain IP addresses if we receive too many GET requests from particular IP addresses for a Drupal 7 website?

Drupal 7 has IP address blocking feature by default.

Login to admin
Navigate to configuration page
Click on "IP address blocking" which available in under People panel
Add IP address which you wanted to block.

OR

Navigate to below page
http://[yourwebsitename.com]/admin/config/people/ip-blocking


How to pass current loged in user id in Drupal view page settings I am new to DRUPAL. Recently I have created a view with 3 pages. 1st page shows in the main menu .
2nd and 3rd page shows in main menu . Now I would like to display the list of the images uploaded by the user in one of that menu tab. So in order to accomplish this I have added a path like user/%/MY-images
in page settings. Now if I click this menu-tab I am not getting the user id passed in the url.

My contextual filter is working fine. Only thing I need to pass the user id through the URL.

Can anybody help me out to figure the solution.

Thanks in advance

First you sure create contextual filter with default value "get default uid from url"(also if you want get logged in user you can get default value from logged in user) then test it in "preview" section. if everything work  in your views correctly try  clear the cache.
If not work update your question with snapshot if your contextual filter settings.


How to programmatically display an image field in Drupal 7 + default value when needed I've used field_view_field to display an image field for a specific entity in Drupal. The problem is when that entity doesn't have any value for field. I expect field_view_field to display the default image for field but it doesn't load default value of the field.

How can I do this?

field_view_field is a correct function to use if you want to display node image (if provided) or default (attached to field settings) if not.

$node = node_load($nid);
print render(field_view_field('node', $node, 'field_image')));


Place block region in node template I am trying to place a block region inside a news content type but it is not rendering.

node--news.html.twig:

{{node.label}}

{{ date }}

    {{ content }}

      {{ page.article_sidebar }}

How can I get the block to render inside of a node?

This is probably the solution, "Making region content available to node templates in Drupal 8": http://atendesigngroup.com/blog/making-region-content-available-node-templates-drupal-8

Replace “THEME” with your theme name below:

/**
* Implements hook_preprocess_node() for NODE document templates.
*/
function THEME_preprocess_node(&$variables) {
  // Allowed view modes
  $view_mode = $variables['view_mode']; // Retrieve view mode
  $allowed_view_modes = ['full']; // Array of allowed view modes (for performance so as to not execute on unneeded nodes)

  // If view mode is in allowed view modes list, pass to THEME_add_regions_to_node()
  if(in_array($view_mode, $allowed_view_modes)) {
    // Allowed regions (for performance so as to not execute for unneeded region)
    $allowed_regions = ['primary_content'];
    THEME_add_regions_to_node($allowed_regions, $variables);
  }
}

/**
* THEME_add_regions_to_node
*/

function THEME_add_regions_to_node($allowed_regions, &$variables) {
  // Retrieve active theme
  $theme = \Drupal::theme()->getActiveTheme()->getName();

  // Retrieve theme regions
  $available_regions = system_region_list($theme, 'REGIONS_ALL');

  // Validate allowed regions with available regions
  $regions = array_intersect(array_keys($available_regions), $allowed_regions);

  // For each region
  foreach ($regions as $key => $region) {

    // Load region blocks
    $blocks = entity_load_multiple_by_properties('block', array('theme' => $theme, 'region' => $region));

    // Sort ‘em
    uasort($blocks, 'Drupal\block\Entity\Block::sort');

    // Capture viewable blocks and their settings to $build
    $build = array();
    foreach ($blocks as $key => $block) {
      if ($block->access('view')) {
        $build[$key] = entity_view($block, 'block');
      }
    }

    // Add build to region
    $variables[$region] = $build;
  }
}

After clearing caches, I can now print content specified in Drupal’s block layout using my node template files. For example, if I’ve specified primary_content in $allowed_regions, then I can access it via node--node_type.html.twig with:

{{ primary_content }}


How do I remove an unused patch? I'm trying, for the first time, to add a patch in composer.json, for a layout builder issue (https://www.drupal.org/project/drupal/issues/3045171#comment-13450756).

It's the first time I do it, I see that after using the patch composer creates a "b" directory in inside the "core" directory.

The question is: when I'll upgrade the core version what should I do, if the patch will be include in the next release? Remove patch from composer.json? And what about that "b" directory?

I've added this code in the "extra" section of my composer.json and before I've installed the cweagans/composer-patches plugin, with composer:

"patches": {
  "drupal/core": {
    "#3045171-140: Forms break Layout Builder saving.": "https://www.drupal.org/files/issues/2020-02-04/layout-builder-save-issue-3045171-140.patch"
    }
  },
"enable-patching": true

Once you removed the patch from composer.json and run updates, core directory will be overridden by the new release and here the "b" directory will be removed.

For best practices reasons, I invite you to manage your project patches using composer patches plugin, and to be more specific use external patch file method.


Various forms of overrides Hi, my friends!

Sometimes, making an override of a contributed module consists only of: in template.php, copy the function we want to modify and change its prefix "theme" for "my_theme". But this is not enough.

Speaking of the Quiz module:

1. I need to modify the multichoice-alternative.tpl.php file. This file contains functions. But, there is only one foreach, and within it is what I want to change. How do I override it?

2. I need to modify the multichoice.classes.inc file. This file has functions without the prefix "theme". So, I can not replace "theme" for "my_theme" in order to make the override.

Help me!

Copy multichoice-alternative.tpl.php to your theme's templates folder. Make your changes in this file.

In your theme's template.php file you are also allowed to create process and preprocess functions for any theme function. So, you could create

function THEME_preprocess_multichoice_alternative(&$variables) {,

wherein you could add/subtract/alter any variable within $variables. This would allow you to pass such variables through to the multichoice-alternative.tpl.php file, which in your case now resides in your own theme's templates folder.

As to overriding the class, first see if what you need done can be done in the theme layer. If that fails you can always create your own class to inherit from class MultichoiceQuestion, make your changes, then look for the code instantiating instances of the parent class and replace with your own class. And if you do make a note so that when you upgrade the module you can make the changes again.

BTW, it is the norm in Drupal  to put more complex processing (PHP) in the default template process and preprocess functions instead of the template file, and to just put enough processing in the template file to print out the variables and do some conditional logic to assist with that.


What may be causing "fails the check integrity"? I need some help with the Rules fails the check integrity issue. I am running the Rules version 7.x-2.7. It works most of the times and appears to be suddenly.

When I checked on the dblog it has error message like so:

  the action Set a data value () fails the integrity check and cannot be
  executed

After clearing all the Drupal caches, it will start working again. It had a message like  Action was marked dirty, but passes the integrity check now and is active again.

This is a screenprint of the issue.

Possible reasons
Some reasons (pretty sure it is an incomplete list ...) that may help to pinpoint the reason for this typical message are like so:

Some module is missing "now" (which was there when the rule was added). It could well be a recently disabled, or uninstalled module.
The rule (or Rules Component) refers (in a Rules Condition or Rules Action) to a machine name of a field that is "no longer there".
The rule (or Rules Component) refers to a Rules Component that is no longer there, or, as a variation, something changed in a Rules Component (eg the data type of a parameter) so that it is no longer compatible with the way some Rule is trying to execute that Rules Component.
The rule (or Rules Component) refers to a content type (or more generic an entity type) that is no longer there, or a role that was removed.
The rule (or Rules Component) has a Rules Condition or Rules Action, which is provided by some module, based on some logic in that module. A good example of this can be found in the Content Access module: the ACL module seems to be a weak module dependency of the Content Access module, i.e. the Rules Action with machine name content_access_action_user_grant is only available if, and for as long as, ACL is enabled (if you disable the ACL module, then any rule that has such content_access_action_user_grant action will show such "... fails the integrity check".

Possible resolutions
Depending on what the actual reason is, these are possible remedies for it:

Re-enable recently disabled modules:

if any such module adds an extra content type with some related fields, and any of your rules still refer to them, then that would cause the typical error message.
if the existence of any such module is used to provide some extra Rules Condition or Rules Action, then any of your rules that still refer to those conditions/actions would cause the typical error message.

If you know/remember which entity some field (which got deleted) referred to, then manually adding that field again (with identical machine name) should make the error message go away.

...


How to make a content type field unique per user I want a date field to be unique per user so they can't add two nodes with the same date. I have Unique Field installed. Unfortunatly, they don't offer user scope.

Anyone know how to achieve this?

I don't know the Unique Field module, but I have a suggestion instead.

Create a little utility module which alters the node form of that node type and adds a custom validation. That validation could check for anything on the form, date inclusive.

In the Drupal 6 days it worked like this. I hope this is enough for a starting point. [Also, reading the book Pro Drupal 7 Development can help you a lot if you haven't written a module yet.]


Chunked Ajax Responses Does Drupal support chunked AJAX responses in either direction?

I have not been able to find materials on this so far and am curious:

Is Drupal AJAX capable of working with chunked AJAX responses (Does it have the functionality of waiting until all chunks are received and display them as soon as possible)
Does Drupal have functionality to send Chunked responses to an AJAX request (Send data as soon as it's ready, so it can be displayed to the client)

What I mean by chunked AJAX is basically what multiple service booking sites do (example: airline tickets) They do multiple requests to different service providers and airlines, and results are displayed as soon as they're available and populated with more as they are sent.

I don't think Drupal 7 or Drupal 8 support chunked AJAX response. Because AJAX in Drupal is implemented with jQuery.ajax which does not support that.


Add/attach saved pdf to node with rules I have a setup with views PDF which send email after creating a node. (This works)

For logging purpose I would like the PDF added to my node in a filefield.
Is there a rule action/php code  available to add the saved PDF to the filefield.

For adding/attaching a file to a node using code you need a file object. If you know the path of the created PDF file, just try the following code in the hook you need. I used this code in hook_node_insert for attaching a programmatically created PDF file, while creating that node.

$source_node = node_load($nid); //load your required node here.
$file_path = 'your file path';
$file = new stdClass;
$file->uid = $source_node->uid;
$file->filename = $filename; //your file name;
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;
// Save file object to make it a 'managed file'.
$file_obj = file_copy($file, 'new path for your file', FILE_EXISTS_REPLACE);

$source_node->your_file_field_name['und'][0] = array(
 'fid'  => $file_obj->fid,
 'uid'  => $file_obj->uid,
 'filename'  => $file_obj->filename,
 'uri'  => $file_obj->uri,
 'filemime'  => $file_obj->filemime,
 'filesize'  => $file_obj->filesize,
 'status'  => 1,
 'display'  => 1,
 'description'  => '',
 );

node_save($source_node);

Hope this will help you.


Add expression db_select What is the corresponding alternative in Drupal 7 for the following query

SELECT row_id,name,email, COUNT(name) AS name_count
FROM tn_api_users
GROUP BY name
HAVING  (name_count > 1)

That would need a combination of SelectQuery::addExpression(), and SelectQuery::having(), e.g.

$query = db_select('tn_api_users', 'u')
  ->fields('u', array('row_id', 'name', 'email'))
  ->groupBy('name')
  ->having('name_count > 1');

$query->addExpression('COUNT(name)', 'name_count');

Output:

SELECT u.row_id AS row_id, u.name AS name, u.email AS email, COUNT(name) AS name_count
FROM
{tn_api_users} u
GROUP BY name
HAVING  (name_count > 1)


Wrap Commerce widget attributes Clicking on Whislist, it adds product to wishlist, and hides the wishlist button and replace it with text 'Already in wishlist' which I need to style and position, so to do that I at least need it to be in a div.

Is there a template?

This video should sort you out. You need to use the hook form alter
http://www.youtube.com/watch?v=xYMd6WDqxKY


Drush Site Install does not populate table prefix sudo drush site-install standard -y --db-prefix='alaska_' --db-su='postgres'
--db-url=pgsql://drupaldbuser:password@localhost:5432/drupal
--account-name='admin' --account-pass='admin' --site-name='alaska'
--sites-subdir='alaska.jobcorps.gov'

This command does not populate the database with tables that have the table prefix.  This prevents us from installing Drupal 8 multi-site on a single database using Drush.

I've tried renaming the tables and then proceeding with the next sub-site install.  This fails because drush drops all tables when it runs subsequent installs on the same database.

I've also tried

install_settings_form.pgsql_prefix='alaska_'

Tried multiple versions of Drush.  Currently on 9.0-dev to see if that has a fix in it.

For the problem of dropped tables, you can use --db-drop-existing-tables=FALSE.

I'm looking for an answer to the prefix problem too ...


How to update drupal (with composer) and not update to the latest major drupal release not very familiar with composer yet

I run composer update on a dev version (thank GOD) but from 8.2.6 drupal was updated to 8.3.0 but some functionality was broken due to the upgrade ... how can I safely run composer update and not upgrade to latest drupal ... or is there some other command I should run instead ?

I understand that I probably have to change the composer.json to do it but I don't quite know what it is that it I need to include in it

Any help would be appeciated

this doc article don't quite explain such a thing

UPDATE

I run the command from eyal composer require drupal/drupal:8.2.* but creates problem and site was unusable after that (received 500 error)

giorgos@glaptop:~/websites/domain.com$ composer require drupal/drupal:8.2.*
./composer.json has been updated
No patches supplied.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
No patches supplied.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/drupal (dev-8.2.x 2125663)  Cloning 2125663da0 from cache
Writing lock file
Generating autoload files

Installation failed, reverting ./composer.json to its original content.

  [RuntimeException]
  Could not scan for classes inside "docroot/core/lib/Drupal.php" which does not appear to be a file nor a folder

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...

I had to run composer update and now with the 8.3.1 version of drupal the composer update run smoothly.  I just needed to run drush up rules-8.x-3.x-dev after that since there was a problem with rules and 8.3.1

EDIT
Anyone knows why my question received -2 ? (was I downvoted ? what is the reason ?)

It depends on the version you specify in the composer.json file. You can specify broad versioning, or exact version, and composer will adhere to that.


How can I ensure this block is properly cached? I have been trying to get the some book menus displayed by nice menu, and after asking some questions on stackoverflow 1 and stackoverflow 2 settled on this code. My ultimate intention is to turn it into a module that creates blocks for different sets of books.

I am not sure whether this block will be cached so the queries are not computed every time. What additional code may be required to ensure this?

<?php
$master_menu = '';
unset($four_books);
  $four_books_list = "91,323,47,149";
  $four_books = &drupal_static(__FUNCTION__);
  if (!isset($four_books)) {
    $four_books = array();
    $nids = db_query("SELECT DISTINCT(bid) FROM {book} where bid in (91,323,47,149)")->fetchCol();

    if ($nids) {
      $query = db_select('book', 'b', array('fetch' => PDO::FETCH_ASSOC));
      $query->join('node', 'n', 'b.nid = n.nid');
      $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
      $query->addField('n', 'type', 'type');
      $query->addField('n', 'title', 'title');
      $query->fields('b');
      $query->fields('ml');
      $query->condition('n.nid', $nids, 'IN');
      $query->condition('n.status', 1);
      $query->orderBy('ml.weight');
      $query->orderBy('ml.link_title');
      $query->addTag('node_access');
      $result2 = $query->execute();
      foreach ($result2 as $link) {
        $link['href'] = $link['link_path'];
        $link['options'] = unserialize($link['options']);
        $four_books[$link['bid']] = $link;
      }
    }
  }

foreach($four_books as $book_nid=>$book) {
  $menu = theme('nice_menus', array('id' => $book['mlid'], 'direction' => 'right', 'depth' => -1, 'menu_name' => $book['menu_name'], 'menu' => NULL));
  $master_menu .= $menu['content'];
}
print $master_menu;
?>

Why not cache it yourself? The Cache API in Drupal 7 is fairly easy to implement and it sounds as if your problem might warrant it. I had this issue with a very expensive function that was used to generate relatively static data and did a quick cache implementation to avoid having to constantly rebuild the query.

Let's say your existing function is something like this

function myfunction() {

   $output = (my calculations and logic);
   return $output;

}

A rough way to wrap this in using cache layer would be

function myfunction($reset = FALSE) {

  static $output;

  //some unique idenitifier for your specific record, ex. content type+nid
  $cache_key = (your logic here)

  if (!isset($output) || $reset) {

      // check whether or not output has already been cached and if so, use it
      if (!$reset && ($cache = cache_get($cache_key)) && !empty($cache->data)) {

        $output = unserialize($cache->data);

  } else {

        $output = (my calculations and logic);

        cache_set($cache_key, serialize($output), 'cache', 3600);

        return $output;

    }
}

The cache_set function is the key to this, here's what each of the parameters is doing:

$cache_key - your unique identifier for you content
$output - the output from your function
'cache' - the specific cache bin you want to use. Most likely, you'll want to use the  default 'cache' bin
3600 - the time in seconds that the item should live before being reset. In this case, this content is set to live for one hour. You can also set it to "CACHE_PERMANENT" to never needing reset or "CACHE_TEMPORARY" to reset the next time the general cache is clear.


Cache_render table grows extremely fast, is there a way to remove the url.query_args cache context from ALL pages? I'm noticed on a clean Drupal installation, the cache context url.query_args is present on ALL requests, that cause one entry on cache_render table per each request (if we change some query params, think about analitycs queries), and that table grows extremely fast. I don't know if this is necessary for ALL pages. Can I disable this behaviour from a config? Is this neccesary for Drupal to work properly?

No, in a clean Drupal installation this should not happen. These are the default cache contexts set in core.services.yml:

parameters:
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

What you might have found are cache entries from the Internal Page Cache for anonymous requests, which doesn't use cache contexts. Instead it stores the cache entries with the complete URL including the query string as cid. There are a lot of complaints that the Internal Page Cache fills up the database even for sites with moderate traffic. Not only because of the variations by the query string, also because the entries have no expire date and there is no way to configure one in UI. But you can easily replace the Internal Page Cache with Varnish or a CDN. You only have to configure the third party solution to invalidate the Drupal cache tags. Another option is to replace the cache backend with a solution that provides an automatic expiration like Memcache or Redis.


URL Redirects and Configuration Management I have installed Drupal's Redirect module to redirect from old URL's to new ones. I have added the required redirects in my local environment, ran drush cex but can not see the redirects in the export directory. Are URL redirects are content and not config? Therefore can not be exported via configuration management and have to be added manually per environment?

Yes indeed. If you wish to carry the redirects around you should probably export
Or manually create the file if they are not too many.
I would recommend a csv file.
You can check this for reference How do I export the list of URL alias into an excel or csv?
Then I would write a simple drupal migrate process to re import them in any environment. If you use csv file it should be quite simple for the redirects.


Adding a script to certain pages I am trying to add a script code on all but few pages. I tried the following code on the template.php bfile, but it doesn't work.

 function THEME_preprocess_page(&$variables) {
   if (isset($variables['node']->type)) {
     $variables['theme_hook_suggestions'][] = 'page__' .
     $variables['node']->type;
   }

   if ($variables['nid'] == '77') {
     drupal_add_js(drupal_get_path('theme', 'THEME') .'/scripts/path.js');
   }
 }

You should try below solution as well. I have added JS & CSS for the specific node.

function YOURTHEME_preprocess_page(&$variables){
  if (array_key_exists('node', $variables)) {
    $node = $variables['node'];
    if ($node->nid == 8) {
      drupal_add_css(path_to_theme() . '/css/cdata.css', array('group' => CSS_THEME, 'media' => 'screen', 'every_page' => TRUE, 'browsers' => array('IE' => 'gte IE 9', '!IE' => FALSE), 'preprocess' => FALSE));
      drupal_add_js(path_to_theme() .'/js/custom_records.js', 'file');
    }
  }
}


Image styles with $settings['file_public_base_url']? I deep dive in the settings.php file of Drupal 8.1 and try to configure $settings['file_public_base_url']and $settings['file_public_path'].

All media links are correctly rewritten, that works with static files, but styles fails with 404 errors as there is no php support and rewriting rules are not implemented.

How can you get styles to work with $settings['file_public_base_url'] ? Is it related with Image cache external ?

Finally got it working. It seems that currently there is a bug in the image core module that prevents the use of absolute paths in the $settings['file_public_path'].

For those interested, you can follow the issue where you can find the patch attached.

Note, that you must also set some rewrite rules on your static files server to get it working. I provided a docker example on how to configure this on GitHub, but mainly here are the main config:

Vhost configuration of the static file server

Configuration example provided for Nginx:

server {
    listen 80  default_server;
    root /files/domain.fr/public;

    index index.html index.htm;

    location @rewrite {
        rewrite ^/(.*)$ http://DRUPAL.SERVER.IP/files/domain.fr/public/$1;
    }

    location ~ ^/styles {
       try_files $uri @rewrite;
    }

    location ~ ^/core {
        rewrite ^/(.*)$ http://DRUPAL.SERVER.IP/$1;
    }
}

Drupal settings file

Add this to your settings.php file:

$settings['file_public_base_url'] = 'http://STATIC.WEB.SERVER';
$settings['file_public_path'] = '/files/domain.fr/public';


How do I conditionally add a field? I'm trying to find out any example of adding new conditional field using ajax in Drupal 8 form API, but I can't find it.

This is my code.

$form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#maxlength' => 64,
    '#size' => 64,
    '#default_value' => $name,
);

$form['floor'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Floor'),
    '#default_value' => $floor,
);

$form['flat_per_floor'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Flat Per Floor'),
    '#default_value' => $flatPerFloor,
    '#ajax' => array(
        'callback' => 'Drupal\bms_flat\Form\FlatForm::flatGenerate',
        'effect' => 'fade',
        'event' => 'change',
        'method' => 'replace',
        'progress' => array(
            'type' => 'throbber',
            'message' => "Generating..",
        ),
    ),
);

if ($form_values['floor']) {
  $form['flats'] = array(
    '#type' => 'checkboxes',
    '#title' => $this->t('Content Type'),
    '#options' => node_type_get_names(),
  );
}

$form['submit'] = array(
    '#type' => 'submit',
    '#title' => $this->t('Submit'),
    '#default_value' => $this->t($submit),
);

This is the callback function.

public function flatGenerate(array &$form, FormStateInterface $form_state) {
  // …
}

How do I add a new field after filling-up my Flat Per Floor field?

I don't have much experience in Drupal 8. Please refer my suggestion bellow.

Please add wrapper item for the ajax call
eg:

$form['flat_per_floor'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Flat Per Floor'),
    '#default_value' => $flatPerFloor,
    '#ajax' => array(
        'callback' => 'Drupal\bms_flat\Form\FlatForm::flatGenerate',
        'effect' => 'fade',
        'event' => 'change',
        'method' => 'replace',
        'progress' => array(
            'type' => 'throbber',
            'message' => "Generating..",
        ),
        'wrapper' => 'flat-per-floor-wrapper',
    ),
);

Add the wrapper container under the flat_per_floor field

$form['flat_per_floor_wrapper'] =  array(
  '#type' => 'container',
  '#attributes' => ['id' => 'flat-per-floor-wrapper']
);

For more details please refer the example module for drupal 8 and check the ajax form
https://www.drupal.org/project/examples


How to mark product if it has already been purchased by current user? I have Drupal Commerce shop, that sells products that by their nature are most of the time not useful to buy twice. Exceptions do exist.

So what I want is to show a field or add a class on products page to mark it in very visible way, if current use has at some point bought this product, ie. if this product can be found in current users order history.

I will also want to show this mark in the product listings.

Lastly, I want to tell you that I do have some experience with templates in drupal, but not that much, especially with commerce. I also have Display Suite installed, if the code field way of doing things would be easier.

This really seems like a perfect fit for the Flag module. Excerpt from its project page (bold markup added here):

  ... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

  Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.

  In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

Refer to Flag's Community documentation for (way) more details.

You should configure an appropriate (non-global) flag, which you should then use to (automagically) flag products each time a user buys some product. And next time some products are shown to such user, you use that info about "has this product yes or no been flagged by this user already".

To actually flag such products, you should use the Rules module, which integrates extremely well with the Flag module. All that's left is to find the appropriate Rules Event for such rule to be triggered (somewhere along the lines of "checkout completed" I would assume).

If you'd want to take this even a step further, you could also consider what is described in the accepted answer to "How to add a custom icon or symbol to a flag link?".