Abnormal website database growth I migrated my site to the production  server about 3 months ago . 2 weeks ago , I noticed that the db was growing too fast(about 40Gb I could not account for) I backed the site , deleted WAMP and restored the site .

Result , slower until within the 2 weeks ,it has grown to a halt . Keeps on "connecting ".
One other thing( could be related ) the site counter is showing a growth of about 1,000 users anonymous users very hour - this is not possible given the site is either too slow or not working at all outside the LAN

I suggest truncate watchdog table, usually this table growth very quick.( maybe you can first  get a backup of this table then truncate(empty) it)

( maybe trucnate cache tables be useful but If you see table size u will see the watchdog have biggest size )


Is there a reliable way to see what other users see when logged in? I've found the Impersonate and Masquerade modules, but the first is for Drupal 5 (I remember the hardest thing about Drupal 5 development was having to keep an eye out to avoid being lunch for a hungry T Rex) and the second is still a release candidate (for Drupal 7) and is "minimally maintained".

Is there another, better way?  Or can anyone vouch for the stability of Masquerade?

I can't vouch for either of those modules, but I've been using the 'Switch' feature in the Devel module to do just that for years. I've used it on probably hundreds of sites and I've never found a problem with it.

When logged in with appropriate permissions you can visit /devel/switch/[username] and it will log you in as that user. There's also a list of users in the admin toolbar that you can choose from directly, but I'm not sure if that's only available if you have the Admin Menu module installed.

It doesn't add a link to log back in to the admin user like the Masquerade module does (it's more 'bare-bones' than that), but if you've got your admin password saved in the browser it'll only take a couple of clicks to log back in anyway.


Setting custom block.html.twig templates in preprocess function (not based on twig naming scheme) I've created several block plugins each with their own block form. My goal is to make it so you can select what template to use based on a field in the blockForm. I understand that I can change a block template within the build function by specifying the '#theme' but that refers to the content. I want to change block.html.twig template being used that surrounds the content.  I also understand that I can specify the block template by using the naming scheme like block--block-name.html.twig but I want to be able to select the template within a preprocess function. Below is my attempt.

In mytheme.theme I have

function mytheme_theme($existing,$type,$theme,$path){
    return [
        'wide_grid_block' => [
            'variables' => [
                'test' => 'Test default value',
            ],
        ]
    ];
}

function mytheme_preprocess_block(&$vars){
      $vars['#theme'] = 'wide_grid_block';
}

and in templates/block/wide-grid-block.html.twig I have

Testing: {{ test }}

I assumed the what should occur is that every block should use the wide-grid-block.html.twig file. But they're all still using block.html.twig.

How do I specify a custom block template in a preprocess function?

UPDATE: I've also tried using a theme_suggestions_block_alter hook but I get a white screen when attempting to do so

function alltechcom2017_theme_suggestions_block_alter(array &$suggestions, array $variables) {
$suggestions[0]= 'wide_grid_block';
}

And I've tried with and without the [0]

UPDATE 2: I've managed to add to the suggestions by using

$suggestions[] = 'wide_grid_block';

The issue I had before with the white screen was because the file was in the wrong location. So I know drupal can see it, I just need it to be the most desired one in the list of possible templates.

In the debug info I see

<!-- FILE NAME SUGGESTIONS:
   * block--product-selector.html.twig
   * wide-grid-block.html.twig
   x block.html.twig
-->

And I have a block.html.twig and a wide-grid-block.html.twig. Why is it using block.html.twig instead? It's acting as if my file doesn't exist. I looked at this https://sqndr.github.io/d8-theming-guide/theme-hooks-and-theme-hook-suggestions/theme-hook-suggestions.html and it appeared like I was on the right track.

UPDATE 3: I've added

function mytheme_theme($existing,$type,$theme,$path){
    return [
        'wide_grid_block' => [
            'path' => drupal_get_path('theme','mytheme').'/templates',
            'template' => 'wide_grid_block',
        ],
    ];
}

but still no luck

I managed to get it working by using

function mytheme_theme($existing,$type,$theme,$path){
        return [
                'wide_grid_block' => [
                        'path' => drupal_get_path('theme','mytheme').'/templates',
                        'template' => 'wide-grid-block',
        'render element' => 'elements',
        'preprocess functions' => ['template_preprocess','template_preprocess_block','comment_preprocess_block','mytheme_preprocess_block'],
                ],
        ];
}

function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
if($variables['elements']['#configuration']['id'] == 'page_title' || $variables['elements']['#configuration']['id'] == 'product_selector'){
        $suggestions[] = 'wide_grid_block';
}


Webform date field format How do I change the date format of a date field in WEBFORM?

I have enabled popup calendar for this field, and when I select a date from the calendar, the default format is in Y-m-d  which I want to change it to d-m-Y.

I do not see any configuration available in date field edit page.

Under configuration -> Date and time -> Short date type has the format "d M Y", I have tried updating this to d-m-Y but with no lock!

Help! Screenshots attached:

I was able to find the webform-calendar.tpl.php file that you used Drupal 7 - Change webform date select to textfield with calendar popup.

Basically what it does is adds a text field and hides the drop down date field.

I figuredout that the date field output is controlled in webform.js

You'll need to change from

  // Set up the jQuery datepicker element.
  $calendar.datepicker({
    dateFormat: 'yy-mm-dd',
    yearRange: startYear + ':' + endYear,
    firstDay: parseInt(firstDay),
    minDate: startDate,
    maxDate: endDate,
    onSelect: function (dateText, inst) {
      var date = dateText.split('-');
      $webformDatepicker.find('select.year, input.year').val(+date[0]).trigger('change');
      $webformDatepicker.find('select.month').val(+date[1]).trigger('change');
      $webformDatepicker.find('select.day').val(+date[2]).trigger('change');
    },
    beforeShow: function (input, inst) {
      // Get the select list values.
      var year = $webformDatepicker.find('select.year, input.year').val();
      var month = $webformDatepicker.find('select.month').val();
      var day = $webformDatepicker.find('select.day').val();

      // If empty, default to the current year/month/day in the popup.
      var today = new Date();
      year = year ? year : today.getFullYear();
      month = month ? month : today.getMonth() + 1;
      day = day ? day : today.getDate();

      // Make sure that the default year fits in the available options.
      year = (year < startYear || year > endYear) ? startYear : year;

      // jQuery UI Datepicker will read the input field and base its date
      // off of that, even though in our case the input field is a button.
      $(input).val(year + '-' + month + '-' + day);
    }
  });

to

  // Set up the jQuery datepicker element.
  $calendar.datepicker({
    dateFormat: 'dd-mm-yy', // changed
    yearRange: startYear + ':' + endYear,
    firstDay: parseInt(firstDay),
    minDate: startDate,
    maxDate: endDate,
    onSelect: function (dateText, inst) {
      var date = dateText.split('-');
      $webformDatepicker.find('select.year, input.year').val(+date[2]).trigger('change'); // changed
      $webformDatepicker.find('select.month').val(+date[1]).trigger('change');
      $webformDatepicker.find('select.day').val(+date[0]).trigger('change'); // changed
    },
    beforeShow: function (input, inst) {
          // Get the select list values.
          var year = $webformDatepicker.find('select.year, input.year').val();
          var month = $webformDatepicker.find('select.month').val();
          var day = $webformDatepicker.find('select.day').val();

          // If empty, default to the current year/month/day in the popup.
          var today = new Date();
          year = year ? year : today.getFullYear();
          month = month ? month : today.getMonth() + 1;
          day = day ? day : today.getDate();

          // Make sure that the default year fits in the available options.
          year = (year < startYear || year > endYear) ? startYear : year;

          // jQuery UI Datepicker will read the input field and base its date
          // off of that, even though in our case the input field is a button.
          $(input).val(day + '-' + month + '-' + year); // changed
        }
      });

4 lines changed, I marked them with // changed

Save the new file in /sites/themes/YOURTHEME/js/webform.js

You can use hook_js_alter to replace the JS file.

/*
 * Implements hook_js_alter
 */
function YOURTHEME_js_alter(&$javascript) {
  if (!empty($javascript['sites/all/modules/webform/js/webform.js'])) {
    $javascript['sites/all/modules/webform/js/webform.js']['data'] = drupal_get_path('theme', 'YOURTHEME') . '/js/webform.js';
  }
}


How can I add entity base field with unique constraint if some entities already exist? The issue is that adding a base field to a custom entity type in code would result in an issue of unique constraint violation as there does not seem to be a way to preset the value to the newly added field.

setInitialValue() would set the same value for all the existing entities triggering a constraint violation.

setInitialValueFromField() would not do any good as it would only allow fetching value from fields of same type. Otherwise it would be possible to utilise the value from an ID field and then replace those initial values with something more suitable.

Is there any meaningful way for doing that?

I think you'd need to write an update hook to first add you new base field via the EntityDefinitionUpdateManager (an example here since automated entity updates were removed.)

function example_update_8701() {
  // Add the unique constraint, etc.
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $field_storage_definition = $entity_definition_update_manager->getFieldStorageDefinition('hostname', 'comment');
  $field_storage_definition->setDefaultValueCallback(Comment::class . '::getDefaultHostname');
  $entity_definition_update_manager->updateFieldStorageDefinition($field_storage_definition);
}

Then in a post_update hook, you would load each entity and populate the new field with values in whatever manner makes sense and re-save.

The two methods mentioned in your question shouldn't be called since you're updating the existing entities rather than creating new ones.


Bind click event to ajaxify form button how the title says I would like to trigger javascript (jQuery) event from generated Drupal form button. I already add an id to the button and added the javascript in theme file like so:

$form['dialogCreateButton'] = array(
    '#type' => 'button',
    '#value' => t('Create'),
    '#ajax' => array(
        'callback' => 'form_kalendar_dialog_validate',
        'progress' => array(
            'type' => 'throbber', // needs to be defined
            'message' => t("Please wait..."), // instead of a message insert a javascript
        ),
    ),
);

