How to use owl carousel in custom module? I am trying to call Owl Carousel from a custom module, but despite the short description of how to do that on https://www.drupal.org/node/2412689, can't figure out.

I could use Views, but then I need to call either list of nodes or node fields, but in this case, I have several items which need to be rotated in a variable. I could put them into array if the implementation requires it.

So basically my question is:

Given a list of items in a variable (or array) how can I rotate them using the Owl Carousel module?

Assuming you've an array, you can print the array items one by one in wrapper
 tag, and apply Own Carousel to wrapper
 tag (check owl-demo class in example below). To do this in Drupal, you can process your array in your module to create HTML, and apply JS using drupal_add_js(). To print HTML you can either create a custom block and show on page or create custom page.

Implementing in Drupal with custom module:

function _owl_carousel_demo() {
  $array = array('User 1', 'User 2', 'User 3', 'User 4', 'User 5', 'User 6', 'User 7');
  $output = '
';
  foreach ($array as $value) {
    $output .= '

' . $value . '

';
  }
  $output .= '
';
  $output .= '

    Previous
    Next
    Autoplay
    Stop

';

  drupal_add_css('http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.css', 'external');
  drupal_add_js('http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.js', 'external');
  drupal_add_js('jQuery(document).ready(function() {
      var owl = jQuery("#owl-demo");
      owl.owlCarousel({
        items : 4,
      });
    });', 'inline');

  return $output;
}

Below example shows complete HTML:

    <link href="http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.css" rel="stylesheet">
    <link href="http://owlgraphic.com/owlcarousel/owl-carousel/owl.theme.css" rel="stylesheet">

    <?php $array = array('User 1', 'User 2', 'User 3', 'User 4', 'User 5', 'User 6', 'User 7'); ?>

              <?php foreach ($array as $value) : ?>

<?php echo $value; ?>

              <?php endforeach; ?>

              Previous
              Next
              Autoplay
              Stop


Form submission not working in template file While theming form in template file I used drupal_render to print selected fields of form. But after hit submit button, data is not saving, means submit button is not working.

I know one solution is to use drupal_render_children but it is giving me every child of form, means I'm getting all of the elements of form.

I don't want form's each and every element.

Only selected fields should get rendered.

Any way to print form selected field elements in tpl file with a working submit button?

You can render form specific form elements with the help of drupal_render. And in order to make submit button work, render all hidden form items and your submit button will work fine then.

Necessary fields for form submission are:

echo drupal_render($form['form_build_id']);
echo drupal_render($form['form_token']);
echo drupal_render($form['form_id']);

and ofcourse your submit button too.


Updating Views Module Not Working 7.x-3.13 --> 7.x-3.15 Drupal has been telling me to update my views module from 7.x-3.13 to 7.x-3.15.

Everything seems to work fine. However, when I return to the admin pages, I receive "No update information available. Run cron or check manually." I proceed to run cron and Drupal simply tells me that I need to update the module again.

I've manually updated to the newest version (7.x-3.15) and even to the dev version (7.x-3.x-dev). In both cases, Drupal continued to tell me I needed to update the module.

Any ideas what's going on?

I checked Views module versions from 7.x-3.13 to 7.x-3.15 and it seems that there are no changes needed to be applied to the database (the views.install file didn't change between the two versions). I think you need just to override the module directory with the new version and clear all caches.


Why does my Quiz rule stop working after adding an extra user profile condition? I have a Drupal 7 site, that uses Rules and Quiz.
I have a rule that adds a role after the user takes a specific quiz, which
work fine. Here are the details of it:

Event

After updating existing content
Conditions

Content is of type

Parameter: Contenido: [node], Content types: Cuestionario

Data comparison

Parameter: Data to compare: [node:nid], Data value: 1985
Actions

Add user role

Parameter: Usuario: [site:current-user], Roles: nivel2

Now I want a similar rule but add the new role only if a specific profile field in the user's profile, has specific content. The field is a selection of certain terms of a certain taxonomy.

So, I've cloned the above (working) rule, and added to it a condition. So that this new rule looks like so:

Event

After updating existing content
Conditions

Data comparison

Parameter: Data to compare: [site:current-user:profile-profile:field-ubicacion, Data value: Provincia de Chaco

Content is of type

Parameter: Contenido: [node], Content types: Cuestionario

Data comparison

Parameter: Data to compare: [node:nid], Data value: 1985
Actions

Add user role

Parameter: Usuario: [site:current-user], Roles: nivel2

Now in this case, this new rule won't work. I.e the role is not added.

Why could this be?

Make sure to add a Rules condition Entity has field (related to your additional field in your first Rules condition). And make sure to add that Entity has field condition BEFORE the condition in which you want to perform that "data to compare".

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


How to have #description in form to be below title and above field? How can I place Description below Title and above field ?

 $form['term-selection']['autocomplete'] = array(
      '#title' => variable_get('autocomplete_sync_shs_autocomplete_headline',t('Type in directly')),
      '#description' => variable_get('autocomplete_sync_shs_autocomplete_info',t('')),
      '#type' => 'textfield',
      '#autocomplete_path' => 'third-level-auto-suggest/autocomplete-taxonomy-term/'.$field_name.'/'.$entity_type.'/' . $node_type ,
      '#states' => array(
         'disabled' => array(
           ':input[name="widget-selection"]' => array('value' => 1 ),
         ),
      ),
      '#default_value' => $default_autocomplete,
    );

The output I get is

User #after_build at the end of your hook_form_alter.

$form['#after_build'][] = 'MODULE_NAME_move_description_up_after_build';

See below function to move the description in between the title and field.

/**
 * build function
 * @param type $form
 * @param type $form_state
 * @return type
 */
function MODULE_NAME_move_description_up_after_build($form, $form_state) {
  drupal_add_js('jQuery(document).ready(function ($) {
    $("label ~ div.description").each(function(index, element) {
      $(this).insertBefore($(this).prev("input"));
    });
  });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

  return $form;
}


Undo to Taxonomy term system path unset with _menu_alter I have a question about taxonomy term system path.
I have run this code:

function MYMODULE_menu_alter(&$items) {
  unset($items['taxonomy/term/%taxonomy_term']);
  unset($items['taxonomy/term/%taxonomy_term/view']);
  unset($items['taxonomy/term/%taxonomy_term/feed']); // If you want to hide the feed as well.
}

Now I want to know how to reverse this for the future need. How can I set system paths for all taxonomy terms.
Thanks in advance.

edit:

Hi David

In first place I have a problem how to forbid anonymous access to all taxonomy terms (eg. mysite/vocabulary/term). I don't want anonymous user to see this pages. I was searching for answer whole day and I found the alter_menu snippet as the only suitable answer, because for now I don't need terms links from outside world.

So, if I put this script in custom module and run once it clears all system paths for all taxonomy tearms (as it can be seen from admin/URl aliases/list). This is good solution, but I don't think the best one. I need a proof that in the future if I will need this system paths, I can rebuild them. I don't know how to do it!?

I have tried to comment that hook_menu_alter snippet but what next I have to do. I mean, system paths will not be automatically rebuilded. Am I right?

Also, i didn't find suitable module to control access to taxonomy terms from outside for anonymous users. Some modules can control that, but my site is using terms thru views and with that modules views are also invisible for anonymous users (eg. Taxonomy Tools module, access part).

The question is a little unclear, to reverse that effect, you would simply delete that hook_menu_alter snippet.

To change the paths to something else, you would use hook_menu and create the relevant menu callbacks.

The last step there would be to change the taxonomy_term entity_uri so it uses your new callback.

i.e redefine taxonomy_term_uri in hook_entity_info_alter

/**
 * Implements hook_entity_info_alter
 */
function mymodule_entity_info_alter(&entity_info){
  $entity_info['taxonomy_term']['uri callback'] = 'mymodule_taxonomy_term_uri';
}

/**
 * Custom taxonomy_term entity_uri callback
 */
function mymodule_taxonomy_term_uri($term){
  return array(
    'path' => 'mymodule/taxonomy/term/' . $term->tid,
  );
}

Not sure why you'd want to do that though ;)

edit: If you want to deny access, better to use hook_menu_alter to add your own access callback to the taxonomy menu paths. Alternatively, override the path with Panels or Views and set access control there.


Display the results of a form submit on the same page just under the form I have created a form and it takes in 3 values which are Brand, Item and Zipcode. The values are queried and the results are fetched the database table. I want the results to be shown in a table

function form_example_form_submit($form, &$form_state) {
$sql3 = /*my select query*/

$result = db_query($sql3);
$records = $result->fetchAll();

//code to display table

 echo "
";
   echo"
";
    echo"Retail Accounts	";
    echo"Address	";
    echo"City	";
    echo"State	";
   echo "
";
   foreach ($records as $record) {
    $record     = get_object_vars($record);
    echo "
";
      echo "";
        echo $record['Retail Accounts'];
      echo "	";
      echo "";
        echo $record['ADDR'];
      echo "	";
      echo "";
        echo $record['CITY'];
      echo "	";
      echo "";
        echo $record['STATE'];
      echo "	";
    echo"
";
}
echo "
";
}

The result is properly fetched but not displayed on the page.

I tried $form_state['rebuild'] = TRUE; but it displays the result on top of the page.

I want the result to be visible just below my form. How can I achieve that?

Any help is very much appreciated. Thanks in advance.

As suggested in the comment the SQl query were made on the hook_form and the hook_form_submit contains only the $form_state['rebuild'] = TRUE;. Detailed code is as follows:

function form_example_form($form, &$form_state) {

//your form fields or items

$form['submit_button'] = array(
 '#type' => 'submit',
 '#prefix' => '
',
 '#suffix' => '
',
 '#value' => t('Find my store'),
 '#attributes' => array('class' => array('btn btn-primary')),
);

/*-----Query database code Start--------*/

if(isset($form_state['values']['item-name'])){
  //get the values to variable
}

if(isset($zip_code)){

//setup the sql query

if(isset($sql3)){
  $result = db_query($sql3);
}
$records = $result->fetchAll();
$tot_records = count($records);
}

if(isset($tot_records)){
 if($tot_records>0){

  $form['result_table'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#markup' => '
Store Name	Address	City	State
',
  );

  $i=0; $j=0;
  foreach ($records as $record) {

    $record_in_array = json_decode(json_encode($records[$i]), true); //Convert object to array

    $form[$j]['result_table1']= array(
      '#type' => 'markup',
      '#markup' => '
',
    );

    $form[$j]['result_table2']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name1'],
    );
    $form[$j]['result_table3']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name2'],
    );
    $form[$j]['result_table4']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name3'],
    );
    $form[$j]['result_table5']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name4'],
    );

    $form[$j]['result_table6']= array(
      '#type' => 'markup',
      '#markup' => '
',
    );

    $i++;
    $j++;
  }

  $form['result_table7']= array(
    '#type' => 'markup',
    '#suffix' => '
',
  );

  }
 }

