how to access custom function in twig template file I've write small custom function in my .theme file. Is it possible to call that function in twig template files?

I would like to fetch description value for a field in views template file, so can we add a function like function getFieldDescription($field) and access in views template file ?

Ex: https://www.drupal.org/node/2486991 has url() function, which we can use in any twig template file.

Depending on the nature of your function, maybe but probably not.

As Clive pointed out, you can use certain functions in Twig. These functions however are mostly variable filters (formatters) for last minute alterations on variables. These can be used to translate, link, or in any way alter a provided variable. These functions are a combination of those provided by twig and some additions by Drupal. You can register your own Twig function, by extending on the TwigExtension class (example).

However most functions will probably be for adding additional data to the template and not to alter existing data. Instead you should place your custom function in a preprocessor and define a variable there. Then display this variable in the template.

Custom preprocessor (replace my_theme with your theme or custom module name):

function my_theme_preprocess_node(&$variables) {
  $variables['my_variable'] = 'value';
}

Twig:

{{ my_variable }}

Here is some reading on twig best practices: Twig best practices.

Some example code on preprocessors is here: template_preprocess_node(). Which is in fact systems invocation of hook_preprocess_HOOK().


What is wrong with hook_schema()? function recipe_submit_schema() {
  $schema['recipe_submit'] = array(
    'description' => 'Recipe base table.',
    'fields' => array(
      'recipe_id' => array(
        'description' => 'Primary identifier for recipe.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not_null' => TRUE,
      ),
      'recipe_title' => array(
        'description' => 'Recipe Title.',
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
      ),
      'author_name' => array(
        'description' => 'The author of the recipe.',
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
      ),
      'author_email' => array(
        'description' => 'The author email.',
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
      ),
      'recipe_description' => array(
        'description' => 'Recipe description.',
        'type' => 'text',
      ),
      'recipe_instructions' => array(
        'description' => 'Recipe instructions.',
        'type' => 'text',
      ),
      'recipe_ingredients' => array(
        'description' => 'Recipe ingredients.',
        'type' => 'text',
      ),
    ),
    'primary key' => array('recipe_id'),
  );

  return $schema;
}

gives me following error

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1171 All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead in /home/insasse/test_workspace/drupal7/includes/database/database.inc:2227                                                     [error]
Stack trace:
#0 /home/insasse/test_workspace/drupal7/includes/database/database.inc(2227): PDOStatement->execute(Array)
#1 /home/insasse/test_workspace/drupal7/includes/database/database.inc(697): DatabaseStatementBase->execute(Array, Array)
#2 /home/insasse/test_workspace/drupal7/includes/database/schema.inc(664): DatabaseConnection->query('CREATE TABLE {r...')
#3 /home/insasse/test_workspace/drupal7/includes/database/database.inc(2776): DatabaseSchema->createTable('recipe_submit', Array)
#4 /home/insasse/test_workspace/drupal7/includes/common.inc(7114): db_create_table('recipe_submit', Array)
#5 /home/insasse/test_workspace/drupal7/includes/module.inc(479): drupal_install_schema('recipe_submit')
#6 /home/insasse/.composer/vendor/drush/drush/commands/core/drupal/environment_7.inc(143): module_enable(Array)
#7 /home/insasse/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1167): drush_module_enable(Array)
#8 /home/insasse/.composer/vendor/drush/drush/includes/command.inc(422): drush_pm_enable('recipe_submit')
#9 /home/insasse/.composer/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#10 /home/insasse/.composer/vendor/drush/drush/includes/command.inc(199): drush_command('recipe_submit')
#11 /home/insasse/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#12 /home/insasse/.composer/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#13 /home/insasse/.composer/vendor/drush/drush/drush.php(12): drush_main()
#14 {main}

What am I doing wrong?

Try replacing 'primary_key' with 'primary key'


How do I create and theme an image link in Drupal 7 Views? Ok... here goes. I've had a lot of trouble trying to track down any sort of example like this, and the Drupal 7 Views documentation doesn't even document the views-view-field.tpl.php.

I'm trying to override the default display for a field inside of a view because the default field html content is not at all sufficient to my needs. I can almost do it, except that the views module likes to inexplicably wrap the field content in a  that I cannot override through the templates. Also I'm forced to hack into the field's $row variable internals directly, which does not strike me as a good long term strategy.

views-view-fields--slider.tpl.php

  <a href="<?php echo $fields['field_slide_link']->content; ?>">
    <img src="<?php echo $fields['field_slide_image']->content; ?>">

views-view-field--field-slide-image.tpl.php

<?php echo image_style_url('slide', $row->field_field_slide_image[0]['raw']['uri']); ?>

views-view-field--field-slide-link.tpl.php

<?php echo $row->_field_data['nid']['entity']->field_slide_link['und'][0]['safe_value']; ?>

So to summarize the two problems:

Diddling with the $row internals directly makes me quite uncomfortable. Surely there's a better and safer way of getting the not quite raw field values that I care about.
The rendered field content is always wrapped in a div.field-contain and I cannot eliminate it through the template, as I would have expected. I'm loath to call strip() to remove the html (I can think of several use cases where I might not want that wrapper).

This doesn't directly answer your two questions but should help...

The Views documentation on template overrides doesn't need to be particularly good...as those overrides are self documenting.

Open up any View for edit, open the Advanced fieldset, and click "Theme: Information" at the bottom.

You'll get something like this:

A complete list of every template file available for every field, and the view itself. From there you should be able to experiment quite quickly to find the template name you're looking for.


How can I translate "Read More" on Drupal 7 I have installed the internationalization module, but can't find where to specify a translation for "Read more" and other system strings.
Thanks for any hints

Assuming you have added and enabled another language in admin/config/regional/language

Just head over to admin/config/regional/translate and search for the string you want translated.

IMPORTANT The strings are both case and whitespace sensitive. Searching for "Read More" returns no results but "read more" has a hit (see screenshot).

Also, since a lot of strings have placeholders that are substituted with variables you might have better luck with other strings if you search for a small subset of it as opposed to the entire thing!

Additionally, I strongly recommend installing the Localization Update module, it will automatically download and update translations for all contributed modules.


How to add currency field? With respect to the question, can anyone suggest a remedy for the same.
How can I create a field for currency(with selecting currency and text field to enter the amount) considering the fact that there are multiple currencies.

I have tried adding prefix but it can input only a single value(for example $ or pound etc). I have also tried the currency module but it gives a single page with multiple currencies.

So to add a decimal field.

edit your content type.
manage fields
add new field
select Decimal from the Field Type dropdown, click the 'Save' button
Change 'Scale' to 2. These are the cents, 'Save field settings' button.
In the Prefix field add '$' and save settings.


View menu routes missing until first page load I having an issue with the installation logic of a custom module. I am trying to add menu links using menu_link_save() that link to a view that is defined in my module in hook_views_default_views().

I am creating a new site using a installation profile that installs this custom module by default. I'm not sure if this is related to being in the install/update environment instead of the normal page environment.

The problem I am having is that the view hasn't created any route in the menu_router table. When I add a link I get a row in menu_links, but the router_path column is empty and the row gets deleted by Drupal when it decides to rebuild the menus.

Is there way to cause the view to populate the menu_router table so that I can add links normally? Is there another way I can use for this? I would like to be able to keep my profile and, rely on a single site install action instead of having to do something after installing, as follow up.

The link never appears; Drupal deletes it from the menu_links table.

Problem background

I actually found an answer to this problem. Drupal has a rather aggressive way of deleting menu items that has the router_path field set to NULL (or empty) in table menu_links. If Drupal finds such a record it will delete the record upon the next run of menu_rebuild(); (see docs) or documentation block below.

/**
 * Populates the database tables used by various menu functions.
 *
 * This function will clear and populate the {menu_router} table, add entries
 * to {menu_links} for new router items, and then remove stale items from
 * {menu_links}. If called from update.php or install.php, it will also
 * schedule a call to itself on the first real page load from
 * menu_execute_active_handler(), because the maintenance page environment
 * is different and leaves stale data in the menu tables.
 *
 * @return
 *   TRUE if the menu was rebuilt, FALSE if another thread was rebuilding
 *   in parallel and the current thread just waited for completion.
 */

Solution

Each menu item created this way must contain the property customized and have its value set to to 1. This forces Drupal to update the record in table menu_links with the matching router_path instead of deleting it. See function _menu_navigation_links_rebuild($menu) around line 2929 in menu.inc. _menu_navigation_links_rebuild($menu) is called from menu_rebuild().

Example

This will create a new link on the top level in a menu named 'your-menu-name'.

$ls = array(
  'menu_name' => 'your-menu-name',
  'link_title' => 'Your Link Title,
  'link_path' => 'your/link/path',
  'plid' => 0,
  'weight' => 0,
  'customized' => 1, // "The magic property"
);

$newpid = menu_link_save($ls);


Why are overrides not included in download file? I have the problem, that some of my features are overridden and will not be updated after recreation.

For example there is one feature that needs a new dependency and the title of one view was changed.
I want to include these changes in my feature and click on recreate.
When i look into the download files, you can see, that the changes (dependency and view titles) are not included.

If i change the files manually, the feature has the status "Standard".

The feature includes content types, panel pages, fields, views, permissions and some strongarm variables.

Does anybody know, why my changes are not included, when recreating my features?

Drupal v. 7.43
Features v. 7.x-2.10

Thanks for your help.

The solution was to use drush.

drush fu feature_name

After that all files were inclduded.


show/hide field based on user's attribute how do I show/hide field of the form based on currently logged in user's field?
my users' profiles have start_date_field.

my form has 5 questions:

day_1_activity -> drop down
day_2_activity -> drop down
day_3_activity -> drop down
day_4_activity -> drop down
day_5_activity -> drop down

Now I would like to do a simple comparison:

start_date_field of logged in user with current_date.

if start_date_field = current_date show day_1_activity only.

if start_date_field + 1 = current_date show day_1_activity and day_2_activity only.

...

First you need to hide all questions drop down fields by setting #access to FALSE then show each field according to the condition.

