How do I create a route that opens an external file? How do I create a route that opens an external file?
As an example I have an XML file in my S3 bucket. I need to create a route to open that file from my website.
Is there a way to achieve this without calling a controller? Can I just set a property in the .routing.yml file for this?
my_module.index:
path: '/file.xml'
defaults:
  _controller: 'Drupal\my_module\Controller\moduleController::view'
  _title: 'file View'
requirements:
  _permission: 'access content'

Is there a way to achieve this without calling a controller from the route file?

No, a route needs a controller, no exceptions. If you can find an existing controller/method that does what you need, reliably, then you should use that. If not, you'll need your own controller and method.


How to integrate a private Google Calendar? My client is a counseling center that would like to use Google Calendar to record and manage confidential information when clients schedule appointments online.  The catch is that they want it to be a private Google Calendar.

Is this possible?

Can a private Google Calendar be embedded with a drupal site?

Check Google Calendar API (GCal)

This module uses google api php client refer
http://code.google.com/p/google-api-php-client/ to interact with
google and manage calendars
Requirements
GAuth - Required for authenticating with google.


Default views argument that can't be overriden? I have an argument comparing the current user ID to a field to determine what nodes to show, but all you have to do to impersonate another user is enter the argument in the address bar thus circumventing my default value. Is there a way to make an argument only ever use the default value and not exist as far as the address bar is concerned?

If the "User: Current" filter is not an option for you, then you can use a hook_views_pre_execute() to modify the argument before the query is run.

In your custom module (assuming you have one argument):

function mymodule_views_pre_execute($view) {
    switch($view->name) {
        case 'name_of_view':
            global $user;
                if ($view->arg[0] != $user->uid) {
                    $view->build_info['query_args'][0] = $user->uid;
                }
            break;
    }
}

Even if a different argument is supplied in the URL, the current user's id will still be fed back into the view.


How do I interpret the line of codes ( \ No newline at end of file) and (+ - core/jquery.once) In the Drupal8 zircon/includes/monokai/monokai.min/css patch how do I manually apply the last two lines of code;  ( \ No newline at end of file) and
(+    - core/jquery.once).
Thank you

diff --git a/zircon.libraries.yml b/zircon.libraries.yml
index bd6a231..3358a49 100644
--- a/zircon.libraries.yml
+++ b/zircon.libraries.yml
@@ -8,7 +8,7 @@ global-styling:
       includes/fontawesome/css/font-awesome.min.css: {}
       includes/slick/slick/slick.css: {}
       includes/slick/css/style.css: {}
-      includes/monokai/monokai.min/css: {}
+      includes/monokai/monokai.min.css: {}
       includes/flexslider/flexslider.css: {}
       css/html.css: {}
       css/page.css: {}
@@ -38,4 +38,5 @@ global-styling:
     - core/drupal.ajax
     - core/drupal
     - core/drupalSettings
-    - core/jquery.once
\ No newline at end of file
+    - core/jquery.once

The message "No newline at end of file" is a warning GIT throws up when there is not a newline as the last line in a file. You can solve this by adding a newline at the very end of the file.


Pager encoded commas I added a pager to a site I'm working on and the URL for a page comes out to: http://example.com/blog/0%2C0%2C0%2C0%2C0%2C5 which is an encoded version of */0,0,0,0,0,5. However, I'd like the URL to be http://example.com/blog/5 or similar.

I'm using Drupal 7.31 and have clean URLs enabled.

It sounds like you have a "Pager ID" value set in your view. From your example my guess is that it's set to "6" instead of the default "0". Check within the "Pager Options" of your view display to see if this is the case, and if so, change that value to 0 to restore the URL to a more standard form.

It's important to note that there are of course some situations where your need this pager ID to be set, notably if you have multiple views, each with pagers, displayed on the same page. If this is the case, and you have to use a pager ID > 0 on one of your views, you could set it on your "secondary" view (the one users are less-likely to page through) and leave it at 0 for the "main" view.