/*-----End Query database code--------*/

return $form;

 }

 function form_example_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
 }

Hope this helps!


Button with Drupal Behavior jQuery Conflicting with AJAX 'Add More' Button on Unlimited Cardinality Field I have a form with an unlimited cardinality field that creates an 'Add more' button to add more fields. I also have a separate pair of fields. One of these fields has a value prepopulated on starting a new form, the other field is another unlimited cardinality field with an 'Add more' button & is blank on page load. I have attached a Drupal Behavior jQuery function to a button that I have added in a custom module with hook_form_alter: this jQuery sets the value of the second of the pair of fields to the value of the first when the custom button is clicked. This works. And the 'Add More' buttons for the unlimited cardinality fields work as well. However, after the custom button has been clicked once, the 'Add More' button will no longer create a new field, & I get the following errors in my logs:

Apr 25 02:56:36 lucifer drupal: https://somesite.com|1366880196|php|111.111.111.111|https://somesite.com/system/ajax|https://somesite.com/node/add/inventory-stocking-ticket|1||Warning: implode(): Invalid arguments passed in form_error() (line 1649 of /hosting/somesite/com/htdocs/cms_sandbox/includes/form.inc).

Apr 25 02:56:41 lucifer drupal: https://somesite.com|1366880201|php|111.111.111.111|https://somesite.com/system/ajax|https://somesite.com/node/add/inventory-stocking-ticket|1||Notice: Undefined index: #ajax in ajax_form_callback() (line 379 of /hosting/somesite/com/htdocs/cms_sandbox/includes/ajax.inc).

Here is my code for the custom button:

$form['field_ending_weight_garbage']['und']['garbage_no_change'] = array(
  '#type' => 'button',
  '#value' => t('No Change'),
  '#attributes' => array('onclick' => 'return (false);'),
  '#name' => 'garbagenochange',
);

And the code for the behavior:

(function ($) {
  Drupal.behaviors.noChange = {
    attach: function (context, settings) {
     $('#edit-field-ending-weight-garbage-und-garbage-no-change').once('noChange', function() {
      $('#edit-field-ending-weight-garbage-und-garbage-no-change', context).click(function () {
     var a = $('#edit-field-starting-weight-garbage-und-0-value').val();
     var b = $('#edit-field-ending-weight-garbage-und-0-value').val();
     if (b == "")
     {
       $('#edit-field-ending-weight-garbage-und-0-value').val( a );
     }
     else
     {
       $('#edit-field-ending-weight-garbage-und-0-value').select();
     }
        return false;
      });
    });
   }
  };
}(jQuery));

Which is attached in an after_build function like so:

drupal_add_js(drupal_get_path('theme', 'corolla').'/js/inventoryNoChange.js');

I'm using jQuery 1.5 by means of jQuery Update module, uncompressed. What could be causing this?

Edit: I've managed to eliminate the first error by adding the custom button like this:

$form['field_starting_weight_garbage']['und'][0]['garbage_no_change'] = array(
  '#type' => 'button',
  '#value' => t('No Change'),
  '#attributes' => array('onclick' => 'return (false);'),
    '#limit_validation_errors' => array(),
  '#name' => 'garbagenochange',
);

So, it's on the first field in the pair rather than the second, & it's at $form['field_starting_weight_garbage']['und'][0]['garbage_no_change'] rather than $form['field_starting_weight_garbage']['und']['garbage_no_change'].

But the ajax error persists, & the 'Add Another' functionality is still broken. I should note that it only throws the error & fails seemingly randomly. I can add several extra fields with the 'Add Another' button, but then it breaks, throws the error, & won't add more fields.

I've determined that it is not the Behavior/jQuery that is breaking things. Simply adding the custom button with no behavior attached to it causes the problem. Still hoping someone can shed some light on this.

So I went with a different approach to achieve the same thing. Instead of adding a button using the '#button' or '#submit' property in hook_form_alter, which was causing the conflict, I added a button with the following code:

$form['field_starting_weight_garbage']['und'][0]['value']['#prefix'] = '<div>';
$form['field_starting_weight_garbage']['und'][0]['value']['#suffix'] = '<input type="submit" value="No Change" class="form-submit" id="garbagenochange"></div>';

& adjusted the Drupal Behavior to attach to this element (id="garbagenochange").

I still don't know exactly what was causing the conflict or how to fix it, but this does what I need, so I'll go this route.


Add Taxonomy Term automatically based on term from user's account I have a vocab called "state of residence" with states in the form of TN, MS, AL, etc. Each user account has one of these references to show the state of residence. I can also place this taxonomy field on a forum post. But how can I make the post pull the "state of residence" term from the account of the user who has created it? I don't want the user to have to choose. I want the choice to be made automatically based on the user's account.

Or is there a better way than a vocab. Basically, I am trying to allow content to be sorted by the geography of the user who created the post. and I don't want the user to have to make the choice.

This sort of thing is generally handled through contextual filters in your view. Views, Panels and Page Manager work well together to manage passing contextual filters to a view for filtered output, but there is a bit of a learning curve involved.

I'm not generally one for video tutorials, but I found this one to be a good introduction to this methodology: http://drupalize.me/videos/overview-page-manager-series

If you want a quick-and-dirty way to achieve this, use the module views_field_view https://drupal.org/project/views_field_view and do something like this:

in your forum posting view, set a contextual filter on your state term reference field tid
create a new view based on users, and add a contextual filter on "User: Uid"
on the contextual filter configuration page, under "when the filter value is not available" select "provide default value"
under type, select user id from logged in user
add a field for the state term reference field tid
add a field Global:View ( provided by the views_field_view module ), with these settings:
View: your forum postings view, as modified with contextual filter above
Display: Master
Contextual filter: [tid]

This should now display all forum postings whose state of residence matches the currently logged in user's state of residence.

note that if you are on a page URL that points to a profile of a different user, and you've set it up so the view is visible on this page, it will show all postings for THAT user, as the view will be able to grab a uid from the URL. ... so ... that may be a benefit or a drawback, depending on your intent.

Best'o'luck

disclaimer: written on short sleep. hope i got all the i's dotted and t's crossed


Is Webform using datepicker.js? I am trying to create an alert when a date is selected that falls within 30 days of today using the following script:

(function ($) {
  $('#edit-select-date').datepicker({

    onSelect: function () {
      var date = $(this).datepicker('getDate');
      var today = new Date();

      if ((new Date(today.getFullYear(), today.getMonth(), today.getDate() + 30)) > date) {
        // Do something here.
        alert(123);
      }
    }
  });
}(jQuery));

Unfortunately this is not working and am getting a $(...).datepicker is not a function in dev console. If datepicker.js is not being used is there a way I can have an alert trigger when the date select is +30 days from today?

Webform provides a fieldable form entity type. And when you add a date field to it (you didn't specify what date field exactly, core, contrib, custom), this date field may make use of a datepicker library.

Speaking of core it most likely is core's core/jquery.ui.datepicker library. Which is used for #type => 'date' form elements for example.

When you in your custom script want to make use of this datepicker library you need to add it as a dependency. Same as core does:

drupal.date:
  version: VERSION
  js:
    misc/date.js: {}
  dependencies:
    - core/drupal
    - core/modernizr
    - core/jquery.once
    - core/jquery.ui.datepicker

See https://git.drupalcode.org/project/drupal/blob/8.8.x/core/core.libraries.yml#L142-150.

And maybe you also make your JavaScript look more like in the examples in the docs.


Migrate is putting map tables in legacy database I'm getting some really strange behavior with my custom migration class where the map tables are all being put into the legacy (6) database rather than the destination (7) database.  This happens for all of my custom migration classes and not the ones using d2d.  I believe it has something to do with my $this->map in the migrations with the final argument being 'legacy' or possibly it's the $query = Database::getConnection('default', 'legacy') part of the migration.

My custom class for term migration does import the data into the new site from the old correctly, but the map tables are still going to the legacy database.

I've found a few sources of others having issues getting multiple databases to work in a migration but they seem to be conflicting with each other.

Here is my class:

class myUserProfileMigration extends myMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->arguments = $arguments;

    $this->description = t('My User Profiles Migration');

    $dependencies = array(
      'User'
    );

    $this->dependencies = $dependencies;

    $query = Database::getConnection('default', 'legacy')
          ->select('node', 'n');
    $query->condition('n.type', 'person_profile_page', '=');
    $query->join('users', 'u', 'u.uid = n.uid');
    $query->fields('u', array('name', 'uid'));
    $query->fields('n', array('uid', 'nid'));
    $query->join('content_type_person_profile_page', 'p', 'p.nid = n.nid');
    $query->fields('p', array(
      'field_about_me_value',
      'field_likes_value',
      'field_dislikes_value',
      'field_google_plus_value',
      'field_twitter_handle_value',
    ));

    $this->source = new MigrateSourceSQL($query);

    $this->destination = new MigrateDestinationUser();

    $this->addFieldMapping('uid', 'uid')
         ->sourceMigration('User');
    $this->addFieldMapping('field_likes', 'field_likes_value');
    $this->addFieldMapping('field_dislikes', 'field_dislikes_value');
    $this->addFieldMapping('field_about_me', 'field_about_me_value');
    $this->addFieldMapping('field_about_me:format')
         ->defaultValue('filtered_html');
    $this->addFieldMapping('field_google_id', 'field_google_plus_value');
    $this->addFieldMapping('field_twitter_handle', 'field_twitter_handle_value');

    $source_key = array(
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'Original Author UID',
        'alias' => 'n',
      )
    );
    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationUser::getKeySchema(), 'legacy');

  }

}