You should use hook_form_alter to alter your entityform form.

function MODULE_NAME_form_MACHINE_NAME_entityform_edit_form_alter(&$form, &$form_state) {
  global $user; // to get the current user uid

  // hide all drop down
  $form['field_day_1_activity']['#access'] = FALSE;
  $form['field_day_2_activity']['#access'] = FALSE;
  $form['field_day_3_activity']['#access'] = FALSE;
  $form['field_day_4_activity']['#access'] = FALSE;
  $form['field_day_5_activity']['#access'] = FALSE;

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

  // get user start_date_field value
  $user_start_date = $account->field_start_date_field['und'][0]['value'];

  // show question drop down based on the condition.
  switch ($user_start_date) {
    case date('Y-m-d'):
      $form['field_day_1_activity']['#access'] = TRUE;
      break;
    case date('Y-m-d', strtotime('+1 day')):
      $form['field_day_1_activity']['#access'] = TRUE;
      $form['field_day_2_activity']['#access'] = TRUE;
      break;
    case date('Y-m-d', strtotime('+2 day')):
      $form['field_day_1_activity']['#access'] = TRUE;
      $form['field_day_2_activity']['#access'] = TRUE;
      $form['field_day_3_activity']['#access'] = TRUE;
      break;
  }
}


Some fields are not sorting properly in view I'm trying to create a directory list in view. But some of the fields are not properly sorting.

See the below image for my view configuration.

And the output of the view.

Update:  Style setting

Update:  Field Settings

Grouping

Please anyone help me to get the correct output.

It's probably not a configuration problem.  Examine the nodes that aren't sorting correctly.  They likely have spaces at the beginning of their titles.


How can I change the date format for user submitted data in confirmation emails The confirmation emails sent by Webform (running under Drupal 8.9.7) on submission are in US format "m/d/Y" for all date fields that the user entered on the form (but not for system generated dates such as the time the form submission was made, which are in UK format).  I need to change them to UK format "d/m/Y" since that is what my users expect.
Web research tells me that Webform picks the date format for emails from the system's "default medium date".  Not so.  My system's default medium date format is "D d/m/Y - H:i".   What I get for the date fields that the user submitted is "D, m/d/Y - H:i" (note also the subtle difference - one doesn't have a comma, the other does).
I have varied the format of all the default date formats, but nothing changes.
Guidance on how to fix or on a workaround would be appreciated.

I have a work-around, but not a solution:

Go to /admin/structure/webform/config/elements
In the section "Element Formats" change "Date/Time" from "- default -" to "Default medium date (medium)"


Check whether a field value exists in a custom table when a webform is submitted I created a custom table named "test_customerid" for the use of select queries from the drupal database. The fields are naid (for national id), name and surname.

My aim is to display an error message if the user attempts to insert an National ID which is already present in the table. Otherwise, all information are added to the table "test_customerid". This must occur when a webform is submitted.

Here are my codes that I included in the webform.module of my drupal project (inside function webform_webform_submission_insert($node, $submission)):

$accessnode=$node->nid;
if($accessnode==6)
{
    $dataSub=$submission->data[1]['value'];//submitted value of National ID

    $result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub));
    if(!(empty($result)))//I also tried "if($result)"
    {
        drupal_set_message(t('The NID already exists.'), 'error');
    }
    else
    {

        db_insert('test_customerid')
        ->fields(array(

        'naid' => $submission->data[1]['value'],
        'name' => $submission->data[2]['value'],
        'surname' => $submission->data[3]['value'],
        ))
        ->execute();
    }

The problem is:
It displays the error message even if the user inputs a new National ID. I can't add new information in the table.

I even tried to convert the data into strings by using these before placing the variable into the insert query but it gives me the same error message:

$dataconvert=implode(",",$dataSub);
$dataconvert=serialize($dataSub);

I want that the query to take the National ID value from the webform and check out if it exists in the table. Can you someone help me with this please?

Just replace

$result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub));

with

$result=db_query("SELECT * FROM {test_customerid} WHERE naid = :naid",array(':naid'=>$dataSub))->fetchAll();

and try, hope it will work


Create node template only for default view-mode I created a node template for my content type which I only want to use for my default view mode and keep the standard view of the teaser. My file is named like node--customnode.tpl.php. As I read I can create a template file for the teaser by adding node--customnode--teaser.tpl.php but it does not work for default in the same way. Does anybody have an idea?

Try adding the following code to your theme's template.php file:

function THEMENAME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type) && isset($vars['view_mode']) && $vars['view_mode'] == 'default') {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type . '__default';
  }
}

Replace "THEMENAME" with the machine name of your theme.

This should allow you to use a template file called node--customnode--default.tpl.php (assuming your content type is called "customnode") which will apply only on the default view mode.

n.b. You will need to flush your caches after adding both this functino and the template file.


View is returning two default results when no value in filter is being selected. Why? I have created a view to display node's title and added exposed filter for filtering content. When the view page is loaded it is returning two nodes , I do not know on what basis it is returning those two nodes.I want no result should be displayed until I select some value in filter.Please suggest ??

There is a views setting "Exposed form style", where you can select "Input required" if you don't want results to be displayed by default.

See the attached screenshots:

Then


Issue with adding fields in Views 3.7 I'm having an issue with Views 3.7 not displaying all fields in the 'add field' dialog when trying to add a field to a view. There is only a small number of fields available from nodes etc whilst on my development version (which is almost identical) there are loads of fields to choose.

I have tried to copy my development version database to use on the staging version and use that but I get the same problem. Flushed caches etc.

Another related problem is when you try to add a custom header to your view, there are no selections to choose from. Click on close, and you get a page full of JSON.
I am unsure where to go on from here. Anyone had a similar issue in the past? Thanks.

Views uses a lot of JavaScript, also AJAX to get latest info from the server. I had a similar problem a long time ago but that was because my Drupal instance was on my localhost and that gave errors with AJAX requests.


Medium editor showing "placeholder" I'm trying to use the Medium module, but for some reason it just shows "placeholder" when I click on the Configuration > Content Authoring > Medium Editor. Could you point me to any solution for that?

That module has not been finished, yet. The function that should return the form for the settings of that module doesn't even allow to set any settings; it just output that Placeholder text you see.

  $form = array();

  // @TODO: Allow users to choose the image style used for media embeds.
  // @TODO: Allow users to choose which media plugins should be exposed.

  $form['whatever'] = array(
    '#markup' => 'Placeholder'
  );

  return $form;

The module is in a alpha state; don't consider it ready for production.


Adding multiple buttons on node submit form - every button submits the form I am adding several buttons to a node form.  The result is something that looks like this pastebin.  The pastebin is a somewhat truncated version, here is the real short one:

$form = [
  '#submit' => [],
  '#actions' => [
   'submit' => [
     '#type' => 'submit',
     '#submit' => ['node_form_submit']
   ],
   'skip_done' => [
     '#type' => 'submit',
     '#submit' => ['skip_done_handler']
   ],
];

I thought that if $form['#submit'] was empty then the only submit handlers that would be called are the ones on the respective buttons.  I'm either completely wrong in my understanding or I've misconfigured something.

Should this work they way I'm expecting it to?  If so, what am I doing wrong?

If you leave $form['#submit'] unset or empty then drupal_prepare_form will try to replace it with a submit handler provided by the base form:

if (!isset($form['#submit'])) {

// Ensure that modules can rely on #submit being set.
$form['#submit'] = array(

);

// Check for a handler specific to $form_id.
if (function_exists($form_id . '_submit')) {
  $form['#submit'][] = $form_id . '_submit';
}
elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_submit')) {
  $form['#submit'][] = $form_state['build_info']['base_form_id'] . '_submit';
}

If you're submitting a node form then $form_state['build_info']['base_form_id'] . '_submit' will be equal to node_form_submit, which is why it's being called.

In order to prevent node_form_submit from being called, you'll need to provide a $form['#submit'] handler, or define FORMID_form_submit, which takes the form NODETYPE_node_form_submit for nodes.


Adding the button implemented from "Printer, e-mail and PDF versions" in node.tpl.php I am using Printer, e-mail and PDF versions, and I was wondering if there were a way I could place the print button in node.tpl.php above the $content area, instead of through the Drupal administration area. Could that be done through a variable?

In the administration area, disable the insertion of the link, then add the following (depending on which modules you use) to your node.tpl.php:

Print: <?php l('Print', 'print/'.$node->nid); ?>
Print to PDF: <?php l('PDF version', 'printpdf/'.$node->nid); ?>
Send by email: <?php l('Send by email', 'printmail/'.$node->nid); ?>

However given you have your own theme template, it could be better to just modify the CSS applied to the print link(s) to be in a different location on screen.


Attach file to email I have a site with a webform, which when submitted sends an email. The form has a file upload which should then attach the file as an attachment to the email. I'm not getting any attachment.

I've created a hook for hook_mail_alter and tried hardcoding any attachment to be sent but every email i get has no attachment.

function my_module_mail_alter(&$message) {
  $file_content = file_get_contents('sites/default/files/tmp/test.pdf');
  $message["params"]["attachments"] = array(
    'filecontent' => $file_content,
    'filename' => 'test.pdf',
    'filemime' => 'application/pdf'
  );
}

I've debugged the MailManager.php just before the email is sent and the $message variables param['attachement'] has the valid contents from the code above.

I've instaled modules: SMTP (so i can send emails from my local), MimeMail and enabled MailSystem The emails are being sent without any issue, but again never with an attachement.

I don't know what i'm doing wrong, any ideas?

Core: 8.6

Here's the answer, which is just an extension on the comment from @berramou

$file = file_load($fid);
  $message["params"]["attachments"][] =[
    'filepath' => $file->getFileUri(),
    'filemime' => '' // argument must be present, but can remain empty
  ];
}


Views help from Advanced Help isn't being displayed or I can't find it It turns out that I actually hadn't installed Advanced Help on this Drupal setup and was only using regular 'Help'

I'm using Views 7.x-3.5 (API version 3) and Drupal 7.17