and the javascript:

jQuery("#edit-dialogsavebutton").bind('click',function(event) {
    if(jQuery("#dialog-event-title").val().length == 0){
        focusElement.children("#eventTitle").text('(No title)');
    }else{
        focusElement.children("#eventTitle").text( jQuery("#dialog-event-title").val() );
    }
    jQuery('#dialog').dialog('close');
});

also with Drupal js:

Drupal.behaviors.rr = {

    attach: function(context, settings) {
        jQuery('#form-kalendar-dialog').once().ajaxComplete(function(event, xhr, settings) {
            console.log( event );
        });
    }
}

Only after several clicks the event is triggered, it acts very strange...

Ajax callback function must to have an ajax_command_invoke function witch trigger an custom made function in JS side like so:

function form_kalendar_dialog_validate($form, &$form_state) {
  $commands = array();
  $commands[] = ajax_command_invoke(NULL, 'customMethod', array('Custom Method Arg.'));
  return array('#type' => 'ajax', '#commands' => $commands);
}

JS

(function ($) {
  $.fn.customMethod = function(arg) {
    // Custom JS goes here.
    console.write(arg);
  };
}) (jQuery);

The answer whas here: Tlattimore blog


How do you set a node reference field's default value when creating a node programatically? I use this:

$values = array(
  'type' => 'competition',
  'title' => 'my title goes here',
);
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($values);

This works perfectly. But the problem is, I also have a node reference field called "field_competition_node_reference". But this doesnt work:

$values = array(
  'type' => 'competition',
  'title' => 'my title goes here',
  'field_competition_node_reference' => 1,
);

How would one go about doing this? The value on the object is "target_id". Maybe that's why "create()" doesnt work?

This should work :

$values = [
  'type' => 'competition',
  'title' => 'my title goes here',
  'field_competition_node_reference' => [['target_id' => 1]],
];
Node::create($values);


Why does the Configuration Management module warn not to use in production? In the Configurations Management module, right before you click the Import button, it warns:

  Importing configurations will write your configurations directly to the activestore. DO NOT USE THIS ON A PRODUCTION SITE!

Should I heed this warning? If so, why? What's the point of this module if it shouldn't be used in production?!

As you can see module is in Alpha phase. It's available for community testing so that they can able to fix issues and make it stable.

Every project in Drupal.org go through different phases. Please see more above Project Versions here.

Alpha version refers to

  These are the first to come out, and are therefore the least stable.
  Most reported errors are resolved but there are most likely still
  outstanding known issues, which might include security issues.

  These releases are not yet stable enough for production use, but are
  essential milestones on the way towards the official release. They
  allow a much wider pool of users to test the latest code and provide
  feedback before the official stable release. These releases should
  only be downloaded and used by developers very familiar with Drupal or
  those wishing to help find bugs in the software.

Since Drupal projects entirely community driven, Module maintainers releases projects for testing. Once they are stable you can use them in Production Environment.


What version of Drush is compatible with Drupal 6 / PHP 5.2 Just installed drush on a system using PHP 5.2.  However, when I run drush, a message is displayed saying Your command line PHP installation is too old. Drush requires atleast PHP 5.3.0. To suppress this check, set the environment variable
DRUSH_NO_MIN_PHP=1.  Since I am using Drupal 6 I need to use PHP 5.2. Could someone please tell me which version of Drush is compatible with Drupal6 / PHP5.2.

A list of Drush versions and their compatibility can be found here. Appears Drush Version 5.x is compatible with php5.2.

Here is the current compatibility table reproduced from the link above


How to change the number of Administration Views results in the Drupal back end? How can I change the number of list items (results), using Drupal's back end?

Is it possible to filter how many results, instead of having multiple pages of items? Something to select like 10, 50, 100, 500, ALL? Should be a simple setting, but can't find it.

I've installed Administration Views, but it's a pain since I have to adjust a dozen views, one by one.

To my knowledge, there is no such thing as a "global setting" within Drupal administration (what you call "back end") to set such "how many results".

The only way to do so (assuming you use Drupal 7), is to perform these steps for each of the individual views where you want to set "how many results" you want:

Use the Views UI to edit the view.
In the 2nd column, within Pager:

Use pager:  use the options "Display a specified number of items".
Pager options: set the "Items per page" to "how many results" you want.


How to select only time without attaching a date? Is there a field in Drupal 8 that lets you select a time without actually selecting a date? Or should you just use datetime?

You can use datetime element and disable date widget:

$widget['time_container']['time'] = [
  '#type' => 'datetime',
  '#title' => $this->t('Time'),
  '#size' => 20,
  '#date_date_element' => 'none', // hide date element
  '#date_time_element' => 'time', // you can use text element here as well
  '#date_time_format' => 'H:i'
];


View display content by value based on user profile field values I need to create a view that displays saved content with defined field values to users with specific attributes.   I.E.

content form with a field boolean of regulated:
  [0] unregulated
  [1] regulated
  [2] both

the view needs to display this content depending upon the user profile value for whether that user is licensed or not.  field value of both needs to display regardless of profile value for licensed.

profile field licensed is a boolean.  0 non-licensed, 1 licensed.

There will be content marked as regulated that needs only to be displayed to licensed users, content that is not regulated that needs only to be displayed to non licensed users, and content that is marked for both that needs to be displayed to both licensed and non-licensed users.

Can this be done in views or do I need to write custom php to accomplish this?

You may use the flag module to flag users (it could be an automatic flagging in conjunction with Rules)as regulated, unregulated or both and then filter via views all flagged users. For anonymous users needs some  special handling.


Error guzzlehttp/guzzle ^6.3 -> no matching package found when update from 8.7.9 to 8.8.1 When i tried to update my project using composer from 8.7.9 to 8.8.1 i get the following error:

Command:

composer update drupal/core --with-dependencies

  [Composer\DependencyResolver\SolverProblemsException]
    Problem 1
        - Installation request for drupal/core 8.8.1 -> satisfiable by drupal/core[8.8.1].
        - drupal/core 8.8.1 requires guzzlehttp/guzzle ^6.3 -> no matching package found.
      Problem 2 .
        - drupal/core 8.8.1 requires guzzlehttp/guzzle ^6.3 -> no matching package found.
        - drupal/ultimate_cron 2.x-dev requires drupal/core ^8.5 -> satisfiable by drupal/core[8.8.1].
        - Installation request for drupal/ultimate_cron ^2.0 -> satisfiable by drupal/ultimate_cron[2.x-dev].

  Potential causes:
     - A typo in the package name .
     - The package is not available in a stable-enough version according to your minimum-stability setting .
       see https://getcomposer.org/doc/04-schema.md#minimum-stability for more details.
     - It's a private package and you forgot to add a custom repository to find it

Any ideas ?

I have just to remove the vendor Folder it works now:
For the complete steps see 8.5.6 Update not being recognized .


Drupal jquery behaviors & views - Ajax multiple times / wrong arguments - triggerHandler('RefreshView') I am having some problems using ajax to trigger an views update (D7).

Basically there is a map (leafletMap) and when it is moved/changed/zoomed, a function gets a list of node ids and triggers a views ajax refresh.
Those node ids are passed into a contextual filter, so only matching packages in that view are displayed below the map.

The problem with the ajax is it often fires multiple ajax requests. When I inspect the extra requests one or two will have the correct arguments, but one will have the old arguments and then the view will refresh with the wrong nodes.

I've tried using return false and binding what I can to this or context. As you can see I've tried unbind()ing the
 but nothing seems to help. Often the first set of ajax calls append the wrong view, but then the next one works. And so on. To be honest I'm a bit out of my depth.

Basically I need there to be one ajax call with the correct arguments, or at least multiple ajax calls that use the correct arguments.

Any hints, ideas or suggestions would be most welcome. Many thanks.

TLDR; The below code triggers an ajax refresh of a view. This view has a contextual filter. It is triggering multiple ajax requests, some of which retain the old ajax arguments & therefore refresh incorrectly. Thanks!

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

      if (typeof window.leafletMap === 'undefined' || window.leafletMap.length == 0) {
        return;
      }
      this.leafletMap = window.leafletMap[0];
      this.leafletMap.$map.once(function () {
        this.leafletMap.map.on('moveend', this.refreshView.bind(this));
        return false;
      }.bind(this));
      // Reset arguments back to default when not filtering map.
      $.each(Drupal.settings.views.ajaxViews, function (key, value) {

        if (value.view_name === 'packages') {
          Drupal.settings.views.ajaxViews[key].view_args = '';
        }

      });
      $('.views-exposed-form-packages-search', context).attr('action', '/packages.json');
    },

    refreshView: function (context, settings) {

      Drupal.attachBehaviors('ViewsAjaxView');

      // This gets markers from the map and converts them to node ids
      var visibleMarkers = this.leafletMap.getVisibleMarkers();
      var totalMarkers = this.leafletMap.markers.length;

      // Do not run if map isn't filtered.
      if (visibleMarkers.length < totalMarkers) {

        var visibleMarkers = this.leafletMap.getVisibleMarkers();

        var nids = '';
        $.each(visibleMarkers, function (i, v) {
          nids += v.node.nid + '+';
        });
        nids = nids.slice(0, -1);

        // nids is an array of node ids for the view to return

        $.each(Drupal.settings.views.ajaxViews, function (key, value) {

          if (value.view_name === 'packages') {
            // this should add the node ids as an views ajax argument
            // to a contextual filter
            Drupal.settings.views.ajaxViews[key].view_args = nids;
          }

        });

        var throbber = '

&nbsp;

';
        $('.views-submit-button').append(throbber);

        $.each(Drupal.settings.views.ajaxViews, function (key, value) {

          if (value.view_name == 'packages' && value.view_args == nids) {
            $('.view-id-packages').triggerHandler('RefreshView');
          }

        });

        $('.view-id-packages').unbind();

      }
    }
  }

For the sake of posterity & future visitors with this issue, here is how I eventually got it to work.