It also looks like you have the "Clean Pagination" module installed, or something similar? Normally I think a paged URL would have the pager query string (?page=#) exposed, so you must be doing some special clean URL processing for that. Still, I think the "Pager ID" notes above would apply regardless.


Passing filters to a View I think this is an easy problem, but cannot solve it.
I need to pass arguments from my module to a View3; suppose that i want to pass a part of the node title and need to get all the nodes that start with that value. I cannot expose filters because i have a particular layout that am not able to desing using exposed filters, so i need to pass arguments programmatically.
I thought to use Contextual filters but i have not found a way to specify the "Starts with" directive ... What can i do to pass argument?

For this purpose is better to use exposed filters. You can hide output of this filter in theming - it still be working. Just pass filters vlue in GET parameters to view's page.


How do I uninstall the Relation module? I am trying to uninstall the modules that are part of the Relation module, after I tested it on my test site.

The Relation Endpoints Field module is not selectable because Drupal says the field implemented by that module is being used.

When I click on the "Field list" link, I get the following list of fields currently used.

None of the reported fields is implemented by that module; they are standard Drupal fields.

What should I do, in such cases? The content type that used that field has been already deleted.

This happened to me with a couple of modules last week; the solution was simply to run cron, allowing the fields marked for deletion to actually be deleted. After that I could uninstall the module in question without issue.


Entity Reference and Views to allow a nested structure I'm trying to implement a nested structure in such a  way as to get a table (within a view?) similar to this:

Parent      Child       Grandchild      Age     Sex
John                                    56      M
            Lisa                        29      F
                        Jim             4       M
                        Louis           6       M
            Mark                        24      M
            Sanda                       21      F
Marcela                                 45      F
            Sam                         21      M
            Andy                        18      M
...

For this I defined the following content types:

Parent:
+Title (name)
+Age
+Sex
+Child [entity reference]

Child:
+Title (name)
+Age
+Sex
+Grandchild [entity reference]

Grandchild:
+Title (name)
+Age
+Sex

The +Age and +Sex attributes are shared between the content types, and the nested structure is implemented with entity reference fields.

I tried using Views, but I couldn't find a way to achieve this.

Any hint ?

Note:

With Views I managed to get the following table:

Title       Age     Sex     Children
John        56      M       Lisa, Mark, Sanda
Marcela     45      F       Sam, Andy

which is a basic use of Views...

Actually I cannot manage to relate Grandchild to Parent entity, through Parent > Child > Grandchild structure.

You should be fine with a content type called person and then have an entity reference field called "children" that points at the content type person.

Then in Views create two relationships using your entity reference field. The second relationship should use the first as relationship setting.

Call the first relationship, child and the second grandchild.

Then output Content Title three times, the second should use the relationship child the second grandchild.

Under row settings set it to group by Content: Title (the first).

Set a filter that the entity reference field can't be empty.

This should list all persons that have children.


How to import image using Feeds which doesn't have a correct file extension? I am using Drupal 7 and Feeds to import an image field into a content type article and it does work when the image URL is a direct link to the image.

However images that are linked to image handlers, like:

  http://business.iafrica.com/apps/imageUtil/view/article/1008937/1/630x385/

are not importing.

I have tried:

to use the Feeds Tamper module and Feeds Tamper PHP and alter the image name, but this resulted in an invalid URL loading,
to use Field Image Grabber, but I have an XML source, not HTML.

Here is my source feed URL:

  http://resource.thumbtribe.mobi/ds1.portal/portal/1/4/resource/view/maximized/9500187?format=atom_extern

and my Image: URI XPath mapping is:

string(link[@rel="enclosure"]/@href)

I managed to solve this by using the feeds tamper module with the following php snippet to save the image and then reference the path on my server.

$checkext = substr($field, -5);

if (strpos($checkext,'.') == false)
{
  $filename = str_replace(".","_",microtime(true)).".jpg";
  $output = "public://field/image/".$filename;
  file_put_contents($output, file_get_contents($field));
  return  $output;
}
else
{
  return $field;
}


Get url from image field in paragraphs I have a node with a field called "field_paragraph" which is a paragraph reference.
Referencing a paragraph type which has a field called "field_image"

I'm trying to get the url of the field_image in a custom module and so far i have this. But i don't seem to get it work.

use Drupal\paragraphs\Entity\Paragraph;
use Drupal\node\Entity\Node;
$node = Node::load($nid);
$paragraph_field = $node->get("field_paragraph")->getValue();
$paragraph = Paragraph::load($paragraph_field[0]['target_id']);

Here is where the problem occurs

$uri = $paragraph->field_image->entity->getFileUri();

The above returns nothing.

I used kint to print "$paragraph->field_image->entity" and it returns null.
What I'm I doing wrong? I tried all answers I could find on here to no avail.

After getting the uri I think calling the below line would be enough.

$url = file_create_url($uri);

Question: How do I get the url of an image field in paragraphs programmatically?

Your pretty much there but when calling the field name use the method get()

$uri = $paragraph->get('field_image')->entity->getFileUri();

Then once you have the uri you'll be able to get the full url

$url = file_create_url($uri);


How output field in $view->result? I need get to field views in calendar module template.

print_r($view->result) output this: https://jsfiddle.net/36pbj7bb/

How output event_calendar_status?

I type this:

<?php print $view->result[0][_field_data][nid][entity][event_calendar_status][und][0][tid];   ?>

But I get:

  Cannot use object of type stdClass as array in

Any help?

Views rows and entities are objects so I would think it should be this:

$view->result[0]->_field_data['nid']['entity']->event_calendar_status[LANGUAGE_NONE][0]['tid'];

but I'm guessing a little bit.

Also note the use of quotes in the array keys and the use of the LANGUAGE_NONE constant instead of 'und' for the field language.

If you still have trouble then try using the Devel module to see the structure of the view object variable.

There is information available via Google for how to use the Devel module to debug.


Why won't my custom content field update on save/edit? I am building a custom content type programmatically within my module. Everything appears as I thought it would on the "Add Content" page, but whenever I create a new piece of content or edit the created content the data from the field is not being saved. When I go back into the content nothing is there.

What am I missing? Is there a better approach? I wanted to keep the scope of this module inside of the related "Add Content" page because it needs to be able to follow the Drupal Workbench workflow.

On .install:

function header_maker_enable(){
  $contentType = "brand_header";
  $readableType = "Brand Header";
  $type = node_type_load($contentType);

  //Verify that the content type has not already been created once for this module
  if(!$type){
    $type = array(
      'type' => $contentType,
      'name' => t($readableType),
      'base' => 'node_content',
      'description' => t("Test"),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    );

   $type = node_type_set_defaults($type);

   //Creating Custom Test Field
   $field = array(
    'field_name' => 'brand_header_config',
    'type' => 'text',
    'entity_types' => array('node'),
  );
  $field = field_create_field($field);
  $instance = array(
    'field_name' => 'brand_header_config',
    'entity_type' => 'node',
    'bundle' => 'brand_header',
    'label' => t('Test Field'),
    'widget' => array('type' => 'text_textfield'),
  );
  $instance = field_create_instance($instance);

  node_type_save($type);
}

}

Here is my .module file. Something a bit more tricky is going on here with some JS. Basically I am rendering a UI to create some JSON. That JSON is then being added to the input field that was created on install in real time.

function header_maker_form_brand_header_node_form_alter(&$form, $form_state, $form_id){
  if ($form_id == 'brand_header_node_form') {
  $form['header_maker_ui'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['header_maker_render'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

$order = array(
'header_maker_render',
'brand_header_node_form',
'brand_header_config'
  );

  foreach ($order as $key => $field) {
// Set/Reset the field's
// weight to the array key value
// from our order array.
$form[$field]['#weight'] = $key;
  }
  }
  return $form;
  }

function header_maker_preprocess_page(&$vars, $hook){
  if(isset($vars['page']['content']['system_main']['#form_id'])){
$formid = $vars['page']['content']['system_main']['#form_id'];
if($formid == "brand_header_node_form"){
  drupal_add_css(drupal_get_path('module', 'header_maker'). '/css/brand-header-form.css', array('group' => CSS_THEME, 'every_page' => FALSE));
  drupal_add_js(drupal_get_path('module', 'header_maker') . '/js/header_maker.js');
}
}
}

I figured out what my issue was. In order to force users to use the UI I set the input field as being disabled from my JS file.

 document.getElementById('edit-brand-header-config-und-0-value').disabled = true;

Apparently setting it to disabled prevents it from being stored even though I could add a value to it programmatically through JS.

Removing "disabled = true"


Which Omega theme should I use with Drupal 7? I need to use the Omega theme framework. I find there is two different versions: Omega 3 and Omega 4.

Which one should I use with Drupal 7?

There are Drupal 7 versions of both, so you can choose either. As of writing the 4.x branch is actively maintained, and 3.x not so much.
The 3.x branch will hold your hand a lot more, and make a lot of decisions about how you want to work. This may be or ideal, or may be frustrating. SASS support is clunky and a bit of a pain to work with, if I'm honest. Its main 'selling point' is that you can configure most of the options it supports through the UI.
The 4.x branch is much more of a developer-focused solution. Very little UI, but it incorporates a full front-end stack of tools for development/asset management. If you're a developer, this will likely be the one for you.
This is what the docs have to say:

Whether you should use Omega 4.x or Omega 3.x depends on several considerations:

Do you rely on the user interface for building layouts, or are you comfortable defining layouts in code in a tpl.php file? Omega 4.x does not include the elaborate layout definition UI that was a hallmark of Omega 3.x
Do you want to use a theme that is under active development, or are you comfortable with a theme that is minimally maintained? Omega 3.x is minimally maintained. In all likelihood, unless a new maintainer steps up to the task, Omega 3.x will not be upgraded to Drupal 8.
Are you comfortable with or willing to learn SASS, or do you want to stick with straight CSS? Omega 4.x does NOT require use of SASS but certainly is much easier to implement if you adopt SASS.

Beyond that, the only way you'll get a satisfactory answer is to install and try both.
Edit: to add a bit of balance to the above docs (thanks @FreeRadical for the info):
The 2nd point (claim?) is hotly disputed. It has been written by the Omega 4.x team who currently holds "ownership" over the project pages. This is a bitter dispute and there are negotiations currently taking place which probably will get the project page rewritten soon.
Sounds like fun :/


Starting new 8.5 site is it safe to delete and reuse field_image field I am starting a new 8.5 website and using the core media module. I want to know if it is safe to delete the field_image field from the Article content type and replace it with a field with the same name but instead make it a media reference field. I have searched high and low and it is not clear as to if this will cause me issues with future versions of Drupal.

Thanks in advance

Any field could be deleted and re-created per your preferences and it won't cause any problems in the future as Drupal 8 does not require fields of certain machine names to be of certain types only.


Redirecting a registration link in logintoboggan I've got a register link and a log in link that is augmented by logintoboggan. All I want to do is redirect the register link from the user account form page to a new page I've just made. It seems very simple, but I can't find where the I can change the link. Any help would be amazing, thanks.

Use a hook_menu_alter to alter the user/register path and add your own page callback to it.


User logout when browser closes Is there a way to automatically log out users when they close a browser?
I've tried to set (settings.php)

ini_set('session.gc_maxlifetime', 0);
ini_set('session.cookie_lifetime', 0);

but this doesn't work. Seems to me like it has anything to do with the 'sid' stored in the 'sessions' table?

There is the session_expire module, and this module's page has some information about garbage collector confs and stuff.


Relevant Content Module Custom/Overwirete Theme The module Relevant Content has a function called

theme_relevant_content_block

Which renders the nodes for the module. The comments say the following

"This is provided (the function) so that an item list is the default, however a themer can
easily override this to make a teaser list or table."

I'm not really sure how to use a 'themer' to overwrite this function.

Any pointers on how to do it is appreciated.

You are the themer. In your theme, copy that function, but call it YOURTHEME_relevant_content_block. Now change the function to output whatever you want it to.


Why does Drupal insist on deleting my configuration? I've got a custom module with a configuration file config/schema/entity.schema.yml. This configuration file is imported via an update hook :
  $active_storage = \Drupal::service('config.storage');
  foreach ($files as $file) {
    $active_storage->write($file, $source->read($file));
  }

This works well, and the configuration in that file gets imported.
However, during the subsequent run of drush cim drush insist on deleting that configuration. I assume that is because the entity.schema.yml does not exist in the root config/synch folder.
Is this the expected behaviour? How can I make Drupal not delete the configuration which is imported from the module's /config/schema folder?

Yes this is the expected behavior. Config import and export is really quite simplistic (uncharitably: dumb). All it is doing when you run a config operation is to look at the active state of the DB and the active state of the sync directory and make one look like the other. On config:import (cim) you are saying "make the DB match those files in the sync directory". Export does the opposite. It's completely ignorant of other factors. So to make your changes "stick"

enable the module
run drush cex
afterwards drush cim should show "no changes"

NOTE: you can override config in settings.php files by using `$config[my.config.file][a_key] = "my_value". This bypasses whatever the files say to do. This is very useful for per environment overrides or sensitive inputs like API keys.
A simpler approach over this manual writing you have is to add your config yml file to your_module/config/install/. When the module is installed this will be imported to the active config state. As commenters have mention when you then run drush config:export (cex) the files will be added to your config sync directory.
Note that your config in /install are essentially one time use. They should also not include the uuid in the top line of the file that is generated in cex built yml.
If you want to install config again from your /install directory you can accomplish this manually by running: drush cim -y --partial --source=modules/custom/my_module/config/install
--partial means do not remove any configuration.


How to make 1 or more of total 4 fields mandatory I have 4 decimal fields where user enters can enter price per day, week, month, year. He can choose to enter 1 or more. At least 1 has to be entered of those 4.

Goal is views exposed filter with around 10 filters, all fields in it are mandatory on node creation so there is always result from view, except those 4 mentioned in first place.

Problem is if i add exposed filters for fields day, week, month, year, "betwean" 0 and 100 for each filter, none of the nodes show up on search page (without using the filters yet), as for now, no node has all prices written, and rarely they do. Users usualy put day and week price, or week and month price, or only year price.

On main view page i would atleast like to have all nodes show up with exposed filters in BEF (like they currently do), and then let view when using filters, filter out those who does not have week or month if customers were using filters with those values.

You have to implement your own validation logic through a hook_form_alter().

    <?php
    function MY_MODULE_form_alter(&$form, &$form_state, $form_id){
      if ($form_id === 'YOUR_FORM_ID')
        $form$form['#validate'][] = 'YOUR_VALIDATION_FUNCTION';
      }
    }

    function YOUR_VALIDATION_FUCNTION($form, $form_state){
      $assingned_values = 0;
      if(!empty($form_state['values']['FIELD1']['und'][0]['value'])){
        $assigned_values++;
      }
      if(!empty($form_state['values']['FIELD2']['und'][0]['value'])){
        $assigned_values++;
      }
      if(!empty($form_state['values']['FIELD3']['und'][0]['value'])){
        $assigned_values++;
      }
      if(!empty($form_state['values']['FIELD4']['und'][0]['value'])){
        $assigned_values++;
      }
      if ($assigned_values === 0){
        form_set_error('', 'You must set at least one field');
      }
    }


D7 equivalent to AutoMenu module In the past I always ensured that I had AutoMenu module installed on any Drupal 6 site I created. This module afforded me the following:

The ability to auto-create the menu item entry (per content type) when a new node is created (instead of manually clicking Provide a menu link), and
(optionally) Automatically set the newly created menu item to disabled.

These 2 features with D6 sites have always allowed me to not worry about another content-editor users messing up the hierarchy of the site. Plus it played well with my menus and breadcrumbs.

I have been desperately trying to get similar functionality working in D7, but haven't had much luck so far. There was an unofficial port of the said module to D7 but after trying it, it gave some errors.

Please can you suggest a way in Drupal 7 for me to achieve the same? Thanks!

That module has a drupal 7 version in the issue queue at https://drupal.org/node/1138946

Comment #25 has a link to a sandbox of the drupal 7 port: https://drupal.org/sandbox/wojtha/1331132

There is another version in a zip file at comment #46 but it seems that one is inferior.

It seems that it has been reviewed by a few people and works but the module doesn't seem to have an active maintainer so it has not been committed to the repository and made available on the project page.

I would try those versions of the module and see if either of them work.


Preventing a field from rendering on a page How would I prevent field_home_slider from rendering when $page['content'] is loaded? I only want it to load when I call it separately. I also still want the page content to be displayed just do not include the field_home_slider

Display image by itself

  if(isset($node->field_home_slider)){
     $field = field_get_items('node', $node, 'field_home_slider');
     $bannerImage = field_view_value('node', $node, 'field_home_slider', $field[0]);
     print render($bannerImage);
  }

and below to display content on the page

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

Go to  Display management of your content type  in admin/structure/types/manage/{yourcontenttypename}/display  and  set Formatter as Hidden.

Also you can  hide it with hide function  before render it in node template.

  hide($content['field_home_slider']);
  print render($content);


Can I delete leftover field_deleted_* tables? I have a lot of field_deleted_* tables in the database and neither drush cr or running cron is removing them. Is it okay to just remove them from the database? How can I tell Drupal to remove them otherwise?

Edit: Per 4k4 troubleshooting tip:

➜  default git:(HUHLR-172) ✗ drush ev "var_dump(\Drupal::state()->get('field.storage.deleted'))"
array(0) {
}

This means:

  If this is empty, then you can remove the tables in the database as
  well, because Drupal has no chance to guess the hash keys of the table
  names without this information.

No, this is not a good idea, because there are more things that need to be removed, not only the database tables. Deleting these tables without checking their usage first (see troubleshooting below) results in this error Cron error message. table or view not found: 1146

The deleted fields are purged by cron, but only 50 rows per run. If you want to accelerate the process, run cron more often or increase the batch size in field.settings.yml:

purge_batch_size: 50

Instead of cron you can run field_purge_batch() from the command line, then with a higher batch limit, for example 1000 or how many rows you have and are able to delete without hitting a memory/time limit:

drush ev "field_purge_batch(1000)"

Troubleshooting

If cron or the drush command has no effect, even not deleting some of the rows (if there are any more rows left in the tables), then check whether there are still field storages registered for these tables:

drush ev "var_dump(\Drupal::state()->get('field.storage.deleted'))"

If this is empty, then you can remove the tables in the database as well, because Drupal has no chance to guess the hash keys of the table names without this information.

If this is not empty, then you can use this output of the field storage definition(s) to debug this further (see comment of @MarioSteinitz).


How to change exposed filter select box style in views i have on exposed filter in views.it in defatult drupal select box style. how to change it like attached screenshot.

You can use fancyselect module.

Fancy select is a jQuery plug-in developed by Octopus Creative.
This module loads fancySelect jQuery plug-in, which converts simple HTML select DOM elements with a specified CSS class into a stylish select box. You may configure DOM CSS from settings form.


Unable to retrieve value from settings file inside custom module I have some specific values that will never change. I could use define and set them as constants but having a module_name.settings.yml file seems more appropriate.

The problem is that I can't seem to get the values from that file. It always ends up in null.

I have a module my_module in docroot/modules/custom', it's installed. Inside the root of the module I've created amy_module.settings.ymlfile with a single entry ofhello: 'world'`.

I've tried retrieving it using:

(\Drupal::config('my_module.settings'))->get('hello')

But the returned value is null. According to the documentation it should be working fine.

I'm using Drupal 8.

What am I missing here?

You need to put this file into

  myModule/config/install/my_module.settings.yml

Then uninstall and reinstall.

You ll get your value.


Form behavior when form creation data changes I've a form which shown from values in the database.

Now next day user fills it in and submits it. But the underlying data has already changed in the database.

I can see that in the validation handler form_state contains data from the form prepared after it is submitted but which contains updated values from other users, while the data submitted by the user is based on 1 day old data and he/she is not aware of changed data.

How does Drupal form behave in the scenario?

For example:

 I load a form and I see one row of data
 Another user comes and adds a new row of data
 I submit 1 row of data I see after checking on the checkbox
 FAPI now rebuilds the form but it now finds two rows instead of one
 In validation handler it sees two rows of data(but I submitted seeing single row)

→ Assume each row is 1 checkbox + textfield

Now I want to give error and ask the user to reload the form and submit again

If you include a function myform_validate, you can test the value in the $formstate array against a query for the current value in the database.  IF they do not match, return false and the original form will be redisplayed. This is explained in greater detail in the documentation for the form api


Searching fields in Group module I cannot figure out how I can be able to search the fields(set as a new content type) in the Group module.

For example, I created Groups(Group-Shop, Group-Salon, etc) under Group-Type-A with 3 fields containing:

Name: J-Shop
Type of Shop: Motor Shop
Address: Chicago (uses geolocation)

After I added more data, I wanted to be able to search an item (Motor) and ALL related results should have shown up on the map (address of each items).

I've tried using a view with filter group content, but of course it would only search for related results (text) and clicking on the item/name would point me to the detailed info. I was looking to filtering/searching via Address/Geolocation of each group.

I found an answer to my question. Its all in the view settings.

First, I changed the format from unsorted list of items/groups to Geolocation - CommonMap and modified its settings. This is to display all groups in a single map(A simple solution that I should have noticed at first).

Second, I added all fields needed to be displayed in a group in the map.

Lastly, I added desired filter(this is to search for a group).


Custom module menu item declaration leads to error 404 function eventi_menu() {
  $items = array();
  $items['eventi/book/%/'] = array(
    'title' => 'Book',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/book_waits/%/'] = array(
    'title' => 'Book Waits',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/unbook/%/'] = array(
    'title' => 'Unbook',
    'page callback' => 'eventi_unbook',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );

  return $items;
}

function eventi_book($nid) {
  echo 'something';
}

All worked OK, but suddenly, when I visit (for example) http://example.com/eventi/book/201, I get an error 404. I cleared the cache, but I keep to get the same error. Do you have any clue why it happens?

I would guess that trailing slash on the path is throwing you

$items['eventi/book/%'] = array(
  'title' => 'Book',
  'page callback' => 'eventi_book',
  'access arguments' => array('allow booking'),
  'page arguments' => array(2),
  'type' => MENU_CALLBACK
);

Also, if you use %node for the variable in the path, the menu router will call node_load() on the given nid from the path and you'll get the full $node object in your callback function, like so:

$items['eventi/book/%node'] = array(
  'title' => 'Book',
  'page callback' => 'eventi_book',
  'access arguments' => array('allow booking'),
  'page arguments' => array(2),
  'type' => MENU_CALLBACK
);

// ...and so on, until...

function eventi_book($node) {
   return $node->title;
}

Also note that your callback function should return a value, not echo it.


Search API Solr fulltext search improve results I use Search_api_solr module with drupal. I have a node with "Sony W800a TV" when I search w800 there is no result but when I search w800a I see this node in results.

How Can I Fix this?

Thanks

You're looking to enable 'partial word' search which would allow for matching w800 with w800a. As described in this blog post, Apache Solr has this capacity built in, it just needs to be enabled by adding this line to the Solr Schema that comes with Search API

<filter class="solr.NGramFilterFactory" mingramsize="3" maxgramsize="25"/>

However, pay attention to their caution about performance issues - you want to only enable this capability on a limited field (ex. the title field) rather than a longtext field as it will greatly increase the size of your index and reduce performance.


How to make Imagefield slideshow display full width I use Drupal 7.20 and try to make my imagefield just like PULLANDBEAR.

This is what I've already done: I'm using field slideshow to make node slideshow (this works as I want it to).

Then I want my image on click to open a bigger image that respects width and height (this part is really confusing).

Can someone give me the right directions or clues? I still haven't found the right ones. Maybe I used the wrong keyword(s) to find them? Right now I'm still using a trial and error approach as in the question How to zoom in an image using jquery?

I have not used the field slideshow module, but if it allows you to select the image style, then you could use the Lightbox2 module http://drupal.org/project/lightbox2. Lightbox 2 is not the only option for displaying the image in an overlay/popup type thing, there are many, here is a comparison of some of them http://drupal.org/node/266126. I just mention lightbox2 specifically as it is the one I usually use.


MiniOrange SAML SSO Drupal Module – Multilanguage Support This is my first post at Drupal StackExchange. Please feel free to redirect it to the proper forum if this is the incorrect one.

How do I configure Apache Server so that MiniOrange SAML SSO Drupal module does not conflict with my Drupal multilanguage settings?

Here is my problem:

I determine the language from the URL as a Path prefix:

URLs like https://example.com/en/contact set language to English (en) - Default

URLs like https://example.com/fr/contact set language to French (fr)

My default language is English.

If I configure my Drupal multilanguage settings to other detection methods such as session, user, browser then the SAML SSO Drupal module works fine but some (not all) of my Clean URLs no longer work with my current modified Drupal and Apache settings. I’d like to retain my multilanguage settings.

All this happens because of the SAML Drupal module ACS, Recipient and Destination URLs are configured in such a way that the language negotiation happens before reaching the ACS, Recipient and Destination URLs.

ACS URL https://example.com/?q=samlassertion

Recipient URL https://example.com/?q=samlassertion

Destination URL https://example.com/?q=samlassertion

Drupal then prepends the default language code, English (en) in my case, to the ACS, Recipient and Destination URLs as follows breaking the module.

ACS URL https://example.com/en/?q=samlassertion

Recipient URL https://example.com/en/?q=samlassertion

Destination URL https://example.com/en/?q=samlassertion

I know Apache Server 2.4 very well but by no means I’m an expert. I strongly believe this issue can be fixed with a simple and magic Apache configuration set of rules.

What I've done to fix all these issues is by restructuring my existing Drupal Clean URLs to work with the SAML module by using other detection methods such as session, user, browser and by creating rewrite rules to redirect existing URLs to the new structure. I wish I could say that I have completely and 100 % fixed all the problems. But that’s not the case. As I mentioned, some of my URLs break.

Any help is greatly appreciated.

Thanks,

I figured it out.

The solution to this problem is so simple that i feel a bit embarrassed posting the solution. However, here it goes for those who may stumble upon it. This only needs to happen during the initial configuration and revert back once this step is completed (Based solely on my experience).

Drupal cache for anonymous users needs to be disabled during initial IdP and SP metadata and certificate negotiation
Drupal language negotiation needs to be turned off during initial IdP and SP metadata and certificate negotiation

Victor
"Patience and perseverance have a magical effect before which difficulties disappear and obstacles vanish"


Drupal Multilingual Home page I am having a problem with multilingual settings. Here is my site URL http://centriumcapital.com/centrium. Everything is working fine but I just want when someone requests http://centriumcapital.com/centrium the default language should be French and also content of the home page also should in French.

I added code in settings.php file to make French language as default language it selects the French language as default but content is still from English language.

Check out this Page. You can set this using locale module and i18n translation module.


Deleting non-active users (e.g., users who didn't log in for 90 days) We use Drupal as an employee portal; as such, when new starters join the business they create an account.

However, we are trying to figure out a good leaving process; right now I get a list and have to manually delete all the users.

Ideally, we would like something which send an email to a user after 14 days and then again after 30 days informing them that they have not logged in into the system; then, after 60 days, they are automatically deleted.

I am guessing that using Rules is the answer, but I cant find any option to delete users.

Maybe this module can help: inactive user

From the module page:

  After configurable periods of inactivity, one or more of the following
  actions can be automatically taken:

  send an email to the user
  send an email to the site administrator(s)
  block the account (a warning can first be issued)
  optionally notify user and/or site administrator(s) that account
  was blocked
  delete the account (a warning can first be issued)
  optionally notify user and/or site administrator(s)1 that account was
  deleted


Public URLs have web/ prefix while admins do not, how to remove 'web' prefix? I've setup Drupal 8 using https://www.lullabot.com/articles/goodbye-drush-make-hello-composer, but when I visit the site, all the links begin with web/ which means they break. If I remove web/ then they work. If I login, the links don't have web.

How would I remove web/? Where SHould I look in the source tree for a config file or otherwise to adjust this?

This appears to be fixed; the following steps for creating a drupal 8 site don't appear to have the issue: https://www.drupal.org/node/2471553.

(Original issue posted on https://www.drupal.org/node/2673164.)


Should I create fielded content types (with 1000+ tables) OR create custom entities with properties instead of fields (way less tables)? I have a case where I have a lot of entities that can be stored with Drupal as node (content types) and fields. I had to end up creating 105 content types, 20 taxonomies and in-numerous fields. And the result is that I have right now 1600+ tables in my database. I'm assuming that is not healthy. Please advise.

The other option that I have now is to create entities. I can use entity api module to create a lot of the above content types as separate entities with all  properties which would mean that one entity information is stored in one table as opposed to 2 fields for each field (i.e. data and revision). The data in these content types need to be imported but I do not need any CRUD interface for them. Will my database calls be better in terms of performance if I make separate entities instead of content types?

My main objective is to be able to present all the information through views. And I believe that if I have entities, I should be able to display the properties through views. Is that true? I have not tried ECK yet, so I am not sure if creating Entities through interface works clean, so some help in that regard will be very much appreciated.

It depends on your requirement. For example, if you want nodes to be revisioned then go for content types. If you do not want them to revisioned and just using them for storing content then I think entity would be a better option.

Update: 19th June 2016 Thanks to @jon-freed

  When it comes to performance-sensitive projects, nodes should really
  only be used for content, and we should separate as much as possible
  from nodes. Why? Nodes are revisioned, they fire a lot of hooks, and
  they have functionality that we likely won't need. Also if we know
  exactly what fields we should have in our entities, we can create our
  own custom entities to avoid all those joins of Field API tables.

As far as the choice between ECK and entity api module, it also depends on your requirement. Entity api module provides more control over an entity, for example if you want to create an entity controller for the entity then you should use entity api module. If you just want to create an entity and define some properties then go for ECK. ECK also allows you to created bundles for entities.

Also, you can easily create views for the entities, this site provides great example to work with entities.

Reference: Drupal 7 Entities: What are they, and what are they good for?

Update: (19th June 2016)

It is true that using fields will increase the number of tables, which means more JOINS during database queries. If the purpose is to store data only then you should go for properties. If you want to take advantage of Drupal fields (display the data in cool ways), then you should go for fields, but in this case you have to think about the performance.

We can add fields to nodes and custom entities. Therefore, using nodes will not affect performance. You can always alter properties of an entity using hook_entity_property_info_alter(&$info)


file_save_upload validate file size I have a simple Drupal 8 form where users can upload a picture.

The issue is that the upload_max_filesize is set to 2M on the server. So if I upload a bigger file, the form submission fails:

  Fatal error: Call to a member function save() on a non-object

Here is what I have tried in the submitForm:

$validators = array(
  'file_validate_is_image' => array(),
  'file_validate_size' => array(1024 * 1024),
);

/** @var File[] $pictures */
$pictures = file_save_upload('picture_upload', $validators, 'public://');
if(null !== $pictures) {
    /** @var File $picture */
    $picture = reset($pictures);
    $picture->save();
}

This actually leads to 2 issues when trying to upload a large .jpg image:

The file could not be saved because it exceeds 2 MB, the maximum allowed size for uploads.
Image type not supported. Allowed types: png jpeg gif

So my questions are: why does the validator not accept a .jpg image? How would I go about avoiding the fatal error and return to the form if the file size is too big?

Edit:

I have changed my validator to this now:

$validators = array(
  'file_validate_extensions' => array('gif png jpg jpeg'),
  'file_validate_size' => array(2 * 1024 * 1024), // 2MB file size limit
);

It works now in the way that it accepts my .jpg image and doesn't accept files larger than 2MB. But how would I go about returning to the form with an error message instead of going straight to the PHP fatal error?

The return value from file_save_upload() is:

  array Function returns array of files or a single file object if $delta != NULL. Each file object contains the file information if the upload succeeded or FALSE in the event of an error. Function returns NULL if no file was uploaded.

So you can handle it a few different ways.

$picture = reset($pictures);
if ($picture === FALSE) {
  $form_state->setErrorByName('field_name', $this->t('Error!'));
}

or

$picture = reset($pictures);
if (!$picture instanceof \Drupal\file\Entity\File) {
  $form_state->setErrorByName('field_name', $this->t('Error!'));
}

are the first that come to mind.

This code will need to be in a validate method rather than a submit method, so that you're setting errors in the right place. You can leave the ->save() logic in the submit method, safe in the knowledge that the file has been validated and exists before that code is executed.


Allow subusers to access parent's content I have 2 drupal roles. Let's say a teacher and student.

A teacher should be able to:

Create student account.
Create new nodes.

Student should be able to:

Edit and view ALL nodes created by the teacher who has created his
account.

Since it involves mapping of users, I've used the subuser module

I have checked the content access and node access modules as well but they doesn't let me map teacher's content to his student (sub-user).
These modules require me to grant permission for individual nodes created by teacher and does not apply permissions automatically to all content created by the teacher.

How do I make all sub-users automatically get edit permission to all content created by parent user?

PS: My actual problem is much more complicated with multiple seller roles and integrating with payment methods. However a solution to this simple case will guide me to go about the problem.

I think you already solved this yourself but searching the same issue I ended up on this post. Since I found a solution I will post it here for all other people running in to this problem.

The solution is in combining the modules subuser and user relationships and rules.

Subuser gives other users the right to add new users. These users are related to each other with the relationship module but there is
no link between their nodes.
To get the link between content of the users I used the user relationship module. This module let's you set up relationships as
friend, coworker or co-editor or whatever name you want to give it. These relationships can give one way or two way permissions to
update, view or delete each others nodes.
Normally you would have to go to a users page and request the relationship with the user but with rules it's possible to set a
relationship when a new user is created.

So what steps to take. First enable all modules. For the user relationship you have to enable the main module but also the User Relationship UI and the User Relationship Rules module. Now go to the relationship module admin/config/people/relationships and create a relationship with the name "friends" (or whatever name you want). At the share content tab make sure that the content type you want to share is selected.

Now go to roles admin/people/permissions/roles and create a new role with the name "friends" (so the same as your relationship, just because it's the most clear).

Now go to permissions admin/people/permissions and set the User Relationship permissions as you want. Make sure that Grant view permission to related users and Grant update permission to related users is set in the right way to the roles you use. So if you want the subuser(friend) to be able to see and edit the parents content make sure the permissions are on for him. Also make sure he has the right to get the friends relationship. Also make sure the parent has all these rights as well.

Now go to the parents user page and go to the share content part, set it up so that the friend is able to update and view content.

When all this is done it's time to go to Rules in rules it's possible to create a rule that says:
 - If User Created
 - And Role is Friend
 - Request Relationship (Friend) - Auto Approve Relationship

Now when the parent creates a subuser the subuser will be able to edit and view its parents nodes. For the parent it is still possible to give his Friends a per node based access to it's nodes. So on default all nodes are shared but the parent can edit this per node.

I hope this is clear enough I did my best, but please let me know if there are any unclear parts.


Unexpected Entity Reference Autocomplete behaviour I'm using Entity API, Form API and Entity Reference Autocomplete in Drupal.
I have a relationship between two types, clubs and courses, each club can have many courses so basically the table course contains a column called goclid which references the club id number like so:

// hook_schema()

$schema['course'] = array(
    // other fields...
'goclid' => array(
    'description' => 'Reference to the club',
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
  ),

// ... a few lines later...
'foreign key' => array(
  'related_club' => array( // join alias
    'table' => 'club',
    'columns' => array('goclid' => 'id'),
  ),
),
// etc.
);

Then I include a field like so in the course form:

$form['goclid'] = array(
    '#title' => t('Reference to the club'),
    '#type' => 'entityreference',
    '#era_entity_type' => 'club',
    '#default_value' => isset($course->goclid) ? $course->goclid : '',
    '#required' => FALSE,
);

Now, the autocomplete gives suggestions only when I type an id number, and then populates the field value with the label (name of the golf club).
What I want is exactly the opposite: I want to get suggestions by typing the name of the club, and then when I choose one, the form field should be populated with the id number of that object.

Why is Entity Reference Autocomplete behaving in an unexpected way? What can I do to obtain the desired behaviour?

EDIT: to understand the solution look not only at the answer but also at the comments that I left below the answer; the answer itself only explains how to get the suggestions working but does not explain how to build and save the entity object in your submit function.

I think you might have not specified the "label" column in the entity definition. That goes within the 'entity keys' array, like the 'id' key.

$entity_info = array(
   .....
  'entity keys' array(
    'id' => 'primary key column...',
    'label' =>  'column holding the label'
  ),
)

Otherwise entityreference will not know which column to use for searching in the DB. That still makes it possible to show the label  (as you're experiencing) after you reference the entity, because 'label' key is not mandatory, and you may have specified a "label callback" instead, which the Entity API will use when entity_label() is called to get the label of a specific entity.

If adding the 'label' column and flushing all caches doesn't solve your problem, I think I'd need the entity definition to be able to help!


Breadcrumbs are cached In Drupal 8, if I create a node, add a menu link, save it, then go back and edit the menu link title in the node, the breadcrumb title does not update until I clear the cache.

How can this be set so it reflects this change without requiring flushing the cache?

Breadcrumbs for nodes have no cache tags. The reason is that the node entity has no specific breadcrumb builder. The generic path based breadcrumb builder gets the title from the title resolver and is not aware where the title is from and what tag it should set.

You can add tags for nodes in hook_system_breadcrumb alter():

function mymodule_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  if ($route_match && $node = $route_match->getParameter('node')) {
    $breadcrumb->addCacheableDependency($node);
  }
}

To test this you need to have extended the breadcrumb behavior to display the title. In my test site this was the Bootstrap theme. Another option would be the module Current Page Crumb.


Does DRUPAL_CACHE_PER_PAGE count pager pages (i.e. frontpage?page=3)? I guess my whole question is pretty much in the title... I'm wondering if blocks that use  DRUPAL_CACHE_PER_PAGE get cached on pager pages (i.e. mysite.com/frontpage?page=3), or if the pager query is disregarded (so the block would only be cached once for frontpage, frontpage?page=2, frontpage?page=3, etc.)?

Yes.

See drupal_page_get_cache() in bootstrap.inc:

if (drupal_page_is_cacheable()) {
  $cache = cache_get($base_root . request_uri(), 'cache_page');
  if ($cache !== FALSE) {
    $cache_hit = TRUE;
  }
  return $cache;
}

request_uri() returns the whole path including any GET arguments.


Role Based Shared Control Panel I'm looking for a way to allow members of a specific role to share a control panel/settings page.  These users do not have admin level access and I would like to use the field api to store data.

Currently I'm leaning towards the Profile2 module, but this doesn't feel very robust.

Is there a common way to accomplish this that I've missed, a module that is better suited for this use case or am I on the right track using the Profile2 module?

Yes, with the combination of profile2 and og (organic group)  you can achieve your job.


entity reference filter condition I have created view and I have added the fields like entity reference fields followed by content fields, then I added the entity reference field in filter condition, but its not displaying the table data.
Following methods I followed to create the filter conditions,

1] created new view added the entity reference and other content fields.

2]added the contextual filters as shown in screen attachment, also the relationship as entity reference of the field.

3]in the left view page-> clicked on ->add filter condition->chosen the field and relationship but still its not able to filter the data of table please help me on this.thanks in advance

In my observation it appears you are mixing some configurations here. Normally when you add Content: Nid, you are telling the view to get the NID from your URL like animal-info-view/% where "%" represents the node ID or somewhere else like Panels but notice that you don't have that. The view will now be asking "Where is my nid? I can't find it.". So now you're having issues with no data being displayed.
If you need a listing page, sometimes you won't need the Contextual and Relationship fields anymore. Just directly add the entity reference field into Filter Criteria and it should look like the Gender filter.
If you need a content/node view page, now you will need the Contextual fields but kinda not need the filter because you're just displaying one content.
EDITED
Apologies for the late reply. So on my research I found a module called Views Reference Filter that enabled you to assign a View to provide the selections for your filter. So install an enable the module.
Create the Entity Reference filter view

Create a new View.

Add a new Views Display called Entity Reference.

Select the Lab content type for the Show field.

Add the Lab Nid and Title/Name.

Under Format, replace it with Entity Reference List

Under the format's settings, choose Nid for Search fields.
You should have something like:

Tweak your Animal Info View

Remove all the Contextual filters and Relationships you have and the (Content entity referenced from field_lab_idc) Content: LAB ID filter you added.

And add the Content: LAB ID field that's in your Animal Info content type

On the LAB ID's settings pop-up, you will notice something new, it's the View used to select the entities. Select the entity reference view that we created a while ago.

You can leave the default Operator setting to Is one of.

Check the Expose this filter to visitors, to allow them to change it.
This would look like:

And click Apply.
Your Animal Info View should have something like this:

Hope this helps you.
NOTE: Please include your requirements so that people would know what you want the result to be like.


Entity Update Failing: How can I clean this up? I recently uninstalled a module and it left behind a bit of a mess in the database. Running drush entup lists a number of fields related to this module that need to be uninstalled across a few entity types.

This fails, though. In addition to these field definitions there are a number of other tables that didn't get removed.

How can I clean this up? I'm comfortable manipulating the database and I'm able to find the fields. I'm just unsure of how to clean it up to satisfy drush entup so it stops listing it as a pending action.

Edit-Including Error:

The following updates are pending:

node entity type :
  The Lingotek translation source field needs to be uninstalled.
  The Lingotek translation status field needs to be uninstalled.
menu_link_content entity type :
  The Lingotek document id field needs to be uninstalled.
  The Lingotek hash field needs to be uninstalled.
  The Lingotek profile field needs to be uninstalled.
  The Lingotek translation source field needs to be uninstalled.
  The Lingotek translation status field needs to be uninstalled.
  The Lingotek translation created time field needs to be uninstalled.
paragraph entity type :
  The Lingotek document id field needs to be uninstalled.
  The Lingotek hash field needs to be uninstalled.
  The Lingotek profile field needs to be uninstalled.
  The Lingotek translation source field needs to be uninstalled.
  The Lingotek translation status field needs to be uninstalled.
  The Translation changed time field needs to be uninstalled.
Do you wish to run all pending updates? (y/n): y
Drupal\Core\Entity\EntityStorageException: The field lingotek_translation_source has already been deleted and it is in the process of being purged. in Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema->onFieldStorageDefinitionDelete() (line 512 of           [error]
/docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).
Failed: Drupal\Core\Entity\EntityStorageException: !message in Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema-&gt;onFieldStorageDefinitionDelete() (line 512 of /docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).       [error]
Cache rebuild complete.                                                                                [ok]
Finished performing updates.

Update: it seems that you need to run cron to complete the field purging process drupal goes through.

Also you may be getting some errors when the fields you are deleting have data in them . entup does not attemp to drop fields with data in them and you have to do it yourself. You have 2 options:

Go to each field in the content type and delete them manually.
Write an update hook that delete the fields before you run entup. In other words, you run drush updb then you run drush entup provided you have implemented an update hook that deletes the fields. Something like this (code not tested):

function my_module_update_8001() {
   $entity_type = 'node'; // or user or wherever the field appears
   $bundle_name = "article"; // or whereever the field appears
   $field_machine_names = array('field_one', 'field_two');
   foreach($field_machine_names as $field_machine_name) {
    $field = \Drupal::entityManager()->getStorage('field_config')->load($entity_type.$bundle_name.$field_machine_name);
    $field->delete();

  }
}

In addition, make sure that you run cron frequently because that's when drupal does garbage collection and deleted field data get purged.


Taxonomy term AND (,) operator does not work In contextual filters, with

validator = taxonomy term
Filter value type = term ids separated by , or +
allow multiple values = true

Giving argument "1+2" works as espected: OR operator

Giving argument "1,2" works as "1+2": OR operator instead of expected AND operator

In both cases, conditions uses operator "IN":
WHERE (( (field_data_field_tags.field_tags_tid IN('1', '2') ) )AND(( (node.status = '1') AND (node.type IN ('flickr_photo')) )))

This is the contextual filter part of my view:

/* Contextual filter: Content: Tags (field_tags) */
$handler->display->display_options['arguments']['field_tags_tid']['id'] = 'field_tags_tid';
$handler->display->display_options['arguments']['field_tags_tid']['table'] = 'field_data_field_tags';
$handler->display->display_options['arguments']['field_tags_tid']['field'] = 'field_tags_tid';
$handler->display->display_options['arguments']['field_tags_tid']['default_action'] = 'empty';
$handler->display->display_options['arguments']['field_tags_tid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_tags_tid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['field_tags_tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_tags_tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_tags_tid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_tags_tid']['specify_validation'] = 1;
$handler->display->display_options['arguments']['field_tags_tid']['validate']['type'] = 'taxonomy_term';
$handler->display->display_options['arguments']['field_tags_tid']['validate_options']['vocabularies'] = array(
  'tags' => 'tags',
);
$handler->display->display_options['arguments']['field_tags_tid']['validate_options']['type'] = 'tids';
$handler->display->display_options['arguments']['field_tags_tid']['validate_options']['transform'] = 0;
$handler->display->display_options['arguments']['field_tags_tid']['validate']['fail'] = 'empty';
$handler->display->display_options['arguments']['field_tags_tid']['break_phrase'] = 1;
$handler->display->display_options['arguments']['field_tags_tid']['not'] = 0;

How can I set a AND filter? I want to display contents with all values of tags.

I am not the best with deciphering exported settings, but I think you should remove that Contextual Filter and use "Content: Has taxonomy term ID" instead.  Make sure you tick "Allow multiple values" under the More section.  That will result in a chain of AND clauses in the WHERE for the view (well, it does in one that I just looked at).


How can I remove decimals when I award user points via commerce-order-total:amount I want award users after completing the checkout process. For this task I use this modules (Commerce, UserPoints, Commerce Credits).

I create a product with a price equal 15$ and create a rule which award user after complete checkout. When checkout is complete, rule works great, but it gives user 1500 userpoints instead 15. I tried use module (Commerce Price Decimals Formatter, Commerce Extra Price Formatters) which remove decimals from commerce also I tried use some code from internet but all of it doesn't solve my issue.

Does anybody know solution for this issue?

it's code that I found on the internet:

<?php
/**
 * Implements hook_commerce_currency_info_alter().
 */
function Zero_commerce_currency_info_alter(&$currencies, $langcode) {
  $currencies['USD']['format_callback'] = 'Zero_rub_currency_format';
}

 /**
 * Currency format callback.
 */
function Zero_rub_currency_format($amount, $currency, $object) {
  $round_amount = commerce_currency_round(abs($amount), $currency);
  $price = number_format($round_amount, 0, $currency['decimal_separator'], $currency['thousands_separator']);

  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

  return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}

It is my Rule:

{ "rules_grantpointaftercheckout" : {
"LABEL" : "GrantPointAfterCheckOut",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "userpoints_rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"DO" : [
  { "data_convert" : {
      "USING" : {
        "type" : "integer",
        "value" : [ "commerce-order:commerce-order-total:amount" ],
        "rounding_behavior" : "down"
      },
      "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
    }
  },
  { "userpoints_action_grant_points" : {
      "user" : [ "site:current-user" ],
      "points" : [ "conversion-result" ],
      "tid" : "0",
      "entity" : [ "site:current-cart-order" ],
      "operation" : "bla bla bla",
      "display" : "1",
      "moderate" : "approved"
    }
  }
]
}
}

Have a look at the Drupal Commerce issue about "Revise the way we handle price amount values". Especially comment nr 37 in it, which states:

  The price field is and will continue to store price amounts as integers ...

So rounding an amount of 1500 dollarcents is ... still 1500, right? And that is the amount of user points you're granting. And because of that, your rule works as implemented: you're using that value of 1500 as the amount of userpoints to be granted.

Obviously, all you need to do next is to expand your rule to devide the price by 100 first (before rounding it). I assume you know how to do that, if not use this link ... bonus hint: have a look at the example rule included in the answer to "How to add up all items of a field collection field using Rules?", especially the "Calculate a value" Rules Action.


Change the url path of /sites/default/files/myfile.pdf When you click to view a pdf file on a page the url is always this: http://yoursite.com/sites/default/files/myfile.pdf. You can modify this path in the field setting and add tokens, dates. But what if you wants the url to be simple and not give out the fact that this is a Drupal site. Can you change it to be this: http://yoursite.com/files/myfile.pdf. Does this require htaccess url rewrite or Apache redirects?

Go to this path /admin/config/media/file-system, and change the public file system path.

It might be this, sites/default/files, change it to files.

Then create a writeable folder in your webroot called files.

This could also be done by adding this line in the settings.php file:

$settings['file_public_path'] = 'files';

Just note that this is only for local development if you want to deploy this change you might use the above solution and then export the configuration.


excessive "access denied" logs? I've setup a Drupal site and had to turn off user registration because of the amount of bogus accounts being created. Now when I check the logs I see loads of access denied messages, usually for pages
node/add
user/register

Is this normal for a drupal (possibly any) site, and something to be expected?
It seems excessive to me, so I'd like to understand if this is a normal problem for websites, drupal or otherwise?

Yes, this is a common problem. A spam bot has crawled your site, realizes it's a Drupal site, and it going through its functions to spam content (e.g. user register & node posting). This isn't exclusive to Drupal; there many kinds spam bot software that target specifics CMSes and any other comment/content submission forms.

You should look into various Drupal spam prevention modules like CAPTCHA, Botcha, etc.


Theme based altering of default image-style for the same node-type and view-mode OK, After some research and since Domain_views module seems to be a little bit buggy (printing always default Domain ID no matter what), I think this is the base question solving my problem the other way around with 2 domains and 2 themes using the same nodes from same node-type, but they both need different image-styles because of their 2 different themes:

How do I alter the given image-style of a given node-type in its default full-node view-mode in the .tpl files of a theme, to have 2 different used image-styles in 2 different themes by the same node-type and the same view-mode?

I've tried to find example themes doing it and I heard of Entity view mode to add custom view modes, but I am still not sure if I am on the right tracks. Actually I only need another image style (size) for the same node-type and the same view mode but in 2 different themes since Domain Access gives me hard times to solve this with conditional view modes or Views displays.

From what I understood there are 2 ways:

a custom view mode for the same node type and a function in the theme telling the node-type to rather use this view mode
or only a image-style altering in the node--full.tpl.php but I can't find a good example explaining it.

The very basic question to research for me is: how to alter image-styles in the code of the theme layer? Is this correct?

Any help would be very appreciated! Thank you very much for any hint.

Well after reforming my question 3 times and rethinking what the actually question should be like to find a solution, I came to the conclusion that the Domain_views module is completely broken (ALL Domain views fields always output the default Domain ID/name/path no matter what), and that the theme layer node--view-mode.tpl.php altering approach is not generic enough to have this functionality in other use-cases.

So I found a nice trick, which maybe also helps others to change field styles in a given steady node-type and same view mode under certain conditions, but it needs Views module:

Use the Views_conditional module and use your fantasy to get the needed result. :-) That easy!

In my case I was able to turn off the Domain_views module completely (finally!) and have used the absolute path setting from the content:path views field to change the image-style under the condition, that the path includes a given pattern of one of my domains. I have 2 image fields (excluded in Views) and a conditional field showing one of them if needed, e violá! :-) My image style changes in the 2 different domains by the same given node-type and node-view-mode! Awesome

Views as a full node view mode designer... I never stop learning. ;-)