I installed Advanced Help (some time ago now) and cleared all caches

When I go to /admin/help I see a list of the following...

Help topics

Help is available on the following items:

Administration menu
Advanced User Management
Block
CKEditor
Color
Comment
Content Access
Contextual links
Dashboard
Database logging

Date
Field
Field SQL storage
Field UI
File
Filter
Help
Image
List
Menu

Menu Block
Node
Number
Options
Path
Pathauto
RDF
Rules
Rules Forms Support
Search

System
Taxonomy
Text
ThemeKey
Token
Trigger
User
Webform

The following is constantly displayed in structure > views

  If you install the advanced help module from http://drupal.org/project/advanced_help, Views will provide more and better help. Hide this message.

Install the advanced help module

  When this module is installed, users with the view advanced help index
  permission can access the advanced help index by going to Administer
  -> Advanced Help (http://www.example.com/admin/advanced_help). Additional view advanced help popup and view advanced help topic
  permissions enable them to access the actual help pages and popups.


Which Drupal function inserts the data in the history table? So as far as I've seen, the history table holds timestamps when users viewed nodes.

Which Drupal function insert the data in that database table? The most logical place for me would be in statistics_exit(), where the accesslog table is being populated, but it's not there. The only place I've seen something similar is in node_tag_new(), but I am not sure if that's the right one.

Can anyone shed some light into this?

It is node_tag_new(), the function that is part of the Node module (line 299 of that file in Drupal 7).

/**
 * Updates the 'last viewed' timestamp of the specified node for current user.
 *
 * @param $node
 *   A node object.
 */
function node_tag_new($node) {
  global $user;
  if ($user->uid) {
    db_merge('history')
      ->key(array(
        'uid' => $user->uid,
        'nid' => $node->nid,
      ))
      ->fields(array('timestamp' => REQUEST_TIME))
      ->execute();
   }
}

Here's the same function in Drupal 6.

/**
 * Update the 'last viewed' timestamp of the specified node for current user.
 */
function node_tag_new($nid) {
  global $user;

  if ($user->uid) {
    if (node_last_viewed($nid)) {
      db_query('UPDATE {history} SET timestamp = %d WHERE uid = %d AND nid = %d', time(), $user->uid, $nid);
    }
    else {
      @db_query('INSERT INTO {history} (uid, nid, timestamp) VALUES (%d, %d, %d)', $user->uid, $nid, time());
    }
  }
}

The function is called by node_show(), which uses the following code.

// Update the history table, stating that this user viewed this node.
node_tag_new($node);

As said from that comment, the purpose of the function call is updating the history table to record the fact the current user viewed the node.


How to sort by title using Search API / fuzzy search? In d7 i'm using fuzzysearch together with a table view for a quite long list of contacts. So far this works quite well – searching for "Mill" will list all "Miller" entries. Problem is: there is no option for sorting the results other than by relevance, ID, content type, random or PHP.

It would be great if the table was sortable by any of the fields – like it is possible in a regular table view – or at least by the title field. I'm not sure if I'm missing something – or if this is anyways not possible?

These are all the option I currently have in the sorting section of the table view:

(sorry, screenshot is partly in german)

All pointers / hints gladly appreciated. Thank you!

Finally I got it working – here is how:

Search and metadata » Search API » fuzzysearch index » filter

First I checked the option "Aggregated fields" in the top section "Data alterations". Then I added an aggregated field that I called "Sort Name" pulling data from the field "Name".

Then I added that field to the list of indexed fields in the tab "fields". It is important to change the field type to "string" – otherwise the field won't be available for sorting.

Then finally the field should be available for sorting from the "Sort by" dialogue inside the views form.

The third paragraph of the accepted answer to the question "I have no fields available for sorting with Search API sorts module" pointed me in the right direction: "If a field is full-text, one trick is to create an aggregated field containing just that field and assign it a string type."

…I hope this may help somebody sometime…


Add html to taxonomy_menu_block taxonomy terms I am trying to edit the html of the taxonomy terms printed from the module taxonomy menu block.

Is there a way to add a theme wrapper or to override a template so I can add html to each and every taxonomy term?

Looking at this module it does not employ a theme template file so overriding with your own template file is not a possibility; therefore, you will need to use Drupals theming later and processing hooks in your theme to alter the HTML output of the module without hacking the module. A start would be to look at hook_block_view_alter


Node values not retrieving properly in .theme and Twig files I created a content type and have a couple of fields: a heading, links, and images.
After creating a node out that content type, I want to pull parts of the node into my homepage. And for that, I used the following in my .themename.theme.

use Drupal\node\Entity\Node;

function amarula_preprocess_page(&$variables) {

    $nid = 62;
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    $variables['field_vanilla_heading'] = $node->field_vanilla_heading->value;
    $variables['field_vanilla_main_content'] = $node->field_vanilla_main_content->value;
    $variables['field_vanilla_home_link'] = $node->field_vanilla_home_link->value;
    $variables['field_vanilla_home_thumbnail'] = $node->field_vanilla_home_thumbnail->value;
}

I get the value of the field_vanilla_heading in my page--front.html.twig

<h1>{{ field_vanilla_heading }}</h1>

But, the rest of the fields are giving problems.

For the main content {{ field_vanilla_main_content }}, which is long text with summary, I am seeing all the HTML in the page. How can I escape this in twig?

For the rest of the fields, kint tells me that they are null, which is not true:

{{ kint(field_vanilla_home_link) }}
{{ kint(field_vanilla_home_thumbnail) }}

Below is the list of all the field settings:

I can already get the node ID. But how can I get all the values of the node accordingly?

not sure if you still need an answer, but the problem is how you want to retrieve the values from the fields. I get confused all the time, so I usually check out what the column name in the database is of the value I want to get from the field.

Links:

$node->field_vanilla_home_link->uri;
$node->field_vanilla_home_link->title;

Images are a bit more complicated, maybe there are more ways, but this is how I usually do it:

$entity = $node->field_vanilla_home_thumbnail->entity;
    if ($entity) {
      $variables['field_vanilla_home_thumbnail'] = $entity->getFileUri();
    }

OR with this you could load different image styles (don't forget to import ImageStyle class):

ImageStyle::load('thumbnail')->buildUrl($entity->getFileUri());

For the image alt:

$node->field_vanilla_home_thumbnail->alt

And I guess you know how to use those values in twig to print links and images (just basic html) :)

Edit: For your problem with your long text with summary, you can filter the markups with "raw":

{{ field_vanilla_main_content | raw }}


Drupal 8: Node preview when using Page Manager I am using the Page Manager module in D8 to show the full node view pages. Drupal also provides a button to preview the content when creating/editing it. Is there a possibility to actually preview the page using the page manager layout?

Thanks for the answers!

Vasi.

Not ouf the box because page_manager is about routes, and node preview is a completely different route than viewing a node.

Something like Display suite and probably also Panelizer (never really used it myself) whould probably work there though.

That said, it should be possible to build something too with Page Manager too by creating a second page (with a duplicated page variant(s) that you need to keep in sync somehow) that overides the preview route, but you also need to somehow write a context provider that loads the node based on the passed tempstore argument and also a write a block that replicates the UI elements for selecting the view mode and going back to edit


Hooking into page specific instance of checkout flow form I'm working on manipulating the buttons used for the checkout flow of using D8 Commerce 2.
I'm using MYMODULE_form_commerce_checkout_flow_multistep_default_alter but its changing both the form buttons on the order information page and the review page.
I want to have different buttons on these two pages.
Is there a way when using a hook to manipulate a form to set it so its page specific?

Conditionals are still the answer, but turns out there's an easier way that doesn't involve getting the current path:

function MYMODULE_form_commerce_checkout_flow_multistep_default_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form['#step_id'] == 'order_information') {
    Do stuff to the order information page form.
  }
  if ($form['#step_id'] == 'review') {
    Do stuff to the review page form.
  }
}


Webform description allowing HTML I'd like to allow HTML in my webform field descriptions. I don't need an editor of some sorts; just the basics like  and  tags and stuff. How can I edit my webform to allow these tags in the description field?

It looks like the module Webform HTML Textarea might do what you're wanting. It allows you to use the site's input methods (Filtered text, plain text, etc.). So you could make a limited one for your users with only the options you need (bold, italic, underline, etc.).


Disable Timezones in User Account How do you disable Timezone from being edited in a User account? Is there a config setting I can turn off?

Visit index.php?q=admin/config/regional/settings to configure whether users are able to set their own timezone.


ctools export_api question: ctools_export_crud_load vs ctools_export_load_object What is the difference between ctools_export_crud_load/ctools_export_crud_load_all
 and  ctools_export_load_object and under what use case should one use one or the other?

ctools_export_crud_load():

  Load a single exportable object.

ctools_export_crud_load_all():

  Load all exportable objects of a given type.

ctools_export_load_object():

  Load some number of exportable objects.

The first two are just shortcut functions to ctools_export_load_object() (with a bit of setup logic) ctools_export_load_object() is a more complicated function that can filter the required exportables by various criteria. The main point of interest as I can see it is that the first two accept a $reset parameter to reset the exportable(s)'s caches, whereas ctools_export_load_object() doesn't accept that parameter.

Basically, I'd say if the exportables you need to load can't be queried by using ctools_export_crud_load() or ctools_export_crud_load_all(), then use ctools_export_load_object(). Otherwise use one of the former functions, as they handle some of the necessary setup for you.


Missing bottom level item when a node is linked to two menu objects I have been trying to create a custom menu block which shows a number of menu items with images on the current level.

I am having an issue where the active trail array doesn't return an menu item for the active node on level 4 of my menu. Here is an example of how I get the active trail:

$menu_tree = \Drupal::menuTree();
$menu_parent_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

foreach($parameters->activeTrail as $active_menu_link) {
  if($active_menu_link !== '') {
    $active_menu_id = explode(':', $active_menu_link);
    $entity = \Drupal::entityManager()->loadEntityByUuid($active_menu_id[0], $active_menu_id[1]);

    kint($entity->getTitle());
  }
}