And here is my settings.local.php:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dest_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'legacy' =>
  array(
    'default' =>
    array(
      'database' => 'legacy_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Read up on the documentation on Map Tables under the heading Map Tables on that page. If you define legacy as the connection to make the map tables on -- then that's where they will go.

  When you construct the MigrateSQLMap object, add a fourth argument to
  tell it explicitly the connection on which to create the mapping
  tables.


Ajax on a webform affecting comment form and user-registration form I have Ajaxified a webform using a (hook) custom module. The code used is:
 function alterwebform_form_alter(&$form, &$form_state, $form_id) {

    //see if webform_client_form_ is in the form_id

    if(strstr($form_id, 'webform_client_form_')) {

      //get the nid so we can use it in the wrapper value

       $nid = $form['#node']->nid;

        $form['actions']['submit']['#ajax'] = array(
            'callback' => 'alterwebform_webform_js_submit',
            'wrapper' => 'webform-client-form-' . $nid,
            'method' => 'replace',
            'effect' => 'fade',
     );

  $form['#validate'] []='alterwebform_test';
      }
    }

The code in the callback function is:
function alterwebform_webform_js_submit(&$form, &$form_state, $form_id) {

  // define the $sid variable (submission id from webform)
    $sid = $form_state['values']['details']['sid'];

 // sid to know the form was properly submitted

    if ($sid) {

  //load up the webform node object

     $node = node_load($form_state['values']['details']['nid']);

  //create an array with the confirmation message of webform
        $confirmation = array(
                 '#type' => 'markup',
                 '#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
                     );

  // return the confirmation message
    return $confirmation;
    }
  else {
   // return the form
       return $form;
        }
    }

The web-form works fine . The problem is: The AJAX code above is affecting other forms (Comments form and User Register form).

How is it affecting ?

If other (comment and user-register) forms are submitted successfully in the first time then its fine. But if there is some error in the first time and we submit second time, then  click on submit does not perform any action but show ajax effect.
The click on submit button now shows ajax kind of affect but is without any action.

As you can see in the picture, the ajax affect comes in this form. This happens if someone is clicking the button the second time (because of some error on first time).
What could be the possible reason for this and how should I fix this? Thank you in advance.

The problem can be that ajax functionality is attached to button by its id attribute. Seems all three buttons - for webform, comment and user-register have the same id "edit-submit".

To fix this - just add unique id for webform submit button.

function alterwebform_form_alter(&$form, &$form_state, $form_id) {

//see if webform_client_form_ is in the form_id
if(strstr($form_id, 'webform_client_form_')) {

  //get the nid so we can use it in the wrapper value
   $nid = $form['#node']->nid;

    $form['actions']['submit']['#ajax'] = array(
        'callback' => 'alterwebform_webform_js_submit',
        'wrapper' => 'webform-client-form-' . $nid,
        'method' => 'replace',
        'effect' => 'fade',

    );
    // Add unique id for submit button.
    $form['actions']['submit']['#id'] = 'webform-client-form-submit-' . $nid;

    $form['#validate'] []='alterwebform_test';
  }
}


Importing large content with Feeds and cron I've used the migrate module in the past, it's great to import large amounts of content but it's pretty complex.
This time I'm trying Feeds and Feeds_SQL to import from a mysql tables. It imports fine when I kick it off with the import UI. However it will give an Ajax error after importing a few hundred records.

I try to import using cron. That's where it gets confusing to me:

I select "periodic import" -> "as often as possible", uncheck "import on submission" and check "process in the background".

I then start the import using the UI, it imports some nodes and then stops.

When I manually run "feeds_cron" nothing happens. When I manually run "job_scheduler_con" it showed "Finished processing scheduled jobs (0 sec s, 1 total, 0 failed)." in teh logs and imported more records (but not all).
When I run it again it shows "Finished processing scheduled jobs (0 sec s, 0 total, 0 failed)." and nothing gets imported.

Do I have the correct settings? How are the "periodic import" setting and the "feeds cron" and "job scheduler cron" related?

Is there a setting somewhere that controls how many nodes are processed each time?

Are you running the actual site cron? If not, run it.

As for the Ajax errors when running a manual import, are you sure that it isn't continuing to import despite these? My large imports will time out the browser connection when I manually import in feeds, but they will actually still continue to process.

Also, could you try changing your setting from "As often as possible" to "Every 30 minutes", to ensure the crons aren't running over each other?


Front page link token in full HTML? When Im using the full html input format. Is there a way I can use some code to print the url of the front page of my site, so If I were to migrate the site it would still work?

I could do this with pathlogic but im wondering if there is a php type value that full html would use?

Thanks

Front page

But this doesn't respect the base folder. E.g. if your Drupal installation path looks like http://example.com/drupal_site/, this won't help you, because link will lead to http://example.com/.


How to maintain and update a Drupal installation and its modules? I'm looking for a comprehensive tutorial on best practices for updating and maintaining a Drupal installation and it's modules where there are multiple instances of the site, that is having a development instance and a live instance, and methodologies for updating the live site with changes made on the development site, and avoiding database conflicts.

TL;DR

Best practices for updating Drupal and it's modules to newer, more secure versions.
Best practices for mirroring changes made in a development instance of a site to the live instance of the site.

Note: I am using Mercurial to track changes.

I'm not sure about a guide but you will want to look into Features for change management between instances and Drush for updating Drupal and it's modules.

Anything you can't do for the database in features should be placed in an install file and applied as updates to maintain the db between instances.


How do I load a form with a specific form display (form mode)? On a custom page I'm trying to load an user edit form with a specific form display.
I'm able to load the form however I can't figure out how to load the form with the specific display.

This is what I have now:

public function content($substep) {

    $user = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->load(1); // loading user 1 for test purpose

    $form_state = new FormState();

    $form = \Drupal::entityTypeManager()
      ->getFormObject('user', 'default')
      ->setEntity($user);

    return \Drupal::formBuilder()->getForm($form);
}

Anyone has an idea?

In D8 you can add display modes for forms in UI. But these form modes can't be used right away like view modes.

If you want to use a form mode in code you have to set a form operation with the same name in the handlers section of the entity type. The form class you use for this handler is the same as in the default handler, because you want to control which fields are displayed in the form mode, not in a different form class.

For example to use a form mode profile2, which you have configured in UI, you have to add a form operation profile2 to the user entity type definition in a hook_entity_type_build:

mymodule.module

function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('profile2', 'Drupal\user\ProfileForm');
}

Then you can use the new form operation (form mode) in the code example from the question:

public function content($substep) {

  $user = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->load(1); // loading user 1 for test purpose

  $form = \Drupal::entityTypeManager()
    ->getFormObject('user', 'profile2')
    ->setEntity($user);

  return \Drupal::formBuilder()->getForm($form);
}


How to add Google Maps data overlay to Openlayers map? So, for data purposes I want to use OpenLayers for my maps presentation but I want to use Google Maps as my data overlay or base layer. I know this is possible, but the UI isn't exactly friendly to new users.

As always, any advice is appreciated.

If you find OpenLayers for Drupal too daunting you could have a look at https://www.drupal.org/project/leaflet. It's easier to configure and more lightweight.

As for OpenLayers:

Create a view that provides an OpenLayers Data Overlay Display.
Then you may want to checkout: "admin/structure/openlayers/layers" and configure a Google Maps layer.
Then create a map over here "admin/structure/openlayers/maps". Make sure you enable your Google Maps layer as base and your Views Data Overlay as the Overlay for this map.
If you want to "show" the map also with Views create a new display (not an overlay) and use the OpenLayers Map formatter. You can then select your OL map created in step 3.


How to create and check block revisions? How to create and check block revisions ? I can see the option at bottom while creating a block but when I click to see the revisions the link doesn't work.

The revisions checkbox on blocks doesn't do anything yet, in fact I think it may have been removed. Block revisioning is being proposed for Drupal 9's generic revision UI. For the latest, please see this post on Drupal.org.


How to link a custom menu to a custom button in drupalgap? I would like to put the pop-up main_menu written in the setting.js to my custom button. It seems that the path name I use is not correct.

l('Menu', 'main_menu', { attributes: { 'data-icon': 'star' } })

I also tried this and does not successful. The second parameter in l( ) link path is needed.

l('Menu', { attributes: { 'data-icon': 'star' }, popup: true, popup_delta: 'main_menu' })

So, what is the correct path name of the main_menu? or how do I link my custom menu to my custom button or link?

This is how I do my custom popup button:

var btn_setup = theme('popup', {
            content: theme('jqm_item_list', {
                items: [
                  l('View profile', 'user'),
                  l('Login', 'user/login'),
                  l('Logout', 'user/logout')
                ]
            }),
            button_text: 'Setup',
            button_attributes: {
              'data-icon': 'gear'
            }
        });

It does not popup anthing, even I just put a simple content, such as:

content:'
This is a test
'

nothing happen when clicking the button.

After several experiments, the popup function needs to set the page id.

var btn_setup = theme('popup', {
            content: theme('jqm_item_list', {
                items: [
                  l('View profile', 'user'),
                  l('Login', 'user/login'),
                  l('Logout', 'user/logout')
                ]
            }),
            attributes: {
              id: drupalgap_get_page_id() + '_this_page_hook'
            },
            button_text: 'Setup',
            button_attributes: {
              'data-icon': 'gear'
            }
        });

So the question is, when I put this button in the header or footer, I want it display in any page. How do I set the page id for any page?

When put in the header or footer block, just give the page id the block name. Here is the code:

/**
 * Implements hook_block_info().
 */
function footer_intrfc_block_info() {
  var blocks = {};
  blocks['footer_intrfc_block'] = {
    delta: 'footer_intrfc_block',
    module: 'footer_intrfc'
  };
  return blocks;
}

/**
 * Implements hook_block_view().
 */
function footer_intrfc_block_view(delta, region) {

var html = '<div>';
var btn_setup = theme('popup', {
            content: theme('jqm_item_list', {
                items: [
                  l('View profile', 'user'),
                  l('Login', 'user/login'),
                  l('Logout', 'user/logout')
                ]
            }),
            attributes: {
               id: drupalgap_get_page_id() + '_footer_intrfc_block'
            },
            button_text: 'Setup',
            button_attributes: {
              'data-icon': 'gear'
            }
        });
html += btn_setup + '</div>';
return html
}


How to set "Language Selector dropdown" required in node form I want to know How to set "Language Selector Drop-Down " required in node form?

I tried to do this via hook_form_alter, but it seems $form['language'] is not created in this hook !

Is there any hook that let me modify language Drop-Down selector?

I found the solution here

You can enable i18n_node module that is included in i18n module. Then:

    Go to edit the content type (admin/structure/types/manage/page).
    Open the 'Multilingual settings' tab.
    Check the 'Require language' checkbox.

Done.

Multilingual content must be installed at first and then in content type, Multilingual settings tab will be added


On/Off Checkbox to toggle filter value in views exposed filter I am using Better Exposed Filters Module and Has Boyfriend field is Boolean Yes/No field type of the content.

The Current View I have is:

When I click the Yes Checkbox I get:

My quest is when the checkbox is not-checked it'd only display girls without boyfriend like: (please ignore the filters here, I just showed it to explain my question, the filter should not have No, it should be default filter)

I can acheive this with such multiple-checkbox as above but I have the requirements to display only Girls without Boyfriend as default display list. When the checkbox Yes is clicked it'd hide all the Girls without boyfriends and display only Girls who has boyfriend.

There were few similar questions like this when I was searching like This and This but the answers doesn't satisfy my requirements.

Not totally sure if this is the same as your requirements, but I managed to have one checkbox that only shows relevant content when checked.
Basically, I chose these options in filter options:

Expose this filter to visitors, to allow them to change it
Filter type to expose: Single filter
Is one of: (select the 'on' value)
Allow multiple selections (checked)
Limit list to selected items (checked)

Then in BEF:
6. Display exposed filter as: Checkboxes/radio buttons.

So, pretty much the only difference is the selection of "Limit list to selected items" in the filter options. See pic below. (And it doesn't use jquery, so should be more performant) Hope that helps.

.


How can i have a custom theme created by myself for multilingual site? My website uses i8ln and it is configured to work with a large amount of languages. Using the page.tpl.php i managed to translate the website. But i had to create another custom theme for a specific path and the 404 page. So i created a page--node--23.tpl.php file and clear the cache. The file worked since the node i was trying to import the new theme was the node id defined when i created node/23.
Now my problem is that i need to translate node/23 but when i click on translate and click save to save the translation another node is created and hence the page--node--23.tpl.php file is not used. How to set up drupal and able to adjust trasnaltion along with the custom themes???

Theming pages based on node id is not the way to handle this because you will have to copy each template to the corresponding translated nids.
A better approach is to create content types based on differences (which can be different layouts as well).
You can create a content type "404_page" for 404 pages in each language and create a template node--404_page.tpl.php to style them. This is all node specific.

There are also page specific overrides like:

page--front.tpl.php
page--user.tpl.php
page--blog.tpl.php

Edit: Some extra information on Theme hook suggestions can be found on the Drupal 7 Theme Hook Suggestions documentation page.


Don't calculate shipping for specific item I have to types of a same product (used a select list field):

1|Physical
2|Digital
(key|label)

Physical items needs shipping calculated. Digital doesn't.

Problem appears when you add physical and digital item to cart, rules calculate the flat rate shipping to both items. Which is wrong, it should calculate rate to physical and ignore digital product.

I'm thinking it has something to do with data comparison? Am I on the right path? I tried various options/sorting.

Update

My exported rule looks like this now (as per the recommendation in the 1st answer to also use the Conditional Rules module):

{ "rules__1_extra" : {
    "LABEL" : "+1$ extra",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "rules",
      "commerce_line_item",
      "rules_conditional",
      "commerce_shipping"
    ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-line-item:order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "data_calc" : {
                "USING" : { "input_1" : [ "list-item:quantity" ], "op" : "*", "input_2" : "100" },
                "PROVIDE" : { "result" : { "result" : "Calculation result" } }
              }
            },
            { "commerce_line_item_unit_price_add" : {
                "commerce_line_item" : [ "commerce_line_item" ],
                "amount" : [ "result" ],
                "component_name" : "flat_rate_flat_rate",
                "round_mode" : "0"
              }
            }
          ]
        }
      },
      { "commerce_line_item_unit_price_subtract" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "100",
          "component_name" : "flat_rate_flat_rate",
          "round_mode" : "0"
        }
      },
      { "CONDITIONAL" : [] }
    ]
  }
}

