Feeds - Background process vs Batch API I've being using Feeds to import a medium sized amount of nodes in a daily basis.
I'm using Elysia cron in order to get fine tuning cron settings.

Here's my flow :

Every day at 02 am a cron task is triggered
This task loads a list of files from its settings, and for each of these files, it triggers a feeds import by calling :

$myFeed->startImport()

If you take a look at this startImport method, you will see something like this :

public function startImport() {
    module_invoke_all('feeds_before_import', $this);
    $config = $this->importer->getConfig();
    if ($config['process_in_background']) {
      $this->startBackgroundJob('import');
    }
    else {
      $this->startBatchAPIJob(t('Importing'), 'import');
    }
}

So, we have two ways of calling the Feeds importer, either using the Background JOB api (which I suppose to be this : https://drupal.org/project/background_process) or the Batch API (https://drupal.org/node/180528).

Since I'm starting the feeds importer from a cron task, which one is more appropriate for this scenario ?

Can we see the Background process as an enhancement of the Batch API ?

I've been digging through this code, and Feeds does not use Background Process.

It uses Job Scheduler

From FeedsSource.inc:

  /**
   * Background job helper. Starts a background job using Job Scheduler.
   *
   * Execute the first batch chunk of a background job on the current page load,
   * moves the rest of the job processing to a cron powered background job.
   *
   * Executing the first batch chunk is important, otherwise, when a user
   * submits a source for import or clearing, we will leave her without any
   * visual indicators of an ongoing job.
   *
   * @see FeedsSource::startImport().
   * @see FeedsSource::startClear().
   *
   * @param $method
   *   Method to execute on importer; one of 'import' or 'clear'.
   *
   * @throws Exception $e
   */
  protected function startBackgroundJob($method) {
    if (FEEDS_BATCH_COMPLETE != $this->$method()) {
      $job = array(
        'type' => $this->id,
        'id' => $this->feed_nid,
        'period' => 0,
        'periodic' => FALSE,
      );
      JobScheduler::get("feeds_source_{$method}")->set($job);
    }
  }

Job Scheduler in turn uses cron to complete jobs, so you're not really saving yourself anything if you are already calling this from cron.

The core Drupal Batch API uses AJAX to break up jobs into batches. You can't start a Batch API batch from cron. If you don't have JS and try to start a Batch with the core API, you'll still need to watch the progress bar move across the screen. If you abandon your browser during a batch, it will stop working.

Contrary to what the previously accepted answer above states, the core Batch API does not use cron

Background process is now a suite of modules, and it does now include a Batch API module. These are 2 separate modules, which are not related to the Job Schedule module. We can't refer to Background Job/Process as 1 thing. These are 2 unrelated modules.

The key differences are as follows:

Drupal Batch API uses your browser to make new requests to the server at regular intervals. This does not work from a cron job

Job Scheduler uses cron to call on a set of scheduled jobs during cron execution. There is a limit on how long the process can run during cron, so this is not ideal for long-running processes. It also is not good if you need your import to occur in a timely manner, when you have your cron job only running at night. Scheduling a new Job during cron is a bit backwards, since it might not be until the next cron run that the job is actually dispatched (depending on if your hook_cron() is called before or after job_scheduler_cron())

Background process / Background Batch uses server-side http requests to chain steps of a process together. This is ideal for long-running processes that need to be started immediately. You can also start a long-running process from hook_cron() with this module, and it will run until finished.

I know you probably don't need this information now, but I did when I found this page from Google.

The information provided in the previously accepted answer is incorrect, and led me down the wrong path.


call from form alter - undefined function error I try to use code for redirecting after submitting a form, but I am getting the below error:

  undefined function my_search_form_submit_funtion in form.inc.

Why do I get this error? Thank you.
The module name is utility.

function utility_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['#submit'][] = 'my_search_form_submit_funtion';
  }
}
function my_search_form_submit_function(&$form, &$form_state) {
  $search_str = $form_state['values']['search_block_form'];
  $form_state['rebuild'] = TRUE;
  drupal_goto('search', array('query' => array('search_api_multi_fulltext' => $search_str)));
}

You have a typo error in your code.

Change

$form['#submit'][] = 'my_search_form_submit_funtion';

To

$form['#submit'][] = 'my_search_form_submit_function';


How to get back the text formats like filtered_html, full_html or php_code for wysiwyg I accidentally removed the text formats like:

Full HTML
Filtered HTML
PHP Code

from admin > config > content authoring > text formats.

I want to get them back but couldn't find a way. I re-installed the third party editor (ckeditor) for wysiwyg and also reinstalled the wysiwyg module, but it didn't help.

You soudln't disable text formats on config > content authoring. Now you only can edit your site's database tables. Table "filter_format" has column "status" and rows with text formats names. Change values in "status" column to 1 for each format you want be enabled.


Background image in node content Is it possible to create a image file upload and then have that image appear as a background image within the "content" area of a particular page?  I then want to put content (text) over the image.  It would only be for a particular content type, but there is about 80 pages within this content type and each page/node would have its own background image.

To simplify, I have about 80 recipes.  I have high-res images of each.  I want the image to be the background and I would then have the specifics of the recipe on top of the background image.

Example:

I've used the Dynamic Background module, which has a whole set of advantages for setting up background which vary according to content. At that particular time I used the Context module, which gave me a varied set of options (including content type, path, taxonomy, etc.) and which is very extensible. For your recipes, you could combine with the taxonomy functionality for different types of recipes, or select a particular image for each.

While I don't like using modules for everything, if this is going to be part of your day to day use of the site, I recommend that you choose the simpler solution, so you can try and choose what works better for you.

When you install the Module, you can set up which images you want to use, style the image and the type of behaviour you want for the whole site:

Since you can assign it using CSS, you can set it up for the content area only (#region-content), or whatever indicator you define in Panels. So, you can combine the logic in panels to show a particular background for a content type, or whatever logic you want to assign.


Desaturated images colored on hover? Is there a clean, "hands-free" way to have a ticker full of logotypes desaturated in normal view, but colored on hover? Or should I prepare CSS sprites by myself and go the "dirty" way?

It's an old question but by now this seems to be the module that you needed:
Image desaturate formatter


Multipage form not multistep Can anyone help me to make multipage form not multistep.
Suppose On front page i have two fields select service and select location and a button and after selecting both clicking on button opens a new form on new page.

You can use Webform module and create multiple separate forms.

On submission of first (on front page), you can redirect users to another page (another webform) based on their selection using custom redirect in webform settings and tokens [submission:values:?] that use data from webform that has been submitted. You just have to set "key" on selects in your form properly.


repeated results with Views Slideshow results and commerce products I have a slideshow view where I am showing most recently discounted items.

each product display has 8 different variable combinations therefore, 8 product SKUs connected to the product content.

I have my view filtering by Content:product. However, it is showing all 8 products for each piece content.

First thing to do is to make sure that the relationship is set to be required, if the duplicate results still coming on .. go to views query settings and check both DISTINCT and PURE DISTINCT


Checkbox value always 0 in custom submit handler I have a single checkbox field (not checkboxes) in a custom form, when I try to get the value in a submit handler the value is always 0 whether it's selected or not.
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['item_specifics'] = [
      '#type' => 'checkbox',
      '#title' => t('Sync item specifics'),
      '#attributes' => [
        //define static name and id so we can easier select it
        // 'id' => 'select-colour',
        'name' => 'field_item_specifics',
      ]
    ];

    $form['fieldset_item_specifics'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Item Specifics'),
      '#attributes' => [
        //define static name and id so we can easier select it
        'class' => ['form-wrapper', 'js-form-wrapper'],
      ],
      '#states' => [
        //show this textfield only if the radio 'other' is selected above
        'visible' => [
          //don't mistake :input for the type of field. You'll always use
          //:input here, no matter whether your source is a select, radio or checkbox element.
          ':input[name="field_item_specifics"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Sync'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    dpm($form_state->getValue('item_specifics'));

  }

}

The output of dpm() is always 0, if I dpm() form state then the values array always has the checkbox value as 0.

try this, it is work with me just change name to item_specifics
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['item_specifics'] = [
      '#type' => 'checkbox',
      '#title' => t('Sync item specifics'),
      '#attributes' => [
        //define static name and id so we can easier select it
        // 'id' => 'select-colour',
        'name' => 'item_specifics',
      ]
    ];

    $form['fieldset_item_specifics'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Item Specifics'),
      '#attributes' => [
        //define static name and id so we can easier select it
        'class' => ['form-wrapper', 'js-form-wrapper'],
      ],
      '#states' => [
        //show this textfield only if the radio 'other' is selected above
        'visible' => [
          //don't mistake :input for the type of field. You'll always use
          //:input here, no matter whether your source is a select, radio or checkbox element.
          ':input[name="item_specifics"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Sync'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    dpm($form_state->getValue('item_specifics'));

  }

}


How we can generate Latitude/Longitude at the time of import while using Feed module I am using Feed Module For Importing Nodes Form CSV File. What i want that at the time of import how we can generate lat/long pair for every node imported. I have address in csv file for every node an i want to generate lat/long pairs.

I use the location module in tandem with the location feeds module (http://drupal.org/project/location_feeds).  It can be configured to geocode the the addresses at the time of import.

I had to adjust some timeout settings as its possible to try to geocode addresses faster than the geocoding api allows.


How can I retrieve the profile2 fields selected in a custom module? I am totally new to entities in Drupal.  I have used the Profile2 module to add a few profile types.  This is displayed in the add/user screen as Customer.

After adding the profile type I manage the fields and add a new entry called cust with a field_id of field_cid.  This is setup as a list(text) and checkbox widget.

When I edit a user I have a checkbox list for Customer that can be selected by each user.  I have a custom module that I am trying to read the selected value by $user->uid from the profile2 field.

The idea is to retrieve the selected item in my module and format the return values to the user from a custom DB table.  Here is what I have tried and got results but cannot get all the values.

In my module using:

$profile = profile2_load_by_user($user->uid);$list = field_view_field('profile2', $profile['customer'], 'field_cid');print_r($list)

I get this result:

Array ( [#theme] => field [#weight] => 0 [#title] => cust [#access] => 1 [#label_display] => above [#view_mode] => _custom_display [#language] => und [#field_name] => field_cid [#field_type] => list_text [#field_translatable] => 0 [#entity_type] => profile2 [#bundle] => customer [#object] => Profile Object ( [pid] => 9 [type] => customer [label] => Customer [uid] => 1 [created] => 1409542969 [changed] => 1409545821 [entityType:protected] => profile2 [entityInfo:protected] => Array ( [label] => Profile [plural label] => Profiles [description] => Profile2 user profiles. [entity class] => Profile [controller class] => EntityAPIController [base table] => profile [fieldable] => 1 [view modes] => Array ( [account] => Array ( [label] => User account [custom settings] => ) ) [entity keys] => Array ( [id] => pid [bundle] => type [label] => label [revision] => ) [bundles] => Array ( [customer] => Array ( [label] => Customer [admin] => Array ( [path] => admin/structure/profiles/manage/%profile2_type [real path] => admin/structure/profiles/manage/customer [bundle argument] => 4 [access arguments] => Array ( [0] => administer profiles ) ) [rdf_mapping] => Array ( ) ) ) [bundle keys] => Array ( [bundle] => type ) [label callback] => entity_class_label [uri callback] => entity_class_uri [access callback] => profile2_access [module] => profile2 [metadata controller class] => Profile2MetadataController [static cache] => 1 [field cache] => 1 [load hook] => profile2_load [translation] => Array ( ) [schema_fields_sql] => Array ( [base table] => Array ( [0] => pid [1] => type [2] => uid [3] => label [4] => created [5] => changed ) ) [configuration] => ) [idKey:protected] => pid [nameKey:protected] => pid [statusKey:protected] => status [defaultLabel:protected] => [field_cid] => Array ( [und] => Array ( [0] => Array ( [value] => 1 ) [1] => Array ( [value] => 2 ) ) ) [field_test] => Array ( [und] => Array ( [0] => Array ( [value] => 3 ) ) ) [rdf_mapping] => Array ( ) ) [#items] => Array ( [0] => Array ( [value] => 1 ) [1] => Array ( [value] => 2 ) ) [#formatter] => list_default [0] => Array ( [#markup] => Disney ) [1] => Array ( [#markup] => Burger King ) )

I want the name in the last line [#markup] only returned to my function.  In the above output the returned values should be Disney and Burger King.

How can I retrieve these values only?

Finally this is giving me the results I am after:

$profile = profile2_load_by_user($user->uid);
$customer = field_get_items('profile2', $profile['customer'], 'field_cid');
$key = array();
foreach($customer as $item=>$value){
  $output = field_view_value('profile2', $profile['customer'], 'field_cid', $customer[$item]);
  $key[] = strip_tags(render($output));
}
foreach($key as $word) {
  echo $word . "</br>";
}


Create a real taxonomy with drupal taxonomy and pathauto I'm creating a taxonomy for reptiles in drupal and wish to use pathauto for the term url's. The problem is to find the right tokens (I do have entity token installed). Lets look at an example of the taxonomy-tree for the vocabulary Reptiles:

Lizards
--Family
----Genus
------Species

So far so good:

[term:vocabulary]/[term:parent:parent:parent]/[term:parent:parent]/[term:parent]-[term:name]

result: /reptiles/lizards/family/genus-species

However sometimes there is also a subspecies, thus:

Lizards
--Family
----Genus
------Species
--------Subspecies

then starting at the lowest level and using [term:parent] doesn't work anymore.

Been looking for [term:child] and to generate the path from the opposite direction but I find nothing similar. Another way would be if I could define the term patters with levels in the hierarchy?

something like this:

    [term:vocabulary]/[term:level:1]/[term:level:2]/[term:level:3]-[term:level:4]-[term:level:5]

Maybe someone else knows how to crack this nut?

A better example on the outcome I seek:

/reptiles/lizards/gekkonidae/phelsuma-klemmeri

or as with a subspecies:

/reptiles/lizards/gekkonidae/phelsuma-klemmeri-subsp

You can configure URL pathauto alias for taxonomy terms as :

[term:vocabulary]/[term:parents:join-path]/[term:name]
for creating url aliases for taxonomy taxonomy hierarchy.

Explore more using replacement patterns for specific taxonomy terms.

Please refer this image for url aliases configuration page


Find out which fields to modify on drupal view for a module I would like to implement a hook on a view that grabs the fields that would be displayed and modifies one of the slightly before displaying it.  However, I am stuck at the first part which is just finding out how to view/see the fields that I can manipulated.  Based on a couple of other post I have read it seems like I should use the parseurl_views_pre_render which seems to make sense.  But, I don't even only how to see what the data looks like.

Any pointers or help would be greatly appreciated.

Thanks,
Derek

I think you can do what you need with hook_views_pre_render.

Here is what you can do to find out what the data you need to manipulate looks like:

Install & enable the devel module - https://drupal.org/project/devel
Create a custom module (if you haven't already)
Add a function based on HOOK_views_pre_render(&$view)
In your function, use the dpm function like so: dpm($view);
Reload the page with the view you want to alter
Explore the data rendered through Krumo which is provided by devel

So, ultimately, your function will start something like this:

function your_module_views_pre_render(&$view) {

  if (($view->name == 'viewname') && ($view->current_display == 'displayname')) {

    dpm($view);


Raw Field Value in Views We have a content type that has a Video Embed Field. In this field, we simply enter youtube or Vimeo url.

In a custom view we are trying to display the raw value of the field.
Since this is a Video Embed Field, the only formatter in Views are to display the video or a thumbnail of it.

The problem is that we want to display just the raw value of this field which will be the video url.

Are there any workarounds that will allow us to display the raw value of this field when added in a view?

Different Field information can be displayed in Views by using the Rewrite results and Replacement patterns options in the Field configuration.

Different Field data is usually available as tokens (replacement patterns) that can be used to construct a different output than those available under the Formatter option.

Here's an example for displaying the image Alt text instead of the actual image:

It works similarly for the Video field, and many others too.


Drupal 7 or 8 for bilingual site I am working on a large project for a bilingual site. I would like to move their site from Wordpress to Drupal and see the multilingual capabilities of Drupal 8. However, the site won't be ready to build until late summer of 2015. Would it be a good idea to build on Drupal 8 or because of lag of modules and such, use Drupal 7. As I'm not using Drupal 7 now and don't need to worry about upgrading modules, I think it would be ok to go right into 8. I would like some feedback as to the best route.

Drupal 8 is great, and has a lot of improvements related to multi language sites. But Drupal 8 isn't ready yet, and it "will be ready when it's ready" (that's what some experienced Drupal-ers say, and I do fully understand that).

Also, after Drupal 8 is released (I've heard dates like somewhere in 2016 only, and it wouldn't surprise me), there are still all the contributed modules that will not be upgraded yet to Drupal 8. Today there are still Drupal 6 modules waiting for their Drupal 7 upgrade) ...

For all these reasons, I will continue to go for Drupal 7 for quite a while (probably at least the rest of 2015). Because of its maturity, and because I would not want to depend on a Drupal 8 release of either core, or any of the contributed modules that I "must have".

There is also that great presentation from David Reid about all those amazing contributed modules in Drupal 7, which are like backports of new Drupal 8 features.


Children links disappear when access to parent blocked When blocking access to a page -- its child links get skipped both in code and display.

The block is achieved via an access callback attached to the menu item that checks whether the user is logged in or not.

The desired behavior is to show the links regardless of the login status.

Any hints?

P.S. I'm using drupal6

With the caveat you should be very careful adjusting any core menu item permissions, and I'm presuming you know what you're doing there, it is possible to adjust any menu with

hook_menu_alter

for example:

function mymodule_menu_alter(&$items) {
  // Enable open access for everyone to foo/bar
  $items['foo/bar']['access callback'] = TRUE;
}

You can also specify your own access callback there, e.g

function mymodule_menu_alter(&$items) {
  // Add custom access callback to foo/bar
  $items['foo/bar']['access callback'] = 'mymodule_special_access';
}

function mymodule_special_access(){
  global $user;
  if($some_condition_is_true){
    return TRUE;
  }
  return FALSE; // default deny
}


Communicating with Drupal from Javascript/Jquery (Drupal 7) I am trying to create a dynamically populated select list field widget.  This widget consists of three Jquery multiple selects.  When the user makes a selection from the first select list I need to dynamically populate the contents of the second select list.  My problem is that I need to access data stored in Drupal about what should be put in the second list based on the first selection and the only way I can think to access this data is through an ajax call to a Drupal endpoint.  Waiting for the return from an ajax call is going to be to slow for a useable widget so I need a better way to access this data stored in Drupal.  How should one go about doing this?

You can send variables to your JS with drupal_add_js() in the $settings array.

An other way (the dirty one) to do it would be to print your data in a hidden div and read it with your JS. (don't hesitate to ask if you need code to do it)

Have fun !


Adding CSS classes to wysiwyg I use wysiwyg with ckeditor, and I was wondering how I would add css styles so a user could, for instance, float images to the left or make other similar changes...?

Thanks!

Ckeditor uses the ckeditor.styles.js file to define the available styles in the Styles drop down.  Documentation in that file states:

'Styles' button is not enabled by default in DrupalFull and DrupalFiltered toolbars.

If you look at the file, it should be fairly straight forward to modify it using the given examples.

The ckeditor.styles.js file can be copied to a directory accessible by Drupal and modified to include your styles.  Then you have to configure your CKeditor profile to point to the new file, including any applicable CSS.


Custom field in a view with a link I created a view listing some Articles, but displaying a custom field I added to the Article content type instead of the usually used title.

When I would display a title instead of the custom field, I could check the option to include a link together with the title. How can I do that with the custom field instead? It only offers me the option to display the custom field as a plain text, without the link checkbox.

Here is a configuration that should do what you need:

Hope this helps!


Add upload/processing status bar/throbber I am new to Drupal/web development and I have been trying to create a module to add files upload menu. Once the files are uploaded, they undergo processing and a message is displayed upon completion of the process. Everything works well but I would like to add a processing progress bar/throbber from the tile Submit button is selected to when the final output is displayed. I am clueless on how to implement this. Any help is appreciated
Here's part of the code I used:
//Before this part of the code, there is function to create Menu ($items[])
function g_p_proc_form($form, &$form_state, $values) {
    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['filter'] = array (
        "#type" => "fieldset",
        "#title" => t("File Process <BR> "),
        "#collapsible" => TRUE,
    );
  // without this attribute, upload may fail on submit
    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['filter']['file'] = array(
        // '#title' => t('File processing'),
        '#type'  => 'file',
        '#name' => 'files[]',
        '#description' => t('Select Submit to start processing the file'),
        '#type'  => 'file'),
        '#upload_location' => 'public://',
        '#attributes' => array('multiple' => 'multiple'),
    );

    $form['filter']['submit_upload'] = array(
        '#type'  =>  'submit',
        '#value' =>  t('Submit'),

    );

    // drupal_set_message(t("in fn"));

    return $form;
}

function g_p_proc_form_submit($form, &$form_state) {
    try{
        $number_file = count($_FILES['files']['name']);
        $f_name = array();
        for ($i=0; $i<$number_file;$i++)
        {
            $file = file_save_upload($i, array('file_validate_extensions' => array('pdf PDF')), 'public://', FILE_EXISTS_REPLACE);
            $f_name[] = $_FILES['files']['name'][$i]; //[]
        }
            }catch (Exception $error){
        echo 'Exception: ',  $error->getMessage(), "\n";
    }
    $n_f = count($f_name);
    drupal_set_message(t('Number of files: !n_f', array('!number_f'=>$n_f)));
    $fn_name = 'g_p';
    $fn_call = $fn_name($f_name);
function g_p($f_name=array()){
    $curr_l = getcwd();
    chdir('My file processing PHP script location ');
    $n_f = count($f_name);
    $shell_command = shell_exec("file_processing_php_script_name.php");
    //header("Location: "Current file processing module menu site"); //Commented out
    drupal_set_message($shell_command);
    chdir($curr_l);
}

As it can be seen from the code, I process the files upon upload and display the output message after processing. I would like to add a throbber/processing-progress bar from the time Submit is selected to the time the output is displayed, after the files are processed. How can I achieve this? Again, please understand that I am new to web development/Drupal and am not very proficient in terms/commands used in them.

Change from file to manager_file and use property #progress_indicator (by default is already set so you won't have to add it).
https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#managed_file


Display discount ad when people visit the page A client of mine wants to display a discount advert on top of the site when user visited the page, so I imagine it will be triggered by the onload handler of my front page.  I thought I can display the ad content in a colorbox to raise it even more above the content. How can I trigger a colorbox to show up with the onload handler of the site?

You are looking for Splash Offer module. It will show the popup on page load.

  Allows the management of one or more "splash offers", which are modal
  popups with an accept or reject form. If a user accepts the offer then
  a new page will open with a provided accept url. If they reject the
  offer, the modal will close. (If they select Do not Show Again, then a
  cookie is set so as to avoid further display.) You may define the who,
  when and where of the splash offers with precision controls. Factors
  such as: user role, site url, device, and whether the offer has been
  previously viewed (cookies), cookie duration, etc. are configurable
  for each splash offer created.

also take a look at this modules - Splashify, Splash and TinyBox (Simple Splash).


Migration from source YML: implode all values of each array element nested inside an parent array We are trying to pull in some data from an outside source that serves JSON.

The structure of said json is like this:

[
    {
        "name":"something",
        "desc":"some kind of desc.",
        "tags": [
            {
                "order":"3",
                "displayName":"Tag1"
            },
            {
                "order":"13",
                "displayName":"Tags 101"
            },
            {
                "order":"28",
                "displayName":"Dogs"
            }
        ]
    }, ...

]

We want to implode all tags.displayName values into one string.  I'll use the body field as an example.
In the UI, if you view the content, "body" would be:

Tag1|Tags 101|Dogs

In the "fields" section of my migration source yml file:

name: tagsCollection
label: "tagsCollection"
selector: tags

Then, in the process section of the YML file I've tried this:

body:
    plugin: concat
    delimiter: "|"
    source:
     - stepsCollection

I've also looked into the iterator plugin.  Nothing seems to click.

If I do this in the process section of the yml file:

body: stepsCollection

body will be "Array" in the UX.  So it is aware that there is an array in that var.

What am I missing??  Many thanks

The documentation examples of concat plugin use a flat, non-associative array of strings as source, you are trying to concat a nested array of JSON objects. You could try to subprocess your tags to only fetch/concat the displayName from them


How do I troubleshoot a node not appearing in workbench? I have a bug report where a user is not able to see 'Draft' status nodes that they have just created in their workbench interface (at /admin/workbench). They are able to see other nodes in various approval phases.

I've backported the site to a local development environment and logged in as that user and I'm able to re-create the issue. Also, with my administrator user, I have the same issue -- the new node doesn't show up in my workbench queue either. However, it does show up in the content overview. The problem is that for most users, we only give them workbench queues to access content, and not the content overview.

I've looked at the various configurations for workbench, and at the fields on the new nodes, and I don't even have a starting point as to what to look at to troubleshoot this issue. My users are able create and publish content on a daily basis, so there's not a major misconfiguration in the site.

What makes a node appear in a workbench queue in Drupal 8? We have both the workbench and workbench_access modules enabled. I'm not sure how these interact with the core workbench features.

Edit I noticed in the module page that "Workbench core is a series of Views", so I looked in the views on our site. We seem to be using the built-in-views, so I edited the "Workbench: Recent content (Content)" view, and removed the Filter Criteria "Content: Published status or admin user". I thought this would prevent my user from seeing the new node. However, after I removed that filter criteria, the draft node still did not appear in the preview of that view. So that doesn't seem to be causing the problem.

Absent the "right way to do it", what I've done is go ahead and given "Bypass Access Restriction" permissions to certain roles. That allows them to get their work done, but I would like to know what the correct thing here is.


Moving site to new domain on the same server We're having a problem (well, a series of problems actually, but this one appears more difficult to solve) moving a clients site to a new domain on the same server / hosting account.

The site is moving to another folder hosted on the same server, so should be no need to change database settings or move the database.

We've moved all the files to the new sub directory and the problem is that whilst the home page displays fine, none of the other pages appear to exist and none of the menu links work. Base URL isn't specified in the settings file (although we've tried specifying one which didn't help).

Any ideas?

EDIT: Changing .htaccess file isn't helping

Check your .htaccess

Open your htaccess and modify line 94 to match your needs.

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /YOUR-FOLDER-NAME
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

If this not work the problem is with your cache tables or custom code in template.php or in .module files

To clear cache tables you can try

drush cc all

OR Try this in phpMyAdmin or mysql console.

TRUNCATE `cache`;
TRUNCATE `cache_block`;
TRUNCATE `cache_bootstrap`;
TRUNCATE `cache_field`;
TRUNCATE `cache_filter`;
TRUNCATE `cache_form`;
TRUNCATE `cache_image`;
TRUNCATE `cache_libraries`;
TRUNCATE `cache_menu`;
TRUNCATE `cache_page`;
TRUNCATE `cache_path`;
TRUNCATE `cache_rules`;
TRUNCATE `cache_token`;
TRUNCATE `cache_views`;
TRUNCATE `cache_views_data`;

Make sure you include all tables starting with CACHE_

More info here Can any of the cache_* be emptied safely?


Form element #default_value and AJAX I can't get a form to display a (default?) value after an AJAX call. I am using the following code:

function foo_form ($form, &$form_state, $foo) {

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  $form['copy'] = array(
    '#type' => 'submit',
    '#value' => t('Copy foo'),
    '#limit_validation_errors' => array(),
    // #submit is required to use #limit_validation_errors
    '#submit' => array('foo_form_submit'),
    '#ajax' => array(
      'wrapper' => 'foo-form-wrapper',
      'callback' => 'foo_form_callback',
    ),
  );

  $form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Short description'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => $foo->description,
  );

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

  return $form;
}

function foo_form_callback($form, $form_state) {
  return $form;
}

function foo_form_submit ($form, &$form_state) {
  if (!isset($form_state['triggering_element']['#ajax'])) {
    $foo = (object)$form_state['values'];

    entity_get_controller('foo')->save($foo);

    $form_state['redirect'] = 'admin/foo';
    return;
  } else {
    form_set_value($form['description'], 'description text', $form_state);
    $form_state['rebuild'] = true;
  }
}

As I understand it, the form should automatically try to display the value if it is set in $form_state. When the callback is executed and the form is built, $form_state['values']['description'] is the value set in foo_form_submit. However, nothing is being displayed.

I know this is late, but for people like me who are still experiencing similar problems with ajax and forms in Drupal, here's how I fixed this.
In your ajax callback function, instead of returning just the render array, you need to call the form_builder() function and return its result.
Eg., my code goes like this:

function inventory_purchase_item_add_ajax(&$form, &$form_state) {
    //...

    unset($form_state['input']['line']);
    unset($form_state['values']['line']);

    //Update the form's lines array
    $lines = update_inventory_purchase_form_lines($form_state['node']->line, $purchase_item_count);
    $form['vtab1']['purchase']['items_wrapper']['line'] = $lines;
    return form_builder($form['#id'], $lines, $form_state);
}


Show related entites on entity view I have two entities, article and author which are related to each other.

When I display an author I want to display also all articles of him.

I was thinking about a block which is displayed on some url patterns, but I didn't find a way to pass the current entity as filter for the block.
Nevertheless I am not sure if it is a good practice to define blocks and place them in the layout when they are only get rendered on some pages.

How can I display content related to other content?

EDIT:

Trying to use contextual filter:

Add a relationship to the other entity, but which one should I use?

Content referenced from
Content using

Add contextual filter using default value, content ID from URL

You can use Contextual filters on Drupal 8 to pass the current entity as the filter. Have a look at:
https://valuebound.com/resources/blog/how-to-use-contextual-filter-in-drupal-8

and https://www.youtube.com/watch?v=FUlj6-Rb7Ds for more details.


Check a truth value in Rules Module For a "Page" node, I want to add an event that only acts on node edited by users who are not administrator user.

I use the following code, it doesn't work:

<?php [node:user-id] != 1 ? TRUE : FALSE; ?>

No matter what I change; for Admin the event is getting called. I've checked all permutations  and combinations of syntax (including return) but it seems that "Check a truth values" is getting ignored.

The code you are using is not outputting any value; the PHP code you are writing is supposed to output 1 if the actions associated to the condition need to be executed, and 0 when they don't need to be executed.

The correct condition is the following one:

<?php echo ([node:author-uid] != 1); ?>

Alternatively, you can use the following one:

<?php echo ($author->uid != 1); ?>

Verify the token you are using is the correct one; the one I see with Drupal 6 is [node:author-uid].
The operator != already returns a boolean value; there is no need to convert it to a boolean, as you do with the code you have written. The "Truth value" field accepts also 1 and 0 as values; there is no need to convert a value to a boolean.

The description reported for "PHP Evaluation" is the following one:

  PHP code inside of <?php ?> delimiters will be evaluated and replaced by its output. E.g. <? echo 1+1; ?> will be replaced by 2.

To notice that the user with ID equal to 1 is a particular user to whom Drupal always give any permission defined from any module; this is the only user account that is treaded in this particular way. Administrator users don't have their user ID always equal to 1; if you are checking the user ID to verify if the user is an administration user, then you are doing it wrong. In Drupal, you usually check the permissions the user has with user_access().


Hook into Web-Form POST to send another POST request to 3rd Party Server? The site I am working on has multiple Contact us type forms that are using a web-form plugin. They have a contact form that is on every page, 1 to 2 times per page. This contact form saves to the back-end and database when submitted.

Below is the basic form without the form elements.

<form action="/" accept-charset="UTF-8" method="post" id="webform-client-form-9" class="webform-client-form" enctype="multipart/form-data" _lpchecked="1">
  <input type="hidden" name="Provider" value="YourLeadSource">
  <input type="hidden" name="Client" value="L360">
  Fname: <input type="text"  name="fname" value="John"><br />
</form>

Now I have been tasked with keeping the current functionality, posting and saving to the database, but also adding new functionality to make it also POST or GET the same form submission to a third party site called leads360.

I need to have it also send a POST or GET request with the form data to https://secure.leads360.com/Import.aspx?Provider=TeledirectBusinessName&Client=CompanyName&CampaignId=12345.

In theory this should be really easy, if I can hook into the system and send a POST or even a GET request to that URL which will then post data into the third-party system.

The problem is my limited knowledge of Drupal. I know its plugin/hook system is nothing like WordPress or Magento.

Would you use some sort of hook in the backend, or intercept the post with JavaScript the way the Stripe API does for payments?

There's the Webform Remote Post module that does exactly this.


How to get specific fields in the login form I'm trying to customize the login form. I added this to my template.php

function neptune_theme() {
  $items = array();
  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'neptune') ,
    'template' => 'user-login',
    'preprocess functions' => array(
       'neptune_preprocess_user_login'
    ),
  );
  return $items;
}

and this is my user-login.tpl.php

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

  <?php print drupal_render_children($form) ?>

    Create an Account | Forgot Password

I wanna know how to show the username, password and submit fields separately in the user-login.tpl.php file. I want to put the links for "Create an account" and "Forgot your password" before the Submit button.

I want to show something like

|Username                 |

|Password                 |

Create an Account | Forgot your password

|Submit|

Thank You. I hope it makes sense. :)

You can create a user login template. In your theme file, put this function in and replace your_themename with the machine name of your theme.

function your_themename_theme() {
  $items = array();
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'your_themename') . '/templates',
  'template' => 'user-login',
  'preprocess functions' => array(
  'your_themename_preprocess_user_login'
  ),
 );
return $items;
}

Then, you can split the individual fields of the form up in a template file called user-login.tpl.php and rearrange them however you want.

<?php
    print drupal_render($form['name']);
    print drupal_render($form['pass']);
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['actions']);
?>

Source: High Rock Media


Use ajax not working in views block displayed programmatically I have a view with a block display. In the "OTHER" area of the view settings, I checked "Use Ajax".

I display this block programmatically inside a node in this way

print $view->render('block_1');

The block is displayed, but when I use the pager to go to the next page of the results, ajax is not used and the page is reloaded with "page=1" added to the url.

any idea?
thank you

I found the solution

To have the "use ajax" working, you have to render the view using:

$view->set_display('block_1');
print $view->preview('block_1');


Custom module implementation for menu items as JSON Through the use of a Drupal 8 custom module for the purpose of providing the menu items/menu structure as a JSON resource, I have encountered a problem which I'm hoping someone will have an answer or lead for.

The output to the extent that it's currently functioning appears in JSON format, the structure following the same as the defacto menu system outputting title, weight, and whether the item is active.

    [
  {
    "title": "Vehicles",
    "url": {},
    "weight": "1",
    "active": true
  },
  {
    "title": "Automotive Parts",
    "url": {},
    "weight": "2",
    "active": true
  },

The URL is not displayed, even though in Drupal there are paths entered for the items. I have made several attempts at browsing the Drupal 8 documentation to search for answers about URL and menu classes. Currently, the relevant code responsible for the output is this one.

public function get($entity) {
$menu_name = $entity;
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$result = array();

foreach ($tree as $element) {
  $link = $element->link;

  // if ($link->getUrlObject()->isExternal() == true) {
  //   $route = $link->getUrlObject();
  // }
  // else {
  //   // $route = $link->getUrlObject()->getInternalPath(); //this is breaking the module because apparently there are no "internal routes".
  // }
  dpm($link->getUrlObject());
  if ($link->isEnabled() == true) {
     array_push($result, array(
      'title' => $link->getTitle(),
      'url' => Url::fromUri($link->getUrlObject()->toUriString()),
      'weight' => $link->getWeight(),
      'active' => $link->isEnabled()
    )
  );
 }
}
return new JsonResponse($result);

}

How can I make the 'url' => part of the code output the path entered in Drupal for that menu item?

You'll want to use this kind of implementation based on the Alias Manager service.

<?php
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($system_path, $langcode);
?>

Details and a further explanation can be found on D.O https://www.drupal.org/node/1853148

If you'd be willing, I'd also like to see the full code for that resource.


Building a simple webservice I need to build a simple JSON webservice for an iPhone application and i would like to give drupal a go :)

Here is the content structure i need, admins should be able to create a Newsletter a news letter should contain (title, description, categories) and then it should be possible to create "news sections" each section should contain (title, text, image) so a section is a group of content and it should be possible to create multiple sections in a newsletter.

First question: how would you structure the above content ? i tried two ways of doing it

created two content types "Newsletter" and "News section" and inside the News section i created a entity_reference to the parent newsletter. works fine, but its not so nice for the admins as they cant really get a overview of what their newsletter is when editing because the content is separated into multiple nodes. also the admins cant sort them.
created a single Newsletter and added the module "field_collection_item" where i setup the "section" fields. This works quite well since it gives the admin a nice way of getting an overview of all the content of the newsletter. But to be honest it looks very messy the admin interface. And i feel like this is a "wrong way of doing it"

When structure is sorted i would like to expose the data as JSON, i found the Services module which seemed perfect. But i have alot of problems exposing the related data, for example if i like to expose a newsletter i would like that all the related news sections is included in the export, but only the id's are exported, i tried alot with Views etc. but cant get it to work properly so i ended up writting a custom hook which looks up the related content. Again i feel like im missing a better way of doing things.

Im very new to drupal so im hoping to get a bit of feedback on how i could build this very simple service in a nice and clean way that makes in intuitive for the admins to administrate the newsletters.

I made a content type Newsletters, You could remove the Body field if you want form the Node. I then used Panelizer with nodes to make newsletter like layouts. The content for the node is actually ctools based custom data.

I also made use of a custom html--newsletters.tpl.php file to remove site themeing from the newsletter and apply generic newsletter themeing for the site.

If you got this much working:

custom content type (title, optional body)
Panelizer enabled, pick a layout (or layouts)

enable node_panelizer.

un-embed newsletter from site with custom html.tpl.php for the content type (optional)

Then I would make a hook_menu entry for your json service. Just do a node_load on the newsletter node and inspect $page['content'] for your nodes layout and "sections". Just build a json array out of how your page is setup in the page render arrays.


How to allow authenticated user to view others data? My sales staff fills in a webform with uploaded pics
The Service department needs to view the submitted pics for the installations.
Wondering if a module is needed to allow an authenticated user to view the submitted data entered by someone else.  Currently my view only shows up when the user is an administrator. Webform Views Integration works Great... if only my Service Dept users could see the data.

Found it in people/permissions
Checked the authenticated user columns for webform submissions and pages.
Now it works as it needs to.


Is PathAuto module a memory hog? I'm probably going to need to use the PathAuto module for a current project. While using it in development, as admin, the site slowdown during changes is insane.

Is PathAuto a big memory sink, and are there ways to mitigate this?

It depends greatly on which version of Core you are using. The main memory issue is with Token module for Drupal 6, when given a node will generate all possible tokens for that node, regardless of the tokens that will actually be replaced. This means that expensive tokens that need to load or render other objects, etc, in addition with the sheer amount of tokens generated causes the issues.

With Drupal 7, the improved token API only generates tokens that you actually use and greatly improves performance and memory usage. In normal use, Pathauto really only matters when an item is being saved but does not affect "normal" page views.


Profile2: How to understand if user has not an associated profile? I'm not able to understand what is the code I should use to verify if user has (or not) a profile (made by profile2 module) associated.

I use profile2_load_by_user($uid, "my-profile-name") and it always returns me a "Profile" object... also for users that has not that profile (for example users listed in /admin/people/noprofile).

I know I can test if some mandatory field is currently filled, but do you know what is the "formally correct" way to proceed?

Thanks

If you are doing profile2_load_by_user and profile object is showing, then its profile object has been created. If Profile object has not been created for a user, then its profile object will be empty, means its pid has still not been created.

You can check for the same, in your database, inside profile table.


How do I integrate a custom filter inside a view I am using entity browser to view my uploaded images. And now I want to integrate a new filter to the view. My objective is to filter the images from the URI path. Currently view has a field in Filter Criteria section in the view with a textfield to enter a part of a URI and filter. But I need to  filter the images with a custom dropdown which has only specific values in the URI.

Lets say my URIs looks as below.

s3://2019-01/image-set-one/image.jpg
s3://2019-01/image-set-two/image.jpg

I need to integrate a dropdown to the filter criteria of the view with elements image-set-one and image-set-two which will filter the images accordingly. I am using entity browser, so I need to add that field inside the view instead of getting the results and filter after.

This is a screen shot of the view that I am using.

Below is a preview of my entity browser that I am using with the above view.

I found a solution for above. I can add a field in the filter criteria selecting the URI. And expose that filter to the user with a grouped filter. In the grouped filter I can define my own keys and parameters with an operator. That worked pretty well.


How to create Drupal Articles Thumbnails and display it on homepage I would like to know what is the BEST WAY to generate thumbnails in drupal?
I need to create a semi news style website in Drupal that requires me to GENERATE THUMBNAILS AUTOMATICALLY from Articles I created. I attached a sample website screenshot from a similar website I am trying to imitate.

Is there a Good Drupal module can you recommend? or much better a Drupal function I can insert in PAGE.TPL.PHP to generate thumbnails from my articles or posts and display it in the front page?

Thank you in advance sirs.

You can use Views module to achieve above...

For more details visit documentation page of views module.


Why doesn't my new tab show? I just made a new tab (quicktabs) with the drupal interface, but it is not displayed like the other tabs. In fact, it doesn't show at all. How can I debug such a problem?

You have to assign the quicktab block to a particular region. Then you might be able to see the tabs


How to use Image EXIF Autorotate? I have been trying to use the Image EXIF Autorotate Module. I have installed all the required modules like

Imagecache Autorotate
Original image with style

Also changed the image field property

Apply style to image after upload = Image EXIF Autorotate

Nothing is happening I upload the image and no changes and it just upload the image as it is and if I try to rotate it manually nothing happens.

My requirements are as the image is uploaded the user sees the image and if wants to rotate it by clicking on it to do so.

The Exif Autorotate module

  Automatically rotates any uploaded image file according to the EXIF
  orientation information.

This EXIF data is embedded into the photo by the camera (and is often lost in compression). It contains the author, aperture settings, shutter speed, camera position and much more.

So if your photo is not created by a camera, or is already in the upright position, or has been compressed or downloaded, nothing will happen.

  My requirements are as the image is uploaded the user sees the image
  and if wants to rotate it by clicking on it to do so.

EXIF Autorotate does not rotate the photo by clicking on it, it rotates the photo to the position the camera shot it in (landscape or portrait).


How to add a dynamic cart link to the user menu? Commerce already defines two menu items in the Navigation menu:

Shopping cart - 'cart' - enabled by default, static
Shopping cart - 'cart/my' - disabled by default, dynamic

'cart/my' uses a custom title callback, 'commerce_cart_menu_item_title' that builds a dynamic menu link in the form: Shopping cart (2 items)

If I want to add a new menu item for the shopping cart to the User Menu, what's the proper way to do this? Do I first need to duplicate a menu item, then override the duplicate?

Ideally, I would be able to set my own title callback so that I can optionally build a dynamic menu in any format I choose.

You can create a new menu programatically through menu hooks, and a great source for sample code and explanation is the menu_example portion of the Examples Module.

For example

function mymodule_menu() {
     $items['cart/new_menu_item'] = array(
    'title' => 'Shopping cart (# items)',
    'title callback' => 'mymodule_new_menu_item_title',
    'title arguments' => array(TRUE),
    'page callback' => 'mymodule_new_menu_item_redirect',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}


Has the Block Cache Settings from Drupal 8 been back-ported to Drupal 7? I noticed in Drupal 8 there are options to cache a block:

I was wondering if these options exist in Drupal 7 with a module? Has the feature been back ported? or was it a contrib module to begin with?

No, it's impossible to backport. See https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_info/7's DRUPAL_CACHE_CUSTOM and https://www.drupal.org/developing/api/8/cache/contexts.


How to truncating url at the word instead of limit Background info:
By default, Pathauto has a maximum alias length is 100.

Request: It would be nice if this could truncate at the last space before the limit, instead of truncating directly at the limit, so that there are no partial words in the URL.

What is the easiest way to do this Drupal?

The pathauto module uses the core function truncate_utf8() to truncate the alias. This call by pathauto uses $wordsafe=TRUE in the call to preserve word boundaries.

If you are seeing partial words in the path, this is a core issue for truncate_utf8, not a pathauto issue.


How to implement stateless authentication I'm having a big problem with Drupal 8, I want Drupal to trust a downstream reverse proxy that performs authentication against a third party provider, then passes a JWT in a X_ID_TOKEN header.
As I didn't find any module that behaves as an authentication provider that trusts HTTP headers to authenticate the user, I developed a provider myself which is implemented as follows:
public function applies(Request $request) {
  // If you return TRUE and the method Authentication logic fails,
  // you will get out from Drupal navigation if you are logged in.
  $trusted_host = "127.0.0.1";
  $headers = $request->server->getHeaders();
  $server_addr = $request->server->get('SERVER_ADDR');
  return ($server_addr == $trusted_host) && $headers && $headers['X_ID_TOKEN'];
}

public function authenticate(Request $request) {
  $headers = $request->server->getHeaders();
  $jwt_token = explode('.', $headers['X_ID_TOKEN']);
  $user_data = json_decode(base64_decode($jwt_token[1]), true);
  if(!$user_data && !$user_data['email']){
    return NULL;
  }
  $users = \Drupal::entityTypeManager()->getStorage('user')
    ->loadByProperties(['mail' => $user_data['email']]);
  $user = reset($users);
  if ($user) {
    $uid = $user->id();
    $rids = $user->getRoles();
    $account = User::load($uid);
    return $account;
  }else{
    /** @var \Drupal\user\Entity\User $account */
    $account = User::create([
      'name' => $this->generate_username($user_data),
      'pass' => user_password(),
      'mail' => $user_data['email'],
      'init' => $user_data['email'],
      'status' => 1,
    ]);
    $account->save();
    // Store the newly created account.
    $this->save_user_info($account, $user_data);
    return $account;
  }
  return NULL;
}

Then the service is registered like this:
services:
  authentication.trust_openid_auth:
    class: Drupal\trust_openid_auth\Authentication\Provider\OpenIDAuth
    tags:
      - { name: authentication_provider, provider_id: open_idauth, priority: 0, global: TRUE }

This sort of works, but the pages we are rendering contain user personal data, and they are being cached by some Drupal internal cache. This cache is "per user" thanks to the native Drupal session cookie.
Problem: this cookie seems to be randomly set (when it's not there it randomly appears when navigating). When the session cookie is not set, the cache is global and results in rendering a page that contains the personal information of the last user that successfully rendered the page (not necessarily the current user!)
I have read that the session cookie starts existing when data is attached to the PHP session, which I'm not in control of.
I'm pretty lost at this point, the two solution I thought of are:

Tell Drupal to trust a remote Cookie (set by the downstream reverse proxy) as the session Cookie, this cookie would contain the user's JWT
Force the Drupal session Cookie even if there is no data attached to the session, just to contextualize the cache

The first solution would be ideal but I'm not sure how to achieve it. Any help on this would be welcome!

If you tag this as middleware and weight it in your service definition, you can control when this runs. If you search through core you will find the Session and Page Cache also run as middleware. The Ban module in core is also tagged as middleware.
Hopefully this will help point you in the right direction.


Image Styles Generate I am running a Drupal 7 site that does a call to an external service using Feeds Module, creates nodes from that coming JSON.

The Feeds Module grabs an image, download it, and generate 4 different image styles. Usually in Drupal, you upload the image that goes through Imagecache, and boom the image is re-sized, why because after node_save you go to node_view that grabs a function which does the real resizing.

In my case, i do not view the nodes, so the images does not get generated unless i run a whole view/page i created with all images so they get generated.

I tried to curl and request the page on a time interval for the page to get generated but it seems you have to really view the page.  What would a solution for this problem be ?

Would doing a batch operation to just view the nodes using node_view help ? What else ?

Note that on each Feeds request the site creates around 50 nodes X 4 images = 200 image.

Help is much appreciated.

A derivative image is generated on the fly when served over HTTP. When the derivative image is requested in HTTP, if the file doesn't exists, the HTTP request is handled by Drupal. Drupal will use the image_style_deliver() page callback to generate the derivative image and deliver it. Once the image exists, Drupal will not handle the request and the file is directly delivered.

If you need to access to files externally without using HTTP to access them, you can use image_style_create_derivative($style, $source, $destination) to create the derivatives images. You will need to provide the destination path for the derivative image, which you can get with the image_style_path($style_name, $uri) function.

The following (untested) code should ensure that the derivatives for the image file identified by $fid are generated for the styles whose names are in the $styles array.

$original = file_load($fid);
foreach ($styles as $style_name) {
  $derivative_uri = image_style_path($style_name, $original->uri);
  image_style_create_derivative($style_name, $original->uri, $derivative_uri);
}


Webform File Upload field I'm using Drupal 8 with Webform module.

I want to allow users to upload one or several files when filling the form. Is it possible with Drupal 8? May be some additional module required for this?

You need to enable webform UI, then set in your sites/default/settings.php file the privates files directory path:
$settings['file_private_path'] = 'sites/default/files/private'; where 'sites/default/files/private' is your privates files directory path. You can choose another directory. And give to this directory the write permission. Then clear all caches. Now you can add files fied in your webform while adding new element. In the popup that appears, typing file, you will see all files type like image, audio, etc.


How can I display nodes in a view both by title and by a short title I am building a site where I need to display a list of diseases in a view, and I need to be able to display them both by their titles and by another field (an abbreviated title). The two fields need to display as if they were two separate nodes both linking back to the same node though.

For example: My users need to be able to find the "Immunosuppressive Drugs - Organ Transplantation" disease in my view under "Immunosuppressive Drugs - Organ Transplantation" and under "Organ Transplantation - Immunosuppressive Drugs".

When I have tried to just show the abbreviated_title field as well, I get the title and the abbreviated_title showing together when I need them to display as two separate nodes.
Does anyone know how I could do that?

Here are pics:
I need this node

To show up here
and here
when I click on the appropriate letters in this search box.
So it is the same node, but needs to show up two separate times in the view

The only way to do this is going to be to create either a custom entity or at least a custom table with Views integration.  Views is designed to list one record per entity (or "row" of data).

Custom code solution:

Create a table that actually has multiple rows per node.  It would need at least 2 fields: nid and title, and you'd have to maintain the data in that table by implementing hook_node_update, hook_node_insert, and hook_node_delete.  Then you'd need to expose that data to views either by defining a custom entity type based on that table, or by writing the Views integration directly.

Field Collection Approach:

You could store your titles on another entity in the system.  A Field Collection is probably the best due to the fact that it won't clutter up any other parts of the interface.

The general idea would be to add a Field Collection field (field_alternate_titles?) to your disease entity.  The Field Collection itself really only needs a single field (field_alternate_titles_title?) with cardinality equal to 1.  You're not using Field Collection because of its ability to let you group fields together, but rather because it creates separate entities for each of your values that you can use Views to query against.  You can set the cardinality for the Field Collection field (field_alternate_titles) to 2 or, if you want to allow an arbitrary number of alternate titles, unlimited.

You could stop now and keep things really simple.  Your users would have to enter all of the titles that they'd possibly want for the disease in this field.  This would require them to re-enter the node title as an additional entry in the Field Collection field, but it would save you from writing any code.

If you want a slicker user experience then you would probably want to do the following:

Hide the Field Collection field on the disease node edit form by
using the available widget type of "hidden" (rather than
"embedded").  You don't want your users seeing or touching the field
in the edit form as you'll be maintaining the values for them.
Maintain the values in that field by implementing hook_node_presave
and creating and relating your node to Field Collection entities
according to the values entered for the node title and short title.

Whether you write the code to auto-populate the Field Collection values or not, you'll now need to build your view based on Field Collection as the base table rather than the Content (node) table.  You can add a relationship to the host node entity so that you can grab whatever info you need from the node.

Search Index Approach:

Another possible approach would be to use something like Search API which maintains a separate index of your content which you can muck about with when content is sent to the index.  So you could create separate index entries for every title you want to be able to search/list by.  You may find it helpful to use this module as a starting point as it does denormalization, which is what you're after: https://www.drupal.org/project/search_api_grouping


Javascript code appears in search results I use JavaScript in the body of a node with some PHP code. After I run cron.php and search on the site, I can see Drupal indexes the JavaScript code contained in a node.

How do I avoid Drupal indexes the JavaScript code?
Alternatively, how do I avoid Drupal indexes those nodes?

Since the javascript code is actually part of the node content it would take a bit of work to get it to be ignored.

An easier solution would be to use implement hook_db_rewrite_sql() and excludes from appearing in search results. Here is a great tutorial: Hiding content from Drupal's search system.

That said, there is a module out there that does this, Search Config. However it is marked as obsolete and not being maintained anymore, therefore you might want to think twice before using it.

For the record it does indeed work as designed, and works well! (I use it on my website with no problems).


Alter menu link path based on content type I'm stumped on how to achieve this in Drupal 8 due to the removal of menu related functions. What I would like to do is check whether a menu link points to a node of content type File, and then alter the link path to point to a File field value on node (so that the menu link points to the file itself). I just need help getting to the point where I have both the path/route and the node object. I have tried to do this in menu--main.html.twig, where I can get the node id for each menu item. However there does not seem to be a way to load a node object through Twig and even if there were, I doubt this is the correct way to go about this.

I have found tutorials pointing me to implement alterRoutes(), for example:

public function alterRoutes(RouteCollection $collection, $provider) {
  // Find the route we want to alter
  $route = $collection->get('example.route.name');
  // Make a change to the path.
  $route->setPath('/my/new/path');
  // Re-add the collection to override the existing route.
  $collection->add('example.route.name', $route);
}

This doesn't seem helpful because I do not want to alter the route to the node whenever it is visited. I only want to alter the route when it is visited from the menu.

wow I feel silly. You can still preprocess the menu template in Drupal 8. So by using hook_preprocess_menu__main() it looks like I will have access to everything I need and not have to do everything in the Twig template.


How do I call a theme function? Can someone tell me that how can I call theme function, in Drupal 8, within other hook function?

Of course, we should write hook_theme function.

For example (in Drupal 7): theme('THEME_NAME');

What is wrong in below snippet:

function theme_sometheme($variables) {
   $another_theme = array('theme' => 'another_theme_for_test', 'arg1'  => 'value');
   return '<div>'. drupal_render($another_theme) . '</div>';
}

Note: Above code is not rendering anything.

The correct code is using the following line.

$another_theme = array(
  '#theme' => 'another_theme_for_test',
  '#arg1'  => 'value'
);

That is similar to the following code you find in rdf_preprocess_comment(). The only difference are the theme applied, and the arguments that theme requires; the way you pass the theme name or its arguments is the same.

$variables['author'] = [
  '#theme' => 'rdf_wrapper',
  '#content' => $variables['author'],
  '#attributes' => $author_attributes,
];
$variables['submitted'] = [
  '#theme' => 'rdf_wrapper',
  '#content' => $variables['submitted'],
  '#attributes' => $author_attributes,
];

Keep in mind that in most contexts you can just return a render array, which in your case is the following one.

[
  '#theme' => 'another_theme_for_test',
  '#arg1' => 'value',
];

The necessity to call drupal_render() is limited to very specific cases, so most likely you don't need it. If you do, you should use \Drupal::service('renderer')->render() instead.


ajax call back function i am using drupal 7

i am trying to add a button within form and successful.  now i want to call a function when someone click on that button

here is my code.

function clicktell_form_alter(&$form, &$form_state, $form_id) {
    //print_r($form);

    if($form_id=='user_register_form') {
        $form['add_button'] = array(
            '#type' => 'button',
            '#value' => 'Verifynow',
            '#ajax'> array (
                'callback' => '_udr_ajax_handler',
                'progress' => FALSE,
            ),
        );

    }
}

function _udr_ajax_handler($form, &$form_state) {
    echo "hello "; exit;
}

But this is not working fine.
Does anybody tell me how to solve this
Thanks


Automatically filling field in related content type I have two similar content types on a Drupal 8 site: groups and projects. Groups can have child projects, but a project does not necessarily have a parent group. I have an entity-reference field on the Project content type, where a parent group can be added.

However, as I am setting up many different views, I would like these child projects to be added to the Groups nodes when users add parents to the Project nodes. In other words, I want to automatically update the field "Projects" on the related node of the "group" type.

How would I go about doing this? I see most people recommend showing a block on the node, but I would like to use this field in various views, so that won't work.

So if I undersand you don't have any relation Groups -> Projects? You just have a relation Projects -> Groups (that you also call parents)? .
And you want to show by views, Groups and their children (projects)?

If this is what you want you have several choices.

Add many relationships in the view advanced filters in order to reach groups projects, (could be tricky).
Add a field entity relationship Groups -> project that you programmatically set on every projects insert/update/delete. Thanks to this it would be much more easier to build a view.
create your own custom block, with your dedicated SQL query. listing all children of a group and attaching this block to all "groups" content type pages.


Can you add methods to node-entities? What is the preferred way to add functionality to nodes?
More explicitly stated: What is the node-entity equivalent of the Entity-class from the entity-API-module?

Sometimes you want to add methods to a entity. That is possible when using the entity-module, where each entity has a "entity class" property. You can take this entity class and extend it to your heart's content.

However, this is not possible with node-entities, since these don't use the "entity class" attribute.

So, the following code would work if drupal-core worked like the entity-module, but throws an error as is:

function myNode_entity_info_alter(&$info){
    $info['node']['entity class'] = 'MyNode';
}

class MyNode extends Entity{
    public function sayHi(){
        drupal_set_message("Hi!");
    }
}

function myNode_entity_load($entities, $type){
    if($type == 'node'){
        foreach ($entities as $entity) {
            $entity->sayHi(); # Error: Call to undefined method stdClass::sayHi()
        }
    }
}

How can I make this work with node-entities?

PS: as a follow-up question: is this any easier using drupal8?

I believe I have found something that does what I want: https://www.deeson.co.uk/labs/extending-entitydrupalwrapper

The basic idea is that, since drupal-core doesn't facilitate the extension of entity-classes, we use the entity-metadata-wrapper instead.

The above example would then be reformulated as such:

class MyNodeWrapper extends EntityDrupalWrapper{
    public function __construct($data) {
        parent::__construct('node', $data);
    }

    public function sayHi(){
        drupal_set_message("Hi!");
    }
}

function myNode_entity_load($entities, $type){
    if($type == 'node'){
        foreach ($entities as $entity) {
            $emw = new MyNodeWrapper($entity);
            $emw ->sayHi();
        }
    }
}

This appears to be a very reasonable approach. Only thing I dislike about it is that you can't use entity_metadata_wrapper to get the MyNodeWrapper-wrapper.


Boost module, drupal-server encoding issue Background

I use Drupal 7.38 and Boost 7.x-1.0. According to Cron everything is up2date. I store my site at a (CentOS) NGINX-based shared hosting plan that seemingly does include UTF-8 encoding (my site is in Hebrew and the problem is language related). I have no idea if the following problem is a Boost bug or a fail, from my side, providing one of Drupal's encoding-related system requirements.

The problem

The Boost module is installed and working (verified it's work when visited root/sitename/cache...) but now, in the bottom of each non-English webpage, I get the following 2 errors:

  Warning: Cannot modify header information - headers already sent by (output started at
  /home/user/public_html/sitename/includes/common.inc:2748) in
  drupal_send_headers() (line 1232 of
  /home/user/public_html/sitename/includes/bootstrap.inc).
  PDOException: in dblog_watchdog() (line 160 of /ho/home/user/public_html/modules/dblog/dblog.module).

The exact whereabouts

These errors appear ONLY in non-English webpages... In English ones, they just don't appear... moreover, The cached webpage files that BOOST creates are named in Hebrew - i.e their file names are in Hebrew and actually resemble their H1. If I change the file name to an English one, and visit it from the site --- these errors no longer appear in it's bottom.

Maybe the server\Drupal\Boost fails to access the files correctly and and therefore prints these errors in their bottom. Note: It doesn't happen on a local Windows WAMP server, so it's likely the problem is in my online server and not in Drupal.

boost_deliver_html_page() sounds like the issue. In your settings set $conf['boost_message_debug'] = FALSE; FALSE is the default value for that variable, this being TRUE seems to be causing the issue for you.


How to change drupal commerce status message? I have created a custom cart and checkout. When product is added to cart, drupal displays a message "The product XYZ has been added to your cart" through rules which links to default cart. How can I change the message to link to my custom cart?
Note: I checked the other questions but none is related to changing links to carts or DC etc.

Thanks in advance.

You need to find the rule called 'Display an Add to Cart message' and edit it.

You'll see there is a related action in there called 'Display a translatable Add to Cart message'.  In mine, I've even added a second action that takes folks to my cart immediately after adding an item:

In any case, what I would do is delete that specific action and then Add a new action instead.  From the 'System' section, choose 'Show a message on the site'.

Then, in the 'Value' field of that action, you can add whatever message you want and you can add html in it as well.  So you can add something like:

Ready to checkout?

Let us know if this worked for you...


List of creators + link I want my user to create content in which he can select a creator (in a select list) of products displayed on his article.
If he selects an existing creator during creation of the article, the publised article has to display the name of this creator + information about the creator (website + adress + maybe more). That means I have to enter this information into X fields for each creators.

If my user wants to add a new creator in this select list, he can do it directly when he creates his article. He enters the name of the creator + link to website + adress

My problem is that I don't know how to do it.

I've tried with that :
*new taxonomy + 2 Link fields added fopr this taxonomy

But how can I enter the content of these fields linked to the taxonomy ? How can I allow my user to add content on new creators he wants to add ?

If I understand your question correctly, and you are using Drupal 7, you need the Entity reference and Entity connect module.

The Entity reference module provides a field type with which you can reference other entities. When attached to your 'article' content type, your users can select an instance of the 'creator' content type.

To allow your users to dynamically create instances of the 'creator' content type, the Entity connect module comes in handy. Two buttons will be provided next to the Entity reference field, one to create a new instance and the other to edit existing content.

Please let me know if you need more information/help.


Does adding more processing power increases Drupal Page Load Speed I have a site hosted on Acquia Cloud.all the unnecessary modules are uninstalled. The site has only couple of nodes (300 almost)and lot of imported registered accounts.
Below optimizations are enabled already

http://www.goodykitchen.com

memcache
varnish
CDN - Cloudfront
Page Caching (Drupal's Default)
CSS / JS aggregation

RAM : 1.7GB
CPU : 1 ECU

Problem:

My comparison site is bbcgoodfood.com in terms of page load. I have gone through some research and they are using most of above mentioned optimizations. Is there a way to find out why their page load is so smooth. OR should i just increase the Cloud size and see my site page load. (currently i do not have many users on the site)

any clues ?
thanks

APC might be your answer

Best APC settings to reduce page execution time

There's a lot here on Drupal speed and performance generally ...


Drupal 7: What's the schema of the 'data' column in the 'users' table? I'm trying to bulk-add some users, all columns of the users table are clear less the last, the data which has some serialised data like this:

a:2:{s:13:"form_build_id";s:32:"form-153847821e107639110c0cae645b3d88";s:4:"contact";i:0;s:11:"newsletters";a:2:{i:67;i:42;}}

I'm looking for a syntax/reference for this field, so I know what I'm getting into.

thanks

There isn't a 'schema' as such, the values can be absolutely anything (that's why a serialised array is used rather than having statically defined fields).

From the user_schema() docs:

  A serialized array of name value pairs that are related to the user. Any form values posted during user edit are stored and are loaded into the $user object during user_load(). Use of this field is discouraged and it will likely disappear in a future version of Drupal.


suggestions needed to define a class for field per entity/node Im not sure the best way to go about this, and not so much a big programmer...

I would like to let the node creator decide whether the image in the image field should be top, left, or right. So i simply want to add class to the image div somehow.

So there should be a way to grab that info, maybe a "list" field?

Now, how to get that info over the image field?

Im thinking something like a field template for the image field (using media module)... or maybe something i heard about preprocessing in template.php?

pointer and tips appreciated!

You are looking for Image Class module - either use it directly, or use it's code - it is open source after all.

  Extends the Image formatter by adding an option to add an element class.


How do I go about telling Captcha that my form exists? I've got a drupal situation where I want to add reCaptcha to a custom form (built in an add-on module).  You can see from the captcha admin page that there is a list of forms that I can dynamically add captcha to... but my problem is that the form I created in the add-on does not appear in this list.

I'm sure I'm missing something (perhaps in the myform_block_info function?)

Does anyone know what hook I'm looking for?  Have a working example?

This was embarrassingly easy.  See that box at the bottom of the table?  Put your form ID in there.  "myform_form"


Splitting exposed form filters amongst several blocks I have a views search page in D8 where I'm I have exposed filters that are shown in blocks. I'm also using search facet blocks. What I want in the sidebar is the exposed filter text search field, followed by the facets, and then an exposed filter for selecting a date range.

I've seen a few places mention you can create a duplicate of the views page keeping the same path and have one set of filters in one views block and others in an additional views block. I think this was for D7 because I can't make it work in D8. Basically they replace the url arguments when one or the other is submitted instead of combining them like they normally would do.

What I've currently done is shown the exposed filter block twice and using CSS (display: none) to  aria-hidden="true" hide the redundant exposed filters from screens and assistive technology.

It gets flagged though when I used WAVE to test its accessibility since there are duplicative form labels. It's also, imho, a nasty hack and I'd rather do it the right way if possible.

Is there a right or better way?

In Drupal 8, Views pages allow you to render your exposed filters as a separate block. In your view, select your Page display, then, under Advanced, toggle on the option Exposed form in block.

You can now separately place the exposed filter like any other block. It doesn't even need to be on the same page as the view results.


How to determine if a translatable field has translation enabled? How can I figure out if a translation for a translatable field has been enabled?

I don't mean if a field is translatable in general. e.g.:

$entity_type = $entity->getEntityTypeId();
$bundle = $entity->bundle();
$fields = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);
foreach($fields as $field){
  if($field->isTranslatable()){
    // Do something.
  }
}

Could the langcode be a reliable information? If it is 'und' e.g.:

if($entity->get('name')->getLangcode() != 'und'){
  // The field translation is enabled:
}

To check if the translation is enabled on a field:

if ($entity->get('name')->getFieldDefinition()->isTranslatable()) {
  // The field translation is enabled:
}

which is by the way the same field definition you get in your code example, only here it is retrieved from the field directly. There is no difference between translatable and translation enabled as long as the entity is translatable.


How best to implement a custom variable in the content creation form in D7? I'm creating a sports league site.

I want to have a variable behind the scenes containing the current league standing. In a content type 'result', upon saving, I first want a field (previous standing) to be populated with this variable, and then for the variable to be updated with the new standing. But I have no idea where to even begin with this!

I believe your best bet is to create your own module, with a custom form hook and the form submit which will process your data and do all your calculations and save the new value. The form tutorials in the Form API Examples can give you a lot of good insight how to do this.


How do I fix a "Mismatched entity and/or field definitions" error on my configuration? I'm getting the following error on my Drupal 8 configuration page;

Entity/field definitions    Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
Content

Update the node.rng_capacity field.
Update the node.rng_registrants_duplicate field.
Update the node.rng_registration_groups field.
Update the node.rng_registration_type field.
Update the node.rng_reply_to field.
Update the node.rng_status field.

I'm not sure what caused these issues or how to go about resolving them - I think they may be leftover fragments/elements from when I deleted a registration or entity type maybe?

You can solve this issue by two ways
If you have Drush -

drush entity-updates

If you don't use Drush add following script before $response->send(); in index.php file(located in Drupal root folder) and reload the web page.

try {
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}
catch (EntityStorageException $e) {
  print_r($e);
}

Then remove this code from index.php file.


customized login block I made a template for the login block on the main page. It works.

Here is user-login.tpl.php code:

<?php
    $elements = drupal_get_form('user_login_block');
?>

Login

<?php
print drupal_render($elements["form_id"]);
print drupal_render($elements['name']);
print drupal_render($elements['pass']);
?>

             Forgot password

       <input type="submit" name="" value="Log in" />
       Sign up

<form> and
 tags were added around my template code, breaking the layout. Now the block doesn't float: left.

Here is the rendedered HTML:

<form action="/node?destination=node" method="post" id="user-login-form" accept-charset="UTF-8">

Login

<input type="hidden" name="form_id" value="user_login_block" />

  Login *
 <input type="text" id="edit-name--2" name="name" value="" size="15" maxlength="60" class="form-text required" />

  Password *
 <input type="password" id="edit-pass--2" name="pass" size="15" maxlength="60" class="form-text required" />

             Forgot password

       <input type="submit" name="" value="Log in" />
       Sign up

</form>

How to remove extra
 and put the form inside
? I tried that manually, but then I get 2 forms.

You could alter the form on the theme layer to wrap the form in a div...

/**
 * Implements hook_form_alter().
*/
function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {

    //dsm($form_id);

    if ($form_id == 'YOURFORMID') {
        // add prefix and suffix to form
        $form['#prefix'] = '
';
        $form['#suffix'] = '
';
    }
}


adding ckeditor color button and font size I am new to drupal.
I am using drupal  8.2.5, bartik theme and i would like to add font size&family and colour buttons to the ckeditor.

i installed the "CKEditor Font Size and Family" module, enabled it and then at "admin-configuration-content authoring-text formats and editors" i configured "Basic HTML" and "Full HTML" and drag the new available buttons of fonts and size to the toolbar. I saved it and then when i tried to add new content (article or basic page), the editor was completely gone, there was only the field of "summary" available to write something!
When i disabled the module, the text editor was back to normal.

Later, I noticed at the module page that the installation process was the following:

Download the plugin from http://ckeditor.com/addon/font.
Place the plugin in the root libraries folder (/libraries).
Enable CKEditor Font in the Drupal admin.
Configure your WYSIWYG toolbar to include the buttons.

So I realised i hadn't followed step 2. I don't know where the libraries folder is, although i searched and have no experience how to create it correctly and how to place this plugin there.
I read various posts on the internet but couldn't find a solution and then i ended up here.
Thank you.

You have to create the folder yourself as the docs say.

You can do this with command line with mkdir libraries in the webroot (where the /core folder is), or with a window and New Directory (New Folder) in either Windows / OSX.

Your application structure will then look like...

/core
/libraries
/modules
/themes

and so on.

All thats left is to download the JS plugin from ckeditor.com (v 4.5.x), unzip it, and place it in the libraries directory.


Is there an ready-made solution to mark edited form fields? When you edit something in text editor or IDE, you get visual feedback - star next to file name, bolded file name et cetera. That way you easily know what has been edited and what not.

Is there a ready made solution to introduce that to Drupal? Either system-wide or manually using Form API? It would make sense to see if any changes was made or not, especially if one opens dozen of nodes for updates and then sees some of them are already up to date and does not need a save (and associated boost cache clears).

In large setting forms, like permissions or Elysia Cron, it would help too.

The ideal would be to add some class to each field with value not equal it's default value, so the theme could deal with it using only CSS.

Anyone written it already?

I've only seen Track Field Changes, but that doesn't give immediate visual feedback.

Edit: I know you asked for something that was already out in the wild, but the following might be useful.

I guess you could write something custom relatively easily though using jQuery's .change event.

Something like the following I guess (code will need checking but it should be pretty near).

JavaScript

(function ($) {
    Drupal.behaviors.formFieldTracker = {
      attach: function(){
        $(input).change(function(){
          $(this).addClass('field-edited');
        }));
      }
    }
})(jQuery)

Module

function MYMODULE_preprocess_page(&$vars) {
  // Only add the JavaScript on admin pages as defined by hook_admin_paths()
  if (path_is_admin(current_path())) {
    $path = drupal_get_path('module', 'MYMODULE');
    drupal_add_js($path . '/js/MYSCRIPT.js');
    $vars['scripts'] = drupal_get_js();
  }
}

Then you could add whatever CSS you fancy afterwards:

.field-edited:after {
  content: 'Edited';
  display: inline-block;
  color: #F00;
  font-style: italic;
}


Redirect loop, add-{type}-node redirects to add-{type}-node for non-admin users when parent type not availab.e Users without admin permissions get a redirect loop error when they try to create a certain (organic group content) content type, when the parent (organic group) content type does not exist.

That is, instead of getting the edit form or a 403 error, they go straight to a redirect loop error. We do not have have any 403 redirect overrides, so that's not the cause. The .htaccess file is the default one provided by the Drupal installation.

Using the "display redirection page" reveals that the add node form is redirected  to the add node form in this situation. I've been unable to find any any Rule or other setting that could be causing this.

I am not using the Global Redirect module (which research indicates is the most common cause of this problem). Putting the site into maintenance mode and turning off all path, url, and indexing related modules, including Pathauto and Rules, (and reverting to the default Drupal theme) doesn't solve the problem.

The problem does not occur for anyone with the "override access permissions" privilege set.

Any thoughts

as to what might be causing this or
next steps I can take trying to debug this problem?

The Rules module that can be used to perform redirects also. So check if your sites uses this module. If so, verify if you have any "Active" Rules (and/or Rules Components) with a Rules Action that issues a redirect.

If no such Rules can be found, then it is not Rules causing your issue. If such Rules (and/or Rules Components) do exist, then temporary disable all such Rules and check if the redirect loop still happens.

If the redirect loop no longer happens, then re-enable the temporary disabled Rules again, one by one, until the problem (loop) starts again. Then disable that Rule again and use Rules debugging facilities to find out what the (customization related) problem with that rule is. For more details about debugging facilities in Rules, refer to my answer to ""How to loop through comments using the Rules module?".


How do I filter a view with a contextual filters on a custom date field? I am using the Quicktabs module to filter out posted that have a field value that in the date range specified. If you have a better solution in mind, please let me know. I am running Views 3.5 and Drupal 7.16

QuickTabs layout
I should be able to pass arguments to it to generate the new date sorted views using a contextual filter on the view.
Contextual Filters
I was able to query with the other contextual filters just fine but the date doesn't want to work at all.
What I would like to do is have a tab 4 date ranges (see first image) and clicking on the tab would load the content items with a that take place in a the range of specified dates. How can I get this to work? Is there a url query that I can pass as the argument for the start date field?

In the arguments follow the pattern

20130904--20130930

for date range between 4th September and the rest of the month.


Prevent Search Results Being Truncated - Drupal 7 Is there a way to prevent Drupal from truncating the search results?

That is, I do not want the search results shortened with a "..." added to the end of the result. I would like the full text.

Cheers in advance.

Yes, there is. Copy the /modules/search/search-result.tpl.php file into your theme directory. Then modify it like this:

  <?php /* this is just so it will be easier to access the body of the node */ ?>
  <?php $node = $variables['result']['node']; ?>
  <li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

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

  <?php if ($snippet): ?>
  <p class="search-snippet"<?php print $content_attributes; ?>>
    <?php /* this part is modified, you could display different data then the body */ ?>
    <?php print $node->body[$node->language][0]['safe_value']; ?>

  <?php endif; ?>
  <?php if ($info): ?>

<?php print $info; ?>

  <?php endif; ?>

Note Like I said in the comment, it's easy to display content from some other field, not just the body. To see what data you have to play with do:

 <?php echo '
';
       print_r($variables);
       echo '
';
 ?>