How do I know if I installed latest version? I am trying to create a cron script which uses Drush, and that does the following (using pseudo-code).

if([My Drupal core version] < [The last core version]) {
    [Backup DB]
    [Put the site into maintenance mode]
    [Upgrade core]
    [Remove the site from maintenance mode]
}

I don't know, how to implement [My Drupal core version] < [The last core version].

How do I check if the site is using the latest version of Drupal?

You could try drush pm-updatestatus drupal and see if you get any results.


How to add data to Drupal.settings without drupal_add_js Is there any way to add some variables to Drupal.settings without drupal_add_js (with setting argument).

I'm creating a site that has a custom ctools popup style but I'm not feeling good with drupal_add_js. How can I add this JavaScript snippet to the page using the theme's .info page ? I'm not sure how can I merge my custom variables (literally, they are just static) to Drupal.settings so ctools module can pick them up as it was added via regular drupal_add_js call.

Thank you in advance.

Maybe I am missing a point to the question, but you should be able to do

scripts[] = path/to/your/script.js

in the .info file of your theme.  And within the script file something like

(function ($) {
$(document).ready(function () {
    Drupal.settings.yoursetting = {};
    Drupal.settings.yoursetting.property = some_value;
});
})(jQuery);

or use the Drupal.behaviors convention.


Programmatically save altered file As I mentioned in my previous question I'm attempting to write tests for a patch that will, ideally, trigger the creation of a redirect if the URI of a file changes.

My patch uses hook_file_update() which is called whenever file_save() runs.

Currently this chunk of code:

  // Move file to new URI
  $new_uri = 'public://qwerty.png';
  file_save($test_file);
  $test_file->uri = $new_uri;
  file_save($test_file);

This calls my hook and creates the redirect, but the redirect fails because drupalGet($new_url) returns a 404.

file_save() returns the error, filesize() [function.filesize]: stat failed for public://qwerty.png.

I've tried file_save() on URIs that linked to existing files, which gives an error, I've tried it on not-yet-extant URIs (as above), which gives an error, and I've tried file_move(), which doesn't call hook_file_update().

How can I programmatically change the URI of a file and trigger hook_file_update() inside a test?

The way I ended up getting around this was:

Upload my file as an unmanaged file at the new URI
$test_file->uri = $new_uri;
file_save($test_file);
file_unmanaged_delete($old_uri);

It didn't like it when I used a URI that was not yet in existence, nor one that was already in use by a managed file, but using one that goes to an unmanaged file seemed to work fine.


Contact form does not work I configured the contact form module core for drupal 7, But the messages are not sent, whitout any error message. I work just in local.

Did you check if your localhost is capable of sending e-mails? (probably not, mine for example can't send an email)


How can I change the selectable years in a date field? I have a date field, birthday, created with the Date module. By default, the selectable years are 1900-2050.  This makes no sense for birthdays so I want to change it to only show years from 1900-(current year-18).

How can I do this?

There is a solution for Drupal 7 but that code does not work in Drupal 8 because form_process_date() does not exist in Drupal 8.

This is the full error:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'form_process_date' not found or invalid function name in Drupal\Core\Form\FormBuilder->doBuildForm() (line 993 of core/lib/Drupal/Core/Form/FormBuilder.php).

Here is the code I'm using:

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['birthday']['#process'] = array('form_process_date', 'mymodule_fix_year_range');

@mpdonadio♦'s answer provides the explanation.  Here is the actual code I used:

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['field_birthday']['widget'][0]['value']['#date_year_range'] = '1950:2005';


How do I print the help text description above the field for all textareas? For all textareas, I want to print the help text description above the field input.

By default, it looks like this:

Field Label
Field Input
Help Description

I want to arrange it like this:

Field Label
Help Description
Field Input

This was actually a hidden configuration option added to Drupal 8.0  So, the basic idea is that I have to set '#description_display' => 'before' for every textarea.

To do that, I tried to use template_preprocess_textarea().

I added the following code to mytheme/mytheme.theme:

function MYTHEME_preprocess_textarea(&$variables) {
  $variables['#description_display'] = 'before';
}

I checked to make sure this code is called with kint() but it doesn't change the positioning of the help descriptions on the forms.  I checked my theme (Bootstrap's) templates and they have logic for handling before and after.  So what is the right way to call this to adjust the position of the help text on all textareas?

The description_display property is still working if supported by your active theme and I understand it is. Adding this to your mytheme.theme should do the trick :

function MYTHEME_preprocess_form_element(&$variables) {
  if ($variables['element']['#type'] == 'textarea') {
    $variables['description_display'] = 'before';
  }
}

Note that this might not work with formatted fields from the field API as the description field is in a parent template, see text-format-wrapper.html.twig. It would be a little more complicated to have this working for those fields.


How would I clear values in ajax loaded select options? http://pastebin.com/TX2UiJGZ

I have 3 select drop-downs, selecting a value in the first populates the second using ajax, selecting the second populates the third. However when I change the value of the first select it doesn't reset the second (If I already chose the first and the second drop down initially).

Method

Choose an option from the first
This populates the second select with options A, B and C
If I change the first one it won't reset the value if that value existed on the first option
So if our first option called A, B and C and we change the first drop-down to something else but it calls C, D and E; if C was selected in the second drop-down it doesn't reset since it existed in both ajax calls, this then doesn't load in the third select unless you select a different option in the second select.

Basically what I need is to reset the second and third select whenever the first changes.

SOLVED

/**
 * The ajax call to return data for the printer model select.
 * @return array             An array of settings.
 */
function first_ajax_callback(&$form, &$form_state) {
  // Reset conditional select values.
  $form['field_printer_model_value']['#value'] = array('All' => 'Select Printer Model');
  $form['field_printer_type_tid']['#value'] = array('All' => 'Select Device Type');

  // $commands = array();
  $commands[] = ajax_command_replace("#second_dropdown", drupal_render($form['field_printer_type_tid']));
  $commands[] = ajax_command_replace("#third_dropdown", drupal_render($form['field_printer_model_value']));

  return array('#type' => 'ajax', '#commands' => $commands);
}

In the above call I set the #value of the selects I want to reset. These lines properly reset two later dependent selects:

$form['field_printer_model_value']['#value'] = array('All' => 'Select Printer Model');
$form['field_printer_type_tid']['#value'] = array('All' => 'Select Device Type');


how to access webform submission data from a custom content type I 'd be grateful if someone could help with this..
I have a webform, let's call it input form, which, when submitted, triggers an external application to run on my server.  That application uses some of the submission data (reading from webform_submission_data table) and after some time produces an output in the form of XML.
Now, through the use of feeds module, I read that XML data and produce a node, of a certain content type, let's call it results CT ..
I have a twig template for the results content type, and output is nicely presented to the user.
So far, so good.
Now my problem is this.  I need to show both input and output in the same results page.
I tried to use Webform Content Creator module and indeed I have nodes with submission data - let's call this input data CT.
However, at the time of input form submission, I don't have the results yet.  And I want to link the two together, obviously upon the creation of the results node.
I tried to reference each content type, using Corresponding Entity References so that when a results node is created (automatically through feeds) it would link to the corresponding input data CT.  I thought that if I can achieve that connection, then I would be able to access the 'input' data through the results page template.
However, I can't make this connection to work - the 'entity reference' field that I use on the results CT, wants an 'entity ID' - and I can't find that.  Remember that nodes are created automatically, I don't have a user creating nodes via a select form or autocomplete text field.
I am trying to figure out how to do this through the sid (submission id) which seems to be a unique key for every submission, and I have this on both my content types .. So ideally I would like to use the sid that I have on my results template, and use that to get the submission data I need.
(obviously) I am not very familiar with the drupal API - I am however comfortable with twig .. I don't know if (and how) I could pass that information through a pre-process function to be available in the results template..  Is there a simpler way to do it?
Could I link two content types based on a custom field (say a unique number, like sid ??).
Ideally, in a few words, what I want is this:
I have a CT (results) with various fields, one of which is sid.  That sid corresponds to a (unique) submission id.  How can I access data relevant to that submission id from within the results twig template?  So I can then present both input (submission data) and output (results) in the same page.
PS - Perhaps one solution would be to refactor the whole logic, and use one CT for both input/output.  Insert some data upon form submission, and then, when results are ready, edit (i.e. fill-in) the rest of the 'output' fields via feeds.  Then all data are in one CT.  However I would rather avoid this as it's quite a big change ..  Shamefully enough, I might just re-enter input data through the XML again - it wouldn't be a problem - but it's a really crap solution  ..
I 'd be really grateful if someone could help .. I hope I explained the whole situation adequately enough ..

One way to accomplish that would be to use the https://www.drupal.org/project/webform_entity_handler module. It is not very widely used module yet but I've used it, it was simple to use and worked well. What that module does it allows you to create arbitrary entity from a webform submission (like the results node). So you could store the input, submission id and whatever else you need to this entity at this time.
Then feeds can update this same entity with the results if you know unique identifier like the submission id.


Panels - Style region to become a drop down/expandable menu Please see: http://drupal.org/project/tableofcontents

I am using Panels and would like to style a panels region so I am able to hide/show just like the TOC module above.

I have looked on Drupal downloads for a module, but none work the way I want.

Any suggestions? Thanks for your time!

I solved this by using the following module & some code:

http://drupal.org/project/panels_extra_styles

Panels region > Change style > Wrapper: raw.

Content prefix:

<form>

    <fieldset class="collapsible form-wrapper">
      <legend>
        Attachments
      </legend>

Content suffix:

    </fieldset>

</form>

Save and update. Voila!

References: Supplied if needed.


How can I catch an EntityStorageException exception? I have a custom Webform Handler that submits a webform to an external SOAP api. Once a user submits the form, the data is sent to the external api, my custom webform hidden field 'error' is updated to read 'Yes' or 'No' depending on the feedback from the api and the form details are saved to the Drupal database. The contents of the custom 'error' field is then used to send a conditional email to the website admin. All works fine except when the SOAP api is offline, then there is an EntityStorageException error and the details in the form are neither saved to the database or submitted to the SOAP api. I've tried to Catch the EntityStorageException, but it's not working.

My code is as follows:

namespace Drupal\mycustom_handler\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\Core\Entity\EntityStorageException;
/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "sentinelapplication",
 *   label = @Translation("Sentinel Application"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers application via SOAP"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class mycustom_handler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }
  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $values = $webform_submission->getData();
    $endpoint = 'www.soapapi.com';

    // Add the SOAP Call
    try {
      global $base_url;
      $wsdlurl = $base_url ."/modules/custom/mycustom_handler/src/Plugin/WebformHandler/mycustom.wsdl";
      $client = new \SoapClient($wsdlurl, array('location'=>$endpoint, 'exceptions'=>true, 'trace'=>true));
      // upload webform detail to SOAP
      $webform_submission->setElementData('error', 'No');
    }
    catch (SoapFault $ex) {
      $webform_submission->setElementData('error', 'Yes');
    }
    catch (Exception $ex) {
      $webform_submission->setElementData('error', 'Yes');
    }
    catch (EntityStorageException $ex) {
      $webform_submission->setElementData('error', 'Yes');
    }
  }
}

I have also tried but had no luck with:

catch (\EntityStorageException $ex)

catch (Drupal\Core\Entity\EntityStorageException $ex)

catch (\Drupal\Core\Entity\EntityStorageException $ex)

Not sure if it is an issue with the preSave function (and postSave function as I tried that too) because if I use the submitForm function, the error does not display and the data is saved to the Drupal database. However, while using the submitForm function solves my error problem, I can't seem to figure out how to update the custom 'error' field in the submitForm function.

So has anyone got any idea how to Catch the EntityStorageException error or alternatively, if that is not possible, how can I update the webform submission within the submitForm function?

Thanks to Hudri, the answer to this problem was to add a backslash before SoapFault in the catch because my try/catch code is made within a local namespace and the Soap call is made in the global namespace. So my code should have been catch (\SoapFault $ex). All working now - thanks.


Add class to first field in fields views How to add class to first fields in views?

I think that I need to add one if but I dont know what argument to put in if...

So how to add class just for first field in views-view-fields template.

{% for field in fields -%}
{%
        set colors = [
        'color-'~cycle(["red","yellow"],loop.index),
        loop.first ? 'first',
        loop.index== "1"?'color-first',
        ]
%}
        <b {{ field.element_attributes.addClass(colors) }}> {{ field.content }}</b>
{%- endfor %}

This code do this :

You can use preprocess field hook which is supported in drupal 8 also .
Example below:

function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}


Limit node reference to 1 per user & per referenced node, Drupal 7 I am trying to limit the creation of a node reference to 1 per user and per referenced node.
More specifically: I have a content type named Debate and another one called Vote. Vote has a node reference field (from URL widget) called *debate_ref* to the Debate type. What i'm trying to achieve is for each user and for each debate to have only one vote
i.e. when a user tries to create a 2nd vote node on the same debate node then he will recieve a message saying "You have already voted!".

"Unique field" module does the job but after the user attempts to save his 2nd vote node. What i would like to achieve is to deny access to the user who attempts to re-visit the "node/add/vote/nid" form if he has already voted for the specific debate.

Any help?

A solution is to use hook on form_alter inside a custom module :

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
 if($form_id == 'vote_node_form') {
    global $user;
    $nid = explode('/', current_path());
    $nid = end($nid);
    // I'm sure that next part can be done waaaaaaay better
    $query = db_select('node', 'n')
    ->condition('entity_type', 'vote', '=')
    ->condition('uid', $user->uid, '=');
    $query->join('your_entity_ref_field_table', 'e', 'n.nid = e.entity_id');
    $query->condition('your_reference_column', $nid, '=');
    $query->groupBy('e.entity_id')->execute();
    // I'd advice to do a dpm($query->fetchAssoc();) to check if I didn't make a mistake         :)

    if(!empty($query)) {
            // We force the user to go on any page if he has already casted a vote on that debate (you can i.e create a page with a word of explanation)
            drupal_goto('/');
            //or do whatever you want here
    } else {
            // If not, we let him go to the normal node creation page
    }
  }
}


How to conditionally display some things in the message text created by the Message module? I am using the Message module to record some activity.

I have a Rule generating a Message. The Message Type has a couple of fields, and I am setting them in the rule. That part all works great. I can verify the contents of each of those message fields.

Now what I'm trying to do is to conditionally display some things in the message text. I have a couple of Message Text rows and they all display what I expect them to. But for one of these, I want only want to display something if one of the tokens matches a condition.

I have selected the PHP Code filter type on that particular Message Text box, but I just don't know to actually evaluate the field values of the current message. I've tried t() and token_replace() and I just am not getting it.

So here is a simple question for this problem I'm having. Say I have a text field on this message type called field_foo. And I want the message text to display the length of that field. I basically want something to the effect of <?php strlen(this-message:field_foo) ?>.

How do I reference my message instance's field?

I couldn't figure out how to do this what I thought was the "right" way - that being inside the message type itself.

Instead, I added a preprocess field from DisplaySuite and put that into my display.

function mytheme_preprocess_message(&$variables) {
    $message = $variables['elements']['#entity'];
    if (isset($message) && $message->type == 'my_custom_message' && isset($message->field_foo) && array_key_exists(LANGUAGE_NONE, $message->field_attachment_themed)) {
        $html = $message->field_fooLANGUAGE_NONE][0]['value'];
        $variables['parsed_output'] = $html;
    }
}

Then I just named my preprocess field parsed_output, and it now displays exactly how I want, and I can add whatever custom code I want to my preprocess_message().


Ctools multistep returning user I am trying to implement a multistep registration form where if the user drops off the first step I then email them a link several weeks later for them to continue to step-2

http://example.com/user/register/step-2

After step two is complete the receive an email asking them to verify the account.

How do I load the users previous data if I send them directly to step2 at a later date. My ctools multistep currently looks like this after following this guide

function MYMODULE_registration_ctools_wizard($step = 'step-1') {
  // Include required ctools files.
  ctools_include('wizard');
  ctools_include('object-cache');

  $form_info = array(
    // Specify unique form id for this form.
    'id' => 'multistep_registration',
    //Specify the path for this form. It is important to include space for the $step argument to be passed.
    'path' => "user/register/%step",
    // Show breadcrumb trail.
    'show trail' => TRUE,
    'show back' => FALSE,
    'show return' => FALSE,
    // Callback to use when the 'next' button is clicked.
    'next callback' => 'MYMODULE_registration_subtask_next',
    // Callback to use when entire form is completed.
    'finish callback' => 'MYMODULE_registration_subtask_finish',
    // Callback to use when user clicks final submit button.
    'return callback' => 'MYMODULE_registration_subtask_finish',
    // Callback to use when user cancels wizard.
    'cancel callback' => 'MYMODULE_registration_subtask_cancel',
    // Specify the order that the child forms will appear in, as well as their page titles.
    'order' => array(
      'step-1' => t('Step One'),
      'step-2' => t('Step Two'),
      'step-3' => t('Step Three'),
    ),
    // Define the child forms. Be sure to use the same keys here that were user in the 'order' section of this array.
    'forms' => array(
      'step-1' => array(
        'form id' => 'user_register_form'
      ),
      'step-2' => array(
        'form id' => 'MYMODULE_registration_group_info_form',
        // Be sure to load the required include file if the form callback is not defined in the .module file.
        //'include' => drupal_get_path('module', 'MYMODULE_registration') . '/MYMODULE_registration_groups_form.inc',
      ),
      'step-3' => array(
        'form id' => 'MYMODULE_registration_invite_form',
      ),
    ),
  );

  // Make cached data available within each step's $form_state array.
  $form_state['signup_object'] = MYMODULE_registration_get_page_cache('signup');

  $output = ctools_wizard_multistep_form($form_info, $step, $form_state);

  return $output;
}

function MYMODULE_registration_get_page_cache($name) {
  ctools_include('object-cache');
  $cache = ctools_object_cache_get('MYMODULE_registration', $name);
  // If the cached object doesn't exist yet, create an empty object.
  if (!$cache) {
    $cache = new stdClass();
    $cache->locked = ctools_object_cache_test('MYMODULE_registration', $name);
  }

  return $cache;
}

you need to save your signup object in MYMODULE_registration_subtask_next

like:

<?php
    function MYMODULE_registration_subtask_next (&$form_state) {
      MYMODULE_registration_set_page_cache('signup', $form_state['signup_object']);
    }

and - in MYMODULE_registration_subtask_cancel and MYMODULE_registration_subtask_finish you should clean that cache, like MYMODULE_registration_remove_page_cache('signup');


How do you convert an existing order into a shopping cart order? I would like to be able to have an existing order that has already been checked out back into a user's shopping cart.  From what I have read from the documentation, a shopping cart is just an order for a user.

This is relevant because when my user's checkout the order, it only does an authorize only transaction, which means the funds have not been transferred yet.  I want to allow my user's a window of time to change their order.

So, I figured the best way to do this was to take the order that they want to edit, void it out, and then put it back into their shopping cart.

I can't seem to find an api call for this.   I saw hook_commerce_cart_order_is_cart_alter in the commerce_cart API, but I couldn't figure out when this was called or if this was a use case for this API call.

As you mentioned a shopping cart is nothing more than an order with the state of cart.

So all you need to do is to update the state of $order to cart using commerce_order_status_update() function:

<?php
$log = t('Reverting back to Cart state so the customer can modify items.');
commerce_order_status_update($order, 'cart', $skip_save = FALSE, $revision = TRUE, $log);

Alternatively if you are using rules, you can use the rule: "Set order status : Cart" which comes with commerce module out of the box.


Setting up a drush sql-dump alias I have the following in my aliases.drushrc.php file --

$aliases['prod'] = array(
    'uri' => 'foo.com',
    'root' => '/var/www/foo/htdocs',
    'remote-host' => '123.456.78.90',
    'remote-user' => 'bob',
    'databases' =>
      array (
        'default' =>
        array (
          'default' =>
          array (
            'driver' => 'mysql',
            'username' => 'foo',
            'password' => 'bar',
            'port' => '',
            'host' => 'localhost',
            'database' => 'foodb',
          ),
       ),
     ),
    'shell-aliases' => array (
        'dump' => '!drush sql-dump --gzip --ordered-dump',
    ),
  );

When I run drush @prod dump it attempts to connect to 'remote-host'. If I comment out 'remote-host' it dumps just as expected. I do need this value though for other functions such as sql-rsync.

I could create a new alias just for dumping but this seems a little excessive.

Any ideas?

Drush decides whether a site is local or remote via the function drush_is_local_host.  Make up a domain name for your system, such as foo.local, and make an entry for it in /etc/hosts (123.456.78.90 foo.local).  Next, make sure that /etc/hostname also contains foo.local, and confirm this by running hostname -f.  If you do all of this correctly, then you can set 'remote-host' => 'foo.local', and Drush will still treat it like localhost for commands such as sql-sync.


How db_query works when I pass query parameter directly I have one doubt for db_query in drupal 7, as in documentation db_query syntax is like

$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

But what happens when I write query like.

$result = db_query("SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = $uid");

Is it still convert in PDO prepared statements?
Is it still reliable as first query?
Will it handle SQL injection?

According to Writing secure code for Drupal 8 (same for D7)

Use the database abstraction layer to avoid SQL injection attacks
Use the database layer correctly. For example, never concatenate data
directly into SQL queries.
Don't do this:
db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);

Instead, use proper argument substitution with db_query. The DB layer works on top of PHP PDO and uses an array of named placeholders:
db_query("SELECT foo FROM {table} t WHERE t.name = :name", [':name' => $_GET['user']]);


Best practice, removing admin access from many websites hopefully this is not a repeat question, not sure how to search for this.

I run over 50 websites, not all are on the same server but some do hold many users together. Not all our servers are ours, some are ones we inherited.

Now say you have a developer who is admin on a dozen of these sites, is there an easy way to add/remove developer access to multiple servers across many domains in a low-effort manner? I'm looking at Drupal access but also SSH/cpanel access, database passwords and many other related passwords [LAMP systems].

It is a pain, as you know, to have to change all passwords on all systems when someone leaves and I was wondering how other people/organizations deal with this issue?

Thanks for any recommendations or thoughts you might have towards this!

Maybe you could use Drush for these operations, such as change passwords for admins ? Also to write a script with several drush commands, which would run via SSH console.

Unfontunately, I am not expert in writing these scripts, but I think that you should look in this direction.

For Drupal 8 another solution Drupal Console has been developed.

P.S. Drush and Drupal Console hardly work on virtual hosting. If you decide to use it, you will have to host your site on VPS as least.


How to exclude a hook function from the hook list? For example, there is some module (some_module). The module contains some hook (some_module_some_hook). I need to this hook function didn't execute. For example, I'm not satisfied its code and I want to refactor it, but don't want to use patches.

Is there an opportunity to switch off this hook function (some_module_some_hook) ? For example, I want to switch it off and define in my module a new function implements this hook but having my code.
How to do it in Drupal 7 ?

You can implement hook_module_implements_alter(). For example to remove the cron hook from the system module:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'cron') {
    unset($implementations['system']);
  }
}


CKEditor automatically making new paragraphs When I'm writing some text with CKeditor and I press enter and want to write something on the next line, the editor automatically inserts the text on the new line into <p> ... </p> tags instead of only <br/>.

I tried to correct it with editing the config.js file and adding the line config.autoParagraph = false; but without success.

Do you know where is the fault?

Out of the box, the CKEditor configuration does a <p> on enter and a <br> on shift + enter.

If you wish to change this, you can visit admin/settings/ckeditor/edit/[profile], and scroll down to the "Cleanup and output" section.


How to get managed_file value url? I'm trying to add a front page image as part of the theme setting. And so far I'm able to upload the image; however, I need to be able to get this in preprocess function so I can use the in my templates.

Here is what I got so far

casper.theme

/**
 * Implements hook_preprocess_page().
 */
function casper_preprocess_page(&$variables){
    $variables['frontpage_background_image'] = theme_get_setting('frontpage_background_image', 'casper');
    kint($variables['frontpage_background_image']);
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function casper_form_system_theme_settings_alter(&$form, &$form_state, &$theme) {
    _casper_theme_settings($form, $form_state, $theme);
}

 function _casper_theme_settings(&$form, &$form_state){
       $form['theme_extra']['frontpage_background_image'] = array(
        '#type' => 'managed_file',
        '#title' => 'Front Page Background Image',
        '#description' => 'Add background image for the front page',
        '#required' => FALSE,
        '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
        '#default_value' => theme_get_setting('frontpage_background_image' , 'casper'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
    );
}

And here is the kint results

So my question is what I'm doing wrong ? What should I do to get the URL instead of a number ?

Your field only stores the file ID, so it makes sense that theme_get_settings only returns a number. If I'm not mistaken, this should work:

use Drupal\file\Entity\File;
function casper_preprocess_page(&$variables){
  // Get the value of the first element in the array.
  $fid = reset(theme_get_setting('frontpage_background_image', 'casper'));
  // Load the file.
  $file = File::load($fid);
  // Generate the URL.
  $variables['frontpage_background_image'] = $file->url();
}


Which Drupal core function might call SELECT * FROM on custom module table? I have a Drupal 6 website which is hosted on a shared hosting service and which is used to communicate with a desktop software application. Over the years I extended the user profile with over 70 different profile fields. With over 45.000 users this resulted in a profile_values table containing over 1.200.000 rows and I was getting complaints about slow queries and I've read it might lead to performance issues. Switching host or upgrading Drupal 6 to Drupal 7 is not an option!

Since the profile data is only used when the software communicates with the website, which is done once per application start I did not really have a need for such a large profile table so I created a custom module which stores the profile data per user in a single row as a serialized array. This also has the benefit that I don't need to update my website every time a new profile value is added in the software.

But my MySQL slow query log is filling up again. The query that's logged is SELECT * FROM {my_table}. As I know this table is quite large I was careful not do call such a query myself and therefore I cannot find this query in my module or any of the modules that use my module. I always select a single column and pass a specific parameter to check.

As far as I can see there are only two functions that might have an influence on this. I implement hook_user() for insert and update operations and I call drupal_write_record() when saving the user data. But running through the code I fail to see where such a query might be called.

Can anyone explain where this query might originate from, within the Drupal system, or how I can extend MySQL (5.1) logging to tell me from which script this function might originate? (As it's only supposed to be called from a software application there's no equivalent web page a user can access.)

If grep/ack-grep can't find a SELECT * (likely) then just add an $debug_query = 'SELECT * FROM {mytable}'; if (substr($query, 0, strlen($debug_query)) == $debug_query) error_log(print_r(debug_backtrace(), TRUE), 4) or match the whole query etc and then look at the Apache error log for the pouring in backtraces. If you dont want to trash the log, log into a file in /tmp.


Follow up Drupal path to PHP function How do I figure out which PHP function is called from a Drupal path/URL (e.g. "/mysite/?q=flag/flag/like/&destination=node/1&token=xyz")?

Thx in advance!

You can find out from the implementing module's implementation of hook_menu.

In your case, look for where Flag implements hook_menu (in the case of Flag 7.x-3.x you're looking at flag.module at around line 301.
Next, look for where the module declares $items['flag/%/%flag/%'], and look for the page callback array key. You can see it says flag_page, so you can tell the menu callback is calling the flag_page.

You can find the Drupal 7 documentation for hook_menu here.


How to hide view's results before applying exposed filter? In a view I have some exposed filters.I would like the view to show no results before applying the exposed filter(s),but only after I have applied the exposed filter.By default,the view shows all the results.How can I achieve that?
Thanks

you could link to the view and pass a filter argument in the URL that doesn't have any results.

Or you could hide the exposed filters in a block. Also, create a "block" display for your view results.

Add the filter block to a page. Add the "results" block to the page but only show it for pages with "pagename?*".
That will hide your results block until filter values are passed through the URL.


Use a custom view for the front page without alias I am a Drupal Newbie, I have not learn't all the features yet.

I want to do the following.

I have created custom twig template for the front page.

By default I have default Frontpage view. I deleted it.

I've created a new view. And I want to use it as my default view for the front page, but I can't figure out how to do this.

I know about setting front page url in global settings. But it requires alias. Or it uses default frontpage.

So basically my questions are

How to create a view without alias, not exactly without, but with / or nothing for the front page.
How to associate a pathless view with a front page ?

I would be grateful for any help.

How to create a view without alias, not exactly without, but with / or
  nothing for the front page.

  How to associate a pathless view with a front page ?

You cannot create a pathless view page. (The default front-page view has a /node path)
Create a block View

Then go to blocks, and place your view block in a region. Content region perhaps?

Under Visibility settings check-mark "display only in" and put <front> so it only gets displayed in the front page.


Variables / settings configurable in Admin UI? I need a simple way to make some custom variables / settings configurable for an Editor in Drupal 8. They are not related to Drupal, only to the custom project. For instance, the editor shall be able to set an Affiliate ID that will be used in the external links of the site.

In Drupal 7, I would have used Variable: I would have defined some variables and they would have been editable under admin/config/system/variable.

Since Variable has not been ported yet to Drupal 8, I am looking for a simple way to get this done in D8.

One idea I came up with was to define some "Magic Nodes", like node/1 for my first variable, and then use its title to set the value. However, that looks very hacky and unintuitive to me.

Do you have any better idea?

According to the change record The variable_get/set/del API is now removed you would need to store the settings in configuration. You can make this configuration available to an Editor by providing a Configuration Form or if you only want to add a few fields you can extend an existing configuration form in a form alter hook. For example add the Affilate ID to the Basic Site Settings. Similar to this example for the menu configuration: How to add field to menu


Dynamically Caclulated Values with Entity Field Query Is there any way to query by dynamically calculated values using Entity Field Query? Take the following:

I want to query where the sum of field_some_number and a user-provided variable are greater than or equal to 5. Right now I'm only able to do the following:

$my_variable = -7;
$query->fieldCondition('field_some_number', 'value', 5, '>=');

But obviously this doesn't include my user-provided variable. How can I calculate this on the fly? Could hook-query-alter help me with this? I have not been able to figure out how to properly implement it. I'm using this with the Restful-Drupal module.

I don't think Entity Query supports expression.

In your case, I think you might not even need it as you can workaround.

$value_to_compare = 5 - $user_provided_value;
$query->fieldCondition('field_some_number', 'value', $value_to_compare, '>=');
But if you need to compute value based on columns of database table, you can go ahead with db_select, where you can have addExpression for calculation.

$query->addExpression('table_columns_1 + table_columns_2', 'sum');
$query->having('sum', 5,'>=');


Is it possible to authenticate against LDAP server without creating a drupal user account In D7 I have a section of my site I need to limit to authenticated users, but auth needs to take place against LDAP server, not drupal user base.

My users don't have a Drupal account and I am not supposed to create one for them, I am required to just check in with the LDAP server and if TRUE, grant access to these pages, if FALSE deny access.

All the LDAP modules I have tested create a Drupal user to mirror the LDAP user, as far as I can see. And it seems to me I couldn't even really keep the user "logged in" without a Drupal account...

What options do I have here, if any?

sorry, I guess you just can't do it that way.

everything you do in Drupal is tied to your user, even if said user is anonymous.

Drupal establishes a basic difference between logged and anonymous users, even if you give the latter every permission from the former.

hence an LDAP solution involves creating Drupal users for everyone, or else they don't get to do what registered users do.


Tabs for Media:youtube multiple videos of single node I am using Media:youtube in a content type and the field in which I embed youtube videos might have multiple values.
I am trying to put those multiple youtube videos belonging to a node in tabs dynamically.

Eg: I have a node created with title: example of tabs
underneath that I have embedded two youtube videos in the node
output should be in tabs with part1 as first horizontal tab and part-2 as second horizontal tab.
Part1|part2

with part1 loaded first and i should click part2 for second video

When there are 3 videos loaded in a node, then I should have like part1|part2|part3

I think using Display Suite with a add code field which i think should have a forloop with delta values of video will solve the purpose.I have no php coding knowledge

Can someone please help me to achieve this.

Maybe you use could use the Field Collection Tab formatter module with Field collection?

Here are some more details about these modules (quotes included are from their project pages):

Field Collection Tab formatter:

  ... provides a field formatter that allows you to output a multi value field collection field as a tabset, with one tab per field collection item.

Field collection:

  ... Provides a field-collection field, to which any number of fields can be attached. A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.


Call apachesolr_mark_entity without node_save I need your advise. I have this code:

$nid = 5; //example
$engine = 'mustang';
$node = new stdClass();
$node->nid = $nid;          // node id
$node->type = 'car';  // aka content type
$node->engine[LANGUAGE_NONE][0]['value'] = $engine;
field_attach_update('node', $node);
//send to solr
apachesolr_mark_entity('node', $nid);

The code was used to update a field called engine in content type car without using node_save(). This way is used because more lightweight then calling using node_load() and then node_save().

But unfortunately I can not send the entity to solr using apachesolr_mark_entity(). apachesolr_mark_entity() needs node_save() to work.

How to allow apachesolr_mark_entity() works although I don't use node_save()?

apachesolr_mark_entity() needs node_save() to work.

I would have to disagree; this is the code:

function apachesolr_mark_entity($entity_type, $entity_id) {
  module_load_include('inc', 'apachesolr', 'apachesolr.index');
  $table = apachesolr_get_indexer_table($entity_type);
  if (!empty($table)) {
    db_update($table)
      ->condition('entity_id', $entity_id)
      ->fields(array('changed' => REQUEST_TIME))
      ->execute();
  }
}

As you can see it's just a simple database update, node_save() is not involved.


how can I identify sidebar blocks in my theme I am working on a theme that I inherited and somehow the sidebar blocks are only coming out on the front page although I have set them up to come out in all of the pages in the block setup.
The programmer has made many template pages which is where I believe he has blocked the sidebar block from coming out but I am not sure where that code is.
Where can I find the code that would disable a sidebar block from coming out.
If I switch templates I can make the blocks come out but I need to do it with the current template.

Check (page.html.twig D8) or (page.tpl.php D7) and check (themename.theme D8) and (template.tpl.php D7)

Worst case scenario, backup first, then start deleting template files one by one and flushing the cache and checking, until you see the one that affects it.


What is node_access table? For granular node access, TAC, TAC lite, Content Access or ACL can be used, but because of some technical limitations and issues, I can not use them.

While implementing the node access part of my module, I've realized there are 2 type of hooks, total of 3. I've watched hours of videos, read many articles and I am still confused which one does what:

hook_node_access()
hook_node_access_records()
hook_node_grants()

For granular access control over each node with an specific nid, I can implement hook_node_access and see if the user has permission to view/update/delete the requested node.
I will also disable any other kind of node access system (roles permissions to access nodes, TAC, ACL,...) so only my module decides who has access to what.

This should work fine but the question is: what is node_access table used for? ACL and other fellas use it. But what is it? does it direcrly concern me too?

hook_node_access() is a standalone hook and has nothing to do with the node_access table.

hook_node_access_records() and hook_node_grants() go together and are different to hook_node_access(). These hooks use the node_access table.

Basically, the node_access table stores all the access grants for nodes.
These grants can then be queried and joined to other queries to check the access rules for a node.

hook_node_access_records() is invoked when writing access rules to the node_access table and hook_node_grants() is invoked when reading them out again.

To give you a better idea of how the hooks work, look at the code where they get invoked from.

For hook_node_access_records() this is node_access_acquire_grants().
It invokes the hook and then writes all the returned grants to the node_access table.

hook_node_grants() is called from a few places, but generally via the node_access_grants() function, which is called from a few places. Take a look at the node_access() function as an example.

It queries the node_access table, adding to the query conditions any access grants returned by modules that implement hook_node_access_grants(). Note that grants are also alterable via hook_node_grants_alter().

While you are looking at the node_access() function you can also see how hook_node_access() is called and you'll see how it is different and why it's not as flexible a solution to access control.

In case you haven't seen it, this is a good article on the topic: http://www.phase2technology.com/blog/drupal-7-node-access-grants-locks-and-keys/


Drupal content type node not overwriting the default node.tpl.php I have a content type with a machine name of 'school' after reading the documentation I should be able to just create a node-school.tpl.php to toy with the output of this in my theme.

Yet it does not seem to be overwriting it. I am trying to hack something together and I am using the twitter bootstrap Drupal theme.

If its drupal6 site then it is node-school.tpl.php . If Druapl7 then tpl should be node--school.tpl.php.

After Creating the files you need to clear the performance cache once.


Views exposed date filter using "Is between" doesn't include end date SITUATION:

Create a view of transactions (a custom entity in my case, but I don't think this is relevant)
Filter against Authored on (which includes both the date and time of creation)
Expose the filter
Choose Operator: Is between
Display the view with 10/01/2020 and 10/31/2020 as start and end dates for October
Note: I'm using the Date Popup module for date entry, which accepts mm/dd/yyyy

PROBLEM:
Transactions on 10/31/2020 are omitted. How can I include end-date transactions, short of telling users to put 11/01/2020 instead of 10/31/2020 (which is what seems natural to them)?
SOLUTION:
Thanks to @prkos in his answer below that a time of 23:59:59 must be included with the end date to compare up to the last second of the day. After learning this, I added a custom submit function to the exposed filter that appends the end time, like so:
use \Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Use array_unshift() so custom submit runs before default submit
  array_unshift($form['#submit'], '_my_submit_function');
}

function _my_submit_function($form, FormStateInterface $form_state) {
  $created = $form_state->getValue('created');
  if ($created['max']) {
    $created['max'] = $created['max'] . ' 23:59:59';
    $form_state->setValue('created', $created);
  }
}

Thanks to @No Sssweat for pointing out in his accepted answer below that array_unshift must be used to make the submit function run before the default. Initially, I simply used
$form['#submit'][] = '_my_submit_function'; // Don't do this. It doesn't work

See the accepted answer below from @No Sssweat for an alternative method of solving the problem using views_query_alter. I tried this and it worked as well, although in the end I chose the simpler of the two solutions.
UPDATE:
Turns out that, although the "simpler" hook_form_alter solution appeared to work, changing the value of the filter by adding a time breaks the filter if you move to another page in the list because the filter is passed via the query string to the page and it includes the time, which won't display in the date field. Given this, I reverted back to the views_query_alter approach, which doesn't have the same problem. My simple code is
function mymodule_views_query_alter($view, $query)
{
  if (!empty($query->where[1]['conditions'])) {
    foreach ($query->where[1]['conditions'] as $key => &$value) {
      if (strpos($value['field'], '.created <=')) {
        $e = explode(' ', $value['field']);
        $e[2] += (24 * 60 * 60) - 1;
        $value['field'] = implode(' ', $e);
      }
    }
  }
}

Note that I have switched from using IS BETWEEN to using two, separate tests against the Author On variable, on with >= and one with <=. You can see in the code that I'm modifying only the <= instance.

I agree this implementation lacks some UX polishing.
The reason why that day is omitted in your case is because you're not including the time, so a time of 00:00:00 is assumed, which is the beginning of the day and most of that day's time will be excluded. The first day also assumes it, but because it's the beginning of the range it includes the whole day.
The solution is to use the time along with the date, and give clues to users to orientate them with using Placeholder example values and the Filter field Description:
Empty form:

After filling in:

You can come up with better UX Label and Description, I'm just demonstrating a good starting point.


How to plot a chart from CSV uploaded in a content type? I am uploading TXT and CSV files in a content type. While displaying it,
I have to show that as a chart when users viewing the content of that content type.

I have tried using the Charts module, etc. Though I am able to plot the chart reading from a file by giving absolute path, I am not able to do it dynamically. Is there a better way of doing this (using Drupal 7)?

The Easychart module may be close to what you're looking for. It comes with these facilities:

Pasting of CSV data to create charts from it.
Entering an URL pointing to a CSV file containing the data to be charted.

For an extremely short demo of these facilities, have a look at this video.

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

It defines a new content type (= Chart) used to add charts to your site.
It creates a chart widget that can be used in your own content types.
It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (CKeditor and TinyMCE are supported).
It provides an intuitive interface to configure charts through the Easychart plugin.
The Government of Flanders contains some real world examples of a Drupal website with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

If you're using an URL pointing to a CSV file with data to be charted, then be aware of what's mentioned in comment nr 5 of the issue about "EasyChart data doesn't update unless I edit and save the chart node", i.e.:

  For performance reasons, the external csv data is only updated when cron runs.

Resources:

Module documentation.
Video demonstrations:

Easychart (quick) demo
Easychart - visual editor for Highcharts (Drupal demo).
Easychart powered dashboard (proof of concept)

Notes:

(1): To resolve an error like "Highcharts not defined" (as per your comment below this answer, you may want to have a look at the issue titled "Highcharts is not defined". Comment # 2 in it includes a possible explanation for that error, ie:

  It was a permissions issue on the library. For some reason the highcharts library had permissions set to: drwx------@

  This worked fine on my local machine, but not on shared hosting. I changed them to: drwxr-xr-x to match all the other libraries.

(2): From the Easychart project page:

  Make sure to clear the website's css-js cache after installing the javascript dependencies

(3): The Highcharts library needs to be placed in /sites/all/libraries/highcharts (as mentioned also in the README.txt)


How can we retain dropdown list value, when we select the option? I want to retain dropdown list value, so that when ever someone select the option from the dropdown list should retain that value after performing the action.

/*
 *implements hook_menu().
 */

function dropdown_page_menu(){
  $items = array();
  $items['page/layout/%'] = array(
    'title' => 'Select Layout',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('dropdown_page_select_form'),
    'access arguments' => array('access content'),
    );

  return $items;
}

/**
 * Implements hook_block_info().
 */
function dropdown_page_block_info() {
    $blocks = array();

    $blocks['dropdown_page_select_form'] = array(
        'info' => t('Select Layout'),
    );

    return $blocks;
}

/**
 * Implements hook_block_view().
 */
function dropdown_page_block_view($delta = '') {
    $block = array();

    switch ($delta) {
        case 'dropdown_page_select_form':
            $block['subject'] = t('Select Layout');
            $block['content'] = drupal_get_form('dropdown_page_select_form');
            break;
    }

    return $block;
}

function dropdown_page_select_form($form, &$form_state){
  $options = array(
    'select' => t('Select'),
    'layout_1' => t('Layout 1'),
    'layout_2' => t('Layout 2'),
    'layout_3' => t('Layout 3'),
    );

  $form['choice'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('Select your layout'),
    '#default_value' => $form_state['choice']['type']
    );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value'=> t('Go'),
    );
  return $form;
}

function dropdown_page_select_form_submit($form, &$form_state){

switch ($form_state['values']['choice']){
  case layout_1 : {

    //echo 'hi';die;
    drupal_goto("layout_1".$options);
    break;

  }
  case layout_2 : {
    //echo 'no';die;
    drupal_goto("layout_2".$options);
    break;
  }
  case layout_3 : {
    drupal_goto("layout_3".$options);
    break;
  }
  default: {
    print 'Select it!';
  }
}

  drupal_set_message(t('Your layout %input', array('%input' => $form_state['value']['choice'])));
}

You can set the default values as follows,

$form['choice'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('Select your layout'),
    '#default_value' => variable_get('choice', $form_state['choice']['type']
)
);

provided you get the submitted values in the variable $form_state['choice']['type'] post submit action.
And the variable name should match the form field name "choice"

Hope this works for you!


How to get image URL with GraphQL? Let's say I have a field image in a Product entity. When I query a Product, I'd like to include the URL of the field image in the response.

The documentation states we can use image_url.

According to this issue I tried the following but I still get null for my field in the response.

$registry->addFieldResolver('Product', 'image',
  $builder->compose(
    $builder->produce('property_path')
      ->map('type', $builder->fromValue('entity:product'))
      ->map('value', $builder->fromParent())
      ->map('path', $builder->fromValue('field_image.value')), // not sure if value is the correct property here
    $builder->produce('image_url')
      ->map('entity', $builder->fromParent())
      ->map('field', $builder->fromValue('field_image'))
  )
);

The property of field_image.value is wrong, it should be field_image.entity.

$registry->addFieldResolver('Product', 'image',
  $builder->compose(
    $builder->produce('property_path')
      ->map('type', $builder->fromValue('entity:product'))
      ->map('value', $builder->fromParent())
      ->map('path', $builder->fromValue('field_image.entity')),
    $builder->produce('image_url')
      ->map('entity', $builder->fromParent())
      ->map('field', $builder->fromValue('field_image'))
  )
);


How Reliable is node_save? When using node_save, how sure can one be that it did what it was supposed to do?

At the moment after any call to node_save I have been checking that the required property did succesfully update. For example:

$node->field_some_field['und'][0] = array('tid' => $some_taxonomy);
node_save($node);

if($node->field_some_field['und'][0]['tid'] == $some_taxonomy) {
    return TRUE;
} else {
    return FALSE;
}

Is this necessary? Or is there a better way to perform the check?

Edit: As an example, say I want to update a node's taxonomy programatically - it would be useful to know if it worked or not. I think it's just bad in general for things to fail silently.

I think you have to believe that node_save() is doing its job.  But, if you don't, node_save($node) is declared as sending $node by reference, so, if anything changes $node during the node_presave() hook, it will be reflected in $node after the fact.  That notwithstanding, if you wanted to be perfectly sure, you could do something like:

$nid=$node->nid;
node_load(NULL, NULL, TRUE);
$node=node_load($nid);

if ($node->.....

which would clear any node caches in your page and then reload the node from the database before your if check.

ADDITION:

From your example, the failure logic imho should be in your generation of the taxonomy value, not in worrying about if node_save() has or hasn't done its job.  For example:

   // assuming we have $node populated

   $some_taxonomy=programmatically_created_tid($args);

   if ($some_taxonomy !== FALSE) {
     $node->field_some_field['und'][0] = array('tid' => $some_taxonomy);
   } else {
     drupal_set_message(....
     watchdog(.....
   }

where your function looks something like this:

   function programmatically_created_tid($args) {

     // do whatever logic is necessary to generate the tid

     if ($success) { // success
       return $tid;
     } else {
       return FALSE;
     }
   }

would alert the user to the problem you are actually concerned about.


How to use term edit page instead of view page? On the terms list page,  each term is linked to the view page (i.e. term/[tid]). As I don't have any details in the view page, I would like to link it to edit page. (.i.e term/[tid]/edit). How to alter this behavior?

There are a few ways we could achieve this:

Option 1: Introduce a route subscriber in a custom module with below code:

    $route = $collection->get('entity.taxonomy_term.edit_form');
    $collection->add('entity.taxonomy_term.canonical', $route);

This code would replace the edit_form to the canonical route.

Note: Might need to update the local task to remove the view tab as it is confusing to see the edit form in the view tab (as below).

Option 2: Extend Drupal\taxonomy\Form\OverviewTerms form and overwrite buildForm method and use $term->toUrl('edit-form') as below:

      $form['terms'][$key]['term'] = [
        '#prefix' => !empty($indentation) ? $this->renderer->render($indentation) : '',
        '#type' => 'link',
        '#title' => $term->getName(),
        '#url' => $term->toUrl('edit-form'),
      ];

However, it might not be a good idea considering how complex buildForm method is and the effort to keep up with any core changes.


From time to time, the system does not find a file that exists From time to time (1 in 20 pages or so), I receive the following Drupal error:

Warning: file_get_contents(/sites/all/themes/MYTEMPLATE/lightGallery/dist/js/lightgallery.js):
failed to open stream: No such file or directory in _locale_parse_js_file()
 (line 1488 of /home/[MACHINE_NAME]/domains/[DOMAIN_URL]/public_html/includes/locale.inc).

The folder has permissions, it works perfectly, but the error message is persistent. I don't know why it happens and how to avoid it.

The problem was traced back to a call to drupal_add_js with relative URLs. I have added a prefix of drupal_get_path and the problem has disappeared for ever; it seems sometimes Drupal did not find the file because it thought it was in another location, but later it found it. This is why clearing the cache reproduced the problem. With the absolute path, problem is vanished.


Using SimpleTest to test an image upload I have a basic test written (per http://drupal.org/simpletest-tutorial-drupal7) but I am unsure how to proceed to test an image field.

public function testSimpleTestExampleCreate() {
    // Create node to edit.
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $edit["body[und][0][value]"] = $this->randomName(16);
    $this->drupalPost('node/add/simpletest-example', $edit, t('Save'));
    $this->assertText(t('Simpletest Example Node Type @title has been created.', array('@title' => $edit['title'])));
}

So this will create a node with a title and body. How should I modify this to allow it to test uploading an image as well? Would I just add another key to $edit of 'files[image_image_und_0]' with the path to the image to be uploaded? But I think something else needs to be done since you have to click "Upload" before you save the node.

There is a base image field test class in image.module, which has a uploadNodeImage() method. You can either re-use that by extending from that class or steal the code there.

See testStyleReplacment() for an example of how it is used.

Edit: The "Upload" is optional and only necessary if you want to upload multiple files. You can always just save the node directly and any selected files will be uploaded and processed.


Inject Link Using Rules->CustomPHP Short version: I'd like to change what is displayed in a certain rendered Node field, if the viewing user meets certain conditions. I think the Rules action "Execute Custom PHP" can do this? But I have no experience with PHP.

Less short version: On the site, users read artistic content. A link at the top of the page gives them the option to buy said content. This should give them access to a .zip file that contains Goodies.

The node's Download field shows a link to go and buy the content. On page load, if the user owns the content (determined by a Rules condition), I want the link to be replaced with a download link. Ideally, the new link would be retrieved from a hidden field on the node.

Clever use of the "hidden" parameter could also achieve this effect, but I imagine the solution would look pretty similar. Or is this at all doable in the way I've described?

Pointers to solutions or alternatives would both be appreciated. Thanks!

If anyone's interested in what I did here: this is best done using Views and Panels. Determining if a user owned a certain item required Views PHP. Once I got that working, it was pretty extensible, and I was able to implement some other displays based on it.


How to get the node id before saving the node in drupal 6? I have created a content type called 'inquiry.'  I am using the rules module to send an email after submitting an inquiry.  My requirement is to get the node id before it is saved.  I need to generate a link from that node id so the inquiry handler can view the inquiry by clicking on that link.

You can use hook_nodeapi presave option to get node content before saving the node.

Example :

function MODULENAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      print $node->nid;
      exit;
    break;
  }
}


Can we use Panels for Responsive web design? I would like to make a new site using responsive design using the Omega theme.
Are panels modules suitable for responsive design or should I use something else(like the Context module)?
Thanks

Two new ways of doing responsive design in Panels include Adaptivetheme 3.x and the Panoply distribution.


Prevent CSS/JS query hash when preformance is disabled When working in a dev environment with performance caching and aggregation turned off is there a standard way to prevent the cache clear hash from being appended to CSS/JS file names?

I'd like to avoiding hooking into the output and removing this manually in a dev only module.

Here's the solution (theme based) in template.php

function MYTHEME_process_html(&$vars) {
  if (variable_get('environment') == 'development' && !stristr($_GET['q'],'flush-cache')) {
    $vars['styles'] = preg_replace('/\.css\?.*"/','.css"', $vars['styles']);
  }
}

NOTE: This assume you have an environment setting in your settings.local.php file like so...
$conf['environment'] = 'development'; or $conf['environment'] = 'production';


User Management Question I realize the title of the post probably made everyone roll their eyes...but bear with me...please.

I need some very advanced user management where some users can be assigned as the admin of a group that can add users to that group, make sub groups and assign admins to it to add users...all the users need to have permissions to add edit and view some info that will be part of a large module I am creating...but unique to each user/subuser.

I think Organic groups, but I don't need, or want the content management/viewing aspects, just strictly user management and permissions, but permissions being restricted only to allowed permissions within my specific module...not system wide permissions...

I am looking for a slimmer solution than Organic groups, if possible.

Thoughts? Thanks for any input.

What I am seeing here is an entity with a bunch of other entity reference fields.
This followed by a bunch of access permission settings.

  some users can be assigned as the admin of a group that can add users to that group

Create a "group" entity that has 2 entity references fields (multivalue) one for users and one for admins. Each referencing the users and the admins who can have privileges.

  make sub groups and assign admins to it to add users...

Add another entity reference field to reference the same group entity type as the parent

  all the users need to have permissions to add edit and view some info that will be part of a large module I am creating...but unique to each user/subuser.

You would just need to play around the access control for that particular entity using a module like https://drupal.org/project/content_access or other ACL modules


Drupal 8 blocks content is not being translated I've searched high and low but can't seem to find any question that has the same problem. We're experiencing blocks that have content that is not being translated. For example, a custom block that has a simple translatable string and is being translated into a different language, it will simply always show the source language. What's up with that?

$build['test_content']['#markup'] = $this->t('Test NL');

Edit: For the record; we have translated this string into the target language but still doesn't show up on the corresponding language.

You need to navigate to admin/config/regional/translate. Try to search for "Test NL" in the input field. It will give you the string on the left side along with a text-field to the right. Enter the translation for the "Test NL" in the text field. and click save translations.

You are done. Clear the cache and check the interface.


Varnish 4.0 vcl for Drupal 7 Drupal7, Varnish 4.0, Ubuntu 12.4

Varnish is installed an working, but returning intermittent 503, I think whenever Varnish goes to the backend.  Even though the request returns 503, a page refresh may return 200, HIT from cache.  Another refresh may be 200 or 503.  I think a subsequent 503 is a HIT-FOR-PASS.

We've opened up the timeouts, as follows:

vcl 4.0;
backend default {
.host = "127.0.0.1";
.port = "8080";
.probe = {
.url = "/ping";
.timeout = 600s;
.interval = 600s;
.window = 5;
.threshold = 2;
}
.first_byte_timeout = 900s; # How long to wait before we receive a first byte from our backend?
.connect_timeout = 500s; # How long to wait for a backend connection?
.between_bytes_timeout = 200s; # How long to wait between bytes received from our backend?
}

So I suppose it's not that Varnish is timing out in a blink of the eye.

Probably the problem is in the vcl; this is what I'm using:
https://github.com/mattiasgeniar/varnish-4.0-configuration-templates/blob/master/default.vcl

Here are fragments from the varnish log for 3 successive calls to the same page: 503, then 200, then 503 again:

First call - returns 503
-   VCL_call       BACKEND_FETCH
-   VCL_return     fetch
-   FetchError     no backend connection
-   Timestamp      Beresp: 1408509130.524000 0.000219 0.000219
-   Timestamp      Error: 1408509130.524013 0.000232 0.000013
-   BerespProtocol HTTP/1.1
-   BerespStatus   503
-   BerespReason   Service Unavailable
-   BerespReason   Backend fetch failed
-   BerespHeader   Date: Wed, 20 Aug 2014 04:32:10 GMT
-   BerespHeader   Server: Varnish
-   VCL_call       BACKEND_ERROR
-   BerespHeader   Content-Type: text/html; charset=utf-8
-   BerespHeader   Retry-After: 5

Page refresh - Returns 200 from the cache
   VCL_return     hash
-   VCL_call       HASH
-   VCL_return     lookup
-   Hit            2147745802
-   VCL_call       HIT
-   VCL_return     deliver
-   RespProtocol   HTTP/1.1
-   RespStatus     200
-   RespReason     OK

Another refresh - returns 503 again.

VCL_call       HASH
VCL_return     lookup
Debug          "XXXX HIT-FOR-PASS"
HitPass        2147811368
VCL_call       PASS
VCL_return     fetch
Link           bereq 196777 pass
Timestamp      Fetch: 1408509419.224633 0.000666 0.000666
RespProtocol   HTTP/1.1
RespStatus     503
RespReason     Backend fetch failed

Any clues on getting the vcl correct appreciated.

The VCL you have linked to and your example in the question show you only using one backend. In this case using the probe to do a health check serves no purpose. As per drifteaur's answer disabling probe resolves many 503 issues and as you have no need for it, problem is solved.

However, if you are testing working towards rolling out on multiple backends then it still needs to be fixed(understood).

Looking at the VCL you linked (https://github.com/mattiasgeniar/varnish-4.0-configuration-templates/blob/master/default.vcl) it uses many sections which have been taken from https://www.varnish-software.com/ so we can presume (hopefully) that they are correct.

Currently, your probe is checking the response from "/ping" at your host and port, 127.0.0.1:8080, so that is 127.0.0.1:8080/ping .

If your set-up is multiple virtualhosts on one server with varnish sitting infront then using probe like this will not get a response(as this full url has most probably not been configured) and in turn this will lead to the backend being marked as "sick / unhealthy" and a 503 will be produced as Varnish will not even attempt to access the backend.

To confirm that it is your server setup add the following to your probe

backend default {
    .host = "127.0.0.1";
    .port = "8080";
    .probe = {
              .request =
              "HEAD / HTTP/1.1"
              "Host: www.EXAMPLE.com"
              "Connection: close";
              }
}

You will need to change www.EXAMPLE.com to a real domain you are using on the server.

If this gives you 200s rather than 503s than it is safe to confirm that using probe as you were with your server set-up was incompatible.

Probes info: https://www.varnish-cache.org/docs/trunk/reference/vcl.html#reference-vcl-probes


Best method for custom login/register I want to create a custom login and register page. I want both forms to show on the frontpage in the content area of my template above each other and not on separate nodes. Also, I would like to try to reuse the already existing code for validation of the forms.

I have looked around and found different ways to achieve this so I wonder what's the best way to do this..custom block, module or inside template or...?

Links to content or particular examples would be appreciated.

drupal_get_form('user_login');

And

drupal_get_form('user_register_form');

Will return the form for you and will deal with all the form stuff that needs to be dealt with. You just need to print whatever is returned by that function out and it should work.

Note: You did not specify the Drupal version, when using 7, drupal_get_form() returns an array which you need to pass through drupal_render() first to get a string that you can print.


Changing filter plugin settings before they are saved (This is for D8, although parts of this filter settings API were already in D7.)

As far as I understand, a filter plugin exposes its settings solely with FilterBase::settingsForm() - the central architecture then automatically stores the submitted form values and loads them when creating the plugin instance, so that a filter plugin can find them in $this->settings.

I'd like to reorganize and clean up the submitted form values before they're stored, but I'm not sure where to intercept the form. Should I attach a #validate or a #submit? If the latter, how do I ensure that my #submit runs before FilterFormatInterface::submitForm()?

It looks like your only options right now are relying on generic form API features, like #process and #value_callback. FilterFormatFormBase doesn't call into the plugins for validate/submit, like we do for example for block plugins.


Adding JS to a Drupal 8 theme (replacement for drupal_add_js) In Drupal 7, I can use drupal_add_js within a theme's template.php file as a theme_preprocess_html(&$vars) function:

   drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/scripts.js',
        array(
          'group' => JS_THEME,
          'preprocess' => TRUE,
          'weight' => '999',
        ));

  $vars['scripts'] = drupal_get_js();

In Drupal 8, I've tried converting this using attached in my theme's .theme file as such:

  $vars['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('theme', 'mytheme') . '/js/scripts.js',
      'options' => array(
        'group' => JS_THEME,
        'preprocess' => TRUE,
        'every_page' => TRUE,
      ),
    ),
  );

... but that did not work and there were no errors in watchdog / console or otherwise.

According to the D8 API page for drupal_add_js:

  Deprecated - as of Drupal 8.0. Use the #attached key in render arrays
  instead.

There was not much more info that that however. It seems that drupal_add_css will also use this method. I know it's still early days for Drupal 8 but I was hoping to get a jump on this.

It seems you can use hook_preprocess_page with attached as such:

function MYTHEME_preprocess_page(&$vars, $hook) {
  $path = drupal_get_path('theme', 'MYTHEME');
     // Render the main scripts file.
  $local_js = array(
    '#attached' => array(
      'js' => array(
        $path . '/js/scripts.js' => array(
          'group' => JS_THEME,
          'weight' => 9999),
      ),
    ),
  );
  \Drupal::service('renderer')->renderRoot($local_js);
}

This works great (theme.inc uses this method), note the extra nested array around the weight.


Fatal error: Cannot redeclare THEMENAME_preprocess_page() In D7, we have two copies of the same Bootstrap Agency base theme modified to show on different URLs using ThemeKey.

This works, but whenever a new module is installed, the site crashes and we see the following in the Apache error log:

PHP Fatal error:  Cannot redeclare bootstrap_agency_preprocess_page() (previously declared in /sites/all/themes/bootstrap_agency_minimal/template.php:13) in /sites/all/themes/bootstrap_agency/template.php on line 13

This is actually a very similar issue to this , I just couldn't comment on the above and Clive's answer wasn't all that clear to me. Is it better to merge the two functions or rename one of them - as the 2nd answer suggests? And what does merging entail?

Function names in template.php have to be prefixed with themename_function. At the same time, you cannot have a function declared twice.

bootstrap_agency_preprocess_page() should exist once in bootstrap_agency/template.php, and the other should be bootstrap_agency_minimal_preprocess_page() in bootstrap_agency_minimal/template.php.

If you do not need to do any override, and the one theme is a subtheme, you can simply omit it from template.php. Otherwise, you would need to copy the function code in and amend what you need to amend.


What's the best way to add a form in a node template? I already have a node created with some custom fields, I would like to show a specific form in the detail page of the node that i created (using the node.tpl.php file)

Why? because I need to use some values of the node to custom parts of that form

What's the cleanest way to do this?

The best way to do it is to create a variable for your template in hook_preprocess_node():

function hook_preprocess_node(&$vars)
{
  $form = drupal_get_form('form_name');
  $vars['my_form'] = render($form);
}

Now you can drop the form anywhere in your template as the variable $my_form


Hiding tab request new password I want to remove the option of request new password from admin section. I have Drupal 8.

/**
 *Implements hook_form_FORM_ID_alter().
 */

function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  unset($form['account']['pass']);
}

Hope it works.


How can I create a View that shows nodes without a relation? On my site, all the nodes of content type ABC are supposed to have a relation (from the Relation module) to a user.

However, although the relations are usually created in Rules, somehow this didn't happen for some nodes, and to make it worse, it happened randomly (non-sequentially).

So, I would like to make a view that shows the nodes which do not have any relation-- but I can't figure out how to configure the view to do that.

If I add a Relationship of Has relation Node -> User, I can get all the nodes that DO have a relation, but how do I get all the nodes that DO NOT have a relation?

You can just create a new filter criteria using your user reference field, and choose "Is empty (NULL)" as operator.

That will show all nodes that don't have any value in the user reference field.


How to set available options for Comment Per Page select? In Drupal 7, In comment setting a option Comments per page show 10, 30, 50, 70, 90, ... 300. I want to option "Comment per page" show like 1, 2, 3, 4, .... .

Comments per page options are taken from _comment_per_page function and as you can see, are hardcoded:

function _comment_per_page() {
  return drupal_map_assoc(array(10, 30, 50, 70, 90, 150, 200, 250, 300));
}

To substitute this with your own function, you need to implement hook_form_alter, and override changes made by comment_form_node_type_form_alter. Specifically, you need to change $form['comment']['comment_default_per_page']['#options'] and make sure $form['comment']['comment_default_per_page']['#default_value'] makes sense after that change.

To make sure your hook fires after the one by comment module, see Can I change the order in which hook implementation by different modules are called?


Customize title template based on page I know I can customize the template by overriding page-title.html.twig
but I'm looking for a way to have more than one title template. in my case, the suggested name form my path is  page__manage__customer_list So I tried to override it with page--manage--customer-list-title.html.twig.
how is that possible to override the title template?

to make the question more generalize and could be useful for other guys that looking for similar circumstances this could be helpful.

How can I override the title template based on content type or route?

You can add new templates to already existing using hook_theme_suggestions_HOOK_alter

Example of adding a content type:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page_title__' . $content_type;
  }
}

Then use page-title--content-type.html.twig

You could use $node->id(); if content type is too broad.


How can I make a gallery of "boxes" of content consisting of an image and some text? My aim is to create a gallery of content boxes. Each box is comprised of a connected image and text, so that when you hover on a box, you could see some css effect like the one you can see in this site here and in the image from it.

Actually it's more than a gallery, the image and text are combined. I'm looking for a way to conjugate them. A gallery of conjugated image and text.

So i want to make the text and the image of the box one unit, so that they could easily get the same CSS, as in the example above. Since I've yet to learn JS, I think I need a module for that.

Module Image Field Caption

The Image Field Caption module adds an extra text area for captions on image fields. Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

The Readme.txt of this module details how you can tune/customize the image caption display, e.g. via theme templates (.tpl files), or via CSS.

Module Textimage

The Textimage module may be a good fit for what you're looking for. Excerpt from itsproject page:

  ... adds text to image functionality using GD2 and Freetype, enabling users to create crisp images on the fly for use as theme objects, headings or limitless other possibilities.

The project page of this module also includes some links about HOWTO manuals.

Other modules to consider

If the above modules are not what you're looking for, then I suggest you consider these alternatives:

Drupal 7 - How to Create an Image Gallery in Drupal contains some great docu about this topic also.
Talking Drupal #083 is a great podcast about creating a Gallery, and includes a lot of recommended modules for it. Just to mention a few of them (mentioned on the linked page):

Gallery formatter

  ... provides a CCK formatter for image fields, which will turn any image field into a jQuery Gallery.

Views Slideshow

  ... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

Flexslider

  ... integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

Node Gallery

  ... allows you to create multimedia galleries where both the galleries and the gallery items are nodes (as opposed to gallery items being file fields, like Media Gallery).

Multiupload Filefield Widget

  The File module of Drupal 7 enables you to select only one file at a time which can be very time consuming in case of many files. This module uses the 'multiple' attribute of html5 to overcome this problem and presents a widget called 'Multiple' that can be used with fields of type File.

  Using this Multiple widget in case of File fields it is possible to select more files at a time, which can be a big time saver.

Multiupload Imagefield Widget

  As an extension to Multiupload Filefield Widget this module presents the same widget to Image fields.

Field Focus

  If you are using ImageField and ImageCache, you might have had hard times trying to get Scale And Crop to show what you actually want of your images.
  That is what ImageField Focus was made for.

  It allows you to tell ImageCache what portion of the image you want to focus to, and what portion you want to be cut out.

Plupload integration

  Provides integration between for the Plupload widget to upload multiple files and Drupal. Plupload is a GPL licensed multiple file uploading tool that can present widgets in Flash, Gears, HTML 5, Silverlight, BrowserPlus, and HTML4 depending on the capabilities of the client computer.


Rules: after saving new content + after updating existing content both triggered on node create I have two rules -

Triggers - after new content is saved
Triggers - after updating existing content

Problem

When I create a new node both rules are getting triggered together.

Probable Cause

I have an image field in my content type. Something that I found - "...Drupal re-saves the node just because it has a file attached to it...". Refer - http://drupal.org/node/1281960#comment-5065932

However, there must be some solution to this. Please any suggestions, workarounds, solutions...anybody?

Thanks.

You could add a condition in both rules to check whether the $node->created and $node->changed timestamps are same.

For a newly created node $node->created and $node->changed time will be same, while for an updated node both will be having different timestamps.

You probably need to add an Execute custom PHP code in rule condition to do this.


How does the view filter: Search: Search Terms works? Can I improve it? I have a View with and Exposed Filter: Search: Search Terms to filter the view result based in the keywords entered in this filter.

I works, but not as I expected.

Lets say I have a node with the title "The car, a good transport". Then:

if I enter the keyword: car the node is shown
if I enter the keywords: car a good the node is not shown
if I enter the keywords: good car  the node is not shown

Is this behaviour right? I need the node to be shown in all these situations

UPDATE: I see that there is already an open issue about this: http://drupal.org/node/1615438

If you want to search nodes based on title alone, you can try with Node:title instead of Search:search terms in filter section and select the operator as "Contains any word"


Create a view with the contents of "self" I am creating a View that will list all the current user's submissions of a specific content type. It is called "My Submissions".

However, I can't find a way to filter all results to "where author is me". Where could I achieve such thing?

You need to use contexts which is located under advanced to the right.

See below:


Get all submissions from specific webform I am trying to load webform submissions by a particular webform sign_up.

Using Query webform submissions, this does get me all the IDs associated and I can load the data using

$query = \Drupal::entityQuery('webform_submission')
  ->condition('webform_id', 'sign_up');
$result = $query->execute(); // Gives me IDs associated with the "sign_up" webform.

$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);
$submission_data = array();
foreach ($submissions as $submission) {
  $submission_data[] = $submission->getData();
}
// $submission_data now contains all the submissions from "sign_up" webform.