How to suppress "page not found" messages in watchdog The issue Add an option to suppress page not found watchdog messages at https://www.drupal.org/node/2836458 indicates that a setting was added to Drupal 8 to suppress page not found errors in watchdog. I can't find the setting in the interface. Am I mistaken in understanding that it was added? If not, where do I find this setting? Running Drupal 8.8.1.

Yes that option is available as described in the linked issue.

Make sure you have the Redirect 404 module enabled, visit /admin/config/search/redirect/settings, and select the Suppress 'page not found' log messages option.

That will stop 404s being logged.


How to handle the cache per user in REST Resource? I have a requirement to expose a specific content type data via REST end point. Below is my code:

public function get() {
    $current_user = $this->currentUser->id();
    $user = $this->entityTypeManager->getStorage('user')->load($current_user);
    $userLangId = $user->language()->getId();

    // You must to implement the logic of your REST Resource here.
    // Use current user after pass authentication to validate access.
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }
    $news_values = [
      'langcode' => $userLangId,
      'type' => ['story'],
      'status' => 1,
    ];
    $news_data = $this->entityTypeManager->getStorage('node')->loadByProperties($news_values);
    $newsfeed = [];
    $newsfeed['stories'] = ['Story' => array_values($news_data)];
    if (empty($newsfeed)) {
      return new ResourceResponse('No Newsfeed exist for this user.', 400);
    }
    $response = new ResourceResponse($newsfeed, 200);