From the screenprint of your calculation rule it's hard to tell what exactly the logic is that you implemented (an exported rule, created with the Rules UI, provides ALL the details).

Anyway, it seems that your Rules Loop is adding "an amount to the unit price" for EACH line item, so it doesn't check (within that Rules Loop) if it is "Physical" or "Digital", which explains why for Digital items shipping gets calculated also (which is not what you want).

The easiest way to correct this, is to use the Conditional Rules module to add an extra test (Rules Condition!) within your Rules Loop to NOT calculate shipping for Digital items (AND remove all Rules Conditions starting from the "AND" you added). As a variation (to not have to use this extra module), transform the 2 Rules Actions within your loop to an equivalent Rules Component (by passing the line-item as a parameter), and within that Rules Component add an extra Rules Condition to check ... indeed ... if it is a Physical item.

Update 1

As per the update that was applied to your question (by adding your improved rule using the Conditional Rules module I suggested before), it seems that you've for sure not correctly used that module. Because the CONDITIONAL near the end of your exported rule is NOT supposed to be empty. Therefor have a look at this variation of your exported rule (if needed, just import it in your own setup to look at it with the Rules UI):

{ "rules__1_extra_not_for_digital" : {
    "LABEL" : "+1$ extra not for digital",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "rules_conditional",
      "rules",
      "commerce_line_item",
      "commerce_shipping"
    ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-line-item:order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "product" } },
                  "DO" : [
                    { "data_calc" : {
                        "USING" : { "input_1" : [ "list-item:quantity" ], "op" : "*", "input_2" : "100" },
                        "PROVIDE" : { "result" : { "result" : "Calculation result" } }
                      }
                    },
                    { "commerce_line_item_unit_price_add" : {
                        "commerce_line_item" : [ "commerce_line_item" ],
                        "amount" : [ "result" ],
                        "component_name" : "flat_rate_flat_rate",
                        "round_mode" : "0"
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "commerce_line_item_unit_price_subtract" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "100",
          "component_name" : "flat_rate_flat_rate",
          "round_mode" : "0"
        }
      }
    ]
  }
}

Note these changes I applied as compared to your exported rule:

The CONDITIONAL is to be contained within your Rules Loop (not after it).
Within that CONDITIONAL, I added some other condition. And only if that condition is satisfied, the 2 Rules Actions (as in your own exported rule) are to be executed.
Attention about that "some other condition": the actual condition I added is for sure not correct yet to make it match your question, so make sure to rework that to fit your case (I just added this condition here to show how to use that CONDITION statement).

Additionally, I'm not sure (actually I doubt) if the very last Rules Action in my updated Rule is still correct. Because you'd only want to do that subtract again if the very first line item actually did pass the test about CONDITION. But after you understand how to use the Conditional Rules module, I'm sure you'll get that part fixed also.

Update 2

Yet another update, as per this additional comment you added after I added my "update 1":

  I can't find my term field in Data Comparison to select if product is Digital or Physical

That is not a surprise (at least not to me), because think about what kind of data about a product are available when processing a "line item" (inside a Rules Loop in this case here) ... No panic, because if it is not available, you can make it available, similar to what is explained in my answer to "How to access commerce_product field of line-items using Rules to flag the Commerce Product?" ...

Here is a blueprint of what you need to do (to further improve your rule):

Create a Rules Component, similar to the Rules Component of Step 1 in my related answer, just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
Execute that Rules Component inside your Rules Loop of the rule you already have. But make sure to do so BEFORE the "CONDITIONAL" Rules Action.
Move the "CONDITIONAL" Rules Action (and everything inside of it) to the Rules Actions of the new Rules Component you need to create. Make sure to place them AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID". At that point you should have access to your field to indicate "if product is Digital or Physical" (because of the "Fetch entity by ID").
Make sure that in that new Rules Component you also add a "Provided" variable (= value returned by the Rules Component to the calling Rule), which actually will, in the end, contain the "Calculation result" (BTW, result is a terrible variable name, hard to know what it is about). And it is that Calculation result that is what your main (further improved) rule should calculate, right?


Leaflet maps multiple icon types in views I have a leaflet map for various attraction types which works fine with using the standard blue icon.

What I'd like is to be able to specify a different icon based on the attraction type field.

I thought this feature existed based on https://drupal.org/node/1882806 but I can't seem to get anything to work.

I've been trying to set it up through the Leaflet settings in views using the POINT ICON Field (html DivIcon) setup. However, whatever I try seems to end up with a page full of errors and no icons.

I can't find any documentation on using this feature so would really appreciated some help.

Thanks,
Chris

Here is what I did. You should be able to tweak it to fit your needs:

I created terms and uploaded images for them.
I created nodes and associated terms with them.
I went ahead and created my leaflet view, using the appropriate
token in Point Icon in leaflet settings.

I hope that helps.


How to save the image of a node to the custom directory programmatically? I have a cck image field and I have the "uploads" directory in the files folder.

I want the images of these nodes are saved to the directory with the name of the node id and then the image file. Suppose if the node id is 4 then the image should be saved to the following directory.

files/uploads/4/filename

the directory with the name of "4" should be created programmatically.

Which hook should I use for this and how to achieve this? Any one who have some idea?

You have to use following module https://drupal.org/project/filefield_paths . then you can add tokens for it .


Organic Groups and Workbench or Revisioning together. Will this work? I'm building a D7 site using Organic Groups and would like some revisioning control.

Is it likely that something like Workbench or Revisioning will work nicely with Organic Groups?

I'm interested in hearing of any good or bad experiences or advice.

I've done some initial tests and Workbench appeared to work okay. Of course the number of configurable options tends to explode with two node access modules. It gets quite complicated. The Revisioning module wasn't quite so smooth. I seemed to get into a situation where an item wasn't visible to a normal group member when it should be but it could be fixed if the author / moderator simply edited the item and saved without doing anything. Maybe I need to have another play with that.

These modules actually do a lot more than we need. We don't really need multiple roles for author, moderator etc. Mostly "all" we'd like is the ability for a user to edit and save an existing node but see what it looks like before making it public. The "Preview" button does that (sort of) but it would be nice to be able to save changes, take a break, and come back later. Also, the public view maybe in a panel so "Preview" doesn't really show the final result.

Thanks

We've built a D7 site with Organic Groups and Revisioning and have found that installing Organic Groups causes a pretty major problem with Revisioning in that the Author and Moderator roles cannot see unpublished content.  We've confirmed on a clean Drupal installation that Organic Groups Access Control is the cause of the issue.

The only workaround that we found was to check the Bypass Access Control checkbox for those roles.  That means those roles bypass all security checks on content on the site so they can edit/delete/publish any content.  That is an okay work around for our site but did present a problem when we wanted a separate moderator role for just one content type.

See this post for full details -> http://drupal.org/node/1494232

We are planning on looking at Workbench for a different D7 site because Revisioning and Rules isn't going to be sufficient for the workflows.


Modal form - cant set error message, and no message for required field In a modal form, i've got e email field that is required.

when the field is wrong, a error message is well displayed
when the field is empty, $form_state->hasAnyErrors() is true but there is no error message
when i whant to set the error message in the form validation function, it's stay empty !

in BuildForm :

  $form['email'] = array(
            '#type' => 'email',
            '#required' => true,
            '#attributes' => [
                'placeholder' => t('Your email'),
                "data-nluid" => $nluid
            ],
        );
$form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => t('Suscribe'),
                '#ajax' => [
                    'callback' => '::submitModalFormAjax',
                    'wrapper' => 'newsletter_add_modal',
                    'event' => 'click'
                ]
            ];

in validateForm

 public function validateForm(array &$form, FormStateInterface $form_state) {
        $emailValue = $form_state->getValue("email");
        if (!\Drupal::service('email.validator')->isValid($emailValue) || trim($emailValue) == "") {

         $form_state->setErrorByName('email', "Email is required and must be valid");
         //binding form_state->getError($form['email']) show empty string
        }
    }

in submitModalFormAjax

 // If there are any form errors, re-display the form.
        if ($form_state->hasAnyErrors()) {
            $response->addCommand(new ReplaceCommand('#newsletter_add_modal', $form));
        } else {
 // else, exec success behavior

What am I doing wrong?

I know i'm a bit late but the problem is that the email field is required.
Required fields may not be empty, otherwise it will throw an error.

If you wish to show an error message you need a form element to catch these messages.

 $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];


Paypal Instant Payment Notifications - Add a role but not as a subscription upon purchase Here's my use case: I have a Paypal "Buy now" button that I have created using Paypal's Website Payments Standards utility.  This provides an Instant Payment Notification when a user successfully makes a purchase.

What I would like to do is automatically give a user a role upon a successful purchase.  I installed the lm_paypal module, but it is a full-featured subscription solution which I don't need; all I want to do is give users a specific role.  (It's impossible to configure lm_paypal to simply give a user a role; it wants to turn the role into a subscription, but my use case is not a subscription.)

At worst, I can just add the role to user accounts manually when I receive payment, but I'd like to find a way to do it automatically.

I'm not sure the PayPal button is the way forward - you're probably better off using one of the cart modules (Ubercart, Drupal Commerce) so that when the IPN comes in the order status will be updated.

Then using Rules or Conditional Actions you can set up an event (triggered by the status update) to fire off an action that will add the role to the user.

Make sure to add conditions so that this only happens if the order balance is <= 0 (fully paid for) and if a certain product is in the cart. Also to make sure that it only occurs on updates between the two particular statuses (In Checkout -> Payment Received).

If there is no built-in action to actually add the role then you can use the "Custom PHP" action (or similar).
If you find the idea of writing that chunk of php yourself, don't fret. Just search for "drupal add user role programmatically" (without quotes) and you'll be on your way.
I don't know it off the top of my head, but I know that it isn't long.

One thing I have found very useful is to add an "email" action to my conditional actions, with myself as the recipient. Set the input format to PHP and put this in the body:

<?php print_r($order); ?>

This gives you the $order array from which you can extract values such as the user ID to use in your PHP action.


EntityFieldQuery BETWEEN condition is not working $query->join('field_data_field_amountpaid', 'amt', 'n.nid = amt.entity_id and amt.field_amountpaid_value >=500 and amt.field_amountpaid_value <=5000 '); //JOIN node with Body

This is my normal query how can I call this in entity query?

I tried this way;

$query->fieldCondition('field_amountpaid', 'value', array('501','5000'),'BETWEEN');

But it's not working. Any idea?

I had the same problem than you, and was able to fix it. The real problem here is that the documentation does not provide any example.

As it was already mentioned, the BETWEEN will only work if you are using the same data types that are being stored.

In my case, the field i was searching was a date field that has a specific format. So instead of passing a timestamp i had to format that date and then pass it.

//something like
start_date = (isset($_GET['startDate'])) ?  date('Y-m-d/T00:00:00',strtotime($_GET['startDate'])) : null;
        $end_date = (isset($_GET['endDate'])) ? date('Y-m-d/T00:00:00',strtotime($_GET['endDate'])) : null;

        if (isset($start_date) && isset($end_date)) {
           $query->fieldCondition('field_publication_date', 'value', array($start_date,$end_date), 'BETWEEN');
        }

Hope this helps you!


Override the output of views with angular directives I use Angular material in my Drupal 8 site (perforce!!!) and I have some problem with views.
 I want to override the output of views with custom text:

but as we all know views is strict with html tags and angular material uses custom directives for his purposes...

Question:

How to solve this problem?

How to make views to don't trim angular material directives?

Dose any one has solution for this?

UPDATE: The problem is that nothing is rendered correctly...

For example.

angular material card is this:

but the view shows this result:

This means that angular directives ware trimmed by Drupal, and that's why view shows incorrect result.

After a lot of research and debugging i came across to this solution...

The problem of restriction of custom text field of a view is that it uses Xss::filterAdmin function (core/modules/views/src/Plugin/views/PluginBase.php:398 line)...

So i created module, then in mymodule.views.inc file I alter "hook_views_plugins_field_alter", i changed class that uses the views custom text filed in my own class that i created in mymodule>src>plugin>views>field>my_Custom.php.
 This class is copy/paste of core/modules/views/src/Plugin/views/field/Custom.php and changed only the \Drupal\views\Plugin\views\PluginBase::viewsTokenReplace only this form:

$build = [
    '#type' => 'inline_template',
    '#template' => $text,
    '#context' => $twig_tokens,
    '#post_render' => [
      function ($children, $elements) {
        return Xss::filterAdmin($children);
      }
    ],
  ];

to:

 $build = [
    '#type' => 'inline_template',
    '#template' => $text,
    '#context' => $twig_tokens,
    '#post_render' => [
      function ($children, $elements) {
        return $children;
      }
    ],
  ];

and from now the custom text don't escapes html tags...

For more control i created also one checkbox in field setting to control f i want to escape the text or note for this field and accordingly to the value of checkbox i activate or deactivate the Xss::filterAdmin function


Add prefix to the error message How I can add some prefix to the all error messages?

Example:

This field is required!

and I need

Error: This field is required!

I'm using Clientside Validation module for error messages in my forms.

You can override the output by implementing theme_status_messages in your theme.

You could work from something like this. See $myprefix that I've added.

function MYTHEME_status_messages($variables) {
  $display = $variables ['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $myprefix = $type == 'error' ? 'ERROR: ' : '';
    $output .= "
\n";
    if (!empty($status_heading [$type])) {
      $output .= '
' . $status_heading [$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $myprefix . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $myprefix . reset($messages);
    }
    $output .= "
\n";
  }
  return $output;
}


Can i make a node reference to some field but not the title field? I have a salary content type and i want to reference the salary value from another content type.
Can i make a node reference to some field but not the title field?

You can make node reference to a view
In a case I added a title and an image in an auto-complete and it worked fine
you can check it by adding any field not a title


Does a third-party module need to implement hook_help()? After having spent hours reading through (very old) coding standards and best practices threads on drupal.org, and even trying to revive the Contrib Development Best Practices group on groups.drupal.org which seems to having been abandoned for years, I'm still struggling to getting an answer to whether a third-party module needs to implement hook_help() to comply with the Module Documentation Guidelines or not.
Above guidelines state

All but the most trivial modules should implement hook_help().

Yet, should is not must, which sometimes leads to discussions within the Security Advisory Application Issues Queue.
I was not able to identify someone to ask, whether it is a requirement or a (strong?) suggestion.
As we're currently reworking the PAReview (pareview.sh) tool, it would be great to know for having a distinct severity for a missing hook_help(). That's why I'm hoping to getting a hint from the grey-bearded Drupalists here, on where to address this inquiry.
Don't get me wrong, I don't want to start a discussion here, nor subjective answers on whether there should be a hook_help or not. I just want to know which board is deciding such issues and where to ask when it comes to contrib module coding standards and best practices.

Modules should implement hook_help() even for just giving a short description of the purpose of the module (an overview help page). The standard structure of that page is described in Help text standards / Help page. hook_help() is the hook used from the core Help module.
In Drupal 8.8.x, a new experimental core module has been added: the Help Topics module. Its purpose is allowing modules to write their help pages as Twig template files with an embedded YAML header, for example like ban.banning_ips.html.twig.
---
label: 'Banning IP addresses'
related:
  - user.overview
---
{% set ban = render_var(url('ban.admin_page')) %}

{% trans %}Goal{% endtrans %}

{% trans %}Ban visitors from one or more IP addresses from accessing and viewing your site.{% endtrans %}

{% trans %}Steps{% endtrans %}

{% trans %}In the Manage administrative menu, navigate to Configuration &gt; People &gt; IP address bans{% endtrans %}

{% trans %}Enter an IP address and click Add.{% endtrans %}

{% trans %}You should see the IP address you entered listed under Banned IP addresses. Repeat the above steps to ban additional IP addresses.{% endtrans %}

Since the module is experimental, third-party modules should not depend on that and use those files for their help text, especially because the module is going to be merged with the Help module. The plan is also to deprecate hook_help().
Third-party modules should:

Drupal 7
Implement hook_help() even to show a short overview page

Drupal 8
Implement hook_help() even to show a short overview page; consider writing integration with the Tour module to add additional contextual help to any page in the shape of a tour, which can have multiple steps, each one describing part of a page (such as different form elements in an administrative form)

Drupal 9 (or 10, depending from when the Help Topics module will be merged into the Help module)
Write topics pages even to show a short overview page; consider writing integration with the Tour module to add additional contextual help


Call to undefined function db_affected_rows() D6 module https://www.drupal.org/project/uc_dependent_attributes is converted to D7 here: http://dupgrade.com/ and I found out db_affected_rows() was removed from D7.

I tried few codes, basically copy and paste, based on this answer db_affected_rows gives fatal error in drupal 7. Now I have a different error: Call to a member function rowCount() on a non-object.

Code which throws Call to undefined function db_affected_rows()

function uc_dependent_attributes_uc_product_adjustments_form_submit(&$form, &$form_state) {
  foreach ($form_state['values']['body'] as $value) {
    if (!$value['enabled']) {
     db_update('uc_dependent_attributes')->fields(array(
        'enabled' => 0,
      ))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
      if (!db_affected_rows()) {
       db_insert('uc_dependent_attributes')->fields(array(
          'nid' => $form_state['values']['nid'],
          'combination' => $value['combo_array'],
          'enabled' => 0,
        ))->execute();
      }
    }
    else {
      db_delete('uc_dependent_attributes')->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
    }
  }
}

Changed: This gives 'Fatal error: Call to a member function rowCount() on a non-object' error.

function uc_dependent_attributes_uc_product_adjustments_form_submit(&$form, &$form_state) {
  foreach ($form_state['values']['body'] as $value) {
    if (!$value['enabled']) {
     $result = db_update('uc_dependent_attributes')->fields(array(
        'enabled' => 0,
      ))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
      $affected_rows = $result->rowCount();
      if ($affected_rows!=0) {
        db_insert('uc_dependent_attributes')->fields(array(
          'nid' => $form_state['values']['nid'],
          'combination' => $value['combo_array'],
          'enabled' => 0,
        ))->execute();
      }
    }
    else {
      db_delete('uc_dependent_attributes')->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
    }
  }
}

How can I change db_affected_rows() to D7 properly?

As it happens UpdateQuery::execute() returns

  The number of rows affected by the update.

So instead of:

$result = db_update('uc_dependent_attributes')->fields(array(
  'enabled' => 0,
))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
$affected_rows = $result->rowCount();
if ($affected_rows!=0) {

use:

...
$affected_rows = db_update('uc_dependent_attributes')
  ->fields(array('enabled' => 0))
  ->condition('nid', $form_state['values']['nid'])
  ->condition('combination', $value['combo_array'])
  ->execute();

if ($affected_rows == 0) {
...

(there's also a small fix to the conditional logic)


Simultaneous Database Connections I have two databases set in my settings.php file. One is used for drupal, one is for our backend which is external from the drupal installation and databases. I would like to query the backend database but cannot change the db_active because then our site users will have issues accessing their profiles. How can I go about connecting to the two databases simultaneously?

I think you are inventing a problem that doesn't exist.

The active database will be per-request, not site wide.  So if one user is accessing your backend, another user can do whatever they need against your default Drupal database.

Within a request, you can use the db_set_active() function to switch databases as much as you want. eg

$query = db_query(...);   // runs against the default database
db_set_active('backend'); // change databases
$query = db_query(...);   // runs against $databases['backend'];
db_set_active();          // change back to default databases
$query = db_query(...);   // runs against the default database

As PHP is single threaded w/in a single request, you don't have to worry about a query running against the wrong database.

So, in summary, just use db_set_active() to change databases when you need to, and then remember to switch back when you are done.  If you isolate your code (which you really need to do in Drupal anyway), you shouldn't run into trouble.

I would also look into hook_views_data().  This works very well to being in external data into Drupal.


Getting all the values from a entity reference field (Drupal 8) I'm trying to figure how I can get all the values inside an entity reference field

As shown in this image, I have an entity field called Target Participants(field_program_participants) with multiple values.

I have tried to output the values using node.field_program_participants.entity.label, but it only outputs one value.

How can I output all the values inside the field

You have to loop over the field items:

{% for item in node.field_reference %}
  {{ item.entity.label }}
{% endfor %}


Detect the taxonomy term(s) of a node from within a template file I have a Drupal 7 site with a content type of event.

I have a taxonomy called "event types" that has 5 options (Party, Conference, Meeting, etc)

I have one template named node--event.tpl.php for styling the standalone event nodes.

How can I detect which taxonomy terms apply to a given event node from within the template file? I need to change some of the presentation logic based on the taxonomy term associated with the event.

I am not using the taxonomy in the URL, so I need to find another method for detecting the event type. Devel doesn't seem to show me any values of taxonomy terms to work with.

As alluded to in the first answer, you should use a preprocess function, but probably for the node template.

For the node.tpl.php template (and all derivatives) the function is defined as

MYTHEME_preprocess_node(&$vars) {
}

and should appear your theme's template.php file.

You must clear the Drupal cache in order to reset the theme registry such that Drupal recognizes and executes this function.

The $vars argument of the function is an array that contains all the template variables which subsequently appear in the tpl file ($vars['foo'] will be leveraged as <?php print $foo; ?> in the tpl file).

This also includes the native $node object, which will allow you to inspect $node->taxonomy, and create any subsequent variables accordingly. You can leverage these in the tpl file.

The best way to inspect and discover the components of $vars is to use the Devel module's dpm() function, which nicely prints any variable to the theme's messages box.

So, enable devel, create the following in template.php, clear cache, refresh viewing a node, and work from there.

MYTHEME_preprocess_node(&$vars) {
  dpm($vars);
}

You may also be interested in my session on Drupal preprocess functions from Drupalcon Copenhagen or the Drupal handbook page.


Views event listing by date with up/down infinite scroll I have a content type called "Event" which contains a "Date" field. What I want to achive:

1) Create a view which can display 5 events sorted by "Date" and displayed as following:

2 events which are previous to the current date
1 event which is of current or the nearest date
2 events which are following current or the nearest date

2) When these things are ready I want to have a possibility to:

scroll up and dynamically load 5 more "previous" events
scroll down and dynamically load 5 more "following" events

I understand how to do it with 2 different views displays (one for current and upcoming events and a block before with past events), but the thing is that I need to create a page slider (where each fullscreen slide is one event) which can be slide both before and forward over all site events (there may be a lot of them, so i can't just load all events at once and need to do it dynamically when sliding over). Will be very thankful for any idea how to create such a display using one view.

You can achieve your requirement by following below steps.

Install Views Field View module.
Create first view of Event content type with 2 events which are previous to the current date
Create second view of Event content type with 2 events which are greater than current date.
Now create on third view with current date and into its header part add first view and into footer part add second view using Views Field View. Follow screenshot attached below

Regarding scroll down functionality install Views Load More module.

I don't know how to achieve scroll up functionality. It something like you have to write custom thing.


A custom Field with #submit function can't pass value i wrote a custom field and i want to do mini validation just in the custom field.

The only input data are the cellphone textfield. The other form fields all are used for validation.

However, i can't pass the value of the field.

Is there something wrong?

 function cellphonefield_field_widget_form(&$form,&$form_state,$field,$instance,$langcode,$items,$delta,$element)
    {
        $base=$element;

      dpm($items[$delta]['cellphone']);

        $element['cellphone']=array(
             '#type' => 'textfield',
         '#title'=>t('Enter your Cell phone Number!'),
         '#description'=>t('System will send you a message '),
         '#default_value'=>isset($items[$delta]['cellphone'])?$items[$delta]['cellphone']:'test for this field',
        )+$base;

      $form['send_sms']=array(
             '#type' => 'submit',
             '#name' => 'send_sms',
             '#title' => t('validate your cellphone number'),
           '#value'=>t('Send Me Validate Code'),
         '#weight'=>1,
         '#limit_validation_errors'=>array(
         array('cellphone')),
         '#submit'=>array('send_sms_function'),
        );

      $form['validate_code']=array(
             '#type' => 'textfield',
         '#name' => 'validate_code',
         '#size' => 20,
         '#title'=> t('Enter the validation code !'),
         '#description'=>t('Please check your cell phone sms message and then enter the code in the sms.'),
         '#weight'=>2,

        );

      $form['validate_button']=array(
             '#type' => 'submit',
             '#name' => 'validate_button',
             '#title' => t('validate your cellphone number'),
           '#value'=>t('Validate'),
         '#weight'=>3,
         '#limit_validation_errors'=>array(),
         '#submit' => array('send_sms_function'),
        );

        $form['submit_message']=array(
        '#type'=>'item',
        '#title'=>t('Cell Phone'),
        '#description'=>t('Your phone is been validated!'),
        '#weight'=>4,
      );

        return $element;
    }

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

$cellphone=$form_state['values']['cellphone'];
      dpm($cellphone);
          }

For validating the content of a field there is hook_field_validate(). As example of implementation of that hook in a module, you can look at taxonomy_field_validate(), or number_field_validate().

function number_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if ($item['value'] != '') {
      if (is_numeric($instance['settings']['min']) && $item['value'] < $instance['settings']['min']) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'number_min',
          'message' => t('%name: the value may be no less than %min.', array('%name' => $instance['label'], '%min' => $instance['settings']['min'])),
        );
      }
      if (is_numeric($instance['settings']['max']) && $item['value'] > $instance['settings']['max']) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'number_max',
          'message' => t('%name: the value may be no greater than %max.', array('%name' => $instance['label'], '%max' => $instance['settings']['max'])),
        );
      }
    }
  }
}

As far as I can see, fields don't add submission buttons. That is not the purpose of fields, which is to add fields to enter data for an entity (e.g. nodes, users, taxonomy terms).

In your case, the workflow is similar to the following one:

The user enters a cell phone number
The module tells to the remote service to send a verification code to that cell phone number
The user enters the verification code
The module checks the verification code is the expected one

Such workflow can work if it is done in two steps:

When the user first enters the cell phone number, the validation hook can just send the cell phone number to the remote service. It cannot wait the user receives the verification code, and enters it.
The second time, the user edits the verification code, and the validation hook will check the verification code is the right one.

You have to see if checking the verification code can be done synchronously, or asynchronously.


import address data from CSV I migrate my content from an old D7 site to D8 site. All went well, except the addresses from field address where not migrated to the new address field.

Then I use feeds, feeds_migrate, content-import... Nothing work for this.

Then finaly start learning how to do this in a custom module. I used the plugin from the module addres, I wrote my own plugin. No migration seems to work.

I have a CSV file with the addresses. There is also a NID row that is unique, I also try with the title field who also is unique. I try to import this csv file into my content type business. The nodes are existing with the NID numbers. Just try to fill the address in each content. All addresses are in Belgium.
Below my YML file in a custom module.

    id: migzaal
label: Adres veld migratie
source:
   plugin: csv
   path: modules/custom/adresmigratie/assets/adresinvoer.csv
   header_row_count: 1
   ids:
     - Nid
process:
   nid: Nid
   field_adres:
     plugin: addressfield
destination:
  plugin: 'entity:node'
  default_bundle: business
  overwrite_properties:
    - 'field_adres/address_line1'
    - 'field_adres/locality'
    - 'field_adres/postal_code'
    - 'field_adres/country'

Can someone guide me in the right direction. Thanks.

I've been through a similar situation and I resolved it depending on the feeds module.

You need to use the following patch to allow the address field to be recognized by the feeds module
https://www.drupal.org/project/address/issues/2882589

This is might not be what you're looking for at this stage but I thought this might help.


select term from reference field but deny edit term How can I allow users of a particular role select a term from a reference field on a node but deny them to 'edit' the terms from that reference field?

Selecting terms: great.
If, under taxonomy permissions, you tick 'Administer vocabularies and terms' for a particular role, they will see my own created term reference field and they are able to select the term of their preference which is great.

Editing terms: bad.
But if they view the node and see the term, they can click on that term and then they also have the 'edit' permission to edit the term. Surely not what we want because the user might potentially mess up the settings of my carefully designed term reference field.

I'm using taxonomy access control but that only takes care of the node access, not of the term edit access.

Found it. It appears to be a bug in both the rc version and the dev version of the module Taxonomy Access Control for D7. Details from project page:

Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.

Once a user has access to the edit node form AND they are allowed to 'add tag' on the access-rules-for-user page for that vocabulary, that term will show up and will be able to be ticked/set on the node form regardless of whether or not the default and other vocabulary terms in that vocabulary have been set to 'allow' or 'deny' the 'add tag' on the access-rules-for-user page. Hopefully this makes sense to others as well.


How to alter the default user permisions based on a returned value after login? I am having some users who have access to a limited modules. Now after a user logs in, i want to alter the permissions of that user based on the uid. I mean i should be able to add or delete some permissions of that user immediately after a user logs in. Immediately after login i wrote a custom code which executes and returns a value whether the user is active or inactive. Then based on the result i should be able to delete some permissions to access some modules of my site if inactive or add if he is active.

user_role_grant_permissions can help you. Or you are using modules which grant permissions based on users not on roles? If yes, look into code of module which control permissions per user to find proper function


Print a node display mode in a tpl file I have a switch statement in my content type tpl file for 2 different view modes:

<?php
switch ($view_mode) {
case 'full' :
?>

//content for full view mode here

<?php break;
case 'custom-display-mode' : ?>

//content for custom display mode view mode here

<?php break;
} ?>

How can I print the teaser view mode within full display mode? Can I print it out in the same way you can print fileds in a tpl file?

<?php
switch ($view_mode) {
case 'full' :
?>

//content for full view mode here
//********* also print teaser view mode here **********

<?php break;
case 'custom-display-mode' : ?>

//content for custom display mode view mode here

<?php break;
} ?>

Are you trying to print full display mode + teaser mode under full display mode? You can always render any display mode directly using node_view as

  node_view($node, $view_mode = 'full', $langcode = NULL)

or with your example:

switch ($view_mode) {
case 'full' :

//content for full view mode here

$rendered_teaser = render(node_view(node_load($nid), 'teaser'));
print $rendered_teaser;

...

I would also recommend breaking your display mode templates out into separate files to simplify management. If your full mode should be the same as your teaser then using this method you can always just symbolically link the files on your server.


Workflow does not work correctly I create a workflow for the content type "Article":

creation -> draft
draft -> expert review
expert review -> head review
head review -> publish

When authors create an article node, and send it for "expert review," they can still view and edit the node but "expert review" cannot view the node.

Is there any bug or trick for Workflow?

Edit your Workflow again (after you created the states) and scroll down to the bottom to 'Access control' section. In there you can set permissions for each state.

You can also look at the Workflow Fields module if you want to set access to individual CCK fields.


Calculate difference between two dates in Webform I am trying to calculate a difference in days between (a) the date a Webform was completed and (b) an "Event Date" field on the Webform. I have added a Computed Twig field to the webform and attempted to use this code (similar to https://stackoverflow.com/a/27205095/1357555):

{% set difference = date(data.event_date).diff(date(completed)) %}
{% set leftDays = difference.days %}

However, I am getting an error message when attempting to save the field.

  Computed value/markup is not valid.

  Calling "diff" method on a "DateTime" object is not allowed in "{# inline_template_start #}{{ completed|date }} {{ data.date_needed|date }} {% set difference = date(data.event_date).diff(date(completed)) %} {% set leftDays = difference.days %}" at line 4.

  Failed to render computed Twig value due to error.

This is a bug in the Webform module. I created the below ticket to address this issue.

Improve Computed Twig element validation to support complex calculations


add to cart - multiple products at once On my commerce site, I would like to use exact functionality like both ubercart cart links or ubercart kits have - to add multiple different products to cart at once (one click on button or link, no quantity).
Requirement is: products inside cart should behave as single products, with quantity enabled. I do not need discounts.

modules I tried:

commerce product bundle - adds all products as one product, you can only change quantity
commerce bundle - separate products but quantity fields disabled.

Rules links look promising but I am not so sure how it would work with many kits. Do anybody have a solution for this? Thank you.

User case: Create various product kits (as content types) with add to cart button. After adding to cart, products behave like normal simple products. (Ubercart has this funtctionality - while creating a product kit, you can check wether you want the products to behave in cart like a kit(a bundle) or as a separate products.)

Commerce Add to Cart Extras

  This module provides alternative ways of adding products to cart.

  The initial version provides a views field handler ("Commerce Product:
  Quantity input field") that relies on the Views Form API (a part of
  Views 3 since RC1) to output a quantity textfield that turns the view
  into an add to cart form. The default quantity can be configured, and
  only products with a quantity larger than 0 are added to the cart.


Single SQL query to pull recent two nodes from each node type As mentioned in the title, I was wondering how this can be achieved with single SQL query. All I need is the node ID from node table that matches the given criteria.

$node_types = node_get_types(); // or create own object of node types
$query = $types = array();

foreach($node_types AS $type){
  $query[] = "(SELECT node.* FROM {node} node WHERE node.status <> 0 AND node.type = '%s' ORDER BY node.nid DESC LIMIT 2)";
  $types[] = $type->type;
}

$query = implode(' UNION ', $query);
$result = db_query($query, $types);

$items = '';
while($row = db_fetch_object($result)){
  $items[] = l($row->title, 'node/'. $row->nid);
}

print theme_item_list($items);

Execute time: 0.002s


Drupal pager, go to specific page I have a form in pager, so user can enter page he want's to view. But I can't figure out how to go to that page number in form submit.

Most drupal pagers work by setting a ?page=XX in the url. So a simple solution would be to set the url to mimic that, entering the number entered by the user in the url.

This might break if the pager argument in the url changes (like if you have multiple pagers on a single page etc), but this might cover your needs.


Custom form handler not found (call_user_func_array() error) Currently on Drupal 8 beta 7.

I'm trying to build a form with separate "submit" and "cancel" buttons. The cancel button has some separate cleanup work to do. I've tried to follow the documentation and examples to create a custom form handler to manage this. Here's my actions block from my form.

    $form['actions']['#type'] = 'actions';
    $form['actions']['cancel'] = array(
      '#type' => 'submit',
      '#value' => 'Cancel',
      '#button_type' => 'cancel',
      '#submit' => array('uso_cancelForm'),
    );
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Submit',
      '#button_type' => 'primary',
    );

Then, in my form object, I define the custom handler.

public function uso_cancelForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message("Editing cancelled");
    // Handle state information here
}

However, pressing the cancel button has no effect, except to log an error:

  Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'uso_cancelForm' not found or invalid function name in Drupal\Core\Form\FormSubmitter->executeSubmitHandlers() (line 116 of /{redacted}/core/lib/Drupal/Core/Form/FormSubmitter.php).

So it looks like, for some reason, Drupal can't find my uso_cancelForm function, which is sitting in the form object definition right next to validateForm and submitForm. The "Submit" button calls submitForm without a hitch.

What am I doing wrong here?

I've figured out that if I move my custom uso_cancelForm function into my .module file, Drupal finds and runs it, but this solution won't work as a long-term solution, because I need to use $this in the code that the cancel function executes.
So, clearly, my form's public functions aren't in scope when the button press is being handled, although the standard validateForm and submitForm functions are. I tried adding include_once "src/Form/{my form filename}.php"; to my .module file, but this doesn't help.

Is there some other way I need to let Drupal know about this method, so that the FormSubmitter will know about it and call it?

Use '::uso_cancelForm' or [$this, 'uso_cancelForm'].


How to setup custom 404 page that will ignore the path? I have the pathauto setting up URLs as /Country/Dept/node-name  (i.e. - /US/Training/How-To-Create-Node).  If I enter a non-existent path at the root, it goes to my default 404 page I created.  However, if the path is /Country/Dept/ anything, it just goes to the parent folder.  How can I get it to go to the 404 page, regardless of the path?

In my case, the main problem was that there were blank landing pages for the parts of the URL.  For instance, there was a blank US page for /US/Training/page-title.  So, Drupal was finding /US and just redirected the visitor to that page.  Because of this, no 404 was being registered, therefore never redirecting to the 404 page.  None of the 404 modules helped for this.

Because I have a Taxonomy term for the Country that is used to set the URL, I simply removed the blank landing pages.  Now, it will properly register a 404 and will go to my custom 404 node.


Why i get the error "Call to undefined function node_object_prepare()" while i try to add a node programmatically in Drupal 7? i'm trying to add a node content programmatically from a custom module file. I have created the .module file and used this code as suggested:

$node = new stdClass(); // We create a new node object
$node->type = "page"; // Or any other content type you want
$node->title = "Your title goes jere";
$node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled.
$node->path = array('alias' => 'your node path'); // Setting a node path
node_object_prepare($node); // Set some default values.
$node->uid = 1; // Or any id you wish

// Let's add standard body field
$node->body[$node->language][0]['value'] = 'This is a body text';
$node->body[$node->language][0]['summary'] = 'Here goes a summary';
$node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format,  you need to define it. Here we define a default filtered_html format for a body field

$node = node_submit($node); // Prepare node for a submit
node_save($node); // After this call we'll get a nid

but when i enable the module what i get is an error saying "Call to undefined function node_object_prepare()"

Thanks.

I think you will have to include node.pages.inc to be able to use this function from within your module:

module_load_include('inc', 'node', 'node.pages');

I just tried the using node_object_prepare() from a sample module without using the above code and it seems to work just fine. As @Clive mentioned is his comment you should add your code for creating a node programatically inside a module hook and not directly in your module file.

// create a node using 'hook_menu' in your module, this might not be the
// best hook for doing this but it should work
function <MODULE>_menu() {
  $node = new stdClass();
  $node->type = "page";
  $node->title = "Your title goes jere";
  $node->language = LANGUAGE_NONE;
  $node->path = array('alias' => 'your node path');
  node_object_prepare($node);
  // ...
}

Reference: Module hooks


Why does drush en give differerent results than enabling mymodule in the ui? When I perform drush en mymodule -y my module enables no problems. When I do the same in the UI it seems to install great. No errors. However the roles defined in hook_install() are not created. In Drush they are. What is the difference between Drush and Enabling the module in the UI?

One gotcha between the UI and Drush is the user. Drush commands are run as anonymous by default. Where as in the UI you are user with greater rights (normally the admin user).

Some parts of Drupal will check for rights before doing things, node_save is one such place. Depending on how you are creating your roll you may find there is another.

A work around for this is to use the -u flag with Drush.

drush -u 1 en my_module

I can't say for certain that this will fix your issue, but there is a fair chance that it will help.


How do I output HTML from a text_long field in Twig? What is the alternative to the |raw filter if I want to output html from a entity field in twig in Drupal 8?

According to this ticket, |raw should be avoided, but I can't figure out how to use what they recommend in that ticket (Safestring/SafeMarkup) in twig.

I have a custom content entity that has a field definition as follows:

$fields['internal_description'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('Internal description'))
  ->setSettings(array(
    'max_length' => 1500,
  ))

The field stores HTML from a CKEditor instance. Now I would like to output this as HTML in a twig template. Currently if I just call

{{  event.getExternalDescription }}

I get the escaped HTML as expected, however that is not what I want. If I do

{{  event.getExternalDescription | raw }}

I get what I want, which is unescaped, rendered HTML. However since it's not checked in any way in this case, I would like to know how to make this output safe and still allow my users to use CKEditor for entering content?

Normally you would configure the display of the field in UI.
You can do this in code by using the render element processed_text.
PHP
  $build = [
    '#type' => 'processed_text',
    '#text' => '
Hello world
',
    '#format' => 'full_html',
  ];

TWIG
In twig you would use instead of the extremely unsafe {{ event.getExternalDescription | raw }} this code:
  {% set build = {
    '#type':   'processed_text',
    '#text':    event.getExternalDescription,
    '#format': 'full_html',
  } %}

  {{ build }}

The safety of the text format depends on the configuration of the text filters and the content of the field. Apply the same security considerations as you would for text formats in ckeditor.


Field validation: hooks vs callbacks In D7 there appear to be various methods by which a module can carry out validation of a form's fields, including:

#element_validate callback
#validate callback
hook_field_validate() implementation
hook_form_validate() implementation
hook_field_attach_validate() implementation

Firstly, can anyone list the execution order of the above?

Secondly, can anyone please explain why one might choose to use a callback instead of a hook or a hook instead of a callback?

#element_validate is used to provide validation for a specific element.
#validate is used for the form, and for elements that cause the form to submit (button, image_button, submit). It provides the names of extra functions to call during the validation process.
hook_field_validate() is for validating fields (not standard form elements). This doesn't necessarily take place in the context of a form submission.
There's isn't a hook_form_validate() - by convention if a function called FORM_ID_validate() exists then it will be used as part of the above #validate array for the form. This is used to validate any part of the form, not just a specific element.
hook_field_attach_validate() runs as validation when fields are attached to an entity, it doesn't run in the context of a form (see field_attach_validate())

Not all of the above are executed at any one time, or in any single context, so listing an execution order isn't possible.

Hopefully the above distinctions will make it obvious which one to use in what circumstance.


Define a normalizer just for a specific use case I try to create a custom API with custom endpoints where API users can receive entity data from our page. We want to have flat arrays for most of the fields and some additional custom data added so I tried to implement some custom normalizer classes. I found out that supportsNormalization() is the place where the decision is made if my normalizer is used, but I have no context. I just have the object which needs normalization and the format on which I can say Yes, please use my normalizer. As I don't want to force all my entities everywhere in the project be normalized with flat array this is too restrictive for us. I want to use my normalizer only when the entities should be normalized for delivering it in a specific API. Is there a way to achieve this?

The supportsNormalization method comes from the Symfony Serializer component, and for this reason it is up to the implementation to decide what to do with these items.

However Drupal core serialization module provides a nice base class, ComplexDataNormalizer, which is probably the class your Normalizer should extend when you need to normalize a complex data type such as an Entity, Map or a list of those things.

Classes that extend the base class should provide a unique interface to target: ComplexDataNormalizer::$supportedInterfaceOrClass.

With the Symfony service locator, as long as the normalizer weight is adjusted for any conflicts, then it will be used. A good example of this is to look at the core hal module.

So for instance, in my module xero, I provide my own Typed Data data types to interact with a third party API and the top-level data types I have my own interface.

Example:

class XeroNormalizer extends ComplexDataNormalizer implements DenormalizerInterface {

  protected $supportedInterfaceOrClass = 'Drupal\xero\TypedData\XeroTypeInterface';

You can read more about how the Drupal serialization module works in the documentation: https://www.drupal.org/docs/8/api/serialization-api/how-the-serializer-works