It seems that the issue is mostly related to the fact that the same node is linked to both a child menu item and a parent menu item. If I remove this then the function works as expected. This is the my menu structure.

The two menu items highlighted in red are both linked to the same node since I want it to act as an overview page for the category. It could be that theres something else I can do to structure the menu differently. I am open to any alternatives on how I can get around this.

I resolved this by manipulating the tree object manually further down my module. I checked if the url of the parent object matched any of the child objects via a loop.

$menu_tree = \Drupal::menuTree();
$menu_parent_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

// Setup current link
$currentLinkId = reset($parameters->activeTrail);
$parameters->setRoot($currentLinkId);

// Load the tree based on this set of parameters.
$tree = $menu_tree->load($menu_name, $parameters);

// Get the parent of current menu so we can use its
// children as the links
$parameters->setRoot(reset($tree)->link->getParent());
$tree = $menu_parent_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_parent_tree->transform($tree, $manipulators);

foreach($tree as $key => $menu_item) {
  // Check if the link is the current page?
  $current_internal_path = $menu_item->link->getUrlObject()->toString();
  foreach($menu_item->subtree as $sub_key => $sub_link) {
    $sub_internal_path = $sub_link->link->getUrlObject()->toString();

    if($current_internal_path == $sub_internal_path) {
      unset($tree[$key]->subtree[$sub_key]);
    }

    // Check if we have another sub tree (we are not the parent). This can happen when a parent
    // link is attached to the same node as a child one.
    if($sub_link->subtree && count($sub_link->subtree)) {
      $lower_level_links = $sub_link->subtree;

      foreach($lower_level_links as $lower_link_key => $lower_level_link) {
        $lower_level_url = $lower_level_link->link->getUrlObject()->toString();
        if($sub_internal_path == $lower_level_url) {
          // Set the active menu level as this.
          $tree = array($sub_link);
        }
      }
    }
  }
}

// Build up our menu
$menu = $menu_tree->build($tree);

This is perhaps not the cleanest solution with a lot of extra processing required but seems to work in this instance.


How to hide a block enitirely which has empty content (unless for a specific role)? I have a custom block and I want to limit it only to one role. The position of this block is administrator->dashboard.

I have set the visibility settings of block to be shown only to role editor, but when I sign in with a user whose role is something else, such as a photographer, it shows the block with a text in it: "(empty)".

It truly does not show any content, but I WONDER why it shows the block's structure? I expect it to be totally invisible as if no such block ever exists.

What's wrong with it?

From the question details (and comments to it), it appears to me that the "(empty)" is somehow the result of your Views output (formatted as a block).

But for anybody who has not the role of Photographer, the result of the View (the output of it) is just "empty". So you may want to try / experiment with the "No Results Behaviour", which is located in the most right column when editing the view details (within 'Advanced').

Also note that you should make a difference between "access" to the content of the nodes (or whatever) that are shown in the block (if not empty), and what Drupal shows as the wrapper/container of such list (such as the block your question is about). Maybe, just for debugging purposes, you should try to build a similar view formatted as a page (instead of a block), and see what kind of output (result) you get in both scenario's (somebody with the photographer role, and somebody who des not have that role). While doing this page-related experiment, you may get different results, depending on what you specified within the "No results behaviour". And that might help to understand that your (empty) block issue is also a matter of "No result behaviour".

If you cannot get it to work this way, you may want to consider using the BEAN module, which gives you way more granularity / flexibility for creating blocks.


Taxonomy term not localized correctly in multilingual site in Drupal 7 I am having multilingual site in drupal 7. I have a content type that should be translated in 2 languages, I am using term reference field in it, with display type select list

First I tested
Localize. Terms are common for all languages, but their name and description may be localized.
 and
 Translate. Different terms will be allowed for each language and they can be translated
But in any language, all terms from all languages are shown in the select list,
Then I decided to use
 Fixed Language. Terms will have a global language and they will only show up for pages in that language.
 and use separate vocabulary per language but when I want add a node in second language or translate english nodes in second language(persian) show the first language (english) terms only.
How can I achieve this job ? I want to show terms only from current language.

Edit
again I came back to using one vocabulary and I have this problem

and my vocab and translations