refreshView: function (context, settings) {
  // Unbind event to prevent multiple ajax refreshes.
  $('.view-id-packages').unbind();
  Drupal.attachBehaviors('ViewsAjaxView');

  // When map changes, update the grid of packages below the map.
  var visibleMarkers = this. leafletMap.getVisibleMarkers();

  // Get all the node IDs to pass into the views contextual filter.
  var nids = '';
  $.each(visibleMarkers, function (i, v) {
    nids += v.node.nid + '+';
  });
  nids = nids.slice(0, -1);

  // Update the Drupal ajax object to use our new set of node IDs.
  $.each(Drupal.settings.views.ajaxViews, function (key, value) {
    if (value.view_name === 'packages') {
      Drupal.settings.views.ajaxViews[key].view_args = nids;
    }
  });

  // Add the throbber on since it doesn't show automatically.
  var throbber = '

&nbsp;

';
  $('.views-submit-button').append(throbber);
  // Trigger the ajax.
  $('.view-id-packages').triggerHandler('RefreshView');
}

And then my view > advanced > contextual filter looks like:


Get value of a field attached to a user entity based on currently logged in user I add a taxonomy selection to the registration from config/account called field_user_class.

Now for my module I need a function that returns the this field value for the currently logged in user, and shows it to them.

I just need the function to return this field for the logged in user.

global $user;
// Only if logged in
if($user->uid) {
  $logged_in_user = user_load($user->uid);
  $field_user_class = field_get_items('user', $logged_in_user, 'field_user_class');
  // Do stuff with array $field_user_class
}


Why does Behat throw an error on "ucan "? In our Behat tests we delete all test users in a before-hook. But sometimes our Behat test throws an error like:

  Could not find a user account with the name vN8eLbrd!

  Could not find a user account with the name some.wiredstuff-registration-test_10706!

Strange thing is that I get this user name direct from database. So I do not understand why this drush ucan command can not find it.

/** @beforeScenario */
  public function before($event) {
    $this->getSession()->getDriver()->resizeWindow(1280, 1024);

    // List all Scenarios which create the testuser.
    $scenarios = array(
      'Register for testing with Credit-Card',
      'Register for testing with Paypal',
      'Register for testing with valid Direct-Debit',
      'Register for testing with invalid Direct-Debit',
      'Access my subscriptions page',
      'Register for testing',
      'Register and use link from registration mail',
      'Logout',
      'Log in with username and password',
      'Recover your password'
    );

    $users_to_clean = array(
      'test@muster.de',
      'shaka@test.de',
      'some.wiredstuff+behat-registration-test@gmail.com'
    );

    $title = $event->getScenario()->getTitle();

    // Delete Testuser before the Scenario.
    if (in_array($title, $scenarios)) {
      foreach ($users_to_clean as $mail) {
        $user = user_load_by_mail($mail);
        if ($user) {
          shell_exec('drush ucan ' . $user->name . ' -y');
        }
      }
    }
  }

Problem with not deleted users is that other tests fail because a test user already exists.

Do you have a clue why this happens?

While debugging with xdebug in PhpStorm I figured out that user_load_by_mail($mail) loads cached users. user_load_by_mail() uses this function:

/**
 * Load multiple users based on certain conditions.
 *
 * This function should be used whenever you need to load more than one user
 * from the database. Users are loaded into memory and will not require
 * database access if loaded again during the same page request.
 *
 * @param $uids
 *   An array of user IDs.
 * @param $conditions
 *   (deprecated) An associative array of conditions on the {users}
 *   table, where the keys are the database fields and the values are the
 *   values those fields must have. Instead, it is preferable to use
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
 *   this function.
 * @param $reset
 *   A boolean indicating that the internal cache should be reset. Use this if
 *   loading a user object which has been altered during the page request.
 *
 * @return
 *   An array of user objects, indexed by uid.
 *
 * @see entity_load()
 * @see user_load()
 * @see user_load_by_mail()
 * @see user_load_by_name()
 * @see EntityFieldQuery
 *
 * @todo Remove $conditions in Drupal 8.
 */
function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
  return entity_load('user', $uids, $conditions, $reset);
}

But it calls this function without $reset == true. That's why it uses cached user objects and tries to delete an already deleted user.

I fixed this lines with:

// Delete Testuser before the Scenario.
    if (in_array($title, $scenarios)) {
      foreach ($users_to_clean as $mail) {
        $users = user_load_multiple(array(), array('mail' => $mail), true);
        $user = reset($users);
        if ($user) {
          shell_exec('drush ucan ' . $user->name . ' -y');
        }
      }
    }


I facing a problem when i want create two registration forums by using (profile2 & profile2 registration path) modules? i want create two registration forums ,each forum in specific page , when i looking for solution in internet, i found it using profile2 & profile2 registration path modules.

But when i working in it , i facing a new problem , the problem is the users can't find registration forums ,because they doesn't have a link or (way to access in forums ) for registration !?

Example :

i have two roles A & B.

URL path for A : {mysite/A/register}

URL path for B : {mysite/B/register]

When user A click on page to create new account can't going to {mysite/A/register} link !!!

Any ideas ??

thanks in advance

Fully not clear problem but you can try by this way

Hook: user A, user B
User: user-profile.tpl.php

if((arg(A)=='user') && is_numeric(arg(1)))
{
$profile = profile2_load_by_user(arg(1));


Webform Conditionals and Email Values The scenario is, I have a form that you order multiple types of stationery. Depending on what items are ordered determines, what email needs to be sent the form results.

The issue I am running into is I need a way to prevent emails from being sent to the other print vendors if their fields are left blank.

Right now they all receive every email it just shows up blank because I have it set to exclude blank fields.

Any guidance would be greatly appreciated!

You may want to try out the Rules module. It allows a lot of powerful conditions and actions to be configured. You may also pair it with the Webform Rules module to connect it to your Webforms (https://www.drupal.org/project/webform_rules).


text_format field value not appearing in full_html mode I'm using a block plugin to display content based on what the user inputs into a form. Select boxes, and radio buttons are saved and displayed in the form just fine but the text_format field isn't working the same way.

public function blockForm($form, FormStateInterface $form_state){

    $form['bodytext'] = array(
      '#type' => 'text_format',
      '#title' => $this->t('Block contents'),
      '#format' => 'full_html',
      '#description' => $this->t('This text will appear in the block.'),
      '#default_value' => $this->configuration['bodytext-submit'],
    );
}

public function blockSubmit($form, FormStateInterface $form_state) {

    $this->configuration['bodytext-submit']  = $form_state->getValue('bodytext');
}
public function build(){

    return array(
        '#title' => '',
        '#type' => 'markup',
        '#markup' => '<div>' . $this->configuration['bodytext-submit']['value'] . '</div>',
    );
}

Anything input into the text_format element in the form is saved properly but when returning to the form, the field is empty unless the format is set to 'basic_html'.
So I know the values are being saved, and are even presently available in the configuration form of the block. It simply isn't displayed in 'Full_html' mode.

You don't need to eliminate the #format.

The format and value of the text_format are stored as an array. So in the same way as you retrieve the value you can retrieve the format.

See this example:

public function blockForm($form, FormStateInterface $form_state) {

  $body = !empty($this->configuration['body']) ? $this->configuration['body'] : '';
  $form['body'] = array(
    '#type' => 'text_format',
    '#title' => 'Body',
    '#format' => isset($body['format']) ? $body['format'] : 'full_html',
    '#default_value' => isset($body['value']) ? $body['value'] : '',
  );
  return $form;
}

public function blockSubmit($form, FormStateInterface $form_state) {
  $this->configuration['body'] = $form_state->getValue('body');
}


Adding a stock while adding a product How can I add stocks in Ubercart while adding products?

I insert a new field in the product setting. How can I link the stock with the product?

Thanks for asking...monymirza.
 finally i find the solution .

After adding the product instead of save click save and continue it will lead to edit page whre we can add stock numbers..


How can I include standard bits of text in a node, depending on the node location or a particular term? I have a product page that is mostly original content, however I would like to include a block of text that is included on similar nodes. Eg, I have several pages for hotels in London, so I would like to include a block of text called 'About London', which then carries a couple of paragraphs about London.

I assume that this could be made to happen based on the node's Location or for a particular term attached to the node, but I don't know the best way forward with what I'm trying to do.

If you create a new content type, say "Location Description", you could add a node reference field into your hotel content type referencing the respective location node.


Ckeditor fake linebreaks with pasted text Problem

When you paste text into ckeditor it creates line breaks in the display which don't appear in the actual text.

How can I either paste in text and have it create actual linebreaks, or paste in text and not show the fake linebreaks?

Example

In order to create an actual line break you have to press delete and then add two returns in order to create a genuine linebreak (I have CKEditor configured to create
 on enter).

Sample Text I Used: Taken from Dolor Ipsum Website

(Shown in HTML Full Text format)

bibendum feugiat tortor a imperdiet. Ut nisl lorem, bibendum iaculis est quis,    mollis convallis neque. Vestibulum vitae erat vitae sem tempus consequat.

Integer a auctor lorem, sit amet sagittis lectus. Sed bibendum at purus eu mollis. Sed pretium tincidunt nulla vitae fringilla. Etiam ac fringilla nulla. Cras lectus magna, suscipit sed felis accumsan, sagittis lobortis justo. Vestibulum volutpat auctor mi, at&nbsp;

If you're experiencing weird behavior on the editing side of CKEditor it's probably because of the CSS file being loaded by CKEditor.

CKEditor implements this in a way where it doesn't show up in my firebug.

I can see the margins and padding when I hover on an element however nothing is shown when it lists the styles effecting the element. This causes the problem above.

How to fix it:

Changing the CSS file works, go to the CKEditor configuration page and select the CSS drop down menu.

Change CKEditor default to Define CSS and enter your own path for the CSS file.

What I did however was edit the CKEditor default css file. It's located in ../modules/ckeditor/ckeditor/contents.css

I was getting a margin of 20px appearing on the top and bottom of all my elements. There was nothing in contents.css about it, I don't really know where it's coming from.

But I added the following snippet which fixed it.

p,
h1,
h2,
h3,
ul li {

margin: 0 auto;

}


How to force Views (or whole Drupal) to lowercase page paths? Is it possible to force Views to always lowercase URL paths? Here is a detailed example. I'm using contextual filters to filter by node field (field's name is country). Here are the node examples:

Node title: Madrid | country: spain
Node title: Rome | country: italy

Country name values are intentionally lowercased. Now I create a country contextual filter with this path: results/%. These are the results:

Path: results/spain
Result: Madrid

Path: results/Spain
Result: Madrid

Path: Results/Spain
Result: Madrid

I want the results to be available only on these paths:

results/spain

results/italy

Is there a way to force Views to convert all of the paths to lowercase letters? If it's not possible in Views, is there a way to make Drupal convert all of the URL requests to lowercase paths?

This is untested, but I believe you can use a hook_url_outbound_alter() for this, since I think Views URLs still get run through url() when they get generated:

function MYMODULE_url_outbound_alter(&$path, &$options, $original_path) {
  $path = drupal_strtolower($path);
}

(Updates to address some comments post acceptance.)

This should update URLs that get generated by Views, and will prevent the uppercased ones from getting out into the wild.

Drupal 7 is case-insensitive with regards to inbound URL routing.  However, I am not 100% sure this is always the case with Views arguments being pulled from the URL.  I suspect that the base part of the path w/o the argument is being matched by Drupal as case-insensitive, and the argument is matching case-insensitive because of database collation being case-insensive.


Instant Drupal documentation I am on Drupal 7. I would like to ask if you know of any Drupal modules or tools that will 'spit' (sorry for using this term) an instant documentation of a given Drupal install (Drupal version, installed modules list, installed modules versions and maybe some more information). Thank you!

I'm not sure about one module to do it all, but Enabled Modules will show you the list of modules and their versions.

To view a sites status, and Drupal version, you can log in and visit admin/reports/status


Filter entities in a view by referenced entity I am creating a website in Drupal 8 that shows info about team members of a business.

I've created two new content types:
- Department
- Team Member

I've created an entity reference field in team member that refers to the department he/she works for. The relation is many to many so I allowed multiple values.

Now I want to create a menu item for each department and when clicked a page shows with the team members working for that department.

I am totally new to Drupal so please explain steps in details :)

I've tried creating a view and add "Entity Reference" but I don't know how to proceed after that.
I also tried to add a filter criteria but didn't work as well.

Phase1:
You would need to construct a view using contextual filters, relationships and dynamic path (url) to display team members for a department.

First create a view with Content type of Department. Also enable Create a page and add path like for example, /department/%. Here % is used to make your path dynamic (to pass arguments such as nid using contextual filters). Then click continue & edit.
Now in your view under the advanced section, add a reverse relationship to your team member content type. You should select something like A bridge to the content entity that is referencing content via field_teammember. The field_teammember is an entity reference field from team member content type.
Next under fields, add all the required fields you need. If you add any of your team member content type fields, do not  forget to add relationship in those fields settings.
Again under the advanced section, add contextual filters. Select Content:Nid and in the settings do not add relationship because this Nid will be of the department content type (base table of your view).
In the same contextual filter configuration, under When the filter value is NOT available section, select provide default value and then select type as Raw value from URL. The path component value will be the position of % in your url. In the path you specified /department/%, its in the second position. Select 2 for your path component value and click apply.

This should have already generated a view as you required.
Now to preview your view, find an Nid of any department node and paste it in the Preview with contextual filters and click update preview. This will display the team members of that department.

Phase2:
Now create a view of departments list for menu items.

Create a view and select Content type of Department. You do not require a page for this view. Click Continue & edit.
Under fields, if you already have a Title field as your department name then add only an Nid field. And in the Nid field settings enable Exclude from display.
Note: If you don't have title field as your department name, then remove the title field and add a department name field.
Now if you are using title field, disable Link this field to the original piece of content option. Then expand Rewrite results section and enable Output this field as a link. In the link path, add your dynamic url created for previous view like www.xyz.com/department/[nid].
Note: In the link, Nid is replaced with %. This could be some other value in your view, so you need to get this from Replacement Patterns in the field settings.

This will create another view for your departments list.
Now install and enable Menu views module if you don't have it. Next in the Administrator/Structure/Menus, create a menu and in the settings select departments list view to display the list as menu items.
Hope this helps.


What hook should I use to alter the File Upload field in Webform 7.x-4.16 In Drupal 7 Webform file field, might there be a way to access the link provided after the a file is uploaded?

The reason is that we have a hot-folder/watch-folder process that runs, cleans a file, converts DOCs to PDFs, checks for accessibility, etc. I'd like to link to converted version of that file.

We want to allow the user submitting everything to ensure their document is converted properly before they click the submit button.

I believe you could go far with hook_form_alter in drupal 7. Unless you're implying a multiple step webform where some webform hook may apply.

Browse over the webform.api.inc file in the module folder and if none of the hooks sound good for your needs try a simple form alter.


Why is my table not automatically created at the time of custom module install? I am writing a custom module for Drupal 7. For the table creation I have created the .install file, but the table is not getting created automatically, when the module is installed. I have already uninstalled and reinstalled the module many times. All the times I do it, I get the following error:

  Base table or view not found: 1146 Table 'drupal.drupalform' doesn't exist

This is the code in the drupalform.install file.

function drupalform_schema() {
    $schema = array();
    $schema['drupalform'] = array(
        'description' => t('A table for holding the drupalform data!'),
        'fields' => array(
            'id' => array(
                'description' => t('Auto increment of the ID'),
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
            'name' => array(
                'description' => t('Person\'s first name.'),
                'type' => 'varchar',
                'length' => 64,
                'not null' => TRUE,
            ),
            'last_name' => array(
                'description' => t('Person\'s last name.'),
                'type' => 'varchar',
                'length' => 64,
                'not null' => TRUE,
            ),
            'email' => array(
                'description' => t('Person\'s email'),
                'type' => 'varchar',
                'length' => 64,
                'not null' => TRUE
            ),
        ),
        'primary key' => array('id'),
    );
    return $schema;
}

function drupalform_install() {
    drupal_install_schema('drupalform');
}

function drupalform_uninstall() {
    drupal_uninstall_schema('drupalform');
}

The following line is not correct.

'primary_key' => array('id'),

Replace 'primary_key' with 'primary key'.

In Drupal 7 you do not need to call drupal_install_schema() nor drupal_uninstall_schema() for the database tables your module uses.

You can just declare the functions.

function drupalform_install() {}

function drupalform_uninstall() {}

Just update the code, uninstall the module, and re-install it.


Create a view to display last browsed content I want to create a view to display last browsed content by the user. My site has a lot of content and I want to create a view, either a page or a block, to show the last browsed content by the user. That view should show the last browsed content first followed by rest. Say for example, content A was browsed 10 seconds ago, content B 10 minutes ago and content C was 1 hour ago, then the view should list them in the order: A    B   C.

Thanks

I am able to do so using the sort criteria timestamp by the Radioactivity module.

  This module provides a field type which can be used as a hotness metric or a regular view counter for entities and for much much more. In essense, entities receiving attention (views or actions defined by Rules) are heated while inactive ones slowly cool down.


Contextual filters with multiple taxonomy vocabularies I have vocabulary "City":

New York
London

and vocabulary "Places" i.e.:

restaurants
cafes

The menu link is, e.g. mysite.com/london.

When a user click on a tag, e.g. cafes, I want the term city term to stay them same
in the url mysite.com/london, but to add the places term on the end, e.g.: mysite.com/london/cafes in London, so that it only shows cafes. I.e. not mysite.com/cafes, which will show cafes anywhere in the world.

How can I do this please?

I think you will need the following setup to work. I'd test this extensively, as it seems somewhat fragile.

a) Prefix your city taxonomy path alias pattern to something like 'cities/[term-name]'. You can't create a view page with a path that starts with an argument.

b) Add another view (you may want to disable the default tax term view or alter the default taxonomy term view ) with 2 contextual filters, 1) Content: Has taxonomy term ID set to provide default value (raw path using 2 component and alias) restricted to the city vocab. and 2) Content: Has taxonomy term ID set to provide default value (raw path using 2 component and alias) restricted to the places vocab.

These contextual filters will share these settings: in the validation criteria, Filter value type set to 'Term name converted to Term ID' and tick the 'Transform dashes to URL to spaces in term name filter values' checkbox.

For the second contextual filter, set 'Action to take in filter value does not validate' to "Show all", which will allow you show all results when viewing 'cities/london'.

Note, using this technique can be problematic if you anticipate any of your terms containing apostrophes, b/c the path alias for a term with an apostrophe can be name-s-something and this won't be converted to a term id.

c) Then, you'll need to alter the link generated by your existing unordered list of places view. Not sure how to go about this in the UI alone. If you share your exported view code, I'll take a look. If you can, you could create a view field template file to retrieve arg(0) and arg(1) and then use those results to generate the link in the template file.


Views entity object sometimes missing Problem

I'm trying to pull data from the entity objects on a views page that is rendered using Search API. I'm trying to pull the data from hook_views_post_render.

Views appears to sometimes load the entire entity in the path:

$view->result[x]->_entity_properties['entity object']

However it doesn't always. Sometimes the objects are just missing and I can't pull data from them. (They appear on flushing the cache and then disappear a couple normal browser refreshes after.)

Does anyone know why this happens? I was wondering if they were cached, but they don't appear in $cache or $view i.e.:

hook_views_post_render ($view, $output, $cache)

This is because I have search specific caching enabled on the view. This is a Search API caching plugin for views which caches both the results of a query and the HTML (I think).

So when a query is repeated it returns the HTML and doesn't load the entity objects. Because that's the entire point of the cache! (In fact it skips the entire view generation, i.e. both hooks like module_views_post_render and theme_preprocess_views_view)


Duration of NEW marker for content What is the duration of the 'NEW' tag that is being added when creating new content? How do I change it so it would last until the content is edited, after that the NEW marker would disappear.

You can find NEW marker in red in admin/content

I do not understand how this works, content added yesterday and today are all marked as NEW which is misleading. I'd like to be able to change it.

The default is 30 days, per the NODE_NEW_LIMIT constant.

Nodes changed before this time are always marked as read.
Nodes changed after this time may be marked new, updated, or read, depending on their state for the current user. Defaults to 30 days ago.

Since use of that constant is hard-coded in node_mark(), I imagine you'll need to provide your own 'marking' system if you want to do things differently to the core version.


Block that shows nodes based on node type I want to create a module that displays nodes of a certain node type. Can this be done, and can anyone point me to a place where I can find how to do this?

There's currently 12,966 sites using the beta3 release of Views 7 (http://drupal.org/project/usage/views). I'd suggest that you install the module and try to produce what you're describing as I suspect it will work fine. A beta3 release suggests that the module is nearing a production release with no new functionality being added.

Be brave, adopt the new software rather than painting yourself in a corner by writing your own custom code.


Change the e-mail value during user registration ?  form_set_value() I have a custom module (entitled ta_module) : in the user registration form, it hides the e-mail field, and add a custom field where user have to enter what's before @ and then choose his e-mail domain name between the one proposed in a list next to it.

Here's the code :

<?php

/**
 * Implementation of hook_form_alter()
 */
function ta_module_form_alter(&$form, &$form_state, $form_id) {

   // If the form is the user_register form
    if ($form_id == 'user_register_form') {
        // Attach our custom validation function as the first validation function
        array_unshift($form['#validate'], '_ta_module_user_validate');
        // Hide the email address field
        $form['account']['mail']['#type'] = 'hidden';
        // Give the email address field a random default value (in this case a random number and a timestamp)
        // as we cannot unset it due to Drupal's validation rules
        $form['account']['mail']['#default_value'] = rand(1111, 9999) . '@' .time() . '.com';
        // Add our new text entry field
        $form['mail_first'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#default_value' => '',
      '#size' => 35,
      '#maxlength' => 64,
      '#required' => TRUE,
    );
        // Add our select list of possible email domain values
        $form['mail_last'] = array(
      '#type' => 'select',
      '#title' => 'Domaine',
      '#title_display' => 'before',
      '#options' => array(
              // These are the possible email address domains
              'myentreprise.net' => '@myentreprise.net',
              'myentreprise.com' => '@myentreprise.com',
            ),
      '#default_value' => 'myentreprise.net',
      '#required' => TRUE,
    );
    }
}

/**
 * Function to piece together our email address
 */
function _ta_module_user_validate(&$form, &$form_state) {
    // If our two form elements have values
    if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
        // Set the email address to the correct value
        $form_state['complete form']['account']['mail']['#value'] = $form_state['input']['mail_first'] . '@' . $form_state['input']['mail_last'];
    }
}

(see This Q/A for more infos).

All appear quite brightly, but when the user click on "create a new account", the user is created but the last function of my module doesn't work : the e-mail finally saved is the default value (something like 0129A@I1I101IZ10IZ.com) instead of the two pieces joined together...

HOW TO FIX THIS : Thus how to assign to mail the value of mail-first + mail-last ?

/!\ I'm working on Drupal 7, so I think it's an issue of uncorrect variables...

Thks for reading !  ;)

If you need to set the value for the form field used to contain the email address, then you should use code similar to the following one:

function _ta_module_user_validate(&$form, &$form_state) {
  if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
    form_set_value($form['account']['mail'], $form_state['values']['mail_first'] . '@' . $form_state['values']['mail_last'], $form_state);
  }
}

As an example of how form_set_value() is used, see system_site_information_settings_validate(), which contains the following code:

// Check for empty front page path.
if (empty($form_state['values']['site_frontpage'])) {
  // Set to default "node".
  form_set_value($form['front_page']['site_frontpage'], 'node', $form_state);
}
else {
  // Get the normal path of the front page.
  form_set_value($form['front_page']['site_frontpage'], drupal_get_normal_path($form_state['values']['site_frontpage']), $form_state);
}


Setup a view to show most recent post or a post promoted to front page I setup a view that displays published articles from a specific content type. I want to guarantee an article always displays, so I'd like to order the results to show the most recent post.  That is easy enough to do using Filter Criteria and Sort Criteria in the View Block.

What I also want to do is if my authors decide to promote an article to the homepage, I'd like that article to get priority over the date sort criteria so that the article marked promote to homepage is the one that displays.

In the event that two or more articles are marked promoted to front page, I'd like the most recent article marked as promote to front page to be the one that appears.

I tried to create a new block in the same view that displays the most recent post and I tried to add that block entity to the No Results Behavior, but I am not sure if I was doing that right because it always showed blank.  Was I on the right track by doing it that way?

Is there a way to do this in a view block in Drupal 8?

You are on the right track but, you don't have to create another view block. You can easily add more sort criteria on your existing view block and rearrange the sorting criteria. Also, just a suggestion it is better to use Sticky at top of lists than Promoted to front page.  For more, you can refer to Frontpage views.


Is there a way to use a generic 'Site is Down' page? I recently experienced issues with my hosting company and a few of my sites went down. All users could see was a standard Drupal PDO Exception page. Is there a way I can create/use a page to show a generic "we're having issues, please check back later" page instead of this if a major problem occurs?

Yes, it is quite simple. Just go to "admin/config/development/logging" and set "Error messages to display" to "none". You will then have only the error page with message "The website encountered an unexpected error. Please try again later.". The PDO exception will not be displayed.


Drupal t() function does not replace placeholders for me Why would placeholders not be replaced?

For example, in the Uninstall page for modules, it shows the following.

It happens under the revisions tab as well.

It looks like electrokate installed a Pattern Lab starter theme for Drupal that has a mock of the t() function that acts as a placeholder for prototyping the front end layer. It only returns the input it was sent, so it "works" under Pattern Lab - but running it inside of Drupal will cause this issue.

/**
 * @file
 * Drupal translate filter.
 */
$filter = new Twig_SimpleFilter('t', function ($string) {
  return $string;
});

This is meant to aid in making a Pattern Lab prototype outside of Drupal, but taking advantage of functions you will expect to use inside of Drupal so it is "Drupal ready".

edit: I may have linked to the wrong starter theme, but I can’t navigate it on mobile.


EntityFieldQuery: number of field values as condition I have a node type which has a field that can contain an unlimited amount of images.

I want to retrieve a set of entities, but only entities that contain at least one image.

So far this is my query:

$result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'reference')
    ->propertyCondition('promote', 1)
    ->propertyOrderBy('created', 'DESC')
    ->pager(12)
    ->execute();

How should I use the extra fieldCondition to indicate I only want nodes with at least 1 value for field_images?

Seems like stating the obvious but you need to count the number of values in 'field_images', then you can set the condition to check that result and make sure it is greater than 0.

There's a good overview of adding expressions and conditions with the count() function on this question.

You'll also need to perform a join between 'node' and the table that holds your field values before you make your count, something like this:

$query = db_select('node', 'n');
$query->join('field_images', 'fi', 'n.nid = fi.nid');
...rest of query


node access not taken in account in views using the hook_node_access, i can restrict access to content by role.

If the boolean field_private_only is selected , only the user with the role private can view it, fine.

 my_module_node_access(NodeInterface $node, $op, AccountInterface $account) {

  global $user;
  if ($node->bundle() == 'my_content_type') {
      if ($op == 'view') {
          if ($node->field_private_only->getString()) {
            $user = \Drupal\user\Entity\User::load($account->id());
            if($user->hasRole('private'))
               return \Drupal\Core\Access\AccessResult::allowed();
          }
      }
   }
 return \Drupal\Core\Access\AccessResult::forbidden();
}

When creating a view displaying these contents, the restriction does not occur .

How can i Make it happen in views?

how can i make it happens in search_api index ?

For doing access control on views, i used the hook_views_post_execute.

For nodes with a restricted_content field set to true, the content is shown or not depending on roles

 function my module_views_post_execute(ViewExecutable $view)
 {
$VIP_member=false;
$user=\Drupal::currentUser();
$userRole=$user->getAccount()->getRoles();

if (( $user!=null )&&(in_array('VIP_member',$userRole))){
    $VIP_member=true;
}

if ($view->id() == 'articles_list') {
    foreach ($view->result as  $elementKey => $result ) {
        $node=$result->_entity;

        $VIP_restricted=$node->field_VIP_only->getValue();

        // Remove node if no rights
        if (($VIP_restricted[0]['value'] == true) && ($VIP_member==false) ){
              unset($view->result[$elementKey]);
        }
    }
}
 }


Delete a feature but keep the content created by it Is it possible to keep the data created by a feature after deleting feature itself?
I created a migration feature that is really just a one off; I would want to delete it without losing the nodes created from it.

Features module is a way to export most of the settings normally stored in the database into code. If you delete the feature, you delete the code which deletes everything.

The cool thing about features is you can change the settings for things (views, panels, etc) at any time and those changes get stored in the database. Once they're stored in the database it should be OK to delete the feature (though I haven't tried this myself).

The easiest way to do this would be to go into each item that your feature has and re-save it. For example, if your feature had a view called "News" you can go to Structure > Views > News > Edit. Then click save on that view. If you look at your feature, it should now say "Overridden."

Once everything is overridden, it should be OK to delete the feature. Make sure you do a backup of everything and try disabling the feature first to make sure everything you need doesn't disappear.


Is there an example OAuth2 client module anywhere? Similar to this post and this request, I'm creating a OAuth client in Drupal 7 but using OAuth2.0. There's an OAuth2 module with an unpublished Drupal 7 version that I've toyed with, but it's geared pretty exclusively for servers or proxies, not clients. I've started writing a skeleton module for an OAuth2 client implementation, but before I go any further I wanted to make sure I'm not just spinning my wheels. Are there are any good modules that either implement a web services client using the OAuth2 standard, or a template module that I've missed?