//    $response->addCacheableDependency($current_user);

    $response->addCacheableDependency(CacheableMetadata::createFromRenderArray([
      '#cache' => [
        'context' => ['user.roles'],
        'tags' => ['user:3', 'languages:' . $userLangId],
      ],
    ]));
    return $response;
  }

I am getting a proper response with this but I am facing issues in handling the cache.
This content is user specific. Based on user language content will popup when they access.

In Response Headers I am getting below things:

X-Drupal-Cache-Contexts: languages:language_interface theme url.site user.permissions
X-Drupal-Cache-Tags: config:filter.format.basic_html config:rest.resource.newsfeed_rest_resource config:rest.settings config:system.site http_response languages:fr node:7 node:9 user:3
X-Drupal-Dynamic-Cache: MISS/HIT

In Cache-tags i have not added node key but its automatically coming and its working once node updated. But if i try to login with different user via basic auth on postman client, content is not changing at all. Its showing cached content for previous user. How I can cache the content per user. Please help me in this regard.

@Leigh is right and user does exist. Cache contexts are hierarchical (see change record https://www.drupal.org/node/2451661) and user is a top level context.

So this should work (note the plural form of contexts):

  '#cache' => [
    'contexts' => ['user'],

You can also add the cache context by IDE autocompleting:

$response->getCacheableMetadata()->addCacheContexts(['user']);


Help with dynamic page cache I have a page generated by a custom module that contains two sections:

Product info
Recently viewed products

The product info only changes when the product is updated.

Recently viewed products are unique to every visitor (data is stored in $_SESSION).

Each section has its own render array.

'productinfo' => [
    // ...
    '#cache' => [
        'tags' => ['product:1234']
    ]
],
'recentlyviewed' => [
    // ...
    '#lazy_builder' => array(
      // ....
    ),
    '#create_placeholder' => TRUE,
    '#cache' => [
        'max-age' => 0
    ]
]

The behaviour I expect is that the dynamic page cache can cache the productinfo section, but the recentlyviewed would never be cached. However, if a session has not yet been started (i.e. first page view), the entire html page is cached to the cache_render DB table, and cache_dynamic_page_cache is always empty.

The X-Drupal-Dynamic-Cache header is always set to UNCACHABLE.

How can I get the dynamic page cache to cache the product info section?

Your question has two different topics:

  How can I get the dynamic page cache to cache the product info
  section?

Set cache keys:

'productinfo' => [
    // ...
    '#cache' => [
        'keys' => ['mymodule', 'product', '1234'],
        'tags' => ['product:1234'],
    ],
],

Sections of a render array are only cached, if they have cache keys. The keys are used to build the unique cid for the cache render table.

  However, if a session has not yet been started (i.e. first page view),
  the entire html page is cached

Anonymous traffic is cached by the Internal Page Cache. If you start a session, the next request will be able to pass the Internal Page Cache and is handled by the Dynamic Page Cache.


Field for additional charge the drupal / drupal commerce way What is the canonical drupal commerce way of storing data for say something like an additional charge?

Would it be a price field / text field / Line item field?

I would like the field to store data like this:

label: color charges
desc: field stores the additional amount for a color foobar product
number of values: 1

example value: 0.75

You don't make the use case very clear, but sounds like you could use some of the existing price fields, fx unit price on product line items, but simple add the price with a custom component. That way the price would be viewable in the order overview, but when seeing the product cost you get the simple and correct value of $ x.xx.


Programmatically load 'add content' form for custom content type in form or block plugin I understand that users could use 'add content' from the admin menu, but I'm building a custom block plugin or form so the add content form can be displayed in a block on the page instead of requiring users to use an actual admin page. I've done this before by manually creating forms in a render array in a form plugin that save the field values into a node upon form submit, but it'd nice to actually be able to just grab the actual add node form and render it directly.

In my research I found code to do this for Drupal 7

module_load_include('inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'yourContentType';
$node_form->language = LANGUAGE_NONE;
$form = drupal_get_form('yourContentType_node_form', $node_form);
return $form;

But I need a way to do this in Drupal 8.
I've loaded custom form controllers before like so

$content = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm');

But I'm not sure how I would add a specific 'add content' form. How would I get the form of any 'add content' for a specific content type?

UPDATE: I found a path to something called 'NodeForm' and I tried to use it like so

$content = \Drupal::formBuilder()->getForm('Drupal\node\NodeForm\publication');

Where publication was a content type I wanted to load the form for. But I receive an error

  The form argument Drupal\node\NodeForm\publication is not a valid form

And out of curiosity I tried

$content = \Drupal::formBuilder()->getForm('Drupal\node\NodeForm');

But that gives me the error

  Fatal error: Call to a member function getEntityTypeId() on null in /Library/WebServer/Documents/aaep/web/core/lib/Drupal/Core/Entity/EntityForm.php on line 77

Entity forms are built by EntityFormBuilder::getForm(). The parameter is an entity not a form class. This can be an existing entity or a new entity to add content.

For example to add content for the content type article you create this entity:

$node = \Drupal\node\Entity\Node::create(['type' => 'article']);

Use the new entity to build the form:

$form = \Drupal::service('entity.form_builder')->getForm($node);


How to scp one file to remote using drush? I'd like to send one file to remote host which is defined as alias in drush.

The file is actually private ssh key, so it needs to be placed in ~/.ssh.

I've tried the following command:

drush -v rsync conf/my_rsa @remote:~/.ssh/

but then it's saying:

You will destroy data from drush@remote:'/var/www/~/.ssh/'

I don't want to destroy any existing data in my ~/.ssh.

Any workaround to that?

I've found the following workaround useful:

cat my_rsa | drush @remote ssh "cat > ~/.ssh/my_rsa"

It'll send content of the file directly via ssh into the file.


In which step in the checkout process is an user account is created? I'm using Commerce Kickstart (Drupal 7.23, Kickstart 7.x-2.9). New commerce orders are linked to user accounts. If an account with the same email address does not exist yet, a new account is created. This is the normal flow.

I would like to know in which part of the checkout process, that account is created or linked to, because I've found some cases where the commerce order is linked to anonymous user with no reason.

This happens in Commerce Checkout through Rules.

Rule commerce_checkout_order_convert will check the order's given mail against existing users and automatically assign it.
Rule commerce_checkout_new_account creates a new account if the mail given doesn't match a user.

See the rule "Create a new account for an anonymous order". It creates a new user based off of the mail provided by the anonymous user during checkout.


is there any module which gives domain list as content type field we are using domain access. we need to add domain list as a field to one content type so based on that result we need to display the result on main domain itself. is there any field module for it?
Thanks.

That feature has been developed for the pending Drupal 8 release https://drupal.org/node/1917780 but is yet to be available for D7 (afaik)


Can't create node programmatically I have this code

<?php
      $node = (object) array(

        'title' => 'Title',

        'body' => array(

          LANGUAGE_NONE => array(

            0 => array(

              'value' => 'Body Text',

              'summary' => 'Summary',

              'format' => 'filtered_html',
            )
          ),
        ),

        'type' => 'article',
        'language' => LANGUAGE_NONE,

        'uid' => 1,
      );

      node_object_prepare($node);

      $filepath = drupal_realpath('http://ppcdn.500px.org/52335278/cbc55dab399a4bd9caf7a27e9bb3564bc8458f65/3.jpg');

      $file = (object) array(
        'uid' => 1,
        'uri' => $filepath,
        'filemime' => file_get_mimetype($filepath),
        'status' => 1,
      );

      $file = file_copy($file, 'public://');

      $node->field_image[LANGUAGE_NONE][0] = (array)$file;

      node_save((object) $node);

      $path['alias'] = 'our-great-dsk-node';
      $path['source'] = 'node/' . $node->nid;
      $path['language'] = LANGUAGE_NONE;
      path_save($path);

      cache_clear_all();
    ?>

But can't understand where to use this code to create nodes programmatically in drupal 7 or how to use this code? To test i saved this as custom-posts.php in drupal root directory to see if this code works or not, but it gives a lot errors, so what to include?

To bootstrap, try adding the following lines of code to the top of your custom-posts.php file:

$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
define('DRUPAL_ROOT', '/var/www/drupal7');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Don't forget to update the path to your Drupal root folder.


HTML: formatting instead of WYSIWYG I personally tend to hate WYSIWYG editors. They take time to load and just love plain old HTML, so I just disable the editor entirely. However, I would like to have HTML from the database to be prettyfied or beautified or ... well, loooking sexy for the time of editing with indents, newlines, etc. Any module out there that does that?

You're looking for HTML Tidy module.

  This module tidies Drupal's HTML output with HTML Tidy by optionally
  sanitizing it when it is saved or when it is displayed, like a
  traditional input formatter. Missing and mis-ordered tag components
  are replaced and reordered automatically so that user input doesn't
  break site structure with open tags and the like.

  User interface configuration supports:

  Code indenting: Automatically format HTML for easier reading, or strip
  indenting for proper parsing and display in the less compliant
  browsers. Word wrapping: Automatically wrap lines in an intelligent
  fashion once they get to a specified length Info/Warning/Error
  information: Optionally appended to pages and includes details about
  the wrong HTML attributes and W3C validation info.


Why is doing KernelTests Code Coverage so slow? In my D8 project I have Unit and Kernel tests.
Running them (via CLI) without "--coverage-html" is fine.
Unit tests in general are ~300ms, Kernels are around 3s (of course based on the size of dependencies and the amount of the test cases).

But when I also want to have code coverage Unit tests are fast as usual but Kernel tests are incredible slow (10-20 minutes).

I started to use filters and whitelisting in the phpunit config file, but that affects only the result (the generated coverage files) but not the speed, which makes the impression that PHPUnit also loops through the Kernel Dependencies (such as core files).

Has anyone met this problem before? What can cause it?

Here is my filtering options:

<filter>
    <whitelist>
        <directory suffix=".php">./web/modules/custom/test_module</directory>
    </whitelist>
</filter>

A kernel tests actually installs Drupal (in-memory only, but still), that means it runs thounsands and thousands of lines of code.

You can't really do anything to change that, xdebug (I guess you use that) would actually have to support a native whitelist to keep the overhead minimal, but that would in turn also result in overhead.


Show available languages, but remove "Language Undefined" I want to show the available languages, that works, but how can I hide the "Language: undefined" text if "language neutral" is selected.

Thx,
Andi

I know I'm not answering the question directly, but you can disabled 'Language Neutral' (and other languages) on a per-content type basis using Disable "Language neutral".


View to show changes in node titles In Drupal 7, I have a content type with revisioning turned on.

Is it possible to create a view that shows only nodes that have had the title changed?

Newest Title | Previous Title | Updated Date

You probably can't get 100% exactly what you want but you can get very close.  The problem is that we don't have a definitive history of the order in which revisions were created or edited.  You may be able to make some assumptions if, for example, you know that you always force the creation of a new revision any time an edit is made, but I don't know enough of your business logic to speak to that.  Regardless, I can get you most of the way there and build a view that shows nodes that currently have a title that differs from other revisions of the same node.

In my solution, you can end up with the following fields (amongst others):

Current Title
Previous title
Date previously-titled-revision was last updated
Date currently-titled revision was last updated

First, create a view based on Node Revisions.

When you do this I believe your view will, by default, have a relationship to the node table based on the vid.  It will be called "Content revision: Content".  You want to remove this.  There's another, identically named relationship that you actually want to add instead; it has a description that reads "Content revision: Content, The revision NID of the content revision."  Add that relationship.

After doing this you may find that you need to click on and re-save the settings for the "status" filter on the view as it will be set to use the old relationship. Or, if you want to see all nodes (even those that are un-published) just remove this filter entirely.

Now, add 2 fields to your view:

Content Revision: Title -- this one probably already exists as it's added by default.  This is the title of the revision and can be considered "previous title" for your use-case.
Content: Title (this will use the relationship we just created) -- this is the title of whatever the "current" revision of the node is.  This can be considered "current title" for your use-case.

At this point, you should be seeing a list of all revisions of all nodes, regardless of whether the title has ever changed.  To limit the view to only show those where the title has changed we need to add a new filter called Global: Fields comparison.  Configure the filter such that the "Left Field" is set to "Content revision: Title" and the "Right Field" is set to "Content: Title".  Set the operator to "is not equal to".

Your view should now be more-or-less what you're looking for.  Feel free to add the appropriate date fields, though none of them will be able to tell you exactly when the title itself was changed, per se.

Also note that this will give you one row per different title a node has ever had.  So there may be multiple rows per node.


Colorbox isn't working, although all settings are correct I'm having a bit of an issue over here. I've installed the Colorbox module like it should (install the library & the module, like described in the documentation), the HTML is generated as it should, but the colorbox module doesn't activate at all...

This is the HTML:

but still, I don't see any colorbox...
Is there something I forgot or oversaw on my install?

Try the following with colorbox:

Do you have the latest version? If you updated recently to version from colorbox notice that in the module page says Changes since 7.x-2.1: Important: When updating to this version of the Colorbox module you need to update the Colorbox plugin to v1.3.21.1 or later as well.
Mohammed Shameem mentioned in the comments above is valid. He remark the following: please note that colorbox 1.3.26 and 1.3.27 had an error due to which the script was not working with older version of jQuery so you should download the latest version.

However, the version of colorbox included in the Drupal 7.x colorbox module is NOT STATED.


How to create user with role(s) through REST service? I could able to create a new user by the following JSON format.(Using POSTER add-on to post this data to REST service.)

{
   "name":"user34",
   "pass":"3323",
   "mail":"sample@example.com",
   "status":"1"
}

My question is how to create a user with specific role. I tried with the following JSON format.

{
   "name":"user35",
   "pass":"pwds3",
   "mail":"sample2@example.com",
   "status":"1",
   "roles":{
      "2":"authenticated user",
      "4":"moderator"
   }
}

but the response gives the following error

  ["An illegal choice has been detected. Please contact the site administrator."]

After many trials, I was able to resolve my issue

Here is the JSON format to create user with role.

{
   "name":"user343",
   "pass":"kes35@r4",
   "mail":"user343@sample.com",
   "status":"1",
   "roles":[
      "4"
   ]
}

To assign multiple roles,

{
   "name":"user344",
   "pass":"kes344@r4",
   "mail":"user344@sample.com",
   "status":"1",
   "roles":[
      "3",
      "4"
   ]
}

I hope this helps someone.


Save form when user refreshes page from browser or click on any anchor tag inside page I have made a form in drupal.

What I want is when the browser unload the page from any click whether by clicking on anchor tag or from browser refresh buttons I want to save data of my form through js/ajax or anything possible in drupal.

If any more explanation needed please do ask me. Thanks in advance.

I was trying do this by browser 'unload' event and 'beforeunload' event. But unable to save data of my form because browser doesn't wait for anything writtent inside and just ask for confirmation. Any help will appreciated.

This what I was trying to do:

$(window).bind('beforeunload', function() {
  return 'Do you really want to leave?';
  //coming here instead of it what i want
  //is save the form then return if user says yes and no the don't save the form.
});

You would need to create your own AJAX implementation to achieve this. Upon some trigger, whenever you want that to be, (I would make it save any time a field looses focus), you would perform an AJAX call saving the information into a database. When the user returns, provided they are traceable in some way either through their UID or a valid session, you would fill the form out again with the information from the temporary table in the database. When the user completes the form, let Drupal write the data accordingly. Otherwise, there is no way to save the users information and present it to them again. This method, if the user is registered, would always work. Make sure you add a "clear form" button though so they can clear it if they want.

Update: You could use .unload


Creating an exam system I am trying to create an examination system with Drupal, and I am not sure how to implement it. I can see many ways to do it, but I am not sure which one is the best way to achieve it.

These are the features am looking at:

Users should have the ability to add questions under different subjects.
Users will take test by answering optional answers (radio buttons).
Users can move back and forward between answers and mark for later reviewing.
In the end the result will be shown.
Users can also choose the number of questions they want, and the difficulty level.

What is the best way to achieve this? This is what I am doing.

I added a content type question.
I added options field for answer option and right-optionfield for the right answer.
I added a drop down field for difficulty level.
I created a taxonomy term list for subject and connected with content type.

From here, what is the best thing to do?
Is creating a view page and giving the limit as per page one a good idea? If so how will I give the options of answer as radio/options, or should I create a custom page from module and take the answers using JSON?
What will be the right and easiest way to achieve this?

Maybe you could use the Closed Question module.
You can find more information about the module here.

  Features

  Designed for practicing: students can take as many attempts as they like.
  Many feedback options, feedback can change with attempts.
  Many question types.
  Questions can be added anywhere in a site.
  Only Questions. Ordering questions in a quiz or case is done by a separate module.


Can jquery code be triggered by ajax success? I know that I can add any code inside ajax success like this

$.ajax({
      type: 'GET',
      url: element.href,
      dataType: 'json',
      success: function (data) {
        //mycode

And mycode would be executed after previous script is done. But is it possible that jquery script alone can somehow detect certain ajax success and be triggered only by that?
I posted this question to this forum because drupal uses behaviours which might be helpful with that. But that is my guess only.
Thank you for any clues.

Yes this is possible to track ajax reuests anywhere in code by jQuery alone, there are some Global Ajax Event Handlers in jquery you can use methods from it like:

.ajaxComplete():Register a handler to be called when Ajax requests complete. This is an AjaxEvent.

.ajaxError(): Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.

.ajaxSend(): Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.

.ajaxStart(): Register a handler to be called when the first Ajax request begins. This is an Ajax Event.

.ajaxStop(): Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.

.ajaxSuccess(): Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.

The last one .ajaxSuccess() is what you need.

you can use it like this:

$( document ).ajaxSuccess(function( event, xhr, settings ) {
  if ( settings.url == "ajax/test.html" ) {
    $( ".log" ).text( "Triggered ajaxSuccess handler. The ajax response was: " +
      xhr.responseText );
  }
});


Is it a bad idea for a view to specify nodes by node id? I'm inheriting a project which contains a view that specifies what to include by node id.  This initially strikes me as a terrible idea, but it could be that in Drupal it's not as brittle as it would be if done in other frameworks that I'm more familiar with.

Is this considered an acceptable practice within the Drupal community?  If so, why is this not as dangerous as it sounds to me?

It really depends what the View is for to be honest.

Is the node ID ever likely to change?  Is it something that can't be done with entity view modes instead?

I've had a couple of occasions where I'm filtering a View on a specific node ID, but it's mainly because it's a use case that doesn't really require the massive overhead of something like Display Suite (and I don't use Panels - for no other reason that I don't really like the markup it produces).

If the node ID is GUARANTEED to stay the same, then it might not be disastrous.  However if the node ID is ever likely to change (through content migration for example) then it WILL break.  It also means that the client won't be able to fix it themselves unless you show them how to use Views and give them access to the Views UI.


Change Template for a Content I'm using Drupal (version 7) for the first time and I have two content types, Landing Page and Article Page, each with their own templates page--landing_page.tpl.php and article_page.tpl.php respectively.  The only reason I have two content types is because each content type needs to be displayed differently on the website.

I have several contents of the type Landing Page which I would like to display with the page--article_page.tpl.php template.  So now I have the troublesome task of manually converting each of these content types to Article Page.

Is there a more effective way for a user to select the template he wants to use for a content instead of changing content types?

I ended up using "template suggestions" feature of drupal 7.  Now I only have one content type called Article Page.  I added a custom field to it called field_template, which takes the name of the template i want to use not including the page-- prefix and not including the .tpl.php suffix.  So if field_template has the value 'landingpage', then the template will be 'page--landingpage.tpl.php';

Then in my ~/sites/all/themes/THEMENAME/template.php file, I wrote the following function

function THEMENAME_process_page(&$variables) {
  if (array_key_exists('node', $variables))
  {
        if($variables['node']->field_template['en'][0]['value'])
        {
        $variables['theme_hook_suggestions'] = array('page__'.$variables['node']->field_template['en'][0]['value']);
        }
        else
        $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
  }
}

Replace THEMENAME with the name of your theme.


How to add ShareThis link field into View I have a view and I want to add ShareThis(module enabled) link to each result of the view.
How this can be achieve so that any of the result row of the View will be shared on social networking sites.

Please check images for how to use sharethis filed within views

RESULT PAGE: