Adding title attribute to #type password_confirm Is it possible to add a title attribute through a form_alter to element #type 'password_confirm'?

For example, I have a form with the following fields:

email
password
password confirm

To apply a title attribute to the email element is fine...

$form['account']['mail']['#attributes']['title'] = 'enter your email address';

When I dump the contents of $form in search for the input elements for 'password_confirm', I only get the following:

[pass] => Array
                (
                    [#type] => password_confirm
                    [#size] => 25
                    [#description] => We will not spam you or give your email address to third parties.
                    [#required] => 1
                )

I'm not seeing 'pass1' and 'pass2' in the array.

Please could someone point me in the right direction?

The password confirm element is converted to two fields in a process function (form_process_password_confirm()), so adding your own process function to the password element would do the trick.

Per this issue it seems you actually need to overwrite the existing #process array instead of just appending to it, e.g for the user register form password element:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['pass']['#process'] = array(
    'form_process_password_confirm',
    'MYMODULE_password_confirm_process',
    'user_form_process_password_confirm'
  );
}

function MYMODULE_password_confirm_process($element) {
  $element['pass1']['#attributes']['title'] = 'Title';
  $element['pass2']['#attributes']['title'] = 'Title2';
  return $element;
}


How to bulk delete nodes by ID? I have a large csv of nodes that need to be deleted from the database.

I need something like feeds but for deleting. I know this can be accomplished easily via a custom module but I'm just wondering if there's a module or feed extension I can use.

One solution here, that is slightly different from your question, is to use Views/Views Bulk Operations (VBO) & contextual filters on a custom View.

VBO contains an operation for bulk deletion. You can create a contextual filter for Content: Nid with the Allow multiple values option selected. If you've created a page view, that would allow you to navigate to http://example.com/my_node_delete_vbo_view/1+2+3 wherein you can view all the nodes you want to delete, select them all, then apply the Delete item VBO operation.

The only work involves taking your CSV, slicing it down to just the node column, and replacing the character delimiters.


How to preprocess file before Feeds upload I am using Feeds 7.x-2.0-beta1 .  I am getting the data in a format that I need to change before inputting, since they are adding one item per row when some data has multiple values in one field . I want to modify the file to put all of those values in one field and one row before continuing with the feeds parser.
Where can I put the php code to do this? what hooks are available? thanks

The Feeds project page doesn't advertise it, but there is an API. If you look at feeds.api.php you can view all the hooks it makes available. A few of them take action before a feed item is processed or saved.


Digit 2 Appended to Field Name on Column in Entity Field Query I have an Entity Field Query that has fieldCondition for field_email

  ->fieldCondition('field_email', 'value', $email , '=');

I have verified that this is the name of the field and I have other entity queries that use this field correctly.  However, in this example, Drupal is adding the digit 2 on to the field name as I understand the error returned.

$dup_query1 = new EntityFieldQuery();
$dup_query1->entityCondition('entity_type', 'node') ->entityCondition('bundle', 'fair_participant')
 ->fieldCondition('field_last_name', 'value', $last_name , '=')
 ->fieldCondition('field_first_name', 'value', $first_name , '=')
 ->fieldCondition('field_email', 'value', $email , '=');

$fpmatch_fandl_email = $dup_query1->execute();

  SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'field_data_field_email2.field_email_value' in 'where clause'

Any help is greatly appreciated.

Thanks,
Josh

If you use Email module, use email instead of value, because the module store the value in field_name_email not field_name_value like other field like text ...
So you Query should be like:

$dup_query1 = new EntityFieldQuery();
$dup_query1->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'fair_participant')
    ->fieldCondition('field_last_name', 'value', $last_name , '=')
    ->fieldCondition('field_first_name', 'value', $first_name , '=')
    // use email not value.
    ->fieldCondition('field_email', 'email', $email , '=');

$fpmatch_fandl_email = $dup_query1->execute();


Drupal hide form items completely with states I try to hide a whole date/image/taxonomy block on my node form dependent on a checkbox.
If use the following for my title field it works perfectly. The title field is hidden/visible dependant on the test_box checked value.

function interceptor_box_listener(&$form, &$form_state) {
  $form['test_box'] = array(
    '#title' => t('You want to choose a title?'),
    '#type' => 'checkbox',
  );
  $states_array = array(
    'visible' => array(
      'input[name="test_box"]' => array('checked' => TRUE),
    ),
  );
  $form['title']['#states'] = $states_array;
  return $form;
}

The point is that I have more complex fields I need to toggle and I'm not able to address them correctly. If I try to adress the following fielditem, nothing happens at all.

Plakat

<input type="hidden" value="109" name="field_plakat[und][0][fid]">

It tried the following:

$form['field_plakat[und][0][fid]']['#states'] = $states_array;

Is there any possibility to just pass an id to drupal but stay with the states system? Of course I'd be able to use plain javascript here, but I really like to stay strictly on the module side.

Find this field in $form array and set states currently to it.
I'm not sure, but maybe it is in $form['field_plakat'][LANGUAGE_NONE][0][$fid]?
It must be somewhere in this renderable $form array.


How to install a module from an archive file with drush? To install a module available on drupal.org, I do drush dl modulename && drush en modulename. However, when I have module available as an archive file on my local disk instead (.zip or .tar.gz), how can I still use drush to install it?

The archive file could come from downloading a sandbox project snapshot, from a self-developed "custom made" module or similar.

I know I could unpack the module into sites/all/modules/, then enable it with drush en modulename. But I'm looking for nice scriptable commands to do both these steps with drush. (Bit silly, but I like to keep a drush workflow.)

You can use drush make to unpack a module named your_module from an archive file, as follows:

Create a modulename.make file containing:

core = 7.x
api = 2
; Install from local module archive file.
projects[your_module][type] = "module"
projects[your_module][download][type] = "file"
projects[your_module][download][url] = "file:///dir/your_module.tar.gz"

While in the Drupal root directory of your site, execute the Makefile and enable your module:

drush make --no-core -y your_module.make && drush en -y your_module

Alternatively, you can script this into one set of commands, using a temporary file instead of a separate Makefile. Again, to be executed while in the Drupal root directory:

#!/bin/bash
module="your_module"
makefile=$(mktemp)
echo "Created temp file $makefile"
cat << end-of-makefile >$makefile
  core = 7.x
  api = 2
  projects[$module][type] = "module"
  projects[$module][download][type] = "file"
  projects[$module][download][url] = "file:///dir/file.tar.gz"
end-of-makefile
drush make --no-core -y --verbose $makefile
drush en -y $module

(Bash named pipes or bash process substitution via <(echo …) cannot be used here to avoid a temp file. They create streams, which are non-seekable files that drush make fails to read from.)


Custom module is not working I created custom module to display Hello world text in custom page. I did not install drush and composer in my windows machine as I don't have admin access. I have pasted my files below:

example.module

<?php

function example_menu()
{
  // The paths given here need to match the ones in example.routing.yml exactly.
  $items['/mypage/page'] = array(
    'title' => 'First page',
    'description' => 'This is a example page.',
    // The name of the route from example.routing.yml
    'route' => 'example.my_page',
  );
  return $items;
}

example.routing

example.my_page:
  path: '/mypage/page'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::mypage'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

src/Controller/ExampleController.php

<?php

namespace Drupal\example\Controller;

//use Drupal\Core\Controller\ControllerBase;

class ExampleController
{
    public function myPage()
    {
        $element = array('#markup' => 'Hello world!');
        return $element;
    }
}

And I have example.info file as well and the module is enabled. When I run the controller, it says page not found. Can anyone tell me that Am I missed anything in the code?

hook_menu doesn't exist anymore in D8.
Instead use a example.links.menu.yml file.

example.my_page:
  title: 'First page'
  description: 'yout description'
  route_name: example.my_page


7: Form API: managed_file: AJAX upload error "Undefined index ... in file_ajax_upload()" I have a problem with "AJAX: add more file fields". The Problem: i create new managed_file field and add AJAX function "add more file fields". When i try to upload a file with first static file field, it works fine. But when use function "add more fields" and try to upload a file with AJAX created field, get error "Notice: Undefined index: ... in file_ajax_upload() (Line 262 in .../modules/file/file.module)."

All Answers for Similar Questions here don't solve this Problem.

The code:

<?php
/**
* implimentation of hook_form_alter()
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {

}

/**
* implimentation of hook_form_FORM_ID_alter()
*/

function mymodule_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
 // Since the form builder is called after every AJAX request, we rebuild
  // the form based on $form_state.
  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;
  $form['howmany_select'] = array(
    '#title' => t('How many checkboxes do you want?'),
    '#type' => 'select',
    '#options' => array(
      1 => 1,
      2 => 2,
      3 => 3,
      4 => 4,
    ),
    '#default_value' => $num_checkboxes,
    '#ajax' => array(
      'callback' => 'ajax_example_autocheckboxes_callback',
      'wrapper' => 'checkboxes-div',
      // See ajax_example_autotextfields for an example of 'fade'.
      'effect' => 'fade',
      // Don't show any throbber...
      'progress' => array('type' => 'none'),
    ),
  );

  $form['checkboxes_fieldset'] = array(
    '#title' => t("Generated Checkboxes"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('This is where we get automatically generated checkboxes'),
  );

  for ($i = 1; $i <= $num_checkboxes; $i++) {
   $form['checkboxes_fieldset']["slideshow_item_$i"] = array(
    '#title'    => t('Image')." $i:",
    '#type'     => 'managed_file',
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://mymodule_images/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
    '#tree' => TRUE,
    '#description' => t("Upload slideshow image. Allowed extensions: gif, png, jpg, jpeg."),
   );
  }
  return $form;
}

function ajax_example_autocheckboxes_callback($form, $form_state) {
  $form_state['rebuild'] = TRUE;
  return $form['checkboxes_fieldset'];
}

?>

I think the Problem is in $form_state. How i can refresh / rebuild $form_state? In ajax_example_autocheckboxes_callback i set $form_state['rebuild'] = TRUE; but without effect :(

Code Test Video:

http://www.youtube.com/watch?v=PtRiQorCTA4

I looking 3 days for a solution :-/

Helpful articles:

How to add more Fields using Form Api

https://drupal.org/node/752056

https://drupal.org/node/331941

How to wrap managed_file Form API element with custom HTML using #theme_wrappers?

You need to pass the parameters by reference if you want changes to persist outside the function scope:

function ajax_example_autocheckboxes_callback(&$form, &$form_state) {


Base URL/Domain problem I moved a Drupal site to a development domain, but for some reason none of the menu links have updated. For example, in the main menu, one of the links is www.example.com/product. I would expect it to change to www.devdomain.com/product after moving it to my dev domain, but it doesn't.

Similarly, even the links in the Seven admin theme still point to www.example.com (my live site) instead of the dev domain. So clicking "Structure", for example, tries to route me back to the live site.

Anyone ever experience this and know how to solve? There are no references to base_url in my settings.php file for this site, and I am not using the trusted host patterns setting (though I have tried with and without).

A few other things I have tried:

running update.php
drush cr
searching for instances of example.com in codebase (there are none)

Any help on this would be appreciated.

Turns out multilingual modules were on, and using URL detection. When that is set, the URL for the particular language you are looking at gets inserted into all links.


Creating view using a field(checkbox) as Contextual Filter I have a content type product.I want to create a page view of the products. The view should show only those products whose field featured (checkbox) is checked.

How do I use Contextual Filters for this ?

If the field was a taxonomy-term ,I would go to Provide default value -> Taxonomy Term ID from URL.

But, since the field is a checkbox I am not able to achieve this.

Thank you .

If you want this filter you should add the field as a "standard filter" and not contextual filter. In Views UI look for the headline Filter criteria, add your field "featured" and choose what value that has to be set.

Here is a screenshot how the UI looks, it is under filter criteria where you should push add.


MariaDB vs MySQL for Drupal 6? I am wondering whether it is a good idea to convert a large D6 database of a community site (with 80% read 20% write and about 1300 qps, using MyIsam engine) from Mysql to MariaDB?

MariaDB seems to be highly desirable:

  MariaDB is a database server that offers drop-in replacement
  functionality for MySQL. MariaDB is built by some of the original
  authors of MySQL, with assistance from the broader community of Free
  and open source software developers. In addition to the core
  functionality of MySQL, MariaDB offers a rich set of feature
  enhancements including alternate storage engines, server
  optimizations, and patches

However I'd like to hear first-hand experiences of fellow drupallers about the expected performance gains. I know that MariaDB uses XtraDB (InnoDB improved) storage engine by default. In fact my site slowed down significantly once I moved the Mysql database to InnoDB engine, so I am a bit unsure about the supposed performance gains.

Also I'd like to know about caveats (possible incompatible modules, etc) of converting to MariaDB.

Thanks

CAVEAT : This commentary is solely based on MySQL not Drupal.

I have personally worked with Percona Server and MySQL, not with MariaDB as of yet. Percona provides support for MariaDB, Drizzle, Amazon RDS, and other MySQL products.

I learned at Percona Live NYC that Percona gets the latest version of MySQL and injects 30,000 lines of C/C++ that is unique to its Performance Enhancements. MySQL (eh, Oracle) tries to keep up with its own enhancements of InnoDB.

Unless your Drupal website is very heavily trafficked, there is no decent performance difference you can feel or see. However, if you do have high traffic and you want to compare MySQL, Percona, and MariaDB, I have posted an article in the DBA StackExchange on how to go about doing this.


Does cron queue manage max_execution time? I have implemented an approximately 1000 nodes update using hook_cron_queue_info() and hook_cron(). When I manually run cron job from the Drupal administration pages, I get a maximum time execution error; once this number is reduced by 10, it works fine.

Any suggestion?

function my_module_cron_queue_info() {
  $queues['my_module_batch'] = array(
    'worker callback' => '_my_module_process_queue',
    'skip on cron' => FALSE,
  );
  return $queues;
}

function my_module_cron() {
  $contents = lade_update_nodes(); // get node list for updation
  $queue = DrupalQueue::get('my_module_batch');
  foreach ($contents as $p_file) {
    $process_data = array(
    // set values for process
    );
    $queue->createItem($process_data);
  }
}

function _my_module_process_queue($arr) {
    // code for updation
    watchdog('update node', 'Custom msg');
}

To answer the question in the title, Drupal cron does check the time used to process the items in a queue, and by default it gives 15 seconds to each queue. This still doesn't avoid the total time given to all the queues doesn't exceed the limit, especially if the call to drupal_set_time_limit(240) (which would set the time limit to 240 seconds) doesn't have success.

Also, since the code used by Drupal is the following one (see drupal_cron_run()), if processing a single item in a queue requires more than the time assigned to processing a queue (for example 30 seconds instead of 15), Drupal cannot block processing a queue when the time assigned to a queue is passed.

  foreach ($queues as $queue_name => $info) {
    if (!empty($info['skip on cron'])) {
      // Do not run if queue wants to skip.
      continue;
    }
    $callback = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
    while (time() < $end && ($item = $queue->claimItem())) {
      try {
        call_user_func($callback, $item->data);
        $queue->deleteItem($item);
      }
      catch (Exception $e) {
        // In case of exception log it and leave the item in the queue
        // to be processed again later.
        watchdog_exception('cron', $e);
      }
    }
  }

If you get a maximum time execution error, you can just limit the number of processed items, or assign less time for your queue.

function my_module_cron_queue_info() {
  $queues['my_module_batch'] = array(
    'worker callback' => '_my_module_process_queue',
    'time' => 3,
  );
  return $queues;
}

As side note, setting 'skip on cron' to FALSE is useless, as Drupal assumes it is FALSE by default. In fact, it uses if (!empty($info['skip on cron'])) {} to decide if skipping a queue; !empty($info['skip on cron']) is FALSE when $info['skip on cron'] is not set, or when it is set to FALSE.


I can't add new icons in CKEditor default toolbar I can't add new icons (tabs) in CKEditor toolbar, in EDITOR APPEARANCE options. Whatever I choose it only gives me default toolbar. I tried all versions. What should I do?

If you have jquery_update installed and using 1.8 you might also run into javascript errors if you are trying to move toolbar elements around. Temporary setting it to 1.5 (doing my changes and setting it back to 1.8) fixed the issue for me.


Feeds duplicate all my images I'm using feeds with Commerce. For each of my product variation, I have 4 images.

Each time I execute the feed import, the images are all copied by the number of variation. For example, if a product has 10 variations that are supposed to use image testpicture.jpg, the result is 10 copies named testpicture.jpg, testpicture0.jpg, testpicture1.jpg, etc.

How can All my product variations point to the same image and not make copies of the image with an incremental number?

I suppose there are a few ways, but this is how I do it:

You need to have your images managed by Drupal. I use Media module (7.x-2.0) and its sub-modules to first upload my images to the Media library. I make sure that my images have unique file names and I do not change it during the upload (Media allows you to rename after upload, just leave at default).

I then map my images via:

Image -> Images: Ref in the feed settings and use Feeds Tamper to
Explode in case I need multiple images
Images: Alt and Images: Title, again using Feeds Tamper.

In my uploader file I then use the exact same image names as the file names for Image. Feeds will then map to the Drupal Managed File entity ids which it looks up by name via the URI stream wrapper (I think). I also include fields for Image Alt and Title.

If you don't want to use Media then you may use FileField Sources, but getting the images in the very first time is then a hassle.


How to create a hit counter for each published node to find out how often a specific node has been viewed? I’m trying to create a hit counter for each published node. I’ve been googling this feature for Drupal 6.x and tried a few hits but with no luck.

I’ve enabled the Statistics module for my site and under admin/reports/settings I’ve enabled the counter but can’t seem to figure out how to put a hit counter on each overview page and node page.

I found a post explaining that I could use a customize query as such SELECT count(*) from accesslog where node = node but when I navigate to my database, the access log is empty (don’t know if it require to some time to enable the page / hit counter).

I want to count every hit and not only unique hits so each time a person access a node it should “just” increment a visitor number and I want to show it within my node-templates (not block) for some specific node content types.

I might miss something but any help or suggestions would really be appreciated.

There is a settings page at admin/reports/settings, try looking there first.

Also, look in the node_counter table instead of accesslog.  The query should actually be as follows ($nid being the node ID of the node which you want records for).:

SELECT totalcount FROM {node_counter} WHERE nid = $nid;

On another note, I'm pretty sure if you enable the Statistics module, you can simply pull the node's page view count out in Views.


Why am I getting a "page not found" error for this implementation of hook_menu()? Here's the implementation of hook_menu() in my theme, "myTheme":

function myTheme_menu() {
    $items = array();
    $items['ajax'] = array(
        'title' => 'AJAX',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    $items['blog'] = array(
        'title' => 'sonia blog',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}

example.com/ajax is working fine, but example.com/blog is returning me a "page not found" error. I have cleared my cache.

Do you have any idea about what is going wrong?

EDIT
One of the commenters suggested that I need a page_callback property. However, the documentation on hook_menu does not say that it's required. Regardless, I tried adding this callback but still no luck. Here's the code with it:

function myTheme_menu() {
    $items = array();
    $items['blog'] = array(
        'title' => 'sonia blog',
        'access arguments' => array('access content'),
        'page callback' => 'myTheme_callback_blog',
        'type' => MENU_CALLBACK
    );
    return $items;
}

function myTheme_callback_blog(){
    return '';
}

I believe you cannot define a hook_menu() implementation in a theme; it should be defined in a module.

When you make changes to a hook_menu() implementation, you need to ensure that you rebuild the menu router, as well. To that end you can manually look at your database's "menu_router" table to see if the callback is being registered.


How do I render two links with a pipeline as separator? How do I render two links with a pipeline as separator? For example, $edit and $action are links generated using \Drupal::l(). Then, I edited them with the following code.

if ($edit) {
  $action =  $edit . ' | ' .  $action;
}
else {
 $action = $action;
}

$action  = $action . "";`

Instead of links, the page is displaying HTML markup as plain text, but no links.

Edit | Archive

Can anyone suggest me how to achieve this?

What you see as displayed HTML is escaped by Twig. Only safe markup is not escaped.

l() produces safe markup, but if you add something to it, the complete string becomes unsafe.

You can use an inline template to get around this problem.

if ($edit) {
  $action = [
    '#type' => 'inline_template',
    '#template' => '{{ edit }} | {{ action }}',
    '#context' => [
      'edit' => $edit,
      'action' => $action,
    ],
  ];
}


Linking image field to an external URL I have a list of images on my node that I want to output wrapped in an anchor tag for linking to external webpages. Images are coming from fields in my content type. I'm not using the Views or the Panels module, and I've edited my page.tpl.php and node.tpl.php files for a rather intricate "About Us" page.

So how do I do this? I'm using Drupal 7.

You can create a custom field formatter (theme function for fields) where you can define how the image field should be rendered. Here you can add the a tag or any other special markup.

There are a lot of guides on how to do this, both here on the site and on the web, so I won't go into details about how to create a field formatter here, but it's nothing more than a few hooks and a theme function.


How to load a entity or node in form builder class? I want to load default values in my form. I am fetching the node of the table row from form list and passing it into route.

my_form_eform:
 path: '/edit/{bar}'
 options:
 parameters:
  bar:
  type: entity:node
 defaults:
  _form: '\Drupal\my_form\Form\EditForm'
  _title: 'Edit Item'
 requirements:
  _permission: 'access content'

and code for editform.php is

namespace Drupal\my_form\Form;

use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\NodeInterface;

class EditForm extends FormBase{

// public function content(AccountInterface $index, Request $request) {

public function getFormId() {
return 'edit_form';
}

public function buildForm(array $form, FormStateInterface $form_state , NodeInterface $bar = NULL){

 // $id = $bar;
//  $result = db_select('my_form','t')
// ->fields('t',array('id','title','author','stream','description','price'))
// ->condition('id',$id)
// ->execute()->fetchAssoc();

// $dtitle = $result['title'];
// $dauthor = $result['author'];
// $ddesc = $result['description'];
// $dstream = $result['stream'];
// $dprice = $result['price'];

$form = array();

$form['title'] = [
  '#type' => 'textfield',
  '#title' => t('Title of your book.'),
   '#default_value'=> $dtitle
];
$form['author'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Author.'),
   '#default_value'=> $dauthor
  ];
$form['stream'] = [
  '#type' => 'select',
  '#title' => t('Stream'),
  '#options' => array(
  'ECE' => t('ECE'),
  'CSE' => t('CSE'),
  'ME'=> t('ME'),
),
   '#default_value'=> $dstream
  ];
  $form['desc'] = [
  '#type' => 'textfield',
  '#title' => t('Description'),
   '#default_value'=> $ddesc
  ];
  $form['Price'] = [
  '#type' => 'textfield',
  '#title' => t('Price'),
   '#default_value'=> $dprice,
  ];
$form['ADD'] = [
  '#type' => 'submit',
  '#value' => $this->t('Update'),
];
return $form;

}

I read about parameter upcasting, but its not required for node instance.

If I am passing the id in function itself through account interface it's giving the error

  must be compatible with formbuilder class

Now I am using NodeInterface argument but its also giving the error

  Argument 3 passed to Drupal\my_form\Form\EditForm::buildForm() must be an instance of Drupal\Core\Form\NodeInterface

Please help. How can I load my id so that default values for form fields can be fetched from db?

You need to make it an optional argument. Annoying but unavoidable workaround with the current design.

And to have it already upcasted to a node, you need to name your variable {node}.


Outputting the sum of multiple fields into a new view that then gives a grand total I have a view right now that takes data such as # of properties owned and Square footage total by region. So for example if someone clicks the northeast region of a map they'll get the number of buildings and square ft of properties in that specific region, displays them, then at the bottom totals them.

I'm trying to come up with a way to take the totals of those regions, display them in another view and then add THEM up for a grand total.

Is this something that can be done with views? If not, is there another solution that can work with the view already implemented?

Probably the simplest way to do this via Views is to add the Computed Field module to your site, and build a new content type (maybe "summary"), and add a summary for each kind of property you'd want to add in the view, and then use the computed fields to calculate all the grand totals. Display the computed fields in a new view, and it should work fairly well.

However, that wouldn't be all that dynamic. There are probably ways to do this in views itself by adding groupings, relationships, and calculated fields, but you'll end up with a view that's fragile and a real pain to maintain via the UI. You might want to approach adding a views attachment, or a display after the view, or just use some plain old custom code to generate a block (or within a block if you use the PHP filter, but I would not recommend this approach).

Another possible solution (if it's simple feature set gives you what you'd need) is the Views Summarize module.


Pass parameter from a custom php function to hook_block I have a hook_menu page callback. I want to use the argument which it receives in hook_block.

For example

function myCustomFunction($args) {

}

modulename_block() {
  // Use $args here
}

How can this be done. Is there a way I can pass this as a parameter.

I'm not sure how this would be expected to work consistently; if your block relies on arguments built up from a particular page callback, then the block will only work on that page.

Having said that, if the page callback arguments are based on a known value, for example a node ID, then I can see how it might work for a particular path/set of paths.

Let's say this is your menu item in hook_menu():

$items['my/path/%node'] = array(
  'title' => 'A title',
  'access arguments' => array('access content'),
  'page callback' => 'MYMODULE_some_function',
  'page arguments' => array(2)
);

And this is your code for MYMODULE_some_function():

function MYMODULE_some_function($node) {
  $the_value = do_something_to($node);
}

In your hook_block() function you can grab the node ID out of the URL, load the node manually, and perform the same function on it that you have in MYMODULE_some_function(). For example:

function MYMODULE_block($op = 'list', $delta = 0, $edit = array()) {
  // I've omitted the 'list' op, obviously you'll need to implement that yourself

  if ($op == 'view' && $delta == $the_delta) {
    // Check that we're on an appropriate page
    if (arg(0) == 'my' && arg(1) == 'path' && is_numeric(arg(2))) {
      $nid = arg(2);

      $node = node_load($nid);

      $the_value = do_something_to($node);

      $block['content'] = $the_value;
    }
  }
}

You might want to centralise the code that runs $the_value = do_something_to($node); into it's own function so you're not repeating yourself.


Product variations getting same name as product I did google this and found the following:

https://drupal.org/node/2146759

however, I cannot seem to find the fields they are indicating. Maybe I have the wrong version of commerce?

Okay, I guess I was unfamiliar with the terminology. Here is what I did to find this, in case it helps anyone else. First go to Structure (which because I have the kickstart installed is actually in Site Settings under the Advanced column) then go to content types. Find the product type you want to edit, go to manage fields, edit the product variations and down the page a bit is a checkbox called "Auto generate the product title".


How to use jquery accordian in side bar first I am using facets search filter. I want to use accordion in facest search filter.

As I understood you want to make it Collapsible.  If yes try below mentioned module

https://drupal.org/project/facetapi_collapsible

https://drupal.org/files/project-images/collapsible_facets_0.png


Properly handling menu items in a custom module In my module I need to install custom menu items (add to existing main-menu) on the front-end side. So basically it's a simple one-time operation, yet it rises some questions about the proper way to deal with programatic menu items in general.

hook_install + menu_link_save sounds good for installing the items, hook_uninstall + menu_link_delete - for uninstalling, but how am I supposed to find out the $mlid parameter of the menu link - required by the menu_link_delete function?
Would hook_enable and hook_disable be more suitable?
How do I protect my module's menu items from deleting on the admin UI side?

You can programatically add/remove menu items on install/uninstall and/or enable/disable events. But that's not how we do usually.

Implement hook_menu and you will be fine to go with almost any menu item implementation.

A few points.
Set menu router item's 'type' => MENU_NORMAL_ITEM and it will now be in a menu. Unless you set 'menu_name', it will be placed in the "navigation" menu.
See the huge (and very helpful) text on the page. Also, have a look at examples module for high-quality hook_menu examples.

Good luck!


Domain Access And Subfolders This has indeed been asked somewhere but still no answer. Is there a way to have domain access provide links like example.com/site1 instead of side1.example.com Thank you

I am sure you are looking for the Subfolders Domain module.

  Create and configuring easily the hierarchy Subdirectory multi-site for your Drupal multi site from one installation and a single shared database. This module allows you to add new subdomains directories or management of subdomains directories without changing/adding any file configuration (such .htaccess, sites.php, Alias in Apache config file, ...)


Drupal Commerce: Theming the Add Products form (Bulk Production Creation) I am using Drupal Commerce Bulk Product Creation to add products to my site.

I would like to theme the Bulk Add Products form to make it more user-friendly to edit.

I can use page--admin--commerce--products--add-bulk--PRODUCTNAME.tpl.php to override the form. However, I don't know what PHP code to use to print out the product fields.

I found some articles online (1, 2, 3) and have tried the following, but none of them work:

<?php print render($content['form']['product:field_FIELDNAME']); ?>
<?php print render($content['form']['field_FIELDNAME']); ?>
<?php print drupal_render($field_FIELDNAME) ?>
<?php print render($field_FIELDNAME) ?>
<?php print drupal_render($vars['form']['field_FIELDNAME']);     ?>
<?php print drupal_render_children($form['field_FIELDNAME']); ?>

Any pointers would be appreciated.

I have figured this out.

Step 1):
Find the ID of your form.
To do this, view the source of the form and search for "form" keep on searching until you see a field like this:

<form enctype="multipart/form-data" action="SOME_URL_HERE" method="post" id="commerce-bpc-create-bulk-form" accept-charset="UTF-8"><div>

The id you want is in the id="" string

You need to tell Drupal where to find your tpl.php file.
In template.php add the following:

function YOURTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'INSERT_ID_HERE' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/add/node--add--TEMPLATE_NAME',
            'render element' => 'form',
            ),
    );
}

So if you were themeing a  Drupal Commerce Bulk Product Creation form, your code would look like this:

function YOURTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'commerce_bpc_create_bulk_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/add/node--add--bpc',
            'render element' => 'form',
            ),
    );
}

3) Create a tpl.php template file and save it in the appropriate directory.
In our example, the file is called node--add--bpc.tpl.php and is saved in templates/add

4) In your tpl.php file, insert variables for the fields on the form. Here is a list of the most common fields:

<?php print drupal_render($form['product']['sku_fragment']); ?>
<?php print drupal_render($form['product']['title_fragment']); ?>
<?php print drupal_render($form['product']['commerce_price']); ?>
<?php print drupal_render($form['submit']); ?>
<?php print drupal_render($form['static_values']['field_YOUR_CUSTOM_FIELD']); ?>

5) At the end of the tpl.php file, put the following code:

 <?php print  drupal_render_children($form) ?>

It's very important you put this code, or you will get errors when trying to upload images.

6) The code in step 5, might print out fields you do not want. So you to have unset these fields. Here is a list of the most common fields to unset.

<?php unset ($form['product']); ?>
<?php unset ($form['combinations']); ?>
<?php unset ($form['title']); ?>
<?php unset ($form['static_values']); ?>
<?php unset ($form['description']); ?>

You put all this code on a line before:

 <?php print  drupal_render_children($form) ?>

7) If you find that any of the steps don't work, be sure to flush your cache. You can do this at: yousite.com/admin/config/development/performance


Views content panes link to view I have a view with multiple content panes and multiple pages. With the content pane, I have used the feature "Link to view" before to get the title of the pane to link to the page view. When using this before, there has only been one pane and one view, which has worked well.

Now I would like to link multiple panes up to different pages within the same view. When selecting "yes" in "Link to view", it always links to the first page. Is there a way to specify which page I would like to link my panes to?

Ok, I figured out you can directly insert html into view titles and it will work. Wrapping the different view panes in an <a> tag solved the issue.


Accessing variable_get when loading bootstrap from an external file I am loading the core drupal 7 components through an external file by loading bootstrap. While the core drupal functions work properly, when I try to access variable_get I keep getting the default value. The variable_get works properly when accessed from within a module. Any ideas?

require_once dirname(__FILE__).'/scripts/encrypt.php';

//Include drupal
$currdir=getcwd();
define('DRUPAL_ROOT',$_SERVER['DOCUMENT_ROOT']);
chdir(DRUPAL_ROOT);
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
global $base_url;
$base_url = (array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

print_r(variable_get('var_name',DEFAULT_VAR_NAME));

This always returns

DEFAULT_VAR_NAME

Why not write a proper Drupal module and include your intended code in there? You miss out on so many of Drupal's nice features if you use it your way, including the issue you are asking about here, but also lots of security and sanity checks. Just sayin'


How to count the children (elements) inside a fieldgroup? I use the Field Group module in a website and I'm trying to count the fields within a Field Group.

I tried …

$num_of_fields = count($content['group_name']['children']);

echo $num_of_fields;

… but it doesn't seem to work. What am I doing wrong?

If you use the following code you will see the value that you need.

/**
 * Implements hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
   //you need the devel module to use dpm() function
  //My field group name is group_g2
  dpm(count($form['#groups']['group_g2']->children));
}

Is easy to track values if you use the Devel and Search Krumo modules


How to get block layout programmatically? Sorry there won't much details but the title is self explanatory.

I need to fetch the block layout of the front page and build a menu from it.

So the question is: How can I get that list programmatically?

You can get the block layout programmatically from the configured blocks by going through each region defined in the current theme:

  $block_layout = [];
  $theme = \Drupal::theme()->getActiveTheme();
  $regions = $theme->getRegions();
  foreach ($regions as $region) {
    $blocks = \Drupal::entityTypeManager()
      ->getStorage('block')
      ->loadByProperties(['theme' => $theme->getname(), 'region' => $region]);
    uasort($blocks, 'Drupal\block\Entity\Block::sort');
    $block_layout[$region] = array_keys($blocks);
  }

This is without checking if the blocks are visible on the front page. That would be difficult, because the visibility condition plugins are context aware and only provide a correct result when they are called in a real front page context.


Feed mapping problem I want to create the following mapping for a product node: This is extracted and amended from an existing feed.

    'mappings' => array(
    0 => array(
      'source' => 'SKU',
      'target' => 'guid',
      'unique' => 1,
      'language' => 'und',
    ),
    1 => array(
      'source' => 'SKU',
      'target' => 'field_product:sku',
      'unique' => FALSE,
      'language' => 'und',
    ),
    2 => array(
      'source' => 'title',
      'target' => 'title',
      'unique' => FALSE,
      'language' => 'und',
    ),
    3 => array(
      'source' => 'body',
      'target' => 'body',
      'unique' => FALSE,
      'language' => 'und',
    ),
    4 => array(
      'source' => 'Group',
      'target' => 'field_product_category',
      'unique' => FALSE,
      'language' => 'und',
    ),
    5 => array(
      'source' => 'length',
      'target' => 'field_dimensions_length',
      'unique' => FALSE,
      'language' => 'und',
    ),
    6 => array(
      'source' => 'width',
      'target' => 'field_dimensions_width',
      'unique' => FALSE,
      'language' => 'und',
    ),
    7 => array(
      'source' => 'height',
      'target' => 'field_dimensions_height',
      'unique' => FALSE,
      'language' => 'und',
    ),
    8 => array(
      'source' => 'unit1',
      'target' => 'field_dimensions_unit',
      'unique' => FALSE,
      'language' => 'und',
    ),
    9 => array(
      'source' => 'weight',
      'target' => 'field_weight_weight',
      'unique' => FALSE,
      'language' => 'und',
    ),
    10 => array(
      'source' => 'unit2',
      'target' => 'field_weight_unit',
      'unique' => FALSE,
      'language' => 'und',
    ),

The first five items are OK and will map via nodes, the others, from 5 to 10 will not.
When I go to /Admin/Content/Settings/Content types/Product display/Manage Fields The field_weight element and field_dimensions elements are clearly shown.
How can I amend the node mapping to take these fields into consideration.?

Based on your code, I believe you are working on eCommerce website.

I think you need to change your target value to:

  'field_dimensions:length', 'field_dimensions:width', 'field_dimensions:height', 'field_dimensions:unit','field_weight:weight','field_weight:unit'


Change Views Path Programatically I have a custom form on my site, and on submission, I'd like to update a Views page path.

Within my module, I have a form alter which eventually attaches a custom submit function where I plan to run this Views path change. Within my submit function, so far I have:

function _my_module_custom_submit() {
    $view = \Drupal\views\Views::getView('custom_view');
    $view->setDisplay('page_1');
    // TODO: Change Views path

    // Save View
    $view->save();
}

This function is running fine, however I cannot find how to change the Views Display path at all. I've tried the setHandler() and setHandlerOption() methods, but these don't appear to be working for this case.

I've found plenty of examples to change the Views path programatically in Drupal 7, but have yet to come across an example for Drupal 8.

In Drupal 8 the configuration of a View is stored in an entity, which you can load, modify and save:

use Drupal\views\Entity\View;

  $view = View::load('custom_view');
  $display =& $view->getDisplay('page_1');
  $display['display_options']['path'] = 'example/path';
  $view->save();


Node Edit Form and twig template - confusion on where some values come from I'm still pretty new to Drupal and had a question about the node-edit-form twig template. In them template, you can render {{form}}, {{form.advanced}}, and {{form.actions}} but when using xdebug, the form variable doesn't actually have those values in the array. How are those being processed? I'm curious now i'f I've missed this in other twig templates for other arrays/objects.

When you xdebug $variables in a preprocess hook

function mymodule/mytheme_preprocess_node_edit_form(&$variables) {

}

you find $variables['form']['actions'] and the other form elements. You can also install a module to set a breakpoint in the twig template directly, see https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

What you now have is probably the form build $form in a different place.


How to clear all caches with Drush 9? https://drushcommands.com/drush-9x/cache/cache:clear/ this doesn't give any option to clear all caches. All you get is to choose from 0-7, old drush cc all or cr all are gone.

Eg.

root@dev:/var/www/example.com/htdocs# drush cc --cache-clear

 Choose a cache to clear:
  [0] Cancel
  [1] drush
  [2] theme-registry
  [3] router
  [4] css-js
  [5] render
  [6] plugin
  [7] bin
  [8] views
 > 7

 [success] 'bin' cache was cleared.

How to clear all options below with one command? I can't find it documented.

To clear drupal caches using drush 9x use the following command:

drush cache:clear

Command aliases:

drush cc
drush cache-clear

To clear all caches you can use:

drush cache:rebuild

Command aliases:

drush cr
drush rebuild
drush cache-rebuild


drupal_http_request times out on Google Maps geocoding URL When I navigate to http://maps.google.com/maps/api/geocode/json?address=1200+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false (the Google Maps Geocoding API test address) in my browser (Chrome), I get a json response as expected. However, when I drupal_http_request() the same url, I get a request timeout error. I tried setting the timeout to 60 instead of 30 but it doesn't help.

Why does drupal_http_request('http://maps.google.com/maps/api/geocode/json?address=1200+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false') return a timeout error?

You cannot directly include url queries in the url when using drupal_http_request(). Use url().

$url = url('http://maps.google.com/maps/api/geocode/json', ['query' => ['address'=>'1200 Amphitheatre Parkway, Mountain View, CA', 'sensor'=> FALSE]]);
drupal_http_request($url);


Disable the comment path site-wide Is it possible somehow to completely disable the /comment/ path on a Drupal 6 site?

Our site really doesn't need comments and despite having disabled comments on all content types and removing any comment hooks in our theme (someone else developed the site with comments in mind, but we have found that we don't need them, users don't use them, and they only bring in spam to clean up)  we still get pretty regular stream of spam hitting the /comment/reply/[some_content_id] paths and while we have a Mollom taking care of the spam for us, I am wondering if its possible to turn those bots away before they have a chance to leave their droppings.

It's been a while now since I've used D6 but can't you just disable the comments module?

Alternatively what about just blocking /comment with htaccess (SO thread on the subject)?


How can I use config-set to "unset" the value of a variable? I am trying to use config-set to "unset" a variable.  In this case, I have a media image field that has required crop types on it, which is breaking my behat tests, so I want to use drush to temporarily disable the requirement during the behat tests.

I tried something like this:

drush -y config-set core.entity_form_display.media.image.default content.field_media_image.settings.crop_types_required ''

But this breaks the config.  What's the correct way to "unset" a config value?

Use config-delete, not config-set:

drush -y config-delete core.entity_form_display.media.image.default content.field_media_image.settings.crop_types_required

Despite the name, config-delete does not delete any of your config .yml files; it only "deletes" the config inside the database.


Is there an easy way to define a "global" if isset condition on node.tpl.php? I'm using some custom node.tpl.php files with lots of custom fields. For each field I have to write down <?php if (isset($content['field_myfield'])):?> SOMETHING <?php endif; ?>

(It gives error if that field is not set without using if isset condition.)

Is there anyway to define a 'global' if (isset...): instead of adding if condition to each field separately?

No.  Consider the case where one field is not set.  Either the global if fails and nothing is printed or you are right back to those errors.  This is one of the shortcomings of coding in the theme layer.


Disabling drush backups after drush up? I use the command drush up for sites I store on a shared server & locally.

Within some months my Inode volume vent from about 25% 96% (96% is insane for most people using a shared server on whatever platform) and given the fact I already have 30 days backwards backup service, I don't really need this specific backup creation.

How can you disable the automatic backups created by drush each time drush update is ran?

Yes, use the --no-backup option with your command.

drush --no-backup up myproject

If you're you're looking to make this a default option, you can do something like Bash aliasing and just run that alias instead:

alias drush-no-bup='drush --no-backup'

Then run:

drush-no-bup up myproject


Text only rotating banner Is there any module for drupal 6 I can use to create a rotating banner with no images for drupal 6 site

Thanks

Colin

Try the Marquee Block module

  Provides a jQuery-based scrolling marquee block that can be customized with your own text or HTML. Configure speed, scroll direction and scroll behavior easily on the Block setup page.

Image from module page:

Or else if you want to do it so simple. just create a block and use <marquee> in your custom block ;)


geofield proximity in views Ive been trying to setup a view where the distance to users is stated.

There has recently been an update of geofield however I am having trouble with calculating the distances to users (only get a zero)

I have checked whether the users have points, which they do, and tried to create a relationship to the user id without results.

I am a newbee in views so every advice would be beneficial

See new documentation page for geofield that shows how to setup a basic proximity search (it is based on MotoTribe's answer, but with a bit more info)

As requested, some of the link content:

Instructions

Required modules

You must download the latest modules. These instructions have been tested with the 'dev' versions of geocoder, geofield, and addressfield modules. I believe these modules have a dependency on geophp, maybe others, install any dependent modules that you are instructed to when installing. Make sure to download the 'dev' versions!

Steps

Setup your content type:

Create a content type for whatever you want to locate (e.g. Dealers, Stores, etc)
In manage fields: Add an addressfield field to the content type (use options as you see fit).
In manage fields: Add a geofield field to the content type. When adding, make sure to select 'Geocode from another field' from the 'widget' dropdown! The geofield option are pretty straightforward, just make sure to select the addressfield field you created earlier for the 'Geocode from field' option.
Now, create a few records with addresses using your new content type.

That was easy! Now, let's setup the view result...

Setup your views query:

Create a view, can be any kind. Select the content type you created earlier for the results.
Add a field: '[name of your geofield] - proximity' (there are a number of geocoding related fields, you want the one with '- proximity' appended)
In the field settings: For the 'Source of Origin Point' field, select 'Exposed Geofield Proximity Filter'.
Add any other identifying fields, such as title, address, etc.
Add a new 'Filter Criteria' for your view for the '[name of your geofield] - proximity' field.
Choose 'Expose this filter to visitors, to allow them to change it'
For 'Operator', choose 'Is less than', because you want results that are closer than a certain distance from the value your users enters, e.g. less than 100 kilometers, etc.
For 'Source of Origin Point', choose 'Geocoded Location', which will allow the user enter friendly values such as city, state, zip/postecode, state, etc. (basically, anything you can put into Google location searches).
For Geocoding Service, choose 'Google Geocoder'.
Add a Sort Criteria: '[name of your geofield] - proximity'. Also, remove any other sort filter already existing, since sorting by date first will foil your proximity filter!
Set to sort ascending, since you probably want to show the closest results first.
Set 'Source of Origin Point' to 'Exposed Geofield Proximity Filter'.
Test your new proximity search!


CKeditor doesn't work in controller response within a default theme In a Drupal 8 project I've a controller which returns a form that contains a text_format field.

CKeditor is working perfectly in my administration theme (Stable), but it does not on the default theme.

I've tried to attach ckeditor core module libraries to the controller returned response with no results.

The role which I test with has permissions "Use simple HTML text format", "Use full HTML text format", also the role is checked on /admin/config/content/formats/manage/basic_html also on /admin/config/content/formats/manage/full_html.

my_module/src/Controller/MyController.php :

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\user\Entity\User;

/**
 * Provide user form.
 */
class MyController extends ControllerBase {

  /**
   * Return page content.
   */
  public function content() {
    // Load user edit form.
    $entity = User::load(\Drupal::currentUser()->id());
    $formObject = \Drupal::entityTypeManager()
      ->getFormObject('user', 'default')
      ->setEntity($entity);
    $form = \Drupal::formBuilder()->getForm($formObject);
    $render = \Drupal::service('renderer');
    $render_form = $render->renderPlain($form);
    return [
      '#theme' => 'customize_user_form',
      '#form' => $render_form,
      '#attached' => [
        // Attach ckeditor core module libraries.
        'library' => [
          'ckeditor/drupal.ckeditor',
          'ckeditor/drupal.ckeditor.stylescombo.admin',
          'ckeditor/drupal.ckeditor.admin',
          'ckeditor/drupal.ckeditor.plugins.drupalimagecaption',
        ],
      ],
    ];
  }

}

Results:

Any suggestions?

Many thanks.

A form usually contains all libraries necessary, but you shouldn't render the form at this point in the controller.

Put it unrendered in the template variable

return [
  '#theme' => 'customize_user_form',
  '#form' => $form,
];

and when you print the form in the template {{ form }} the libraries should be attached automatically to the page.


How i can popuplate user's facebook data into my built-in drupal register form? How can I populate an authorized user's Facebook data into my Drupal registration form?
Note: user is authorized from my Facebook application and allowed my Facebook app to access his data.

Update: I am using Drupal for Facebook, and to populate the user info I am implementing fb_form_alter inside fb.module. My code is

function fb_form__alter(&$form, &$form_state, $form_id) {
if(!($form_id == 'user_register_form')) {
return;
}
if ($GLOBALS['_fb'] && $fbu = fb_get_fbu($account)) { // @TODO - is fb_get_fbu() a performance hit here?
    try {
      $data = fb_fql_query($GLOBALS['_fb'], "SELECT name FROM user WHERE uid=$fbu", array(
                             'access_token' => fb_get_token($GLOBALS['_fb']),
                           ));
      if (count($data) && isset($data[0]['name'])) {
        $form['account']['name']['#default_value'] = $data[0]['name'];
      }
    }
    catch (Exception $e) {
      fb_log_exception($e, t('Failed to alter username for facebook user %fbu', array(
                               '%fbu' => $fbu)));
    }
}
}

I put the above code after the form_username_alter() function but with no success :(

The Dupal for Facebook module kind of does the trick.

The problem is that it uses soon to be deprecated FB APIs, and it isn't exactly Drupal 7 ready yet (though it's very well maintained and I am sure it'll catch up soon), so you might as well want to write your own module from scratch. These are the basic info you should check if you want to get into this

Get user Authentication and Permissions. (You will
probably need to also look into offline_access permissions.)
Access to the FB user object using the PHP SDK for Basic profile informations. It is session based, so you can access it from anywhere in your site, for instance to pre-populate you registration form. (Don't forget to include the PHP SDK to your script.)
Access or write other user data (e.g., activities, picture, wall feed) via the Graph API.


Exposed filter - based on first three number in Zipcode? I have been using Basic Exposed Filter for filtering the zipcode(Number) field.

Now, I want to filter based on the first three number, though the 5 digits number is entered.

How do I achieve this ?

Please check this link

Is has an example how to implement query alter having exposed filters.

function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  // (Example assuming a view with an exposed filter on node title.)
  // If the input for the title filter is a positive integer, filter against
  // node ID instead of node title.
  if ($view->id() == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on title, chang the
        // condition to filter on node ID.
        if ($condition['field'] == 'node.title') {
          $condition = array(
            'field' => 'node.nid',
            'value' => $view->exposed_raw_input['title'],
            'operator' => '=',
          );
        }
      }
    }
  }
}


Overriding user edit page with Panels loses the user edit form I am using panels to override the user edit page (/user/*/edit) to add a block with a form in it. However I wanted to maintain the existing user edit form, including the password, username, etc. When I overrode the page, I was able to add my block, but lost the original user edit form. I've tried adding the various widgets from the 'User' category (user profile, Profile:Main Profile, etc) on the 'Content' section of the new variant, but they just seem to contain various bits of user information, and none of them add the user form.

How can I add back the user edit form to an panels-overridden user edit page?

I think it's fair to say the pane could have had a better name, but here it is.


Ajax callback called on textfield typing I'm trying to reach exactly the same state as autocomplete field does. When user is typing in textfield I'd like ajax to wait with its callback so the user can write all the text.

I'm trying to achieve it with help of this question. But I'm failing. Maybe because I'm playing with JavaScript in drupal for the first time. Anyway here is my code.

form_alter in .module (I have form generated with features)

if (empty($form['nid']['#value'])) {

    drupal_add_js(drupal_get_path('module','MY_MODULE') . 'my_script.js');

    $form['field_my_field']['und'][0]['value']['#ajax'] = array(
        'callback' => '_test_callback',
        'event' => 'finishedinput',
    );
}

my_script.js (from the link above)

(function ($, Drupal) {
Drupal.behaviors.MY_MODULE = {
    attach: function (context, settings) {
      var typingTimer;
      var doneTypingInterval = 10;

  $('.andtimer').on('keyup', function (e) {
    clearTimeout(typingTimer);
    if ($(this).val) {
      var trigid = $(this);
      typingTimer = setTimeout(function(){
        trigid.triggerHandler('finishedinput');
      }, doneTypingInterval);
    }
  });
}
};
}(jQuery, Drupal));

And I have script attached to my .info file.

here my solution:

first you've to create (or alter) a text field

$form['user_search'] = array(
  '#type' => 'textfield',
  '#title' => t('Search'),
  '#description' => t('Cool description'),
  '#ajax' => array(
    'callback' => 'MODULE_ajax_user_search',
    'wrapper' => 'user-search-replace',
    'event' => 'finished_input', // custom event called by js code
    'effect' => 'fade',
  ),
  '#attributes' => array(
    'class' => array(
      'delayed-search-submit' // custom class to attach behavior to
    ),
    'data-delay' => '300', // custom property to set submit delay
    //'data-event' => 'finished_input', // custom event name, default is "finished_input"
  ),
);

then you'll have to create some js code to attach to your form

(function($){
  $(function(){
    Drupal.behaviors.delayedSearchSubmit = {
      attach: function (context, settings) {
        $('input.delayed-search-submit').once('event', function (){
          var $self = $(this);
          var timeout = null;
          var delay = $self.data('delay');
          var triggerEvent = $self.data('event');
          if (!delay) {
            delay = 1000;
          }
          if (!triggerEvent) {
            triggerEvent = 'finished_input';
          }
          // Every time a keyup event is fired
          // timer is reset
          $self.bind('keyup', function(){
            clearTimeout(timeout);
            timeout = setTimeout(function(){
              $self.trigger(triggerEvent);
            }, delay);
          });
        });
      }
    }
  });
})(jQuery);

now attach js file to your form

drupal_add_js(drupal_get_path('module', 'MODULE') . '/js/MODULE.textsearch.js');


Best Practice - Node Template Logic I have a node template file that requires a lot of logic. So much so that in order to make things easier I have created functions inside my custom node.tpl file. What is best practice for separating logic from the node.tpl?

Thanks!

You should use the template_preprocess_node() function. Add this to your template.php in your theme and do whatever you have to do.


Deleted nodes appears in Views VBO list with their pathauto links Deleted nodes appears in Views VBO lists with their pathauto links.

I have custom VBO view which I use to delete filtered nodes. After processing I get this message i.e. 'Skipped Delete node on node id 251'. It's probably because the node doesn't exist, but in the views list it's still listed and has its original title and path to it and when clicked it gives page not found.


Alter comment pager to jump to comment section right away? I set up a content type and a specific comment type for this content. I set the comment pager to display 10 comments per page. When I now use the pager, I get redirected from the node URL itself www.domain.com/node/1, to www.domain.com/node/1?page=1.
Is there any possibility to add an ID to the URL for the comments pager only, for example www.domain.com/node/1?page=1#comments?
I want to do this, so the user doesn't need to scroll over the whole content of the node again, just to get to the second comments page. Instead, I want to jump to the comment section right away.
Is there any elegant way to do so? A module that does it, or similar? I already thought of altering the pager.html.twig in my theme. But then I would alter the node pager as well.
Thank you very much in advance for pointing me any way to achieve this.

The only hook Drupal uses to alter a pager is hook_preprocess_pager() but that is invoked for every pager on any page, not just the pager used for comments.
The alternative is adding a new formatter for comments, which by default is the CommentDefaultFormatter class, and make it the default one with hook_field_info_alter().
function mymodule_field_info_alter(&$info) {
  // Change the default widget for fields of type 'comment'.
  if (isset($info['comment'])) {
    $info['comment']['default_formatter'] = 'mymodule_comment_formatter';
  }
}

(mymodule_comment_formatter is the formatter ID used in its annotation.)
The relevant code that sets the pager is in CommentDefaultFormatter::viewElements(), which contains the following lines.
if ($comments) {
  $build = $this->viewBuilder->viewMultiple($comments, $this->getSetting('view_mode'));
  $build['pager']['#type'] = 'pager';

  // CommentController::commentPermalink() calculates the page number
  // where a specific comment appears and does a subrequest pointing to
  // that page, we need to pass that subrequest route to our pager to
  // keep the pager working.
  $build['pager']['#route_name'] = $this->routeMatch->getRouteObject();
  $build['pager']['#route_parameters'] = $this->routeMatch->getRawParameters()->all();
  if ($this->getSetting('pager_id')) {
    $build['pager']['#element'] = $this->getSetting('pager_id');
  }
  $output['comments'] += $build;
}


How can I hide the title in my user registration form? I am using LoginToboggan module. And I want to hide the title.

As you see in first picture "Log in" title is shown, and in second "Create new account" title is shown. How can I hide these titles?

Use disable/hide title module. Alternatively, you can disable the title pretty easily with css.
Another way is to disable the title using template.php using drupal_set_title()


Simplenews: node links not working The problem I face is the following:
I have set up simplenews for creating newsletters. I am able to select articles, pages, events etc. which are already displayed on the website itself.
However, after I selected the ones I want to show up in the newsletter and create a table of contents, there is no link to the article. It just shows the plain text without linking. Also the view mode dropdown menue is empty.

can anybody help me with this?
cheers,
nebelwueste

It's hard to say without seeing your Views settings but you may need to change the Field settings to link back to the full article.

E.g. See the bottom checkbox.


Increase Product Quantity based on attendees added Drupal Commerce I am developing a training website using Drupal Commerce. The person can book a single slot every time and can add attendees(used field collection for dynamic rows) to the training slot. How Can I increase the Order total based on the people added in the form in checkout?

For Example, If the slot is 33 dollars per person then if I add two attendees in the checkout, automatically the quantity should increase and should change the order total.

I thought to try with rules, but I didn't get how to get the count of field collection items in the rule and increase the price.

Could anyone please suggest on this?

Thanks in Advance!!!

If you want to do this solely via Rules, then you'd likely need to write a custom Rules action that can count those attendees and apply an appropriate price adjustment to the unit price of the line item. If you want to bypass Rules completely, you can change your price calculation process to support module based alterations and write custom code that hooks into the sell price calculation process via hook_commerce_product_calculate_sell_price(). The challenge here is that you aren't getting these attendees until the checkout form, so you'll want to make sure the customer has a chance to review the final price before paying.


Get Last NID into Variable I need to get the previous (referrer) NID into a variable on a page. After saving new content of a certain content type a rule will redirect the visitor to a set page where I would like to have the NID of the new node to play with. Can anyone point me in the right direction? I think its possibly going to be one of those ones that you'd think is simple but ends up being awfully complex but I'm really in need of a solution and can't find anything very relevant.

Thanks in advance folks!

You might be able to create a rule based on this:

event: After content has been saved...
condition:  content is new
condition:  content is type (select type)
action: page redirect:  fill in page here with tokens based up content above

In the page direct you can create a query variable after the ?, eg foo=[TOKEN], and then in your page, you can access that variable via $_GET['foo'] or $_REQUEST['foo'].


Is it correct that a node and it's translations have the same node id? I just translated a node and I saw that both nodes have the same node id. Since I cant find anything about it: is this correct?

Yes it's correct because Drupal 8 use Entity Translation (in core) for the translations.

You can more about this in Drupal 8 multilingual tidbits 17: content translation basics

  If you already built multilingual sites with Drupal 7 that had content
  translation, you may notice this model is a refined version of the
  Drupal 7 Entity translation module (without awkward modules required
  like Title) rather than the Drupal 7 core content translation module.
  The core module in Drupal 7 keeps different copies of nodes and
  relates them together in a translation set. In Drupal 8 this feature
  is not available, instead you can configure translatability on a field
  (and in some cases subfield) basis. However if you configure all
  fields to be fully translatable, you can essentially reproduce the
  Drupal 7 behavior. Compared to the Drupal 7 core solution with
  different entity identifiers then, Drupal 8 will have the same entity
  identifier but a different language variant.

  The biggest advantage of the Drupal 8 solution is you can configure to
  translate as much as needed and not more. With one unified solution to
  translate only some fields or all fields, (contributed) modules only
  need to deal with one system instead of two. With storing translations
  under one entity, modules that don't want or need to deal with
  multilingual scenarios can still consider the entity as one, no need
  for special translation set support. That is way more flexible than
  Drupal 7 and best of all it applies to all kinds of content, not just
  nodes. It is future proof for modules you enable like rules and
  commerce.


Views exposed taxonomy hierarchy I have a taxonomy with 4 categories; each category has child-categories beneath them.

This taxomony term is exposed in a view filter, but I get a combination of the parent and child categories in the resulting dropdown list options. What I actually want is just the parent-categories listed and not the child-categories.

Can anyone help?

Never mind!

I just discovered the "limit list to selected items" check box which solved my problem.
It does mean I have to manually select the taxonomy terms I want visible. So, it's not a fully automated solution but it will do for now.


Taxonomy Menu & Hierarchy Trees So I tried this tutorial on Taxonomy Menu and Menu Block. Now I set up the block to go in the header showing only 1 level deep.

My goal is to click on that 1 level deep link and generate a second menu showing the hierarchy. Instead I get a generic template that displays all posts of the parent taxonomy.

So, ideally:

[Header Menu Item] > Goes to hierarchy tree

Sub category 1 > Goes to hierarchy tree

Nodes of sub category 1

Have a look at Taxonomy Split, Drupal 6 only at the moment.

if you have a vocabulary in the form of a tree, eg it has terms within terms with nodes attached to them.
It will place all the first level terms in a block and when a term is clicked displays the tree below that term in another block.


Flag module views integration Following an excellent suggestion, I added the Flag module to a website in order to allow users to store their favorite stories in a dedicated page. This seems to be working really nicely, but how do I now add the option to flag content as a field in a view?

If you want to display a list of content a user has flagged - You want build your view as you would any other. Then you add a relationship to the view for the flag you wish to display.

If you wish to allow your user to simply add a flag directly from the view results, you would add a field to the view of the type "Flags: Flag Link". This will add the add/remove flag link to each result in your view.


Auto pulling an image from a post in Views I'm creating a custom view and I want to create thumbnails for the posts.

The problem is there is hundreds of posts and they all have 1-2 maybe 3 images in them. I want to pull the first image in the post and use it as a "post thumbnail" in a view.

Is this possible?

Thanks for any tips.

Yes select the cck field in the fields of the view and then in its options select number of images to display  to one. This should do the job.


I want to filter to show orders that their ending date is today I am using Drupal 7 and I have a webform where people can order a product and they enter the date that they will pick up that product. I want to make a view that will show me the poeple that are picking a product today, but when I try to make a filter for that the fields that are given are only the date that they submited the order not the date_field. Here is a picture of which fields are given to select.

In order to use webform fields in views filter/sort, you will need to add relationship with them. They should be available for relationship in the format or Webform submissions: Data :XXX.

Once you add them, you can further use them in filter/sort with more conditions. Hope it helps !!


Drupal Migrate doesn't register When trying to set up a migration, I can't seem to register new Migrations. When running drush migrate-status, I only see my User migration, even after a drush migrate-register.

My migrate.inc looks like this:

function module_migrate_api() {
    $api = array(
        'api' => 2,
        'migrations' => array(
            'User' => array(
                'class_name' => 'UserMigration'
            ),
            'News' => array(
                'class_name' => 'NewsMigration'
            ),
            'Activity' => array(
                'class_name' => 'ActivityMigration'
            )
        )
    );

    return $api;
}

And my module.inc file contains classes for each of these Migrations, based off of the UserMigration I wrote first (example given is UserMigration, which works, and NewsMigration, which does not work):

class UserMigration extends TestMigration {
    public function __construct($arguments) {
        parent::__construct($arguments);

        $this->description = t('Migrates users');

        $query = Database::getConnection('default', 'original')
            ->select('users')
            ->fields('users', array(
                'user_id',
                'username',
                'firstname',
                'lastname'
            ));
        $this->source = new MigrateSourceSQL($query);

        $options = array();
        $this->destination = new MigrateDestinationUser($options);

        $this->map = new MigrateSQLMap($this->machineName, array(
            'user_id' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'description' => t('Source ID')
            )
        ), MigrateDestinationNode::getKeySchema());
    }

class NewsMigration extends TestMigration {
    public function __construct($arguments) {
        parent::__construct($arguments);

        $this->description = t('Migrates news');

        $query = Database::getConnection('default', 'original')
            ->select('news')
            ->fields('news', array(
                'news_id',
                'user_id',
                'title',
                'text'
            ));
        $this->source = new MigrateSourceSQL($query);

        $options = array();
        $this->destination = new MigrateDestinationNode('news');

        $this->map = new MigrateSQLMap($this->machineName, array(
            'news_id' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'description' => t('Source ID')
            )
        ), MigrateDestinationNode::getKeySchema());

        /* $this->addFieldMapping('target', 'source'); */
    }
}

So far, I haven't added fieldmappings, since I want to set up everything that should be migrated first, to get a complete view of the work that's left.

When running drush migrate-register, I'm getting the following output:

All statically defined migrations have been (re)registered.                                                                                [success]

And a drush migrate-status gives me the following:

 Group: Test  Total  Imported  Unprocessed  Status  Last imported
 User         55     0         55           Idle    2015-12-03 13:40:30

So as you can see, no errors, not even when running with -v. But only User is recognized. Both classes are in the same file. Am I missing something simple?

Make sure you clear your cache (drush cc all) after (re)registering your classes.  Not doing so will often result in the migrate page showing error ClassName no longer exists.


Fatal error while editing and deleting menu items Facing one issue in deleting the menu items on my Drupal 8 Site.
Steps to reproduce:
Add a link to main menu.
Create Child terms under one link.
Delete the parent term.
After deleting the parent link child links stays they don't get deleted
automatically.
If you want to edit/manually delete those links then a Fatal error is
coming.
Error Message : Drupal\Component\Plugin\Exception\PluginNotFoundException: Plugin ID 'menu_link_content:adad91f8-19c7-48c7-a88e-67aae4edd21e' was not found. in Drupal\Core\Menu\MenuLinkManager->getDefinition() (line 207 of /var/www/crain-platform/docroot/core/lib/Drupal/Core/Menu/MenuLinkManager.php).
After doing some debugging i see the menu data missing from menu_link_content table.Anyone have any idea why this is coming and how to fix this issue?

This error was coming because of responsive menu module.Responsive menu was fetching the parent links using

\Drupal::service('plugin.manager.menu.link')->createInstance($parent);

Adding the condition before calling createInstance will fix this issue.

\Drupal::service('plugin.manager.menu.link')->hasDefinition($parent)

Created a issue on D.o also

https://www.drupal.org/project/1786786/issues/2924229


How to use the Message module to log site and user activity? I am just unable to use the Message module or the Activity module to record the following activities and show them in a view.

User A just got 10 points.
User B just became User A's friend.
User C just joined the site.
User D just logged in.
User E just viewed "Any Blog".
User F just commented on "Any Blog".

The Activity module does not provide hooks for some of this in the CMS UI itself and I am having real difficulties to configure the Message module for these cases.

There is not enough documentation for this, especially the Message module. There is one tutorial at Log Site Activity with Message and Rules but that is for only one of my cases. I haven't been able to figure out the other use cases. I don't get exactly the same options (entity and tokens) as described in the tutorial.

Any help with my use cases?

The Message module is great, really! But still poorly documented. However, have a look at the tutorial "How to use Rules to notify users about new or updated posts on a Drupal site?", which explains how to use the Message module, together with the Rules module. What follows is a summary of what's included in this tutorial.

  You can use the Message module in combination with the Rules module create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages that got created in the format you need (page, block, etc).

  Here is a blueprint of what you'd need:

  Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to nodes.
  Create a rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in 'Which user related token(s) can be used to create a Rule for setting up a message type?' for some examples.
  Make sure to also add a Rules Action to pass any relevant tokens, via the Rules module, as Replacement tokens that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
  Use Views to display the created messages in the format you prefer.

Some more details specific to your question here:

For each of the 6 activities you want to record, define an appropriate (corresponding) Message Type (using the Message module). Let's name those message types like M1, M2, ... M6 for now.
For each of the 6 activities you want to record, there is an appropriate Rules Event you can take advantage of. If you'd just create 6 custom rules (1 for each activity to record, let's name those rules like R1, R2, ... R6 for now), it's a matter of combining each rule with a Rules Action to "Create an entity" (i.e. of type "Message"). E.g. Rule R3 should have a Rules Action to create a message of type M3.
As per the "I don't get exactly the same options (entity and tokens) ..."-part of your question: I bet sooner or later you're going to run into the issue that you want to create a message using a token which is NOT made available by only the Message module. E.g.: Assume that for recording your 6th activity (= "User F just commented on ...") you want the message to also include the actual comment body (text) that was posted. But the Message module doesn't offer any relevant token related to that comment body. In that case, you can use the approach/solution as documented in "What's the purpose of "Replacement tokens" of a Message type?", which is basically a technique to create your custom tokens (the comment body in the example here) and make them available to the Message module (so that you can include them in the message to be created).
Obviously, creating appropriate views of these messages (which are just entities) should be straight forward.

More info about the Message module

There is not a lot of documentation available about the Message module, which is what makes it a hidden Drupal gem. A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to also have a look at these tutorials:

What is Drupal's Message Stack and how do its modules work together?
How to allow users to manage their own Message Stack messages?


Url params not working -> access denied I'm new to Drupal 8.

I tried to do some batch process (for example installing modules or importing language files).

I got access denied for example on this address :
http://localhost/en/batch?id=17&op=start

I tried to investigate and debugging and find out in the file batch.inc

$request->get('id')

is Null

That means id=17 is not working.

What am i missing? Is it related to my Nginx server block config?

It was related to my nginx config and fast cgi params

using apache instead of nginx temporarily fixed he issue


Need to add filter with more than one word in view filter criteria Drupal7 I need to add one filter that can take more than one word for searching.
Right now i selected "contains" option in Operator for filter criteria.
ie i need search string like this:
title=word1 or word2…

So in this case what should be my search url:
search-page?title=word1 word2


Ubercart and payment gateway options I'm trying to recommend a good payment gateway for a client. We'll be using ubercart, and one of the main requirements is recurring automatic orders (recurring/subscription model I guess).

Also important is the ability to not store the credit card data on the server.

What options are there for this? The main one I see is an authorize.net cim module. Is this the option I should recommend? What other options are there?

The authorize.net module supports recurring payments using ARB. You can also setup recurring payments using the paypal module. I wouldn't be surprised if the other credit card payment gateways support recurring payments too.


How to display title of a webform in twig template Drupal 8 I want to display webform title in a webform.html.twig but I did not find anything in variables array regarding the title of the webform

function THEMENAME_preprocess_webform($variables){
  $title = "?";
}

How do I get webform title in a preprocess function ? Any suggestions or other approach ?

Here is what I came up with

function THEMENAME_preprocess_webform(&$vars){
  $wfid = $vars["element"]["#webform_id"];
  $wf = \Drupal\webform\Entity\Webform::load($wfid);
  $vars["title"] = $wf->label();
}

Then in your theme's webform.html.twig you can use {{title}}


Don't render html.tpl.php for a specific path Is it possible to load page content without rendering html.tpl.php? I mean on default Drupal has the follwoing:

Html.tpl.php --> Page.tpl.php -->...(etc.)

my goal is to remove Html.tpl.php for a custom path (site://ajax-unesco)

so:

page--ajax-unesco.tpl.php --> ... (etc.)

You could do something like this:

/**
 * Implements hook_menu
 */
function MY_MODULE_menu(){
  $items = array();
  $items['clean/view'] = array(
    'page callback'    => 'MY_MODULE_clean_view',
    'page arguments'   => array(2, 3),
    'access arguments' => array('access content'),
    'type'             => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Menu callback for clean/view
 * Output view without wrapper page markup
 */
function MY_MODULE_clean_view($name, $display = 'default'){
  // Note views_embed_view performs views access check
  print views_embed_view($name, $display);
  drupal_exit();
}

You can then use the dynamic path /clean/view/view_name/display_id to render the View without the wrapper markup.


How to close (ctools) modal node/add form after submit? I wrote this module that print the node/add form for a content type (article) in a ctools modal window. It works and the new node is saved, but the modal window remains opened after submitting the form.

I would like to automatically close the modal window after saving the node, end and optionally redirect drupal to the new node. Any hint?

      <?php

    function modaltest_menu()
    {
    $items['modaltest']            = array(
        'title' => 'Modaltest Page',
        'page callback' => 'modaltest_page',
        'access arguments' => TRUE
    );
    $items['modaltest/%ctools_js'] = array(
        'title' => 'Modaltest page 2',
        'page callback' => 'modaltest_page_modal',
        'page arguments' => array(
            1
        ),
        'access arguments' => TRUE
    );
    return $items;
}

      function modaltest_page_modal($js = NULL)
    {
      $nojs_message = t('Hello World');
    if (!$js) {
        return $nojs_message;
    }
    module_load_include('inc', 'node', 'node.pages');
    $form = node_add('article');
    ctools_include('modal');
    ctools_include('ajax');
    $output   = array();
    $output[] = ctools_modal_command_display(t('My modal test'), $form);
    print ajax_render($output);
    exit();
}

    function modaltest_page()
    {
    ctools_include('modal');
    ctools_include('ajax');
    ctools_modal_add_js();
    return ctools_modal_text_button(t('Popup link'), 'modaltest/nojs',      t('test popup'), 'ctools-modal-test-style');
    }

ctools_modal_command_dismiss() will close the modal.

You can find more information on that command and ctools modals in general by installing the Advanced Help module and visiting /help/ctools/modal.


Should store input format in the database? When using the WYSIWYG editor, should I store not only the text but also the format ("Full HTML"/"Filtered HTML"/...) in the DB?

Yes, if you have your own form elements that are using the WYSIWYG, and are storing those results in th database, then you should also save off the input format. I did a survey of well-used modules looking into this a few weeks ago, and didn't find any that didn't do the same.

Even if you don't need it now, you will have some need in the future tho render out that input, and you will need the format to pass to check_markup.


How to handle translation correct way? Some background: On the site I'm maintaining, I installed Internationalization module and also enabled Node Translation. I added a few languages, then set a node's language to French and site default language to English.

When the site's current language is set to French, the node shows up as en/node/28, however shows up as fr/sous-specialites when the current language is French. How do I work this around?

UPDATE: Detection and Selection page has URL, Session, User and Browser enabled.

I guess you want the url alias to be /sous-specialites for the english node. If so, I think you can use Global redirect module.

  From the documentation,

  What?

  GlobalRedirect is a simple module which…

  Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
  Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
  Checks if the current URL is the same as the site_frontpage and redirects to the frontpage if there is a match.
  Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the
  'unclean' method.
  Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private
  aliased node's.
  Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias
  "articles/cake-making" to node/123, then the user can access the alias
  with any combination of case.
  Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect_admin
  module. In Drupal 6, the settings page is bundled into the module.


How do I programmatically create a list of new users? I'm trying to use the following drush script, but I keep getting errors. Currently, it is not properly setting the user role to Premium.

#!/user/bin/env drush
<?php
  $users = [
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
  ];
  foreach ($users as $key => $val) {
      drush_invoke("user-create", $val);
      drush_print("Created account for email " . $val);
      drush_set_option("password", $key);
      drush_invoke('user-password', $val);
      drush_print("Created password for email " . $val . " with password " . $key);
      drush_set_option("mail", $val);
      drush_invoke('user-add-role', "Premium members");
      drush_print("Added premium role to " . $val);
  }
?>

Is there a better way to achieve this?

If you are having trouble with drush_invoke, try drush_invoke_process, which has two advantages over drush_invoke:

It is executed in a separate process, so you can set options explicitly, and do not need to worry about option "pollution" from previous calls to drush_set_option()
The results of the operation, including all log messages, is returned as structured php data, so you have a better idea of what was done.

Example:

$values = drush_invoke_process("@self", "user-add-role", array("Premium members"), array('mail' => $val));

You will find the output of the command in $values['output'], and structured results (if available) in $values['object'].

Note that in general, there is nothing wrong with calling drush_invoke as you are doing above; you may use that technique if it works for your use case. It is likely to be faster, but may sometimes be fragile.


Problem with remote sync because of wrong UUID I have a problem with syncing my config to the remote server with Drupal 8. When I pull everything with GIT, and use drush to update the config via drush cim I get the following error:

Attempt to save a configuration entity &#039;field_bestand_en_&#039; with UUID &#039;&#039; when this entity already exists with UUID
&#039;b8bbd770-1533-4680-88cd-3409b0921d02&#039

So the problem is that the UUID doesn't match, the new file for some reason lost its UUID and is null now. I tried adding the given UUID by hand to the right yml file but on every new config update it gets overwritten.

So when I do drush cex locally, the UUID is null again. How can I fix this, I guess deleting the field and creating it will fix it but this is not really an option.

Thanks in advance

I was synchronizing the configuration between local environment and remote repo, and after doing the Pull and drush cr, when using drush cim, I got a similar error.

In my case, the UUID (unique identifier of Drupal element), of the configuration entity was in NULL value. Since I didn't know the origin of this, I went to the remote repository and I saw that it was pushed like this. In origin, it seems an export failure (drush cex).

I solved it by getting the number and writting the UUID (it's the same one that announces the error of drush cim by console). I edit the field configuration file and change NULL for this value of the UUID and again drush cim works again. Next, it is important to commit this change to remote (git push) so that it can be modified there, otherwise it can be lost locally after a global "pull".


In which table should I save the value of system_settings_form in Drupal 7? I am using Drupal 7 and creating a form with some fields like position.

function mycustom_form($form, &$form_state){
  $form = array();
  $form['position'] = array(
   '#type' => 'textfield',
   '#title' => t('Position for the magnifier'),
   '#options' => array('left' => 'Left', 'right' => 'Right','up'=>'Up','down'=>'Down'),
   '#required' => TRUE,
  );
  return system_settings_form($form);
}

When I click on save with any position selected, these values are saved. So I am not getting where these values are saved and how to use these values in a JavaScript file... I am saving these values in a database.

If you use system_settings_form function your data will be saved in 'variable' table.
To get saved data you may use variable_get function.

To show saved value in form

       function mycustom_form($form, &$form_state){
         $form = array();
         $form['position'] = array(
           '#type' => 'textfield',
           '#title' => t('Position for the magnifier'),
           '#options' => array('left' => 'Left', 'right' => 'Right','up'=>'Up','down'=>'Down'),
           '#default_value' => variable_get('position', ''),
           '#required' => TRUE,
         );

         return system_settings_form($form);
       }

If you want to use saved data from your form in the javascript, you may use next code

drupal_add_js(array('myModule' => array('position' => variable_get('position', ''))), 'setting');

Then this data will be available in javascript in Drupal.settings.myModule.position variable


Deprecated configuration for the temporary files path After updating to 8.8.1 I get this warning:

  You are using deprecated configuration for the temporary files path. Remove the configuration and add the following to settings.php. $settings["file_temp_path"] = ".tmp"

But I can not remove the configuration, because the page:
"admin/config/media/file-system" is not editable.

Starting in 8.8, Drupal no longer allows setting the temp directory on the file system setting form. The form deliberately disables the field to prevent folks from using it. For full info about this change, see Deprecate file_directory_temp() and move to FileSystem service on d.o.

All you have to do is set the temp directory path in settings.php as the message indicates.

$settings['file_temp_path'] = '/path/to/tmp';

Note: if your temp directory is not /tmp, do this before running database updates. From the d.o issue where this change was implemented:

  If your site is not using /tmp, you must update settings.php before
  running database updates.

What if I run database updates before setting the temp path in settings.php?

Looking at the issue and reviewing the most recent patch (patch #121), it doesn't look like anything terrible happens. The only thing that happens during update.php is it attempts to delete the deprecated config for temp file path from system.file.path.temporary (where it's set on the /admin/config/media/file-system page). However, it'll only remove the config if it's safe to do so.

/**
 * Remove 'path.temporary' config if redundant.
 */
function system_update_8801() {
  // If settings is already being used, or the config is set to the OS default,
  // clear the config value.
  $config = Drupal::configFactory()->getEditable('system.file');
  if (Settings::get('file_temp_path') || $config->get('path.temporary') === FileSystem::getOsTemporaryDirectory()) {
    $config->clear('path.temporary')
      ->save(TRUE);
  }
}

While nothing is broken, you will end up with deprecated config just hanging around (forever?). To get your site to a state that matches where it would've been had you made the settings.php update before running updates, make sure you set $settings['file_temp_path'] in settings.php and then do one of the following:

Create a new update hook in a custom module that has the same contents of system_update_8801() then run updates again after making the update to settings.php.
Manually edit the config file in your config directory to remove the configuration, then import.
See How do I re-run updates (change module schema version)? to attempt to rerun the original update.