A year later, there is OAuth2 Server which provides the server part only, but has tests which are a good demonstration of client code in Drupal (using drupal_http_request()), so that code can at least be used as an example.
The module documentation also tries to explain basic OAuth2 concepts and potential pitfalls.


Fields UI export to code for editing? I am creating a new registration form with the Fields UI module and need to
be able to add variable_get instances for username, email, etc and also add
select lists for birthday info, typical drop downs like range(1,12), range(1,31),
and range(2015,2012). I'm having trouble trying to figure out how to do this,
or how to put preset variables into my fields. Can I dump this and edit it
myself, or can I put in what I need?

EDIT

I found out that I can use list(int) then select widget type select list to create
select boxes, BUT I still cannot assign things known variables.

To further this along, lets say I have I have $variables['bio']['firstName'], I
am trying to assign name_bio_firstName to the field for name, if that doesn't confuse
anyone more.

You can export it with Features module. Basically it creates a new module which you download and plug into modules folder. There you can further edit it's code.


Starting batch operations from hook_node_update() When importing content using Feeds using an importer associated with a node type, the mapping can be configured to assign taxonomy terms from the Feed Node to the imported Feed Items. On a project, we need to extend this feature by also updating all the already imported Feed Items when a Feed Node is updated.

This can be done using hook_node_update($node). But since a single Feed Node can have a lot of Feed Items, they cannot be all updated in a single HTTP request otherwise we may encounter a timeout. The obvious way to avoid timeouts, is to use the Batch operations API.

Most of the time, hook_node_update() implementations will be executed because node_save has been called from a form submit handler, therefore, most of the time, there is no need to call batch_process from a hook_node_update() since it will be called automatically at the end of the form processing. Calling batch_progress from hook_node_update()  may also produce unexpected result since it will prevent other implementation of the same hook or others hooks to be executed.

But what about the times when the hook_node_update() implementations are not executed from a form submit handler. For instance, when node_save is called from an implementation of hook_cron? Is there a way to detect these cases to either run all the update at once or delay them to a dedicated queue?

As pointed in kiamlaluno's answer, there is no execution context information passed to hook_node_update() implementations. So we ended up using debug_backtrace() to look up for the currently processed form (if any). If a form is processed, drupal_process_form() will handle batch processing for us. If not, we can't safely start a progressive processing of the batch. But we can run the whole batch in a single pass. This can lead to timeout and should really be replaced. Either by delaying operations execution (queued operations) or by starting progressive processing of the batch after all update hook have been run (but how ?).

function _MODULE_get_currently_processed_form() {
  $backtrace = debug_backtrace();
  while ($frame = next($backtrace)) {
    if (isset($frame['function']) && $frame['function'] == 'drupal_process_form') {
      return array(
        'form_id' => $frame['args'][0],
        'form' => &$frame['args'][1],
        'form_state' => &$frame['args'][2],
      );
    }
  }
  return FALSE;
}

function MODULE_node_update($node) {
  if (some_condition_on($node)) {
    $batch = array(
      'operations' => array(
        // ...
      ),
    );
    batch_set($batch);
    $currently_processed_form = _MODULE_get_currently_processed_form();
    if (!$currently_processed_form) {
      // We are not currently processing a form, the batch processing won't be
      // automatically started. But we cannot start processing it because it
      // will end the request and prevent any other post node update code to
      // run. So we process the batch in a single pass and hope for the best.
      // FIXME: Start progressive processing of the batch after node update
      // processing (using hook_exit?) or use other delayed execution (using
      // queued operation?)
      $batch =& batch_get();
      $batch['progressive'] = FALSE;
      batch_process();
    }
  }
}


Freetagging with location? I want users to be searchable by their location. How do you add a free tagging widget type to a location field. Or, can GMAP/Location recognize every city as a term? Basically, how can users have location terms in their profile.

If you are talking about the location module you'll have a couple of barriers with profiles on D7. I think they are working on a fapi compatible version but it is not ready yet.

There is a D6 module (html5 user geolocation) which may provide a good starting point.

Given a location (lat long) the Google maps API can give you an address.

You can then just pick the administrative level you like and save that as a tag.


Best way to render a form on a node? I am trying to add a textfield to the bottom of a node (for a specific cck type), that once (an authenticated user) submits, stores the value as a term in a taxonomy vocabulary.

What is the best way to do so?

I have tried adding the form to my subtheme's node.tpl.php file for a custom cck type.

I am having trouble with form validation. I'm able to submit the form properly, but get the red borders around the field that needs to be validated, instead of the message; Until I resubmit and the cached error message then shows. I get why it's happening - code executing prior to node.tpl.php load. See - How do I use form_set_error() the right way?.

If Form Builders are not supposed to be called from within a template file, how else can I add a form to a page? I'm sort of working off this  form example tutorial

I started with this - Embed form inside a block - and since added this to my node.tpl - https://gist.github.com/1847060.

I'm still trying to wrap my head around using the forms api, so thanks for any advice.

You want to avoid putting this into your node template. Generally you want to keep "business logic" (any php functions other than print) out of template files. You might be better served by creating this as a block and placing it below or above the node because it is more reuseable. If you don't want to use a block you can use hook_node_view() and add an additional element to $node->content as in the linked example.


Display text according to the access to a field With field permissions, I restrict the access of a field to certain users.

I would like to display some text to inform the user that he has no access to the field.

I tried it in node.tpl.php :

<?php if (!field_access('view', field_info_field('field_name'),'node', $node)): ?>

<?php print t('my text.'); ?>

<?php endif; ?>

It works, but I do not know how to restrict according to the type of content.

How can it be done?
Also, is it the good method?

You can use drupal_set_message in hook_node_view to display the text as a message to the users.

function MODULE_NAME_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'your_node_type') {
    if (!field_access('view', field_info_field('field_name'),'node', $node)) {
      drupal_set_message(t('Your text.'), 'warning');
    }
  }
}


Add a class to main menu links I've searched and found variations of this question but I've never found an answer that seemed to work. I need to add a class to the
 elements, currently the main menu is rendered like this:

print theme('links__system_main_menu', array(
    'links' => $main_menu,
    'attributes' => array(
        'id' => 'slidemenu',
        'class' => array(
            'links',
            'inline',
            'clearfix'
        )
    ),
    'heading' => t('')
));

As far as I can tell, this only sets up the
 element of the main menu, so I was wondering if there's a way to edit the attributes of the 'links' part.

---EDIT---

Alright, I think I solved it. Apparently you can use theme_links__system_main_menu in templates to override the whole thing. I ended up doing this:

function mytheme_links__system_main_menu($variables) {
    $html = '
';
    $html .= '
';

    static $linkClass = 1;

    foreach ($variables['links'] as $link) {
        $html .= '
' . l($link['title'], $link['href'], $link) . '
';
        ++$linkClass;
    }

    $html .= '
';
    $html .= '
';

    return $html;
}

Not entirely sure if this is correct Drupal, though it did solve my issue!

Menu Attributes is another great module that allows you to set class, id, rel and other attributes on either the a or li element.


How to change a user reference field from select list to autocomplete in a Views exposed filter? In Views filter I have added user reference field and its showing me as select drop-down. I have exposed that field in the filter.

Those user reference fields are related to a content type, but I want those as auto-complete fields instead of drop-down, just as taxonomy fields can be drop-down or auto-complete fields.

The issue with select list is that there are thousands of users in that list and it is taking time to load all values and render the page.

How can I achieve this?

To get User Reference Field as autocomplete exposed filter,

Let me consider you have created a user reference field in your content type as Users-ref

Now in your View :

Add a relationship for your entity reference field for Eg: Entity Reference: Users-ref and make it required.
Now add a filter criteria User:Name  with the relationship Entity Reference: Users-ref
you should find (User entity referenced from field_users_ref) User: Name (exposed) in your filter criteria now.
And this should be an autocomplete widget!!

There is also a module named Views Autocomplete Filters along with this wonderful tutorial!!


Upload Image on form submit I have a form with an image field, I want to remove the upload button and submit the image while the form is submitted. I not able to find out how to proceed further with this. Any help is greatly appreciated.

Look at the HTML of the page, find the id of the input/upload button, then hide it via a display:none; in your css will get you going quickly; otherwise, you will have to do a form_alter() in drupal to remove it from the form.


Drupal 6 make a content edit form be in a specified theme This is in Drupal 6.

How to make a content edit form be in a specified theme?

The administration theme is 'seven', and use admin theme for content edit.
Site configuration: /admin/settings/admin
Administration theme: Seven
[x] Use administration theme for content edit

Create a new content type 'example'.

In the module, this function makes 'example' edit form in example_node_form.tpl.php template.
But this template will be in 'seven' theme, themes/seven/example_node_form.tpl.php

function modulename_theme() {
  return array(
    'example_node_form' => array(
    'template' => 'example-node-form',
    'render element' => 'form',
    ),
  );
}

Want 'example' edit form in another theme, not 'seven' theme?

How to make a content edit form be in a specified theme?

Implement hook_form_alter in custom module and check for current theme :

global $theme;
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'example_node_form_id' && $theme != 'theme_machine_name') {
    // redirect anywhere using drupal_goto.
  }
}


Detailed breakdown of what takes Drupal so long? I'm trying to figure out why my Drupal 7 take so long to render. I've installed the "performance log" module, but it was underwhelming, to say the least. It tells me a page took 2785 ms to render, with 51 ms in queries.

Now what? That's 2.7 seconds spent in PHP. Can I break it down further?

The site load is essentially zero.

You need the xhprof extension and module.