and when I am in english site show perisan terms :(

why does this happen? and what is the solution ?

I had the same problem. I enabled 'Synchronize translations' (i18n_sync) module. This solved it. It is bundled with i18n module.

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


How can I copy theme configuration when copying a site? I have written a script that copies a drupal 8 site. The steps go something like this:

dump old site database into file
replace old site name with new site name in said file
create a new database using that file
Copy all files from the old directory into the new directory
Modify sites.php and settings.php to contain the new site's configuration.

This works (I've debugged the script quite a bit) except for theme settings are not transferred over. Are the theme settings stored in the database? If so, why are my settings not transferred over? If not, where are they stored?

Assuming access only from a command line, how can my script copy theme settings from one Drupal 8 installation to another using the same theme?

Theme settings are stored in the database. However, Drupal 8 has configuration management. You can export the configuration to yml files. Theme configuration is included.

You can download the yml files at /admin/config/development/configuration/full/export

Or you can export it to the configuration folder by
$ drush config-export sync


hook_update_N - expose new field to views after module update I've added new field to existing table with hook_update_N. Now, is it possible to expose this new field to views? I want it to be exposed when module is updated...

Possible?

Yep, you can use hook_views_data_alter():

Alter table structure.
You can add/edit/remove existing tables defined by hook_views_data().


Dynamic page content How can I include body content on a dynamically generated page?

The page in question is defined in hook_menu(). I have successfully given it a title but I don't know how to give the page text content.

I think you're just looking for a standard page callback for your menu item. To extend the example from the hook_menu() docs slightly:

function mymodule_menu() {
  $items['abc/def'] = array(
    'page callback' => 'mymodule_abc_view',
  );
  return $items;
}

function mymodule_abc_view() {
  $text_content = 'Text to print to the page.';

  // You could just return the string itself here, that will also work fine,
  // but it's 'best-practice' to return a render array so other parts of the system
  // can alter the content if they so desire.
  return array(
    '#markup' => $text_content
  );
}

Remember to clear Drupal's caches after making the changes to hook_menu(), or they won't be picked up.


Why 'excluded from display' fields in views are not available in template files? There is a slide show in my website and I implemented it using views_slideshow module. its content type has 2 fields: 1. an address 2. and image. when user clicks on the image it must be redirected to the address.

this is views-view-fields--VIEWNAME.tpl.php

<?php
global $base_url;
$address = strip_tags($fields['field_site_link']->content);
$address = str_replace($base_url,'',$address);
print $address;
?>

<a href="<?php print $address;?>"><?php print     $fields['field_site_image']->content; ?>

I excluded the field_site_link from display but it is not available in this function. I also tested <?php kpr($fields); ?> and it was still unavailable. How do I can get its content?

If you exclude any field that means you don't want to display that fields.
So obviously that fiels is not avilable to any template for exclude's default behaviour. That field only available as token in views.


Scrolling display module I'd like to make a scroll display for sponsor's logo like this demo.

Is there any module for Drupal 7? if there is no one how can i achieve this?

You could modify http://drupal.org/project/jcarousel to do this. Since the link you provided already provides a guide (http://valums.com/scroll-menu-jquery/) to implement this why don't you put the code in a drupal block and display it.


What module or views recipe can display a featured node with different layouts from the rest? I'm building out a views layout where I need to display a featured node with a different layout from the rest of the nodes being displayed. It looks something like this:

As you can see the middle node is larger than the rest and has body content displayed. What methods are there to output a custom views layout like this?

Seem that you can go with the module called views_nodes_split https://www.drupal.org/project/views_nodes_split

BUT, this is better solution if your using display suite already:
You can just use Display Suite + Views as there is a setting when choosing an output. Display suite lets you pick which view mode to use for each output:


Views module: How to limit access by user I'm using the Views module to create a view that only specific users should be able to access.  I know that Views includes access control by role or permissions, but I need something more fine-grained: Basically, I want to be able to say only user "x" and user "y" can access a particular view (or else someone with a site administrator role). So this would function very similar to how ACL module acts for individual nodes.

Is the best approach to create a custom views access plugin?  I don't have much experience with this.

Also, I'm wondering about using an argument with some validation to accomplish this (so that I don't have to create dozens of separate views). For instance, since this view will be a tab on a specific node path, I'm wondering about setting up a user reference field on that node that specifies who could see the view. I'd just need a way for the view to only validate if the current user equals a user specified in the user reference field.

Any ideas?  Or am I making this more complicated than it needs to be?

Thanks,
Ben

Try the Views Access Callback module.

  Provides callback-based access control for Views.

  Available callback functions are defined by modules using hook_views_access_callbacks() function (in the same way as in hook_perm()), then could be set in the view's "Access restrictions" configuration.


Displaying the node title in different region My designer just killed me, I realised he put node titles in a different region of the page layout, just beneath a menu and before left/right sidebars. No going back now.

How can I display titles of things (nodes, views etc) in a different region and hide it from the content region?

Not sure which version of Drupal you're using, but the method is basically the same. In D6 just place  where ever you need it in the page.tpl.php template and remove it from the node.tpl.php template (or use conditionals to output it there when needed).


how to prevent javascript from running again when an AJAX form is submitted I have this code in a javascript file to hide some search filters...

$('#views-exposed-form-faceted-search-page .form-type-select').once().hide();

The user can toggle the visibility of the filters by clicking on my #advanced-search link...

$('#views-exposed-form-faceted-search-page #advanced-search a').once('advanced_search').click(function(){
        $('#views-exposed-form-faceted-search-page .form-type-select').toggle();
});

It works, but when the AJAX form is submitted, the hide() function runs again and the .form-type-select elements are hidden.  How do I prevent them from being hidden a second time?  I only want my code to hide the selects when the page first loads.

If Ajax reloads this part you are hiding, the marker once() has set is overwritten, also the show/hide status. Then you need a different approach, either submit the show/hide status, so that it can be returned by Ajax, or create a show/hide Ajax form element to have full control over it through Ajax.

If this is outside of the Ajax wrapper you can do this in javascript, but apply the jQuery selectors on context:

$('#views-exposed-form-faceted-search-page .form-type-select', context).once('search-hide').hide();

See https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


Use administration theme for verified users when adding or editing content I'm having a problem with the administatration theme. I want verified users to see the administration theme when they are adding or editing content. Right now only the admin user sees the administration theme and verified users see the standard theme. Is it possible to also enable this for verified users?

Thanks!

Enable View the administration theme permission for verified/authenticated users.


How does core triggers cleanup of expired sessions in database? core/lib/Drupal/Core/Session/SessionHandler.php defines a method (gc()) to clear expired sessions from the database (sessions table)

when is that triggered ? is there a way to trigger it from the interface ?

i know i can just truncate sessions manually or with a cron or a custom drush command..., but i wonder how does core uses it and what triggers it by default

Thanks

Configuring Garbage Collection

  When a session opens, PHP will call the gc handler randomly
  according to the probability set by session.gc_probability /
  session.gc_divisor. For example if these were set to 5/100
  respectively, it would mean a probability of 5%. Similarly, 3/4 would
  mean a 3 in 4 chance of being called, i.e. 75%.

  If the garbage collection handler is invoked, PHP will pass the value
  stored in the php.ini directive session.gc_maxlifetime. The
  meaning in this context is that any stored session that was saved more
  than gc_maxlifetime ago should be deleted. This allows one to expire
  records based on idle time.

  However, some operating systems (e.g. Debian) do their own session
  handling and set the session.gc_probability variable to 0 to stop
  PHP doing garbage collection. That's why Symfony now overwrites this
  value to 1.

  If you wish to use the original value set in your php.ini, add the
  following configuration:

# config/packages/framework.yaml
framework:
    session:
        gc_probability: null

  Source: Symphony's official docs on Configuring Sessions and Save Handlers

In Drupal this is seen in /sites/default/default.settings.php

/**
 * Some distributions of Linux (most notably Debian) ship their PHP
 * installations with garbage collection (gc) disabled. Since Drupal depends on
 * PHP's garbage collection for clearing sessions, ensure that garbage
 * collection occurs by using the most common settings.
 */
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

Since the above "most common settings" is set to 1/100, Garbage Collection would run 1% of the time.

Now, as per the code comment, I presume this does not get put into settings.php when it gets auto-generated if your distribution has one already set one in one of its files as I don't see this in my settings.php

You can also set this in services.yml as seen in this answer.

In Conclusion

Note that while Drupal is built on top of Symphony, it does not rely on Symphony for this. I just quoted their nice explanation from their documentation.

We learned that PHP automatically calls this gc() method every session.gc_probability/session.gc_divisor % of the time and if you look at PHP docs on SessionHandler.

  SessionHandler is a special class that can be used to expose the
  current internal PHP session save handler by inheritance. There are
  seven methods which wrap the seven internal session save handler
  callbacks (open, close, read, write, destroy, gc and create_sid).

  Source: http://php.net/manual/en/class.sessionhandler.php

core/lib/Drupal/Core/Session/SessionHandler.php

/**
 * Default session handler.
 */

class SessionHandler extends AbstractProxy implements \SessionHandlerInterface { ...

 /**
   * {@inheritdoc}
   */
  public function gc($lifetime) {
    // Be sure to adjust 'php_value session.gc_maxlifetime' to a large enough
    // value. For example, if you want user sessions to stay in your database
    // for three weeks before deleting them, you need to set gc_maxlifetime
    // to '1814400'. At that value, only after a user doesn't log in after
    // three weeks (1814400 seconds) will his/her session be removed.
    $this->connection->delete('sessions')
      ->condition('timestamp', REQUEST_TIME - $lifetime, '<')
      ->execute();
    return TRUE;
  }


Login attempt failed My Drupal 6 site's login function stopped working all of a sudden, with no error other than "login attempt failed".

No database table crash
Cookie domain is not set
Drupal runs in "single-site" mode, not "multi-site"

The copy of the site runs well on my local machine.
Do you have any advice?

Now I found the cause: The "pass" field in "users" table by some accident was set as 32 chars long, which is far less than required by phpass module (128 chars long).
I re-installed phpass to make the table change as required and fixed the problem.


Grant users of role the ability to edit users that have specific role Is there a way to make it so users of role A can edit/create users with role B, but not users of role A?


Email notifcations based on specific dates i.e. employee anniversarries We are utilizing Drupal 7 as an intranet application for our company. One of the content types of the app is a Views-based Employee Directory. Within this directory is a field detailing the employee's start of employment date.

My boss requests a feature implemented where we will receive notifications via e-mail in regards to upcoming anniversaries of employee start date, i.e. 1 year, 5 years, 10 years, etc.

Is this something I can create using Rules+Views? Thank you

You should be able to configure a rule that will run with cron. Then it will check the employee start date field as the condition and send an email as the action.


How To Remove Table border or hid to show my page I made a view and display " tender" and the Page Format is Table and I don't want show the table border how to hide or remove?

Add this to your theme CSS:

table {border: none;}

Which will alter all the tables in your theme
To limit the border removal to just this view, find the view class [in Google chrome, use the code inspector] to find the div with the class 'view' and select the class appropriate to this view.
For example if you have the classes:

view
view-Tender
view-display-id-page_1

you can limit the table border css by:

.view-Tender table {border: none;}

for all the displays in the view or

.view-Tender.view-display-id-page_1 table {border: none;}

for just this display.


Manage display at entity reference field Drupal I have created two content types A and B.I have a date field in A which is referred in B. But in B I want to display the date field separately.

i.e 3 Different select list for month, year and day.

It sounds like you want to create different display modes to be used in the different contexts that this entity's date field is being displayed.

Create a display mode for each different way you want it displayed with either of these possible methods:

Modules that let you create and customize view modes through the UI:

https://www.drupal.org/project/entity_view_mode
https://www.drupal.org/project/ds

Custom code

https://www.drupal.org/node/1577752 & https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_entity_info_alter/7

The entity_view_mode module is the simplest approach, as display suite (ds) has many more features and options.

Once you create the view modes, then you can select the mode to be used for the entityreference field when the entity is being rendered there.


Admin page to show 2 blocks (or page+block) with 1 filter that affects both blocks I am new to Drupal and would love some guidance on how best to achieve the following:

An admin page that has (top-down):
- a date selector, defaulting to today's date
- a section displaying Arrivals for the date selected (this selects custom content type 'Bookings' with filter of arrivalDate = dateselected)
- a section displaying Departures for the date selected (this selects custom content type 'Bookings' with filter of departureDate = dateselected)

I'm interested in how conceptually an experienced Drupal developer would approach this with Views.
Note: The project uses Drupal 7.

My approach so far:

One view with Page display that lists the Arrivals and uses an Exposed Filter for the date
One view with block display that lists the Departures and uses a hidden filter for the date
The block display (2) is shown in the Footer of page display (1)
The mymodule_views_pre_build hook is used to set the exposed filter date in (1) and hidden filter date in (2)

The initial load of Page (1) is working fine. Changing the date via the Exposed Filter in (1) correctly updates the Arrivals list; but not the Departures. I'll need to update the hidden filter in (2) somehow.

The described scenario doesn't need custom coding as it is shipped with Drupal 7 Views module.

The approach to use a views block in a views page that shares the same filter can be done using the "Attachment" view.

You can find more about views attachment here

Also, there is an answer to place the attachment in a different page region here

Hope this answers your question.


How to bulk delete Orders in Drupal Commerce module I need to delete 200 Drupal commerce orders. Is there any way to do this in a bulk action?

Orders are at:   /admin/commerce/orders

Same with Customer profiles. I need to delete them with a bulk action. Can I accomplish with this?

Customer profiles are at:   /admin/commerce/customer-profiles/list

If you've got 65,000 orders that you need to wipe, VBO isn't an option. You can try this:

TRUNCATE commerce_customer_profile;
TRUNCATE commerce_customer_profile_revision;
TRUNCATE commerce_funds_transactions;
TRUNCATE commerce_funds_user_funds;
TRUNCATE commerce_line_item;
TRUNCATE commerce_order;
TRUNCATE commerce_order_revision;
TRUNCATE commerce_payment_transaction;
TRUNCATE commerce_payment_transaction_revision;
TRUNCATE commerce_paypal_ipn;

TRUNCATE field_data_commerce_customer_address;
TRUNCATE field_data_commerce_customer_billing;
TRUNCATE field_data_commerce_customer_shipping;
TRUNCATE field_data_commerce_line_items;
TRUNCATE field_data_commerce_order_total;
TRUNCATE field_data_commerce_price;
TRUNCATE field_data_commerce_product;
TRUNCATE field_data_commerce_shipping_service;
TRUNCATE field_data_commerce_total;
TRUNCATE field_data_commerce_unit_price;

TRUNCATE field_data_commerce_coupon_order_reference;
TRUNCATE field_data_commerce_display_path;
TRUNCATE field_data_field_order_deliveryinstructions;
TRUNCATE field_data_field_order_flags;
TRUNCATE field_data_field_order_id;
TRUNCATE field_data_field_order_notes;
TRUNCATE field_data_field_supplier;

TRUNCATE field_revision_commerce_customer_address;
TRUNCATE field_revision_commerce_customer_billing;
TRUNCATE field_revision_commerce_customer_shipping;
TRUNCATE field_revision_commerce_line_items;
TRUNCATE field_revision_commerce_order_total;
TRUNCATE field_revision_commerce_price;
TRUNCATE field_revision_commerce_product;
TRUNCATE field_revision_commerce_shipping_service;
TRUNCATE field_revision_commerce_total;
TRUNCATE field_revision_commerce_unit_price;

TRUNCATE field_revision_commerce_coupon_order_reference;
TRUNCATE field_revision_commerce_display_path;
TRUNCATE field_revision_field_order_deliveryinstructions;
TRUNCATE field_revision_field_order_flags;
TRUNCATE field_revision_field_order_id;
TRUNCATE field_revision_field_order_notes;
TRUNCATE field_revision_field_supplier;


One node on multiple pages with tabbed navigation between fields I would like to create a Product content type with multiple fields and then showing those fields on seperate pages, let me give you an example:

I create a product type content named "Car" that has fields like "Mileage", "Color", "Year" and so on. When you open this content's page, you see the "Mileage" by default and you have a few tabs with "Color", "Year" that you can click to show those fields.

One possible solution I found is to use the Field Groups module, but I am looking for another one because the different sections will be heavy, lots of images and styling and I worry about that jQuery show, hide implementation will result in laggy, slow experience for the visitor.

Also it would be ideal if we could have a different URL for the sections like, car/mileage, car/color and so on.

Is there a rock solid solution for this?

Thank you.

This is fairly easy to implement so I think you're right not to want to include a whole module to do this. There's loads of ways to do this but here's one way I've done it recently:

In an overridden node.tpl.php, individually print out the fields you'd like tabbed in a wrapper. Within the wrapper you'll also need to print the links for each tab, with a href pointing to the ID of the item it's related to. Something like this:

You can then write some simple jQuery to show and hide the tabs on click:

$('div.product_tabs ul a').click(function () {
  $('div.tabs > div').hide().filter(this.hash).show();

  $('div.tabs ul a').removeClass('selected');
  $(this).addClass('selected');

  return false;
}).filter(':first').click();

You could easily extend this so when the URL is visited with the fragment identifier on the end, the correct tab is shown.


How to get core to leverage a MySQL master/slave configuration? I read this question MySQL master/slave replication not working and its answer:

  Using slave databases is barely implemented in Drupal core. If you are
  developing your own modules then calls to db_query need to specify
  that they want to use the slave database using the $options array. See
  DatabaseConnection::defaultOptions for how to set this array.

Is there a way without killing kittens hacking the core to get db_query() and db_select() to make more slave SELECT queries ?

By default, these functions will query the master unless specifically told to query the slave (see their API). You have to write db_query($query, $args, array('target' => 'slave')) in order to query the slave and the core (and all the modules) aren't written to achieve this.

Only search (see the slave part) and aggregator seems to leverage this.

Edit: Oct, 25
I saw pressflow 7 is out but I'm not sure if it helps a lot right now.
I haven't found something relevant so let's try a little bounty to help this getting an answer.

Edit: Oct, 31
I'm mainly worried about Crell's comments regarding this topic: What to do with slaves?.
Mainly, is there troubles if I send SELECT queries to the slave, what happens with delays in the replication and the fact that I may want to do a node_load() just after saving a new node.

Here's how I currently implement this.

First you need to set up a SelectQueryExtender class like this:

class SlaveTarget extends SelectQueryExtender {
  public function __construct(SelectQueryInterface $query, DatabaseConnection $connection) {
    if ($connection->getTarget() != 'slave') {
      $connection = Database::getConnection('slave', $connection->getKey());
    }
    parent::__construct($query, $connection);
    $this->addTag('SlaveTarget');
  }
}

Once you have that, then all you have to do is get all the other queries to extend the extender. :) if that makes sense. Here's the snippet.

/**
 * Implements hook_query_alter().
 */
function example_query_alter(QueryAlterableInterface $query) {
  if (is_a($query, 'SelectQuery') && !$query->hasTag('SlaveTarget')) {
    $query->extend('SlaveTarget');
  }
}

And now all your SelectQuery hit the slave ;-) This is the only way I've been able to accomplish this. Anyways it works great.

Also if you have this on a custom module you can set up the SlaveTarget to be it's on file SlaveTarget.inc and add a files[] = SlaveTarget.inc to your module info file.


Sort a related products view based on product features Hi I followed the intructions here for createa a view of related products for my commerce kickstart website, those related products are selected based on taxonomy vocabularies like texture, color, size, etc...

Right now the products are sorted by the title, but I do not want to sort them like that, I want to sort them based on a feature like color, texture, etc..

Allow me give you an example:

if I go the the product display of the product X that is of gray color, in the related products block I want to display first those that match the same color, so other related products that also have gray color will be displayed first.

Thanks for your help

If you want to display those product first that matches the current product features, include all those fields in view accordingly and then apply views_query_alter function to override the order and sort according to current product.

For example, If you want to sort according to product color taxonomy term, Include the field (Products referenced) Commerce Product: color (desc) in sort criteria of view. Then write following code in module file

function MYMODULE_views_query_alter(&$view, &$query) {
  // condition for current view
  if($view->name == 'related_products') {
    //Get current node product color tid & override order query to sort according to that id
    $node = node_load(arg(1));
    $product_id = $node->field_product_reference[LANGUAGE_NONE]['0']['product_id'];
    $product = commerce_product_load($product_id);
    $query->orderby[0]['field'] = "commerce_product_field_data_field_product_reference__field_data_field_product_color.field_product_color_tid = '".$product->field_product_color[LANGUAGE_NONE]['0']['tid']."'";
  }
}

Let me know if you face any query regarding this.

Thanks!


How to prepopulate the currency of a commerce_price field I want to prepopulate the currency (select list of available currencies) of a commerce_price field.

(edit – specify my question):

I don't want to prepopulate any value (e.g. EUR) for my field as a default value for all new content. I need to have different currency values prepopulated through content-create links out of different views.

Example (I know the syntax doesn't work, that's my problem):

1st Link: http://www.example.com/node/add/contenttype?[curreny-value]=USD

2nd Link: http://www.example.com/node/add/contenttype?edit[title]=EUR

The curreny value should be visible but disabled (not editable) in any prepopulated forms.

Is that possible with the prepopulate module or do I need a hook?

You can use Commerce Multi Currency module.

  This module enhances some of the multi-currency capabilities of Drupal
  Commerce.

  Current features:

  UI for fine granular definition of exchange rates. (Every currency
  combination can be defined separately if needed) Synchronization of
  currency exchange rates directly from the European Central Bank (ECB).
  UI to specify which rates shall be synchronized and which are handled
  manually. Generation of currency specific price fields inclusive
  generation of rule-set to handle them. hooks for easy integration of
  custom currency exchange rate sources.

This will give you a 'Price with currency' widget for your field.

And you will have a dropdown with all active currencies next to the price.


Is there a simple boolean formatter that allows custom content? I have a boolean field that stores 0 or 1. I'd like a formatter that lets me enter custom markup to display on 0, and different content to display on 1. I'm happy enough doing this in code, just thought I might be reinventing the wheel if I did.

You can give a try to custom_formatters in Drupal, this module allows you to do things without writing a code


Bootstrap subtheme move main navigation I have a sub theme based off Bootstrap and my current nav bar look like this

My goal is to move the menu (Home ... contact) to appear underneath the slogan when the page is larger than 768px as it is the breakpoint when it turns into a burger button and appears on the right. I was trying to play around with the css and the page.tpl.php, but no results there. This is the first time I've used Bootstrap with Drupal.

To move things around like that you will either need to use the CSS top property within your CSS or SASS file(s), or move it around with Javascript.


How can I invalidate cached field access grants for anonymous users? We have a Drupal 8 application that uses an event subscriber class to validate IP addresses against a table of white-listed addresses on kernel requests, and adds that value to a session variable. Basically, anonymous users with authenticated IPs can access privileged content on the site. I can use hook_node_access and hook_block_access to control access when appropriate, but hook_entity_field_access only fires once after rebuilding the caches, and not for each session, so field access seems more difficult to control this way. I've thought about injecting a service into my event subscriber and adding the necessary logic there for field access control, but I'm wondering if there's something easier that I'm missing about invalidating cache tags that would cause that hook to fire for each session.

I was able to use hook_entity_field_access and return an AccessResult $result->addCacheContexts(['session', 'user.roles.anonymous'])


CKeditor not showing for authorized users Drupal 8.5.3, all modules and themes up to date.

The CKEditor only shows up for administrator users when creating or editing nodes. The authorized users are listed as Roles for the Text Format "Basic HTML" which is the Text Format for the field in the Content Type too.

There is a javascript error being thrown in /core/modules/ckeditor/js/cheditor.js, line 134 saying "drupalSettings.ckeditor" is undefined.

Thanks,
Greg

it would be helpful if you could share a screenshot.
However, if you have not yet done so, verify that the CKEditor's permissions are enabled for that role and be sure to also verify the permissions of the directory where the module is located.


What is wrong with my JQuery UI datepicker option code? I have an AJAX view using Views 3 and Better Exposed Filters (and therefore jQuery UI datepicker).  One of the exposed filters is dates between [post-date] (core).

The form works fine, but when dates are entered and submitted (via AJAX) the visible entries in the input fields disappear.

Before:

After:

It doesn't happen to other text fields, only date fields, and it stops happening when I change the Exposed Form type to 'Basic'.  I'm sure it's BEF causing the issue but what's really puzzling is that the input values are there in the HTML after submit:

<input ... value="2015-05-01" ...>

Why isn't it showing in the input field?

[edit:] I tried to reproduce this on a blank site and couldn't.  No longer certain the root cause is in BEF.

Additional information:

I've tracked the problem down to some custom JQuery code to add options to the datepicker post-render.  The options are added no worries, I just can't figure out why it breaks the inputs.

(function ($) {
Drupal.behaviors.myPageFilters = {
  attach: function (context, settings) {

    $("label[for='edit-post-date-max']", context).once('changeBetweenText', function(){
        $(this).text("to");
    });

    // This is the culprit, commenting out this block stops the weird behaviour
    $(".bef-datepicker", context).once('changeDatePickerFormat', function(){
        $(this).datepicker("option", "changeYear", true).datepicker("option", "changeMonth", true);
        $(this).datepicker("option", "dateFormat", "yy-mm-dd").datepicker("option", "showButtonPanel", true);
        $(this).datepicker("option", "buttonImage", "/sites/all/themes/mytheme/images/exposed-filter-calendar.png").datepicker("option", "showOn", "both");
    });

    $(".bef-secondary-options", context).once('createSecondarySubmit', function(){
        $(this).append('<input type="submit" id="bef-secondary-submit" value="Apply" class="form-submit">');
    });

  }
};
}(jQuery));