Is this the correct way of getting the submissions? I would think Webform comes with some sort of API to query the submission results.

I also tried: https://www.drupal.org/project/webform/issues/2902682 but ended up with an empty array.

The Webform module stores submission data using a custom Entity-Attribute-Value model. Your example code is the easiest and fastest way to get all the submission data. The only limitation would be the number of submissions vs PHP's memory limit. You will run out of memory if you are loading 1000's submissions


How to theme output of node_view_multiple()? If I want to theme the output of node_view_multiple() I can just set the #theme element of the renderable array generated by the node_view_multiple() function.

But, what if I'm not the one that called the node_view_multiple()? Is there a tpl file for that?

A good example would be a taxonomy term page. The taxonomy-term.tpl.php allows to theme only the term itself, not the actual list of nodes. So how can I theme that list of nodes?

Note that I don't want to theme individual nodes (that's not the scope of the question). I want to theme the list of nodes.

The return from node_view_multiple is supposed to be a dumb collection of node render arrays, it's not meant to be themeable in and of itself (at least not on a generic level, obviously case-by-case you can do it). The function sepecifically doesn't get involved with the theming, as that should be up to the caller to determine. So using #theme or #theme_wrappers on the outer array is the correct thing to do.

There isn't anything you can do to target other modules' use of node_view_multiple() in this respect, short of:

Patching the module code
Patching node_view_multiple itself so it has a default theme function, which you can then hook into.
Use a broader attack like hook_page_alter() to make specific changes to specific arrays when it makes sense to.


jQuery ui buttonset is not a function in Drupal 7 Like the title of this post suggests, I'm trying to add a fancy jQuery ui buttonset to my custom Drupal 7 module. But I'm getting the error message "TypeError: jQuery(...).buttonset is not a function" in Firebug. How can this be fixed? Do I need to update Drupal's internal jQuery ui version or something? Or maybe I need to add the buttonset widget manually?

Thanks for the help.

HTML:

<input id="edit-service-amount-0" class="form-radio" type="radio" value="0" name="service_amount">
Enkel

<input id="edit-service-amount-1" class="form-radio" type="radio" checked="checked" value="1" name="service_amount">
Dubbel

JS:

jQuery(document).ready(function() {
 jQuery('.form-item-service-amount').buttonset();
}

You're probably just missing the UI button library (libraries are added when they're needed rather than every js file being included for every page).

To fix, add this in your page callback:

drupal_add_library('system', 'ui.button');

To ensure your JS code is invoked after AJAX calls, you just need to wrap it in a Drupal behaviour:

(function($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $('.form-item-service-amount', context).once('mymodule').buttonset();
    }
  };
})(jQuery);