Unable to compile css with Aurora compass watch

      Change detected at 02:13:25 to: style.scss
          error sass/style.scss (Line 20 of sass/partials/global/_base.scss: File to import not found or unreadable: aurora/susy-grid.
      Load paths:
        /Applications/MAMP/htdocs/txmo/sites/all/themes/txmo_aurora/sass
        /Users/davidfells/.rvm/gems/ruby-1.9.3-p362/gems/compass-0.12.2/frameworks/blueprint/stylesheets
        /Users/davidfells/.rvm/gems/ruby-1.9.3-p362/gems/compass-0.12.2/frameworks/compass/stylesheets
        Compass::SpriteImporter)

Running Ruby 1.9.3, latest versions of all gems freshly installed with JewelryBox. Other users on dev team are able to build this with matching gem versions.

The problem turned out to be that the "aurora" gem cannot be installed alongside compass & compass-aurora for all this to work properly.


What is the php code to display a field of a referenced node in the node form of the node that references the node? So I have a node (content type A) with some text fields and a reference field referencing another node (content type B).

When a user wants to update one of the text fields an existing node (content type A) , they need to see the text field of the referenced node (content type B).

Question: what is the php code that I can use to output that textfield from the referenced node (content type B) on the node form of the referencing node (content type A).

I'd like to add this to a code field in Display Suite and I also like to learn how to retrieve the variables from a loaded node and how to display them.

Cheers!

One way is to use panels, I highly suggest this method. It might be complicated at first but no coding is required.

Enable the built in panels page for the path node/%node/edit.
Add a selection rule: node (from node being edited) is of bunle 'type A'
in context configuration page of enabled panel variant, create a relation using the entity reference field you have other.
in Panels content add each field of node being edited (and submit buttons too!).

or perhaps add the general form instead of each field individually.

again in add content, node section, choose rendered entity.

or create a view with a display of type content pane (ctools views content panes has to be enabled). Add a contextual filter of type nid, choose argument input: nid from context in view's configuration and use it to render the entity in panel. while adding this view to panel, choose the node you added with relationship.

Any way, the original question:
First, implement hook_field_extra_fields. take node module's node_field_extra_field as an example. or follow this question: how should I use hook_field_extra_fields()?

/**
 * Implements hook_field_extra_fields().
 */
function MODULE_field_extra_fields() {
   $etype = 'node';
   $bundle = 'content_type_a';
   $field_name = 'the_other_entity';
   $extra[$etype][$bundle]['form'][$field_name] = array(
     'label' => t('The other entity'),
    'description' => t('Renders the related entity'),
    'weight' => 0,
  );
  return $extra;
}

Next, taking node.module as an example, implement a form alter for your content type:

function MODULE_node_form_content_type_a_form_alter(&$f, &$fs) {
  $field_name = 'the_other_entity';
  $f[$field_name] = array(
    '#markup' => $the_mighty_markup,
  );
}

Here is another example how to do it: http://johnheaven.eu/en/extending-drupals-user-contact-form it attachs fields to contact form though.

And about the $the_mighty_markup, here you have to generate output of your entity. One suggested way is to create a view, add a contextual filter on nid to it, display the fields you want. Then in your code execute the view to generate the output:

$this_node = entity_metadata_wrapper('node', $this_node);
$other_node = $this_node->field_the_other_node_er->value();
$nid = $other_node->nid;
// or simply:
$nid = $this_node->field_the_other_node_er->nid->value();
$the_mighty_markup = views_embed_view('the_created_view_of_yours', 'master', $nid);

edit:
This is how to output a view: http://codekarate.com/blog/outputting-drupal-7-view-programmatically-contextual-filters-arguments


Custom Node Template not inheriting page.tpl.php In my theme, I have page.tpl.php and page--node--1.tpl.php.

When page--node--1.tpl.php is rendered, everything in page.tpl.php is lost. I only want page--code--1.tpl.php to replace the $content line in page.tpl.php and inherit everything else in page.tpl.php.

How can I do this? Do I need to first create a template for the content type?

Below is what I have in my template.php

if (strtolower($vars['template_files'][0]) == "page-search") {
    $vars["template_files"] = array();
    $vars["template_files"][] = 'page-search';
} else {
    if ($vars["template_files"][2] != 'page-node-edit') {
        if (isset($vars['node']) && ($vars['node']->type == "mytheme_page" || $vars['node']->type == "person" || $vars['node']->type == "blank_page")) {
            if ($vars["template_files"][2] == "page-front") {
                $vars["template_files"] = array();
                $vars["template_files"][] = 'page-home-mytheme';
            } else {
                $vars["template_files"] = array();
                if ($vars['node']->type == "blank_page") {
                    $vars["template_files"][] = 'page-blank';
                } else {
                    //print "made it here";exit;
                    $vars["template_files"][] = 'page-mytheme';
                }
            }
        } elseif ($alias == "sitemap") {
            $vars["template_files"] = array();
            $vars["template_files"][] = 'page-blank';
        }
    }
}

You cannot do this with those templates.

Only one "page" template will be used.   You could try using one "page" template, and one "node" template:  https://api.drupal.org/api/drupal/modules!node!node.tpl.php/7

but the node template won't allow you to modify the page template.


How do I convert a string like node/1 into a RouteMatch or Url object? I'm creating a text filter that modifies links. I am processing all the hrefs, and I want to load a RouteMatch or Url object for all valid urls like "/node/1". I need this to also handle i18n URLs. How do I convert a string like node/1 into a RouteMatch or Url object?

One way is to use the path validator service:

$url = \Drupal::service('path.validator')->getUrlIfValid($path)

I don't think that can handle URL's prefixed with the langcode if that's what you mean. That's usually handled/stored separately.


CCK field. how to use dynamic names to call CCK fields? (like: $node->$cckname) I have several cck image fields. Each field has a consecutive name, for example:

field_photos_1,
field_photos_2,
field_photos_3,
field_photos_4
... until 20

So my question is: How to call the image fields in a loop?

for example (pseudocode:)

for($i = 0; $i >= 20; $i++){
$cckname = 'field_photos_'.$i; //$cckname is changing the image field name, then...
echo "<img src='/".$node->$cckname[0]['filepath']."'";
}

The question in a general way could be: how to use dynamic names to call fields?

You use curly braces {} to delimit the variable inside your reference, as

for($i = 0; $i >= 20; $i++) {
  $cckname = 'field_photos_' . $i; //$cckname is changing the image field name, then...
  echo "<img src='/" . $node->{$cckname}[0]['filepath'] . "'";
}

This syntax is used in many places in Drupal core, see for example hook_field_prepare_translation.


Setting up a mobile site I understand that there is already I want to get a Mobile version of my drupal site working about setting up a mobile website, but I'm still having such a hard time figuring out what to do. I'm a newbie in web development in general. I was hoping that I'd get some more handholding here.

Basically I have a Drupal site up and running, e.g. http://example.com/fullsite/, and I want to set up a mobile site on http://m.example.com/fullsite.

I'm a Lunarpages customer, which uses LPCP (instead of CPanel). I've created the m.example.com subdomain for the mobile site, but I haven't created any redirection. Some CPanels apparently let me setup the redirection through it, but not LPCP.

Following the instructions on some random blog I found, I set up new folders in my Drupal's "sites" folder. My "sites" folder currently looks like the following:

public_html

fullsite

sites

default (and all its contents)
all (and all its contents)
mydomain.com.fullsite

settings.php (copied from default)

m.mydomain.com.fullsite

settings.php // copied from default, but with the theme_default line modified

    $conf = array(
      'site_name' => 'My Drupal site',
      'theme_default' => 'zen',
      'anonymous' => 'Visitor',
    );

I've also:

installed Drupal's Mobile Tools,
set the mobile url to http://m.mydomain.com/fullsite
set the desktop url to http://mydomain.com/fullsite
enabled "automatic redirection of the mobile user" under "redirection options"
chosen a different node as frontpage for my mobile visitors under "additional settings"
Under "Theme Switching", chosen "Switch theme based on the URL"

But accessing my site from my mobile device, here's what I'm seeing:

Going to m.mydomain.com/mysite = "Not found. The reqeuested URL /mysite/ was not found in the server"
m.mydomain.com/mysite/node/somenode = "Not found. The reqeuested URL /mysite/ was not found in the server"
mydomain.com/mysite = "Cannot open the page because too many redirects occurred".

Am I even on the right track here? Do I have to do a new Drupal install on my m.mydomain.com/mysite for this? I was under the impression that I could just get m.mydomain.com/mysite to get its data from the main drupal site, and display the contents with a mobile theme. Is this true?

I'm pulling my hair out over this (Well, not literally. I'm actually bald)! Any pointers will be greatly appreciated.

I think you are on the right track, but I think doing this as a true multi-site is overkill, and potentially the wrong idea.

Ideally, you want your desktop site and mobile site to share the same content.  If you are not going to go down the route of just using mobile stylesheets, then I suggest using Domain Access to create the mobile site.

You can use this module to set up your mobile domain, and then create your content accessibility rules for what is visible where.  When used in combination with Panels, you have great flexibility.

Mobile Tools let you choose your theme for a user and also shows up in panel selection rules, and domain tools lets you show/hide content for a particular user.

Note the issue log for Mobile Tools, though.  I found a bug with how the ctools selection rules work, and have a patch on the issue that hasbn't been committed or commented on.


Is there a media-handling module that can handle midi files? I've been using MP3 Player to provide an on-page mp3 player, but I also need to be able to handle midi files. Right now the best I can do is allow them to be uploaded into the "mp3 file" field, but when it renders the node, it just gives a link to the file, which mean you have to navigate to the file (or open it in a new tab) for the browser to play it.

MIDI files can be embedded straight into the page with the <object> tag, so there should be some way to then output that with the link that views gives you at the moment. If you went with a separate field then it's be easy enough to do with Views output rewriting.

After a quick look for a flash solution, it seems that flash itself doesn't have any support for MIDI, so a flash based player is unlikely.


Override _user_mail_notify() to NOT send email on user_save() if user status is changed I have an external service registering and altering the status of Drupal users, performing user_save() on several occasions depending on the service response.
So i am blocking and unblockiing users and other operations.

My problem is i cant find a descent way to override this code inside user_save()

// Send emails after we have the new user object.
if ($account->status != $account->original->status) {
 // The user's status is changing; conditionally send notification email.
 $op = $account->status == 1 ? 'status_activated' : 'status_blocked';
 _user_mail_notify($op, $account);
}

ideally i would like to have full control on what is going to be sent depending on user role, the account status etc. say for example

// pseudo code
if (user_is_external and statusChanged){
  dont send email
} else {
  send_email
}

Is this possible?
thanks

Maybe you should take a look at drupal_mail function

// Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
drupal_alter('mail', $message);

// The original caller requested sending. Sending was canceled by one or
// more hook_mail_alter() implementations. We set 'result' to NULL, because
// FALSE indicates an error in sending.
if (empty($message['send'])) {
  $message['result'] = NULL;
}

Then hook_mail_alter

From description

  $message: An array containing the message data. Keys in this array include:

  'send': Set to FALSE to abort sending this email message.

  'params': An array of optional parameters supplied by the caller of drupal_mail() that is used to build the message before
  hook_mail_alter() is invoked.

Parameters usually contain $message['params']['account'], so you can abort e-mail sending by role or other way.

Example (not tested) aborting any e-mail to account with specific role:

function MY_MODULE_mail_alter(&$message) {
  $role = 'CUSTOM_ROLE';
  if (!isset($message['params']['account'])) return;
  $account = $message['params']['account'];
  if (is_array($account->roles) && in_array($role, array_values($account->roles))) {
    $message['send'] = NULL;
  }
}

There is an issue then sending custom e-mails, $account contain sender account object, not receiver. But for default notifications this should work. So don't forget to check $message['key'] for default notification types from _user_mail_notify, it always provide $account object mail is sending to:

'register_admin_created': Welcome message for user created by the admin.
'register_no_approval_required': Welcome message when user self-registers.
'register_pending_approval': Welcome message, user pending admin approval.
'password_reset': Password recovery request.
'status_activated': Account activated.
'status_blocked': Account blocked.
'cancel_confirm': Account cancellation request.
'status_canceled': Account canceled.


How to retrive menu_get_object() in javascript, jQuery? I'd like to use the $node object in JavaScript, preferably Drupal's DOM. Is there a recommended way to do this in Drupal?

There are several ways to go about this.  The most straightforward is use template_preprocess_node , drupal_add_js, and drupal_json_encode.

Something like this:

function mytheme_preprocess_node (&$variables)
{
  $node = $variables['node'];

  drupal_add_js(array(
    'mytheme' => array(
      'node' => $node,
    )
  ), 'setting');
}

The node will then be JSON encoded as Drupal.settings.mytheme.node.  The above is untested, but will be a decent starting point.  Keep in mind that if you have multiple nodes on a page, then this will get called multiple times.  You would need to add some logic to handle these cases.

If you do this as part of themeing, rather than a module via the Node API, then all modules that alter  the $node will have run at that point, so all data should be there.  Personally, I would only add the data that I need.  $node can get pretty big, so adding all of it would be a lot of JS on a page.


Getting an error while installing drupal 7 using xampp Getting an error while installing drupal 7 using xampp

  An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path:
  http://localhost/tes/install.php?profile=standard&locale=en&id=1&op=do
  StatusText: OK ResponseText: Fatal error: Maximum execution time of 30
  seconds exceeded in C:\XAMPP\htdocs\tes\includes\database\database.inc
  on line 2171

I also tried reinstalling xampp but still didnt work out

Try to compare & update these values in php.ini.

  max_execution_time = 300

  max_input_time = 180

  max_input_nesting_level = 300

  memory_limit = 512M

Note : After these changes, restart the server.


Can't log in to Drupal websites after upgrading to OSX Yosemite I have just upgraded my local machine to OSX Yosemite which has changed my Apache version from 2.2 to 2.4 and my PHP version from 5.4 to 5.5.

When I visit both example.dev/user and example.dev/user/login and enter my username and password, the login form appears to post the data and then 'loops' back to it's original state i.e. blank fields.

This is the same across all websites and all browsers and is the same for all users.

There is nothing in any of the error logs but…

"POST /user HTTP/1.1" 404 16744

… in the access logs

Has anyone encountered a similar problem?

Thanks,

S

That happen to me when I upgraded to OSX Yosemite. I had to reconfigure my apache to make it work. Make sure that the rewrite module in apache is enabled, that you are allowing override. I had a similar problem also with mysql. I had to reinstall again.


Add conditional where condition to hook_views_query_alter() I was stucked making a few tweaks to a view trying to do the following.
In mysql exists the possibility to use WHERE IF to evaluate some variable/operation to apply differents conditions depending on the result/value, like a common IF/ELSE block, is there any way to do it with add_where() or any other similar method?
I need to apply a WHERE condition to the query when the value of a variable called $scope is G and a different when its L, there's any way to achieve that?

What I need to do is to do this query on Drupal 7 Views hooks

SELECT * FROM tbl1 AS t1 JOIN tbl2 AS t2 ON t2.entity_id = t1.nid JOIN tbl3 AS t3 ON t3.entity_id = t1.uid  WHERE t1.status = 1 AND t1.type = "article" AND IF(t2.field_alcance_nodo_value = '{char}', t3.field_pais_usuario_value = '{string}', t3.field_pais_usuario_value LIKE '%') ORDER BY t1.changed DESC;

but I'm stucked on the IF part...
I'm using the hook_views_query_alter() but I don't know if it's enough.

Thank you in advance,

You can achieve this using switch-case or if-else in mymodule_views_query_alter.

function mymodule_views_query_alter(&$view, &$query) {
  //Get your variable $scope here
  switch($scope) {
    case 'G':
      $query->add_where_expression(0, "$variable = :placeholder", array(':placeholder' => 'value');
      break;
    case 'L':
      $query->add_where_expression(0, "$another_variable = :another_placeholder", array(':another_placeholder' => 'another_value');
      break;
  }
}

Hope this helps.


Retrieve a field value without loading the entire node? I have a large number of NIDs and I need one field value from each node. Is there any way to avoid the overhead of loading the entire node to get one field value?

I don't think there's anything built in to the API but in a pinch you could just query the database directly:

$entity_type = 'node';
$bundle = 'page';
$nids = array(1, 2, 3);

$field_values = db_select('field_revision_FIELD_NAME', 'f')
  ->fields('f', array('entity_id', 'FIELD_NAME_value'))
  ->condition('entity_type', $entity_type)
  ->condition('bundle', $bundle)
  ->condition('entity_id', $nids, 'IN')
  ->condition('deleted', 0)
  ->execute()
  ->fetchAllKeyed();

After running that you should have an array of field values, keyed by their respective node's nid.

It's worth remembering the column name won't necessarily be FIELD_NAME_value; for example a node reference field would have a column name of FIELD_NAME_nid. Which one you use will depend on your field type.

UPDATE

It seems there is a way to do it with the API, but it's not pretty and still involves a manual query:

// Get the field meta data for the field_id.
$field_name = 'field_something';
$field_info = field_info_field($field_name);
$field_id = $field_info['id'];

// Load up the properties from the node table.
$nids = array(1, 2, 3);
$sql = 'SELECT * FROM {node} WHERE nid IN (:nids)';
$nodes = db_query($sql, array(':nids' => $nids))->fetchAllAssoc('nid');

// Attach the single field to all nodes.
field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

That method takes advantage of the $options parameter in field_attach_load() by specifying a field ID to load data for. It's worth noting, per the docs:

  Note that returned entities may contain data for other fields, for example if they are read from a cache.

So the code might have appeared to load extra field data, but anything other than the field you've specified will come from cache.


Pass a preprocess variable to a template? In subtik.theme, I have:

/**
 * Implements template_preprocess_field().
 */
function subtik_preprocess_field(&$variables) {
  if ($variables['field_name'] == 'field_language') {
    $variables['language'] = $variables['element']['#object']->get('field_language')->getString();
    ksm($variables['language']);
  }
}

All good. It dumps 'php' to my page, which is correct.

I also have, in field--node--field-body.html.twig, I have:

...
{{ kint(language) }}
...

Not so good. It dumps 'null' to my page. Why not 'php'?

At a glance it looks like you have a condition checking for:

if ($variables['field_name'] == 'field_language') {

but the template you are using is field--node--field-body.html.twig instead of field--node--field-language.html.twig.

To get it to pass to field body twig, you would need:

  if ($variables['field_name'] == 'field_body') {
    $variables['language'] = $variables['element']['#object']->get('field_language')->getString();
  }


how to prevent user from clicking button twice on server side in jqx $('#save').on('click',function(){
  $('#form').jqxValidator('validate');
});

How can I prevent user from click button twice on server side?

Preventing users from submitting forms twice becomes very easy with that module hide_submit.

Take a look at the issues as many features patched but not yet in the master branch of that module.

It may guides to achieve the same thing for (non submit buttons).


Set pager none in a view programmatically I want set pager none in a view programmatically, but I can not find a way to do it, the object "$view" does not seem to exhibit a way

I believe you can do something like:

$view->display_handler->options['pager']['type'] = 'none';

in your function. This calls the view's display handler to set the pager type option to 'none'.


Update existing node (not created by Migrate) via Migrate 8.5.x I have got existing Drpal 8.5 site with hundreds of nodes. With migrate, if i try to upgrade, new nodes are rather created. Node have a field which is being used as key however that seem to be not working. It seems that node are only updated if their record present in migrate_map_xyz. Any suggestions?

Updating existing content was possible by changing the default behaviour of a migration with the system of record concept in Drupal 7.

In Drupal 8 this concept has been revised & is available with the overwrite_properties option in the destination of the migration YAML:

...
destination:
  plugin: 'entity:node'
  # define the entity properties that are to be updated.
  overwrite_properties:
    - title
    - field_foo
    - field_bar
...