It's this:

$(this).datepicker("option", "dateFormat", "yy-mm-dd");

I placed it there to change the date format away from the US format provided in BEF code (AUS site).

I just discovered the jQuery UI Datepicker option field in BEF. /facepalm

I'll leave this question here in case anyone ends up with the same issue.

Put your datepicker options in via the Views UI rather than custom jQuery.


Run a drush command via module Is there a way to run a Drush command using a module? I tried exec("drush ..."); but I have found out it is not recommended. Is there any other command I could use?

It is better to use drush_invoke_process() rather than exec().

$values = drush_invoke_process("@site", "cc", array("all"), array("verbose"));


How to get node object from node ID in a drupal 8 custom module, how do I get a node object if I have the node id?
I tried :

$node = new Node($nid);
$node->save();`

but got this error:

  Argument 1 passed to
  Drupal\Core\Entity\ContentEntityBase::__construct() must be of the
  type array, string given,

There are a few ways.

If your context allows for Dependency injection, inject the entity_type.manager service and use it like so:

$node = $this->entityTypeManager->getStorage('node')->load($nid);

If not you can still use the entity_type.manager service:

$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

If you prefer, you can use the Node class directly:

$node = \Drupal\node\Entity\Node::load($nid);


How to integrate a custom header and footer? I need to add a custom header to a theme that I am currently building.
The only way I can seem to get the header and footer to show up on the page is to hard code it into the page.tpl.php file. I've tried to use the include trick, but that isn't working.
The header and the footer need to appear on every page.
Any help?

Use the Block system in Drupal. For example, create a custom block with the footer content, and place it in the footer area using the UI in Structure > Blocks.


how to add tags to article pages I'm new to Drupal. I accidentally deleted the Tag feature on our article page. Could someone explain how I can add it back to that page.

It also populated on a specific page.

in Drupal 7

Go to admin/structure/types/manage/article/fields and add a new field named "Tags" with the type "Term reference" and the widget "  Autocomplete term widget (tagging)"
in the setting field page, configure it to reference the vocabulary named "Tags" (if the vocabulary doesn't exist, just add it in admin/structure/taxonomy/add)


How to disallow selected roles to edit node titles? In project I have a content type that the owner only allows to edit some fields. I used the Field Permissions module in order to configure field edit permission and it works fine in fields.

But this module doesn't support permissions for the "TITLE" field. In my project the default users & roles don't have permission to edit title and some fields.

Any recommendations for a solution for this issue?

You could use the Title module

This converts the Title to fields API and should work with permissions as well. Basically it replaces the node title with a field


Configuration export/import doesn't work I did a drush config-export staging on a local version of my site then a drush config-import staging on the server. It imported all the taxonomy vocabulary but no terms. I also tried it via the UI (Configuration->Development->Configuration Synchronization). Is this a bug or just the unfinished nature of Drupal 8?

Configuration management is exporting exactly what it was designed to do: Export the configuration settings. The actual taxonomy terms themselves are sitting in the taxonomy_term_field_data table in the database.


Is it true that CCK has no API to work with from other modules? A colleague of mine was trying to import some huge data (from Excel) into a drupal 6 project with pure PHP and MySQL. The result is supposed to be few content-types(CCK), thousands of nodes(CCK nodes I mean),some vocabularies and few other things.

Seeing him trying to decipher the tables involved, I suggested instead of trying to reverse-engineer what CCK is doing, he should use CCK API. The problem is I couldn't find any such thing as CCK API!

Despite my heavy search to no avail, I can't in any right mind believe this to be true. I say, to myself, perhaps I can't find it ?

So how do you add a content-type, a CCK node etc etc Pragmatically ?
How do you utilize CCK in PHP code ? not from the user interface ?

No, it's not true.

CCK does its field processing when node API hooks are invoked, so when you (or another system process) call node_save(), CCK will run through the node object and save any field values it needs to.

For example, this code would load a node, change the value of a field called field_my_field, and then save that to the database:

$node = node_load($nid);

$node->field_my_field[0] = array('value' => 'Some new value');

node_save($node);

There are also CRUD functions in includes/content.crud.inc which will come in handy to create fields and instances on the fly.


How to change a field type from free-form text to a taxonomy term and keep its existing data? I need to change one of the fields of a type of a node from a free-form text to be a taxonomy term, but the data already has about 250,000 records.

How can I change this field type without losing the existing data?

Changing the field type as you asked is not possible.

However a possible alternative to achieve a similar result is like so (in the order specified):

Create a new taxonomy term field, so that "from now on" any future node updates (or new nodes being created) will use that new field.
Use the Rules module to create a rule like so:

Rules event: before saving content.
Rules conditions:

entity has field, with field = the old field.
AND NOT (entity has field, with field = the new field).

Rules Action: set Drupal message, which contains some instructions that the old field must be blanked out, and the new field should contain the appropriate value(s.

Obviously, this approach will take "some" time if this has to be done manually, 1 node at a time. But using Views (to build a list of similar nodes to be updated) and VBO (to mass update such lists) you might (should!) be able to speed up this process quite a bit. Refer to my answer to "How to bulk update select list fields?" for an example with way more details about that.


Huge delay on first request due to many slow SQL queries Possible Duplicate:
  Performance Problem: Delay on first request

The first page of my site takes up to 15 secs to load and then the site become responsive. If I leave the site for 20 min or so, the first request is very long again.

Following recommendations found on this similar question, I checked the Devel query logs and there is a whole bunch of queries related to field_sql_storage_field_storage_load taking more than 250ms.
I am not sure it is purely related to field_sql_storage_field_storage_load though as there is another language_list query with a simple SELECT * FROM languages ORDER BY weight ASC, name ASC taking 186ms.

My questions are: why do I encounter such delays and how can I reduce them?

So this is how I fixed the problem. It is not a real solution as I could not nail the exact source of the problem (if there is one).

1) Aggregate CSS (cache settings). This reduced the latency by half
2) Set cron to never (and run it externally)
3) Set up a cron job that calls the home page with Lynx every 30 minutes


Force drupal 7 to place "www" in front of urls there is a problem when a use logs in after typing "domain.com", clicks on a internal link that leads to "www.domain.com/somthing" and they are no longer logged in until they navigate to "domain.com" again. I just want the system to force the url to add the www at the beginning.

Adding this to your .htaccess file will do it...

RewriteCond %{HTTP_HOST} !^www\.YOURDOMAIN\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule (.*) http://www.YOUDOMAIN.com/$1 [R=301,L]


Multiple pieces of data attached to multiple states I want to have two fields attached to each state a user selects on a multiple select form field - they can select as many states as they want.

Each state will then have a text field and a date field attached to it.

How do I do this? I can can't figure out a way to make this data optional.

So basically it would go as follows:

State
textfield associated with state
date associated with state

and this, up to 50 times, but optional aside from one instance.

The answer to this was the field collection module (alternatively, multifield can be used).

This allows you to create an unlimited amount of field collections, and served my purposes perfectly.


Create a kind of coupon with a entity references or node reference and no autocomplete I should create a webform with a field which is related to a node.
With webform seems no possible to add a node reference, so probably I should create a content type (coupon) instead of using the webform module.
Basically, when they complete the form they can fill the field "coupon" and if the coupon exists they can go through.

The most important thing is that the node reference should be a text field with NO AUTOCOMPLETE I don't want them to see the the other coupon. How do I create it?

I've already installed the module reference and entity reference and using drupal 7.12.

Thanks in advace

This is the way to avoid the autocomplete in a node reference
    unset($form['MYFIELD']['#autocomplete_path']);


How can I let registered users upload images using a form in Drupal 7? I'm using Gallery formatter on my Drupal 7 site which allows administrators to upload images to my articles that are then shown on the article body. So great so far, but what I want is for the registered users themselves to upload images to the article using a form. I've been searching for a while, but haven't been able to find anything that would allow me to do this.

Is there a module that would allow image upload using a form that integrates with Gallery formatter (or just Drupal Image - both would work, I think, as the images are stored in a field), or do I have to create a custom module?

You need the field permission module. Everything is already contained in Drupal core.

Create a content type.
Add an image field and allow multiple instances of this field.
With help of the field permission module make sure registered users have the right to edit your image field.
Configure ImageCache to output the images the way you want.

As an add on you might have a look at views, wich allows you to output many nodes with their images, sorted and/or filtered the way you want.


How can one Rewrite results of a view using a Group By I have created a view and then added a group by a certain field. Normally one would just add a new field then rewrite the results with custom html using replacement patterns.

How would I go about this when I use group by

You can use both Rewrite and Grouping at the same time. You can Rewrite the field and use that as Group by.

If you need the same Field in the results as well as in the Group by headings, then simply add the Field twice. You can style/Rewrite them separately too.

If you want to style the grouping in a special way, or need more than one field in the Group, then you can use the Custom text field for advanced styling of the Group. You can see an example in this article: Control Group by styling with Custom text field


How to pass multiple target_id/values field using entity reference prepopulate? I read the documentation and saw that this is possible: node/add/page?field_bar=1,2,3

But how do you code this? I wanted to pass multiple target id, not just one.

I tried this code but this only passes 1 value which is the first field value.

<?php
$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' =>$node->field_product_food['und'][0]['target_id'])  ));
echo $l;
?>

I also tried using an array loop like this:

<?php
$nids = array();
foreach ($node->field_product_food[$node->language] as $index => $item) {
$nids[] = $item['target_id'];
}
$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' =>$nids)  ));
echo $l;
?>

but the result is not like the example from the documentation.

Can somebody help me?

Thank you very much!

So if you want to create this link: node/add/page?field_bar=1,2,3

You need to put a comma between each nid, so implode() is what you want.

E.g.

$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' => implode(',', $nids))  ));


Custom php code using the site header and footer I have a very complex page (Multiple Ajax calls and access to other three other mysql databases) that i would like to create within Drupal or find a way to embed it into Drupal. Now I do not want Drupal to manage the page, i would only like to just pull the header, navigation and footer  from Drupal and manage the "content" with my own code manually. In Wordpress this is very easy to do but in Drupal it does not seem to be straightforward.  What is the best way to accomplish this in Drupal.

can custom modules handle that?
can views handle that?
what are my best options?

Note that i just want to know if it is possible and how do i embed my own code into Drupal without having Drupal manage the code.

Yes, you'll generally solve this by writing a custom module. In your .module file you'll probably want, as a minimum:

An implementation of hook_permission to provide access control to your content
An implementation of hook_menu to define the routing to your page, in other words which URLs will cause your custom code to be invoked.
The actual callback which generates the content.

In the callback you can use whatever PHP code you want, though if you do use Drupal's APIs and established good practice you'll be less likely to create security weaknesses and your code will work better with other modules. That's likely to save you time in the long run.


Core Update to 8.9.4 Removed Block Visibility Options? Recently updated core from 8.9.2 to 8.9.4, in doing so the options to place blocks on specify pages is now gone?


Does commerce send an order notification email to site admin (site email) out of the box? Does commerce send an order notification email to site admin (site email) out of the box?

If not how do I do this?

It doesn't look like it does, no. There is, however, a rule set up to send the order notification to the user. It's called "Send an order notification e-mail".

You can easily clone this rule, but instead of sending the email to the owner of the order, send it to the admin's email address.

The admin user isn't available as a data selector for this rule, so you'll either have to expose it yourself somehow (not sure exactly how you'd do that without custom coding off the top of my head), or simply switch to 'direct input mode' and put the email address in manually.


prevent webform from storing user input Must I use webform in order to create a custom form? I need to create a form validator that will validate if a number (social security number) is valid. I've used webform for this but whatever I enter in the form, it's always storing it and I have to clear the data by going to admin. I dont want the webform to store user input. The point of the form is just to validate. Basically client side validation (or PHP side) is the only purpose of the form. No storage needed. Is there a way to turn off the storage in webform? Or do I have no choice but to store all inputs entered by users?

I've seen this but I dont want to redirect. My form is just an ajax call..

You can edit the form with function_form_alter(), and modify what to do on submit. Try this:

function MY-MODULE_form_alter(&$form, &$form_state, $form_id){
  if( $form_id == 'YOUR-FORM-NAME' ){
    $form['actions'][]= array(
      '#submit' => array('_CUSTOM_FUNCTION')
    );
  }
}
function _CUSTOM_FUNCTION(){
  //put what to do here
}


How do I troubleshoot a jQuery/AJAX issue? On a current Drupal Commerce installation, I just started experiencing issues where a field is not updating after a jQuery click event.

When a user selects an option, the price typically updates for several of the products on our store. When adding the item to the cart, the correct price is shown. (While helpful on my end that the customer is being charged the right price, it's not great that they cannot see the right price until it is in the cart.)

Everything was working well. No updates were pushed for our distribution and added modules, but this feature is no longer working.

From the Chrome Console, I pulled the error msgs below. How do I troubleshoot? Should I just restore a backup?

ui.spinner.min.js:7 Uncaught TypeError: Cannot read property 'msie' of undefined
at ui.spinner.min.js:7
at ui.spinner.min.js:22

jquery.formalize.js:13 Uncaught TypeError: Cannot read property 'msie' of undefined
    at jquery.formalize.js:13
    at jquery.formalize.js:135
commerce_kickstart_product_ui.js:6 Uncaught TypeError: $(...).spinner is not a function
    at Object.attach (commerce_kickstart_product_ui.js:6)
    at Object.<anonymous> (drupal.js:76)
    at Function.each (jquery.min.js:4)
    at Object.Drupal.attachBehaviors (drupal.js:74)
    at HTMLDocument.<anonymous> (drupal.js:504)
    at c (jquery.min.js:4)
    at Object.fireWith [as resolveWith] (jquery.min.js:4)
    at Function.ready (jquery.min.js:4)
    at HTMLDocument.q (jquery.min.js:4)

It is because you are using jQuery 1.9 or superior.

To fix it, use jQuery Update version 7.x-3.0 and enable the jQuery Migrate plugin.


Deactivate system path I want to deactivate the system path which comes with Drupal.
I've installed the pathauto, so when I create a new page, it automatically changes domain.com/node/12 to domain.com/books/jacks-journey

But both page exist. I only want the /books/jacks-journey to exist and deactive the /node/12. Is it possible to do that?

Deactivating the internal path is technically route normalization by redirecting incoming requests, which in D8 is provided by the module Redirect:

  D8: Maintaining a canonical path and redirecting alternative URL's
  like non-aliased path, path without language prefixes and so on
  (Previously provided by Global redirect)

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


unable to see drupal home page when configured live site into in my local system? I need to configured my live site into local system, I had configured database, settings.php and enable module rewrite and .htaccess file also there in my root folder etc.
But I'm unable to see the my site home page it's showing blank page, please help me I'm new to drupal.

Try adding

error_reporting(E_ALL);
ini_set('display_errors', TRUE);

in index.php file, that will be showing the actual error on front page.


Ajax in textfield adding extra div in markup I have created a form using a custom module. I am working on ajax functionality and updating markup when user enter text in textfield of the form.

Creating form in module

/**
 * Implements hook_form().
 */

  $form['name'] = array(
    '#type' => 'textfield',
    '#description' => 'Enter your name',
    '#title' => 'Name',
    '#size' => 50,
    '#ajax' => array(
        'callback' => 'custom_print_ajax_name_callback',
        'wrapper' => 'custom-print-name',
        'method' => 'replace',
  ),
  );

  $form['name_msg'] = array(
    '#type' => 'item',
    '#markup' => (!empty($form_state['input']['name']) ? $form_state['input']['name'] : ''),
    '#prefix' => '
',
    '#suffix' => '
',

  );

Ajax submit callback:

/**
 * Ajax callback
 */
function custom_print_ajax_name_callback($form, &$form_state) {

  return $form['name_msg'];
}

Everything is working correctly except that when I checked HTML of the page, an extra div is added in HTML of markup after updating ajax as shown in below image.

I do not have any idea why is this extra div rendering with markup.

Thanks in advance.

I have checked ajax.js in Drupal site and I have found that extra div is added as ajax wraps new content inside an empty div after a successful ajax request.

Comment Mentioned in ajax.js:

  We don't know what response.data contains: it might be a string of
  text without HTML, so don't rely on jQuery correctly iterpreting
  $(response.data) as new HTML rather than a CSS selector. Also, if
  response.data contains top-level text nodes, they get lost with either
  $(response.data) or $('

').replaceWith(response.data).

Code:

var new_content_wrapped = $('

').html(response.data);
var new_content = new_content_wrapped.contents();

Check this also.


How to block all users not containing a pattern? I'm trying to block all users except ones with a specific role, and would love to use something like: drush user:block !roadie.

I suggest use drush block

drush ublk $(drush sqlq 'SELECT GROUP_CONCAT(ufd.name) FROM users u join user__roles ur on  u.uid = ur.entity_id  join users_field_data ufd on ufd.uid = u.uid where ur.roles_target_id ="YOUR_ROLE_MACHINENAME" and ufd.name like "%PATTERN%"')

before that make sure the query is correct and it respond what you want by

drush sqlq 'SELECT GROUP_CONCAT(ufd.name) FROM users u join user__roles ur on  u.uid = ur.entity_id  join users_field_data ufd on ufd.uid = u.uid where ur.roles_target_id ="YOUR_ROLE_MACHINENAME" and ufd.name like "%PATTERN%"

and finally, make sure they are blocked by checking "User status" column of the result of the following command

drush uinf $(drush sqlq 'SELECT GROUP_CONCAT(ufd.name) FROM users u join user__roles ur on  u.uid = ur.entity_id  join users_field_data ufd on ufd.uid = u.uid where ur.roles_target_id ="YOUR_ROLE_MACHINENAME" and ufd.name like "%PATTERN%"')

PS:

YOUR_ROLE_MACHINENAME: change it with your desired role.
PATTERN: you can use MySQL LIKE statement


creating a date field for date range? I'm working on a date range field. The date field only provides you the ability to input a date. I'd like to construct a field that displays the length of time from the date start field and the date end field.

My Use case:
The content type is a job. E.g. I worked at that  job from january 1, 2001-January 23rd, 2002.

Desired output:
e.g. (11 months) or (3 years 2 months)

How do you create a field that calculates the length of duration? Is there a module that currently exists? or would a formatter be needed?

I have an idea!  How about if you add an additional field to your Job content type called 'Time at job' that's simply a text field.

Then, create a new rule with the rules module that fires off when a Job node is saved or modified.  In that rule, you can simply set the 'Time at job' field by calculating its value from the values of the two date fields (using php).

For the php code calculating the length of time between two dates, there are countless of tutorials online.  Here's just one that's quite comprehensive: https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php.

Would that fit your scenario?  Calculating a third field upon node save/edit and displaying that instead?


How to change the place of a block or region based on url path? I have a menu block and it will be displayed on all pages, but I need to change the placing of it. On certain pages (dependent on path) I need to display it above the main content, while on other pages I need to place it below the content.
I am experimenting with the context module and I was able to put the block above the content, but then on these pages, the menu shows BOTH above and below the content.

I have a solution in mind, but there must be a better way: I can set up two regions, one above and one below the content, then put the menu block in the region below the content, and set up a context to put the menu in the above region AND hide the below region. This could work, though I think there should be a more elegant way.

Hope this will help you.

In Drupal 7 you can achieve it using Context module as suggested by the Jack.

Steps

Fist of all disable the menu block using admin/structure/block.

As you specified you need to show menu block in two regions, then those 2 regions(main content and above the content) must exist. If not then create it.
Create a new context and add menu block based on your requirement and path.
Showing menu block block in region Content

Showing menu block block in another region user bar second

Reference :

create custom regions