There's no need to use ready() in this context, Drupal will fire attachBehaviors() on document load, and when ajax calls occur, and your module's attach function will be called each time.

once() just makes sure the buttonset is only applied to an individual element once only, to avoid reattaching behaviours to elements that have already had it.


How do I repack an existing site into Open Source repo with bundled content and configuration? I have been tasked to repack an existing live Drupal 7 site, that will go out of commission, to make it available as Open Source on Github so anyone interested may find some use of it.

This will require that the repository comes with a database dump containing an example configuration and content.

What I need to do is to first anonymize the database from usernames/passwords, and also remove any not needed old revisions of existing content to compact the dump.

Is there any best practice strategies for how this can be done as simple as possible, and in the documentation provide a simple step-by-step guide on how to install it using the database dump?

Please note: While a Drupal Distribution would be optimal, in this case the wast amount of extra work, and testing, required is not possible.

You can anonymize some content using drush and the sql-sanitize command found in Drush by default:
https://drushcommands.com/drush-8x/sql/sql-sanitize/

If that doesn't clean up enough of your content to be suitable for Open Source release, you can use the underlying hook drush exposes for this task and implement it for your site as seen in this blog post, https://www.codeenigma.com/support/blog/doing-more-drush-sql-sanitize, found on google. An excerpt of the additional sanitation examples you could do from the blog post are:

/**
* Implements hook_drush_sql_sync_sanitize.
*/
function my_module_drush_sql_sync_sanitize($source) {
  // The query to sanitise field_data_field_profile_linkedin_page
  $linkedin_page_query = "UPDATE field_data_field_profile_linkedin_page SET field_profile_linkedin_page_value = CONCAT('http://uk.linkedin.com/user-name/', FLOOR(100000 + (RAND() * 900000)));";

  // The query to sanitise field_revision_field_profile_linkedin_page
  $linkedin_page_query .= "UPDATE field_revision_field_profile_linkedin_page SET field_profile_linkedin_page_value = CONCAT('http://uk.linkedin.com/user-name/', FLOOR(100000 + (RAND() * 900000)));";

  drush_sql_register_post_sync_op('sanitise_linkedin_page', dt('Sanitise field_profile_linkedin_page'), $linkedin_page_query);

  // The query to sanitise field_data_field_profile_telephone_number
  $telephone_number_query = "UPDATE field_data_field_profile_telephone_number SET field_profile_telephone_number_value = CONCAT('+44', FLOOR(1000000000 + (RAND() * 100000000)));";

  // The query to sanitise field_data_field_profile_telephone_number
  $telephone_number_query .= "UPDATE field_revision_field_profile_telephone_number SET field_profile_telephone_number_value = CONCAT('+44', FLOOR(1000000000 + (RAND() * 100000000)));";

  drush_sql_register_post_sync_op('sanitise_telephone_number', dt('Sanitise field_profile_telephone_number'), $telephone_number_query);

  // The query to sanitise field_data_field_profile_twitter_handle
  $twitter_query = "UPDATE field_data_field_profile_twitter_handle SET field_profile_twitter_handle_value =  SUBSTRING(MD5(RAND()) FROM 1 FOR 8);";

  // The query to sanitise field_revision_field_profile_twitter_handle
  $twitter_query .= "UPDATE field_revision_field_profile_twitter_handle SET field_profile_twitter_handle_value =  SUBSTRING(MD5(RAND()) FROM 1 FOR 8);";

  drush_sql_register_post_sync_op('sanitise_twitter_handle', dt('Sanitise field_profile_twitter_handle'), $twitter_query);
}

If you dont want to attempt to delete revisions manually yourself, in packing the site for git (make a backup first), I would look at the following module: https://www.drupal.org/project/field_sql_norevisions

Once the above steps are done. I would simply provide a drush archive-dump (or the contents thereof) in a GIT repo and instruct users to use Drush and the provided zip (or place the contents of the git repo into a zip) to use drush archive-restore to install the site. The only gotcha with this approach is to assure they use the same database engine on their system as the live site expects (that I can think of).


Use Ajax on Exposed Filter of a View but NOT on the pager of that View I'm experimenting with a "page" view, and would like to submit the view's exposed filters via Ajax, but not the same views pager.(I currently have a checkbox "has taxonomy term" filter that has been enhanced by the BEF module.)

Currently if I select "Use Ajax: Yes" in the "Advanced" column of the views settings, both the pager and exposed filter are submitted via Ajax. Is there a way to make it so that only the exposed filter submits via Ajax, and the pager reloads the page with the default "?page=X' GET parameter?

I was thinking I could leave "Use Ajax: No" in the view settings, and then somehow add the ajax functionality to the exposed form, via some hook. (form_alter?) Or maybe add some inline javascript which disables the ajax functionality of the pager? (which isn't even a form.)

Hoping someone could point me in the right path.
(Using Drupal 7 and Views 3)

I'm sure you've found a solution / workaround for this by now, but this thread came up while I was faced with the same issue, so I figured I'd share the solution that worked for me.

All I did was simply remove Drupal's AJAX event handler from the pager links using jQuery's unbind method, e.g.:

$('.pager a').unbind();

With the event handlers removed, the pagination links fall back on the HREF URLs contained within the anchor tags.


How to modify the registration form? I need some help adding text to the bottom of the registration form. I've never modified the registration form before and I did not set up this site.  Bootstrap Modal is being used for the form. Here is a screen capture of it:

The content needs a check box that must be checked for the submit button to work. Is there a module that can help, or, how do I locate this form to do some modifications?

You can always alter any form by hook_form_alter,in your case it would be somewhat closer to following

// Implements hook_form_form_id_alter().
function my_module_name_form_user_register_form_alter(&$form,&$form_state) {
  $form['help_text'] = array(
    '#markup' => 'Your help text will go here',
    '#weight' => $form['mail']['#weight'] + 1; // Or could be a fix value.
  );
}