how to send $user variable from drupal to another php non-drupal page under same root? I have drupal cms and another php site with each own session and db etc on same root.

What I want is to pass somehow the drupal $user variable with all the login details of the user to the other non-drupal php site in order to bypass the login and make the user logged in there too.

The non-drupal site has its own login/register and sessions etc. I want to override this by getting the user info from drupal registration.

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

I tried to use the above code on the index of the non-drupal site, but I get errors about session and headers that already sent.

Any help?

I have a similar setup running; what I did was sending the session ID as a URL parameter, including the "bootstrap.inc" file, bootstrapping the database, and then looking up the info I needed.

Example where I've stored some info in the session:

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

if (@$_GET["sid"]) {
  $_SESSION["sid"] = @$_GET["sid"];
}

if (@$_SESSION["sid"]) {
  //Get the get username/role from the database
  $result = db_query("SELECT session FROM {sessions}
    WHERE uid > 0 and sid = '%s'", array(
      $_SESSION["sid"],
    )
  );

  while ($row = db_fetch_object($result)) {
    $_SESSION += unserializesession($row->session);
  }
}

function unserializesession($data) {
  if (strlen( $data) == 0) {
    return array();
  }

  // Match all the session keys and offsets.
  preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

  $returnArray = array();
  $lastOffset = null;
  $currentKey = '';

  foreach ($matchesarray[2] as $value) {
    $offset = $value[1];

    if (!is_null($lastOffset)) {
      $valueText = substr($data, $lastOffset, $offset - $lastOffset);
      $returnArray[$currentKey] = unserialize($valueText);
    }

    $currentKey = $value[0];
    $lastOffset = $offset + strlen($currentKey) + 1;
  }

  $valueText = substr($data, $lastOffset);
  $returnArray[$currentKey] = unserialize($valueText);

  return $returnArray;
}


Filter by specific field when webform exports I have a webform with a field_custom field. I need to download the submissions filter by this field.
I saw in the download page this:

Can I do the same programmatically with a plugin or something else to filter by my field(field_custom)?

You need to use the Webform View Integration and create a custom Views Data Export.


Passing arguments into hook_block_view in custom module I'd like to pass a variable ($myvariable) into the block_view function in my custom module, so i can see the content of the variable in the block content.

But there must be something i do wrong, because the below code gives me the following error:

  Warning: Missing argument 2 for mymodule_subscribe_block_view ...

/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
$myvariable = 'test';
function mymodule_subscribe_block_view($delta = '', $myvariable) {
  switch ($delta) {
    case 'mymodule_test':
      $block['subject'] = t('Test block');
      if (user_access('access content')) {
          // Pass data through theme function.
          $block['content'] = $myvariable;
      }
    return $block;
  }
}

I'd greatly appreciate any hints on what's going wrong here.

If you need to pass a variable into a block, maybe you should try using template_preprocess_block ?

Inside this function you define your variable and afterwards in your block you use it.


How to set "Entity has Field" when the Rules Event is unrelated to the entity? In Rules, I am trying to update/calculate a field in the User's account upon completion of a commerce payment.

The condition data selector obviously only wants to populate commerce related fields, since my Event is "After saving new payment".

How can I define my custom field in the Rules Conditions?

My attempts to set the user or current-user entity has field are unsuccessful. But I know this must be simple.

Here are the steps to get this to work (whatever your existing Rule looks like ...):

Assume your current rule has some actions (= SomeRulesActions).
Create a new Rules Component like so:

Use parameters related to the user (= say ParmUser) and  payment (= say ParmPayment).
Add the Rules Conditions related to your custom field, which you should have available via the ParmUser.
Add Rules conditions identical to SomeRulesActions, using ParmUser and/or ParmPayment.
QA-test your Rules Component using the "Execute" link in front of it (in the Rues UI).

Update your existing rule like so:

Delete all Rules Actions corresponding to SomeRulesActions (their equivalents are now included in the Rules Component you created in the previous step.
Add a Rules Action to execute the Rules Component you created in the previous step.

Easy, no?

An alternative solution where you don't need an extra Rules Component, is to rework your Rules logic by using the Conditional Rules module. If you wonder how to do that, use this link.

Ps: I'm assuming this is about D7.


How to change field setting using on some condition based? I want to change image property like resolution based on other field.Like I have a field that tells how the image will be shown. If I select a large image then minimum image resolution have to change higher.

There is no option to do it with conditional field. So Is there any other way?

It looks like you are looking for Formatter Field:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

Emphasis mine.


Invoke function from module in form I'm trying to port the OpenID module from Drupal 7 to Drupal 8.

I have a form OpenIdLoginForm.php with the following code.

<?php
...
namespace Drupal\openid\Form;
use Drupal\user\Form\UserLoginForm;
use Drupal\Core\Form\FormStateInterface
use Drupal\Core\Url;
use Drupal\user\UserStorageInterface
...
class OpenIdLoginForm extends UserLoginForm {
... // getFormId, buildForm methods work nicely

  public function validateForm(array &$form, FormStateInterface $form_state) {
    ... // some validations
    openid_begin($claimed_id, $return_to, $form_state);
  }

... // submitForm method
}

openid_begin is defined in openid.module.

<?php

use Drupal\Core\Routing\RouteMatchInterface;

... // openid_help, working nicely

function openid_begin($claimed_id, $return_to = '', $form_state = null) {
  // some stuff
}

The folder structure is the following.

modules/
  openid/
    README.md
    openid.module
    ...
    src/
      Form/
        OpenIdLoginForm.php
        ...

Whenever I submit the form, and validateForm() is called, I get an error:

  PHP Fatal error:  Call to undefined function Drupal\openid\Form\openid_begin() in /modules/openid/src/Form/OpenIdLoginForm.php

What am I doing wrong? How would I invoke a module function from a form belonging to the same module?

Fun fact: invoking the function user_login_finalize() from submitForm() in OpenIdLoginForm.php works and I don't know why.

I was looking for a solution for hours. Right after posting the question, i found one:

calling

\Drupal::moduleHandler()->invoke('openid','begin',array($openid,$return_to,$form_state));

seems to do the trick.

Still, I wonder why I can call user_login_finalize directly.


How can I hook into the system Contact form Message Sent process and alter the HTML generated? I have a Drupal site where I am using the sited-wide system Contact to allow visitors to send messages to the site owner.  Once a visitor submits the form, the user is redirected to the home page and a sticky appears at the top reading:

Your message has been sent.

My question then, is it possible to change this message and add some HTML to the output?  Ideally I would add some javascript to create a virtual page view for the Google Analytics account so that I can track it as a Goal Conversion.

I imagine this would be a hook_ function sitting in my template file, but I'm relatively new to this process.

Sure, just use hook_form_alter() and add a callback to $form['#submit']. The easiest way to find your form's id is inspecting it using firebug. This article has a lot more detailed info: http://www.lullabot.com/articles/modifying-forms-drupal-5-and-6.

In short:

Find the id for the contact form, "contact_mail_page" or something (notice how hifens turn to underscores)
In a new custom module implement either: yourmodule_form_alter($form_id, &$form, 'contact_mail_page') or yourmodule_form_contact_mail_page_alter($form_id, &$form)
Modify the contact form as you want using the $form variable passed by reference


Views Filter to display field only if it matches a certain value how do I display a field in views ONLY if the value matches a certain specified value?

Example: I have a field name called "Product". Add FILTER CRITERIA. Filter choose content and search Product. Save the views and click the recently added FILTER CRITERIA. You will able set a setting like Product = Book.
This will appear if you choose Autocomplete

This will appear if you choose select


Token authentication- "The form has become outdated" and rules issues I'm using the Token Authentication and Privatemsg modules together.  When a user receives an e-mail notification that they he/she has received a private message, I have placed a link (using a token provided by the Tokenauth module in a query string) that allows the user to log in and see the message.

At the bottom of the page is the message reply form.  I would like the user to be able to reply via this form as well (without logging in, via token authentication).  However, when I tested this, I received the following error:

  The form has become outdated. Copy any unsaved work in the form below
  and then reload this page.

A Google search revealed this helpful comment on drupal.org:

  So it seems you would have to either

  unset($form['#token']) or $form['#token'] = NULL

Privatemsg has two message creation forms, the new message form and the reply to message form.

To fix the new message form, I added unset($form['#token']); to hook_form_privatemsg_new_alter() (new messages) and hook_form_privatemsg_form_reply_alter() (replies). I tested this and new private messages as well as replies can now be sent.

I then disabled caching for the privatemsg module so that the messages would always be refreshed.

However, I have a rule that is set to Show a message on the site ("Your message was sent to User X!") whenever a private message or reply is sent; this rule is not triggered when a private message is sent if the user is authenticated via Tokenauth even though the private message is saved to the database properly and displayed upon page refresh.

How can I make sure rules are still triggered when authenticated via Tokenauth?

From my point of view, it would seem Rules are not being triggered at all. You could, however, try invoking a rule manually by placing a rules_invoke_event() call within inside a custom form submit function.

Note that the #submit property on Drupal forms allow multiple submit handlers to be called for a single form.

In the hook_form_privatemsg_new_alter() and hook_form_privatemsg_form_reply_alter() form alters you have implemented you should be able to find and modify the #submit property. Just do something like:

// Implementation of hook_form_FORMID_alter().
patricks_form_privatemsg_new_alter($form, &$form_state) {
  ...
  $form['#submit'][] = 'patricks_privatemsg_submit';
  return $form;
}

Then in your submit handler you can use the rules_invoke_event():

function patricks_privatemsg_submit($form, &$form_state) {
   drupal_set_message(t('The form has been submitted.'));
   // Pass parameters for the variables provided by this event, as defined in hook_rules_event_info()...
   rules_invoke_event('privmsg_foo_rule', $foos, $barf, $bam);
}

If for some reason you get a rules_invoke_event() function not found error, just add a module_load_include() to your submit handler before invoking the rule.


What does a/ and b/ stands for in patch header? The first line of patches always has this kind of code:

diff --git a/i18nviews.inc b/i18nviews.inc

or

diff --git a/plugins/views_plugin_localization.inc b/plugins/views_plugin_localization.in

What does the a and b  stand for?

A' and the 'B' are prefixes to differentiate source and destination.

You can change the prefixes with

--src-prefix=<prefix>
Show the given source prefix instead of "a/".

--dst-prefix=<prefix>
Show the given destination prefix instead of "b/".

From http://git-scm.com/docs/git-format-patch


Multiple hook_menu_alter over-writing issue I want to customize my menu by using hook_menu_alter by over-writing another installed module, which also has a hook_menu_alter inside.

I check the procedure using xdebug, finding that drupal execute my hook_menu_alter first, and then the existing hook_menu_alter in that module. In this case all my alteration is being over-written. How can I reverse the order of execution?

Thanks!

You can try to change the weight of the module in the systems table but doesn't always work and can cause other issues.  I would use the hook_modules_implement_alter function.  You will need to unset yours and then add yours to the top or before the other module.  Here is an example I used doing a hook_user_delete and hook_user_insert

function users_module_implements_alter(&$implementations, $hook)
{
  if($hook == "user_insert" || $hook == "user_delete")
  {
    unset($implementations['user']);
    $user = array('users' => false);
    $implementations = $user + $implementations;
  }
}

Yours would be like this:

function users_module_implements_alter(&$implementations, $hook)
{
  if($hook == "menu_alter")
  {
    unset($implementations['mymodule']);
    $mymodule = array('mymodule' => false);
    $implementations = $mymodule + $implementations; // Also could use array_merge
  }
}


Drupal commerce payment callback endpoint Currently I'm work for a payment gateway plugin, the payment gateway will returning data by using the post method to my Drupal site once the payment transaction occur. I would like to know is that any endpoint and what are the hook is able to handle this process.

so - this sounds like an IPN (instant payment notification), commerce payment does not handle that, so you have to pass the ipn url defined in hook_menu to your gateway in the specific parameter when submitting the _redirect_form, or setting it in your gateway configuration - depends on the gateway ..

/**
 * Implements hook_menu().
 *
 * adds the callback uri
 */
function YOUR_MODULE_menu() {
  $items = array();

  // Define an always accessible path to receive IPNs.
  $items['some_uri/IPN/%'] = array(
    'page callback' => 'your_module_process_ipn',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

so - your ipn looks like this httpx://example.domain/some_uri/IPN/What/ever
maybe that the What/ever is set by the gateway. if nothing is set, adjust the item in hook_menu !

then your callback function does take the action, like:

/**
 * Processes an incoming IPN.
 *
 * @param $uri
 *   dynamic URI
 * @param $debug_ipn
 *   Optionally specify an IPN array for debug purposes; if left empty, the IPN
 *     be pulled from the $_POST.
 *
 */
function commerce_postfinance_process_ipn($uri = NULL, $debug_ipn = array()) {
  $ret = 'IPN failed';
  if (ipn_valid($uri, $debug_ipn)) {
    $ret = 'IPN OK';
  }

  print $ret;
  exit(0); // hook_exit will not be invoked !
}

and in the ipn_valid function you access the $_POST array.

  don't forget to create a commerce payment transaction if the ipn is
  OK.

refer the paypal wps module for this (see funciton commerce_paypal_wps_paypal_ipn_process)


Ajax modal does not show for authenticated users I'm testing a simple ajax modal link on a Drupal site and figured out that the modal

Search

does only show when logged in as admin. For authenticated users it does not load (it just shows the search page). This is independent of the underlying theme I am using (bartik or a bootstrap subtheme). No error messages or status-reports give any indication what's going on. I thought only for anonymous users ajax needs to be added for the theme dependencies ? What am I missing here ?

For use-ajax to work for Anonymous as well as Authenticated user, Core core/drupal.ajax library must need to be loaded on page, where we're using 'use-ajax' class.

You can include this library with either using #attached in your Form or Controller or you can implement hook_page_attachments hook and attach ajax library.

If you're trying to add link to text inside your form, you can directly use #ajax instead of using classes as per directed in Ajax commands for opening and closing Dialogs and generic Dialog Controller added to core

  $form['link'] = [
    '#type' => 'link',
    '#title' => 'Link 1 (modal)',
    '#url' => Url::fromRoute('ajax_test.dialog_contents'),
    '#ajax' => [
      'dialogType' => 'modal',
    ],
  ];

Hope this helps.


How can I generate a list of PDF Forms based on user input? I am looking to make a user-friendly "form" for the HR department but am not sure how to do it.

My goal is to display a list of PDF forms based on the type of employee is being hired.

The HR user would be asked to select option that pertain to the type of worker that is being hired (hourly/salary, type of employee, etc.)

Based on what is answered, certain forms will be given to the user to download.

How can I accomplish this task?

It may not be the best way, but an easy way to do this would be to use core's taxonomy module. From the module's docs: "Taxonomy, a powerful core module, gives your sites use of the organizational keywords known in other systems as categories, tags, or metadata. It allows you to connect, relate and classify your website’s content."

In a nutshell, I'd suggest to create a taxonomy vocabulary for your type of workers, and add a term for each (hourly, salary, etc.) and attach a file field to the vocabulary, where you can upload and attach the PDFs for each term. Then on the front end, you can create a view that lists all of the file fields attached to that term.


How to redirect based on views results? I have a view that shows a list of nodes and has a contextual filter.
If the number of nodes shown is only 1 then I want to redirect to that node page instead of showing the view.
Can I do that in views or do I have to code it?

I don't think Views does anything like that by default, but a quick...

if (count($view->result)==1) {
  drupal_goto('node/' . $view->result[0]->nid);
}

...at the beginning of a display output template for the view in question should do it for you.

Or better yet, per @MPD...

function MOTOMODULE_views_pre_render(&$view) {

  if ($view->name=='JUSTONEPLEASE' && count($view->result)==1) {
    drupal_goto('node/' . $view->result[0]->nid);
  }

  // any other pre_render()ing here

}


User URLs based on the usernames Is there a module that changes the user URL from "user/1" to "user/username"?

Pathauto does exactly that.

All new user aliases generated after enabling the module will look like users/[user:name] (obviously this could be changed in module configuration - Configuration / URL aliases / Patterns).

You can use "Bulk update" to generate aliases for already existing users (and other type of content).


Add image styles with images I am trying to print an image using an image style that I've created in my drupal 8 theme.

I'm implementing a field template for the field collection. I have an image in my field collection, So i need a way to get the URL for a different image style of the same image.

Any effort will be appreciated.

mythemename.theme

use Drupal\image\Entity\ImageStyle;
use Drupal\file\Entity\File;

function mythemename_preprocess_page(&$variables) {
// change _page to _node or _html depending on the template you are targetting.

  if (isset($variables['node'])) {
    $node = $variables['node'];
    // now you can use $node->field_something

    // Since I have yet to use field collection in D8, I'll let you figure this part out.
    // So all you gotta do is get the fid from your image field.

    // Once you get the FID
    $file = File::load($fid);
    $uri = $file->getFileUri();
    $url_large = ImageStyle::load('large')->buildUrl($uri);
    $url_medium = ImageStyle::load('medium')->buildUrl($uri);
    $variables['large_image_style_url'] = url_large;
    $variables['medium_image_style_url'] = url_medium;
  }
}

Then in twig you can do {{ large_image_style_url }} and {{ medium_image_style_url }}

I had to do it like this, since I needed to print the image in page.html.twig. If you need yours in node.html.twig you could try the answers to How to use an image style in a Drupal 8 twig template?


How do I change the used PHP version? I am using Drush to update modules.
When I run the command php -v it correctly shows I am running version 5.5

I then use the command drush rf followed by drush up to perform any updates.

I am using the Schema.org Metatag module which requires php version 5.
The website is running php version 5.5.37

The default CLI version on Hostgator shared server is 5.4.45.
That is what I was originally using for drush. When I received the message below I found the path to use php 5.5 but I am still getting the same message.
So I can't figure out how it still sees php ver 5.4.45 and how to resolve this so it doesn't keep disabling that module.

When Drush runs an update I get the following message:
Schema.org Metatag requires at least PHP 5.5. (Currently using PHP   [warning]
5.4.45)

And then it disables the Schema Metatag module.

NOTE:
When I run command drush status:
PHP configuration: opt/php55/lib/php.ini
Drush version is 8.1.11

Thanks

Extra information

.bash_profile

PATH=$PATH:$HOME/bin
export PATH
alias composer="/opt/php55/bin/php ~/bin/composer.phar"
alias drush="/opt/php55/bin/php ~/.composer/vendor/bin/drush.php"

.bashrc

 alias php='/opt/php55/bin/php'
 alias composer='/opt/php55/bin/php ~/bin/composer'
 export DRUSH_PHP='/opt/php55/bin/php'

php -v returns PHP 5.5.37
which php doesn't return anything
drush status returns PHP configuration /opt/php55/lib/php.ini

But, when I use Drush to update a module I still get: Schema.org Metatag requires at least PHP 5.5. (Currently using PHP [warning] 5.4.45)

Find the path to php 5.5’s binary.
Find the path to drush.

Execute

/path/to/php_55/bin/php /path/to/drush status


Conditional token pattern I am looking for a module or a hook that allow me to use if conditions with tokens.

For example I want to check if a field is equal to a specific value or text

[if][field_name][eq]hello[then][field_name_alt]

any ideas will be helpful.

Here is an idea, which I have not tried yet.

Sometimes you have tokens in combination with text formats. E.g. in commerce_checkout_completion_message_pane_checkout_form() the token replacement happens first, before the text format is applied. I am not sure if I agree with this order, but in this case it gives us some interesting options.

You could define a custom text filter which detects and evaluates markup like this:

{if true}hello{else}goodbye{endif}

and then you can use tokens to insert the true/false.

{if [token-which-returns-true-or-false]}hello{else}goodbye{endif}

This still leaves a lot in the open. Most tokens do not produce true/false, so maybe instead you want real equation formulas. But it is a direction you can explore further.


Not able to overwrite old value in Drupal.settings I am facing Problems in overwriting old value in Drupal.setting.

Problem Statement

I am passing FID value from PHP to JS. At first it is getting correct value in JS.

Ex. When PHP is passing FID=59 to JS for first time then it is correctly received by JS.
Next time when it is passing FID=60 then it is showing FID=59 in JS always.
Drupal.setting is not refreshing with current value.

My sample php code is like this

 function TraverseSnap($nextFID)
 {
    $thm_slideshowimg .= '<input type="image" src="nxt.jpg" class="clsNextSnap" width="25" height="25">';

    $nxtSnapSetting = array(
            'fid' => $nextFID,
     );

    drupal_add_js(array('nxtSnp' => $nxtSnapSetting), 'setting');
 }

JS Code

(function($) {
 Drupal.behaviors.VidsImgsContent=
 {
      attach: function (context, settings)
      {
          var fileId = Drupal.settings.nxtSnp.fid;
          var dataNextSnap = 'fid=' +fileId;
          $.ajax({
                  url: 'nextsnap',
                  type: 'POST',
                  async : false,
                  dataType : 'json',
                  data : dataNextSnap,
                  success : updateMainNextDiv,
                  error : function(jqXHR, textStatus, errorThrown){alert("Some Error occured");},
                  beforeSend: function()
                  {
                  },
               });
               return false;
       }
  }
  })(jQuery);

My hook_menu call

$items['nextsnap']=array(
   'title'=>t(''),
   'type'=> MENU_CALLBACK,
   'page callback' => 'nxt_snap_post',
   'access arguments' => array('access content'),
);

Page Callback

function nxt_snap_post()
{
    $fid=$_POST['fid'];

    $htmlResult = TraverseSnaps(60); //An arbitary Value for sake of this example
    drupal_json_output($htmlResult);
    exit();
}

So I believe when the button is clicked next time it will take FID=60 in JS but it is taking old value instead.

Please help here as my crucial logic depends on this.

I think you can not do it this way. Data Drupal.settings only run in first load. This data store in tag head of page.

When you call ajax your function was execute, but tag head don't reaload. So Data.settings don't change.


Form validation: text has to be a number I have a textfield in a form that must contain a number. Using an integer for the field type is not possible - it must be text; however, I need to ensure that the input is actually a number. I've used:

function myfunc_form_user_register_form_validate($form, &$form_state) {
  if (!is_numeric($form_state['values']['number'])) {
    form_set_error('number', t('Field must be Numeric'));
  }
}

However, it does not work, that is, no errors are ever displayed. I have implemented the above code in template.php. I know there are Form Validation modules; however, I would like to do such a simple thing myself. I also think it's a bit overkill to create a whole module to simply validate a single field in a single form! I also wonder how to find the $form[] keys. I named the input field number so I imagine that's the key but it's just a guess. I've looked through the Form API and it is not very clear what I am supposed to do. Simple things, such as finding out what's even in $form[] alludes me and it doesn't seem to be clearly explained.

Drupal already has a helper for this, in the shape of the element_validate_number() validation callback:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['number']['#element_validate'][] = 'element_validate_number';
}

You can also use element_validate_integer() or element_validate_integer_positive if either of those make more sense for your use case.


How do I change the base URL? In Drupal 7, we can quickly change the base URL of the website.
How can I do this, in Drupal 8?

In Drupal 8 this option has been removed. You don't have to configure  base_url to run your site. Drupal 8 can detect this without your help. If not, you should first check your webserver configuration.

Instead of base_url you should configure trusted_host_patterns in settings.php. This is not needed to run the site, but important for security reasons.

More info: Removed base_url option from settings.php and New setting for trusted hostname configuration

Edit:

There are some special use cases when running drupal from command line or reverse proxy, that used $base_url in the past. This can no longer be supported in the same way because of symfony. There is a discussion going on how to provide a solution for these cases. This does not mean that you cannot run drupal from the command line or reverse proxy. The standard way is of course possible without problems.

You can follow the development here: https://www.drupal.org/node/2753591


Is Drupal Cache Warmer for real? I am using  Varnish + Default Page cache with a expiring time (1 day) in a site.

When I am browsing the site, everything seems loading fine; once I come back to the site after a day or so, the the pages start loading slow and they become okay after a while.

It seems like the cache is being cleared after a while and generated again once someone visit the site again. I do not want that user to suffer.

I read about Drupal Cache Warmer; is there something which can keep the cache alive and no user suffers?

Well, there's the Cache Warmer module you can set up if you have drush access on your server.

You can also use a 3rd party service like Pingdom to do that as well.


Why is it not recommended to change the default language? I have a fresh installation of Drupal 8.2.5 and want to use it for mostly Spanish content, but keeping the admin interface in English. /admin/config/regional/language says,

  It is not recommended to change the default language on a working site.

And /admin/config/regional/language/detection/selected says,

  Changing the site's default language itself might have other undesired side effects.

What will break if I change the default language? Or is a better question to ask, should I want to change the default language? I found this question, but it does not answer my question, aside from also being pre-Drupal8.

Thanks.

In Drupal 7 it was total chaos. With Drupal 8 things have improved a lot. It's now possible to switch default language but but there may still be effects:

URL alias has a language. Changing default language can bring some strange behavior, especially if some alias was created manually: https://www.drupal.org/node/2484411
Configuration entities can end up not having the right language. You will perhaps need to export the configuration and do some manual work like making sure the exported configuration has the right lang code.
...


Display Suite show results from blocks I am using Display Suite search as default search module. Is there a way to add the contents of blocks to the search results?

If you enable the Display Suite extras module you can create a display suite field that contains a block. It's included in the DS module you just have to enable it.


Is a content type needed by a custom module? I want to write a custom module for my drupal website to get some information from users and process them. because my form fields are complex so I have decided to write my own module to generate form instead of default add content in drupal.

Should I have create a content type for storing data or I can create my data structure for storing data ?

You can create you own data structure but I think your life will be a lot easier if you create a new content type or an entity. You can alter the form in the way you need it or get it and render it wherever you want. You also have validation and submit handlers.


Get an error message "invalid file extension" I always get the error message: "Invalid file extension" when I'm trying to upload a PDF file? Does anyone know how to solve that problem?

When you create the field file, you need to definy the extention.
You have already created the field but you can always modify it.
Go on your content type, edit the field file adding pdf on "Allowed file extensions *"

You can add all the extensions you want. Separate extensions with a space or comma and do not include the leading dot.


How to show fontawesome icons in admin page inside Ckeditor? I managed to insert fontawesome iconS using Ckeditor with the Font Awesome Icons v1 module.

I just put this code in the HTML view of Ckeditor.

<i class="fa fa-camera-retro fa-lg">&nbsp;</i>

The icon is shown correctly in frontend but in CKEditor it is not shown at all.

I guess I need to load all fontawesome files inside Ckeditor. How can I do this? I need to see the icon in ckeditor in the same way as I see it in frontend.

Fontawesome is located at: sites/all/libraries/fontawesome

A CKEditor plugin for fontawesome exists. If you're using the WYSIWYG module there are a number of hooks that allows you to modify your WYSIWYG editor. In fact, someone has done a write up on how to manually add CKEditor plugins using Drupal.


What is the difference between "Limit allowed HTML tags and correct faulty HTML" and "Correct faulty and chopped off HTML"? In CKEditor Filter processes (/admin/config/content/formats/manage/filtered_html) there are filters.

If you use "Limit allowed HTML tags and correct faulty HTML" do you still also need the other one, or does this one do all that, plus limit?

"Limit allowed HTML tags and correct faulty HTML" does not correct unclosed tags in HTML.  SO it doesn't REALLY fix "faulty HTML" at all.

You also need "Correct faulty and chopped off HTML".


D7 - db_select: order by most recent, commented status I'm writing my custom module.
I use the modules Statuses and 'fbss_comments' (part of the Statuses module). Comments are used to comment on statuses.

Using the following code I get a list of results:

 $query = db_select("statuses", "thread")->distinct();
        $query->join("fbss_comments", "comment", "comment.sid = thread.sid");
        $query->fields("thread", array("sid", "sender", "created", "message"));
        $query->fields("comment", array("created"));
        $query->orderBy("comment.created", "DESC");
        $result = $query->execute();

Now the list of results will be sorted by the most recent posted status. I want to achieve the following: sort the result list by statuses with the most recent comments

Some clarification: normally status(100) will be shown above status(30). When I comment on status(30), status(30) should be shown above status(100). On top of this, when I create a new status(101), this status should be shown on top of the result list.

I hope my goal is clear to you, sadly, I have no idea how to achieve this.

Any advice or help is much appreciated

edit: I've managed to order the results by the most recent commented statuses, however, if a status has 9 comments, the status is shown 9 times. Any advice why/how this happens?

edit 2: I probably should use ->distinct(), I've added it after the db select statement, but  this doesn't work (probably because I select two tables)

You have a classical case, that requires using 'HAVING' SQL operator. Suppose, we have 2 related tables:

| table1 |
|--------|
|   id   |
|--------|
|    1   |
|    2   |
|--------|

table2.f_id is the FK for table1.id

|         table2        |
|--------+------+-------|
|     id | f_id | order |
|--------+------+-------|
|      1 |    1 |     1 |
|      2 |    1 |     2 |
|      3 |    2 |     3 |
|      4 |    2 |     4 |
|--------+------+-------|

And you want to get all the records from table1 with MAX of the related table2.order. And sort them by table2.order. You must use this SQL to get the data:

SELECT
  table1.id AS id1,
  table2.id AS id2,
  table2.order
FROM
    table1
INNER JOIN
    table2
ON
    table1.id=table2.f_id
GROUP BY
    table1.id
HAVING
    MAX(table2.order)
ORDER BY
    table2.order DESC

And you will get:

| id | id1 | order |
|----+-----+-------|
|  2 |   3 |     3 |
|  1 |   1 |     1 |
|----+-----+-------|

Fiddle

Converting this SQL to Drupal, we'll get this:

$query = db_select("table1");
$query->innerJoin("table2", NULL, "table1.id=table2.f_id");
$query->addField("table1", "id", "id1");
$query->addField("table2", "id", "id2");
$query->addField("table2", "order", "order_field");

$query->groupBy("table1.id");
$query->having("MAX(table2.order)");
$query->orderBy("table2.order", "DESC");
$result = $query->execute();
while($row = $result->fetchAssoc())
{
      var_dump($row);
}

So, for your case, this query must work:

$query = db_select("statuses", "thread");
$query->innerJoin("fbss_comments", "comment", "comment.sid = thread.sid");
$query->fields("thread", array("sid", "sender", "created", "message"));
$query->fields("comment", array("created"));

$query->groupBy("thread.sid");
$query->having("MAX(comment.created)");
$query->orderBy("comment.created", "DESC");
$result = $query->execute();


DIsplaying images on nodes? In one of the sites I have created, I am using a specific made up 404 page instead of the default one that comes with the server. This 404 page contains an image, and then a block containing text next to it. I then made the url alias for this page "404." Now when I go into the configurations, and set 404 as the 404 error page, it automatically saves it as "node/4." The problem then arises when you go to a page that doesn't exist. If the page is something like www.yrambam.org/nonexistentpage then there is no problem. The page works. But if the page is something like www.yrambam.org/something/nonexistentpage then the page displays without the image, and the formatting of the page becomes all messed up. I am wondering why this happens, and if there is a way to fix it.

This is definitely an error where the HTML of the 404 page is referencing the image via a relative path rather than an absolute path.

Screenshot of the page + source

Change the HTML of the page to use the image source path '/sites/default/files/pictures/404-error.png'


Check for WebForm Errors Some of my website visitors are stating that they are filling out the webform (ver 7.x-4.2) and we are not getting the email. They have not provided any detail (error messages, etc...) and when I login and review the Results tab I do not see their emails. I've tested the webform and I get the emails. My questions are as follows:

1) Is there anyway to look for webform errors in a log file? Where would I look?
2) If a webform is not successfully sent, it won't show in the Results tab correct? When does the submission get recorded?

Regards,

John

The email may not have been sent without any error at the Drupal end. I recently experienced this problem, and found that the mail server was rejecting emails sent "from" someone claiming to be the same host as itself.

In short, Drupal could successfully send the email without knowing that it wasn't received.

We solved the problem by installing the modules "mailsystem" and "mandrilL" and signing up for a free Mandrill account.


Set view plugin submit handler I'm trying to create my own AreaPlugin. But there's submit handler doesn't work.

Here is a part of my code.

class MyAreaPlugin extends AreaPluginBase {

  /**
   * {@inheritdoc}
   */
  public function render($empty = FALSE) {
    $result['my_plugin_form'] = [
      '#type' => 'form',
      '#form_id' => 'my_plugin_form_id',
    ];
    $result['my_plugin_form']['actions'] = ['#type' => 'actions'];
    // There will be more actions.
    $result['my_plugin_form']['actions']['button_id'] = [
      '#type' => 'submit',
      '#value' => 'Button text',
      '#name' => 'button_name',
      '#submit' => [[$this, 'buttonClickHandler']],
    ];
    return $result;
  }

  /**
   * Button click handler.
   *
   * @param array $form
   *   This form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   This form state.
   */
  public function buttonClickHandler(array &$form, FormStateInterface $form_state) {
    drupal_set_message('exportData');
  }
}

How it can be done correct way?

Submit handlers only work in a form. If you want to put some kind of an action in render(), then use a normal link to an export display of the view or to a batch which uses an embedded view.


Help with database query How can I convert this sql query into a Drupal 8 query?

I need all nodes of type 'page' that has not been referenced by nodes of type 'article'. Article content type contains an entity reference field, from where nodes of type 'page' can be referenced.

SELECT *
FROM node_field_data
WHERE type = 'page' AND
node_field_data.nid NOT IN (
   SELECT 1
   FROM node_field_data
   LEFT JOIN node__field_ref
   ON node_field_data.nid = node__field_ref.entity_id
   WHERE type = 'article'
);

I tried with this approach, but it doesn't work:

$sub_result = $this->database->query("
   SELECT 1 FROM {node_field_data} n
   LEFT JOIN {node__field_ref} r
   ON n.nid = r.entity_id
   WHERE n.type = :type",
   ['type' => 'article']
);

$result = $this->database->query("
   SELECT * FROM {node_field_data} n
   WHERE n.type = :type AND n.nid NOT IN :query", [
      'type' => 'page',
      'query' => $sub_result
   ]
);

I get this error:

The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Object of class Drupal\Core\Database\Statement could not be converted to string in Drupal\Core\Database\Statement->execute() (line 59 of core/lib/Drupal/Core/Database/Statement.php).
Drupal\Core\Database\Statement->execute(Array, Array) (Line: 625)
Drupal\Core\Database\Connection->query('
      SELECT * FROM {node_field_data} n
      WHERE n.type = :type AND n.nid NOT IN :sub_result', Array, Array) (Line: 87)
Drupal\Core\Database\Driver\mysql\Connection->query('
      SELECT * FROM {node_field_data} n
      WHERE n.type = :type AND n.nid NOT IN :sub_result', Array) (Line: 141)
...
...
...

Try this out.
get_all_nodes_not_referenced_by_article('page');

use Drupal\Core\Database\Database;
/**
 * @param $type
 *
 * @return mixed
 */
function get_all_nodes_not_referenced_by_article($type){

  $connection = Database::getConnection();

  //- Step one get all referenced nids
  $query = $connection->select('node_field_data', 'nfd')
                      ->condition('nfd.type', 'article')
                      ->fields('nfd', ['nid']);
  $query->leftJoin('node__field_ref', 'nfr', 'nfd.nid = nfr.entity_id');
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

  $referenced_nids = [];
  foreach ($result as $key => $value) {
    $referenced_nids[] = $value['nid'];
  }

  /**
   * Check if $referenced_nids to avoid
   * Drupal\Core\Database\InvalidQueryException: Query condition 'nfd.nid NOT IN ()' cannot be empty.
   * */
  if (!empty($referenced_nids)) {
    return $connection->select('node_field_data', 'nfd')
                      ->condition('nfd.type', $type)
                      ->condition('nfd.nid', $referenced_nids, 'NOT IN')
                      ->fields('nfd', ['nid', 'title'])
                      ->execute()
                      ->fetchAll(PDO::FETCH_ASSOC);
  }
  else {
    return $connection->select('node_field_data', 'nfd')
                      ->condition('nfd.type', $type)
                      ->fields('nfd', ['nid', 'title'])
                      ->execute()
                      ->fetchAll(PDO::FETCH_ASSOC);
  }
}
?>


How to Create a single page within a module and set page variables? I create a page within my custom module with the following code:

function mymodule_menu(){
    $items['product-detail'] = array(
        'title' => t('Product detail'),
        'page callback' => '_mymodule_product_detail',
        'variables' => array('var1' => "Hello World Attempt #1"),
        'type' => MENU_CALLBACK,
        'access callback' => TRUE,
     );

 function _mymodule_product_detail(){
      // global $var1 = "Hello Workd Attempt #3";

     return array('variables' => array("var1" => "Hello World Attempt #2") , '#markup' => '
This is some markup content displayed correctly in the page
');
 } // function

It renders the template, sets the title and display the markup (content of the page). However, I would like to fill some variables defined in the page.tpl.php and I don't know how to send these parameters, I tried with the variables key in the code but nothing is written. I want to display the message "Hello World Attempt #?" in the place in page.tpl.php where I have the code <?php if(isset($var1)) print $var1; ?>

I have been able to reach my goal with the following code, but using GLOBAL, which is not adequate:

function mymodule_preprocess_page(&$variables) {
   global $var1;
if(isset($var1) && $var1 != "") $variables["var1"] = $var1;

}

The global $var1 is set to $var1 = "HELLO WORLD Attempt #3" in the _mymodule_product_detail() function above (lines commented).

The link in my comment may not get you all the way there so I am adding a working example. Assuming everything else in your code is working changing this line

 return array('variables' => array("var1" => "Hello World Attempt #2") , '#markup' => '
This is some markup content displayed correctly in the page
');

to

$output = array("var1" => "Hello World Attempt #2" , '#markup' => '
This is some markup content displayed correctly in the page
');
return theme('page', $output);

Added the entire $output array to the hook_preprocess_page`.

NOTE: You may have to add a theme callback to your menu item. Example here.


How to create a select list of which the selected item is used as parameter in VBO rules component? It's a common scenario, but I couldn't find a solution yet:

I have a view (a list of tasks) with checkboxes (views bulk operations)

I want:
1) a dropdown select list of taxonomy terms 'Priority' above the view.
2) a rules component that uses the selected taxonomy term, as parameter for applying the priority to the selected tasks.

VBO uses the core 'actions'. You can create new actions with hook_action_info.

The https://www.drupal.org/project/examples module has a good action example.


How do I force unique values within a multi-value set? When programming my own field and autocomplete widget, how can I ensure that each delta has a unique value?

I would like to handle the case as much silently as possible, so to not bother user with validation errors. Most gladly I would just prohibit the autocomplete test from returning the duplicate matches but as far as I can see, the autocomplete function does not accept any context, just the search string.

Should I then keep the already selected values in a session variable - would it be the Drupal way?

It might be easier to filter the autocomplete results using JS. You could either extend the prototype being used by Drupal or use some sort of trigger for when the results are being displayed.

I don't think that server-side solutions such as session variables and so on are practical as there's no guarantee that the results of previous calls were actually used by the user. Similarly, hacking the autocomplete feature to perhaps send existing values along with current user input is inherently impractical.


How is drupal able to see a module even when I renamed it I ran down into a serious issue with mediabox module. After spending some time I realized its because the update has broken some functionality. I just wanted to revert back to older version. I did it by copying my local folder which is older version to the production. However it looks like drupal is still taking the older version. This I confirmed by observing the html code which is different for two versions.

I cleared cache, restarted apache. But it still somehow is getting it from the bugged code. I even removed the folder. But surprisingly it is still reading it from somewhere. I made sure I removed the cache and rebooted apache. I did this in my local machine which actually broken my site which was expected but I am wondering why its still not throwing any error even after I renamed the folder name

Drupal stores information about where to find module files in the system and registry tables.  If you want to revert an update, you'll have to replace the updated version with the old version. If you ran database updates to update the module, you'll have to disable and uninstall it first, and then re-enable it after you've replaced the module files.

If you've removed the module without disabling it, the site should break. If it's still running with the updated module, there must be another copy of it somewhere.

If you want to know where drupal's reading the files from you can run the following SQL on the db:

SELECT filename FROM system WHERE name = 'mediabox';


Adding an external image to a views output I am trying to alter the output of a view  with a tpl.php file. My goal is to insert an image immediately after another image in the view. This should only happen for 1 result. That is to say, if the value of my array image is apple, I want to also display another image of apples. So if I have a view that returns images of fruits:

Grapes
pears
apple
peaches
bananas

I want to display these images:

Grapes
pears
apple apple1
peaches
bananas

I'm open to ideas, so far I've been trying to solve the issue programatically by creating a custom .tpl file for the view, but if a cleaner solution exists I'd be willing to give it a try.

I've come to the conclusion that I believe the best/easiest way to do this is by adding another field to my content type, and inserting the associated image in that field. Even though I've created a field in that content type that is only required for one piece of content.


How to dislodge drupal from Apache and remove drupal Excuse me please.. I am new to website development. I am using LAMP on fedora 20.
I am also using bluefish to edit html/php.

As a shear experiment, I installed Commerce Kickstart on my system. I did some terrible mistakes and now I need to remove drupal completely from the system..

I was just thinking of deleting the files and dropping the database. but is it enough?

thanks in advance

Yes, deleting the files and dropping the database should be enough.

If you made any changes to Apache (eg. creating a virtual host) and/or the operating system (eg. a line in the /etc/hosts file) you may want to revert that as well.

Don't worry about messing it up the first time, that's actually a great way to learn and get comfortable with any CMS (not just Drupal).


context block visibility - disable block for certain role I use drupal 6. I want to show a block for all users (anonymous, authenticated, all roles) except role XY and some paths.
I use context module where it is easy to set path rules. However, setting rules does not work - I want to disable block for role XY but enable it for all other authenticated users. So I check all roles I have + authenticated users and leave role XY empty. This way it does not work, probably drupal thinks that all authenticates are all roles.
What would be the way of achieving this? Thank you.

Perhaps this module might do the job for you https://www.drupal.org/project/hide_block_by_role doing a quick google search suggests that this would be the ideal module for you

Hope that helps

Seamus


Have a Rules condition that will take the current time minus last comment posted time Overall goal:  If a node has not been commented on in a given time frame, send an email.

How it could possibly be done:  Have Rules look at the last time a comment was posted when cron runs.  Then do a data comparison of that unit (current time - last comment posted time) to see if its greater than the time frame assigned to the node (ex: hours).  If so, send email.

Is this approach correct?  I am struggling to get the Rule to work if it is.

Overall goal:  If a node has not been commented on in an in a given time frame, send an email.

Here is a bare bones solution. On paper this should work.

Basically, we use sticky as the tell tell sign if a new comment has been added (if it's not sticky, no one has commented). Once the e-mail gets sent, we set node to unsticky.

1) Create a rule after saving new comment.

Add Action: Under Node, Make Content Sticky >> comment:node

  Then it's very similar to my answer to your question Rules Conditions
  being evaluated after schedule time
  elapsed?

  Create a New Component

  1) Add Compotent of Rule.

  2) For Data Type: select Node. Name, Label and Machine name use
  whatever you want.

  3) Add condition of Content is of type

  For Data Selector: put your Node Data Type machine name. Ex: if you gave the node data type a machine name of test you put test
  Select your content type

4) Download and Install Conditional Rules Module

Then for action, click on Add IF >> DATA COMPARISON >> test:sticky >> False

Then in IF: Data Comparison row click Add Action >> Send Mail

Then in Conditional row (1st row white) you will now see an Else button, click on it.

Then in Else click on Add Action >> Make Content Unsticky >> test

  Now Create a new Rule

  1) For action use after content is created

  2) Leave the condition empty (no need for condition here)

  3) for Action add the scheduled component evaluation and select the
  component you just created.

  use node as your data selector


Video host URL different in full content page links than in View links Background: Site in question has a custom content type "video record" containing many custom fields including a URL to brightcove.com-hosted video. (Note, the site is not using any Brightcove-specific modules.) A thumbnail image activates the link in both the full content view of a page and also in a View displaying a smaller selection of the fields from this content type. In both cases, the link is opened in a modal window generated by the module "lightbox2."

Problem: Thumbnail links from the View work as intended. Links from the full content page do not work, although they were working at an earlier point in site development. Unfortunately we don't know at what exact point, in the course of core or module updates, this functionality was lost.

Additional Info: Looking at the links in Firebug, we see an obvious difference: The ones that work (from the View of fields drawn from this content type) include a string beginning with "bcpid1235797793001?bckey= ..." and ending with a string of type "&secureConnections=true&secureHTMLConnections=true" that exists in the URL field of every node of this type. The ones that don't work are lacking both strings.

The Question: The link in the View and the one in the full content page must draw from the same URL field, as there is only one such field for each content item. In the case of the full content type, why might it be stripping out parts of the original URL and delivering a result that doesn't work?

The solution was to install the Dev version of module Image Link Formatter (7.x-1.0+6-dev). It now seems clear, this module (the current recommended version) was invisibly rewriting the URL, as there is no other way it could be specified to be rewritten in the standard interface options for the content type's fields. Although there was no documentation found for this issue in the issue queue or in documentation about the Dev version, apparently it is a bug that was fixed.


Putting a  tag around fields in nodes I have three fields in my node that I'd like to group together with a  tag (so I can center them all next to each other) but I'm not sure how to do this.

The fields are a user photo (the author of the node) a field that just says 'by' and then the 'author name' field.

Right now they look like this:

PHOTO
by
authorname

I could just 'float: left' but I also need to center the whole group on the page so that actually won't work in this case. Hence my need to put them inside a  tag.

Note: I'm also currently trying to use display suite to display my nodes, if that make a difference.

I looked at the display suite tpl file I'm using and frankly it doesn't give me many options other than 'print $ds_content;'

Anyone know how to do this?

To provide the custom markup, you have to override the tpl.php file for that node.
To override this, follow these steps :

1) Copy the node.tpl.php in your theme.

2)Rename it node--"yourContentTypeMachineName".tpl.php
for example my custom file is now node--image_archive.tpl.php

3) to test it out write some text(anything) in your new node.tpl file.

4)paste your new node.tpl file back in you theme folder

5)Clear all cache

Now access all the field and provide the custom markup as you want.


How do I show login form to anonymous user when accessing particular form I have created an entry form. Only authenticated user can access it. I have created a menu link for it and if any anonymous user clicks on menu link I want to show a login form and after successful login user is redirected to that entry form. I don't want to hide the menu link from anonymous user.(I have about 5 to 6 forms with same condition)

Logintoboggan will allow you display a login form when a user hits an access denied page:

  Provide a login form on Access Denied pages for non-logged-in (anonymous) users.


External login should set custom properties in user object I have a Drupal website and a Symfony based API. I have configured Drupal to use my API for logging in. The users are stored in Symfony.

When logging in, Drupal will store a user in the database to create a user object. On this user object, I want to set some custom properties. For example an id which is a reference back to my Symfony user so that I can load the users settings, etc. later on.

I have not managed to figure out how to do this. I hope someone has an example on how to do this or can point me in the right direction.

Below is the code I use for logging the user in. First I check if the entered username matches an administrator that Drupal knows of. If it does, I will use the default Drupal login validation. If not, I will login through the API.

/**
 *  Validates the login. Uses either the default Drupal validation or a custom validation.
 */
function myy_authenticate_validate($form, &$form_state)
{
    // Retrieve name and password.
    $name = $form_state["values"]["name"];
    $pass = $form_state["values"]["pass"];

    // Check if the user exists in the Drupal users
    if ($user = db_query("SELECT * FROM {users} u WHERE name = :name", array(':name' => $name))->fetch())
    {
        // A user exists. Loads the user information.
        $user = user_load($user->uid);

        // If the user is an administator, log him in using the Drupal validator.
        if (in_array("administrator", $user->roles))
            return user_login_authenticate_validate($form, $form_state);
    }

    // The user didn't exist in the Drupal users. Now, try to authenciate using the custom validation.
    $authenticated = myy_symfony_auth($name, $pass);

    // Check if we did authenciate
    if ($authenticated)
    {
        // This sets up the external user with Drupal by creating a local entry. If they don't exist they are added.
        user_external_login_register($name, "myy");

        // We must set the "uid" to pass back. This looks up the logged in user and sets the Drupal UID.
        $user = user_external_load($name, $pass);
        $form_state["uid"] = $user->uid;
    }
    else
    {
        // Do nothing. Drupal will handle the errors.
    }
}

myy_symfony_auth is a method which returns whether or not we were able to login using the API.

Does anyone have an idea how I can add custom properties to the user object when a login succeeds? It is only relevant to do this when the login was performed using the API (meaning that it was not an administrator who logged in).

I've done the same thing in D7. I see you're using the user-login-form directly and skipping over UID = 1 .... thats ok.

What you want todo is essentially copy the PHP logic of user_external_login_register into your own function, you're already calling your own *_authenticate() function to process the login page.

So you would change your:

// This sets up the external user with Drupal by creating a local entry.
// If they don't exist they are added.
user_external_login_register($name, "myy");

To like:

// This sets up the external user with Drupal by creating a local entry.
// If they don't exist they are added.
MYMODULE_user_external_login_register($name, "myy", $external_data);

and define the necessary function that mimics the D7 login logic AND adds you're own fields for the user upon creation (I mean literally copy the D7 function body into your function body and tweak as needed)  -- I've added additional fields using the Field UI found at /admin/people to my User accounts as seen below.

So I have this function to do that:

function MYMODULE_auth_idstaff_user_external_login_register($name, $module, $external_ldap_details) {
  $account = user_external_load($name);
  if (!$account) {
    // Register this new user.
    $roles = user_roles();
    $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      'access' => REQUEST_TIME,
      // This is where we are different from the default function and add our fields.
      'roles'        => array(array_search('staff', $roles) => 1),
      'mail' => $external_ldap_details['mail'],
      'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $external_ldap_details['first_name']))),
      'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $external_ldap_details['last_name']))),
    );
    $account = user_save(drupal_anonymous_user(), $userinfo);
    // Terminate if an error occurred during user_save().
    if (!$account) {
      drupal_set_message(t("Error saving user account."), 'error');
      return;
    }
    user_set_authmaps($account, array("authname_$module" => $name));
  }

  // Log user in.
  $form_state['uid'] = $account->uid;
  user_login_submit(array(), $form_state);
}

I've actually done the same exact thing in Symfony 1.4.x a few years ago ... except it was all object oriented lol (because Symfony's forms are Objects).


Programatically change exposed filter value based on another exposed filter I have 2 exposed filters in my Drupal 8 view - both are select dropdowns. I want the value of the 2nd filter to change based on selection of first filter
Here are the filters
$filters = $view->display_handler->getOption('filters');

$filters['country'] and $filters['states'].

Problem is that I always get an empty value when I try to access country filter in my views_pre_view hook.

dpm($filters['country']['value']) always prints empty.

How do I solve this please?

You don't have access to your filter options inside hook_views_pre_view.

$filters = $view->display_handler->getOption('filters');

give only informations about the filter something like:

 "field_country_target_id" => array:20 [▼
    "id" => "field_country_target_id"
    "table" => "node__field_country"
    "field" => "field_country_target_id"
    "relationship" => "none"
    "group_type" => "group"
    "admin_label" => ""
    "operator" => "or"
    "value" => []
    "group" => 1
    "exposed" => true
    "expose" => array:13 [▶]
    "is_grouped" => false
    "group_info" => array:10 [▶]
    "reduce_duplicates" => false
    "type" => "select"
    "limit" => true
    "vid" => "countries"
    "hierarchy" => false
    "error_message" => true
    "plugin_id" => "taxonomy_index_tid"
  ]

To get the selected filter values with:

$filters_selected = $view->getExposedInput();

Even you get the filter options you can't alter it because exposed filters are form inputs.
So i thing the best way to achieve this is by using hook_form_FORM_ID_alter like the following.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODUOLE_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Here is options of your country filter
  // Note that they key is FIELD_NAME_target_id
  // Change the FIELD_NAME with you field name
  $countries = $form['field_country_target_id']['#options'];
  // Get the city options the same way .
  /**
   * TODO: To alter options array change $form['field_country_target_id']['#options'] not the $countries
   */
}


Display custom block to specific content type programmatically I created one custom module, it will create one custom block when it is installed. I want to display it on "product" content type only. Can I do the same with programmatically. It'll save my time. Here is my code.

<?php
function my_module_block_info() {
    $blocks = array();

    $blocks['my_module_config'] = array(
            'info' => t('My Module'),
    );
    return $blocks;
}

/**
 * Implements hook_block_view().
 */
function my_module_block_view($delta = '') {
    $block = array();

    switch ($delta) {
        case 'my_module_config':
            $my_module_form = drupal_get_form('my_module_form');
            $my_module_form = drupal_render($my_module_form);
            $block['subject'] = '';
            $block['content'] = $my_module_form;
            break;
    }
    return $block;
}
?>

This code should work for you

function my_module_block_info() {
  $blocks = array();
  $blocks['my_module_config'] = array(
    'info' => t('My Module'),
    'status' => TRUE,
    'region' => 'content',
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
 function my_module_block_view($delta = '') {
 $block = array();

 switch ($delta) {
   case 'my_module_config':
     $block['subject'] = '';
     $node = menu_get_object();
     if (isset($node->type) && $node->type == 'product') {
       $my_module_form = drupal_get_form('my_module_form');
       $my_module_form = drupal_render($my_module_form);
       $block['content'] = $my_module_form;
     }
     else {
       $block['content'] = '';
     }
     break;
  }
  return $block;
}


How do I put username into email when send mail to role in Rules? I'm using Rules 7.x-2.11 and create new rules. I created additional fields in profile and when user select there from option list he got a new role.
Next, i created new rule. When create new node with certain type drupal send mail to all users with this role.

EVENT
Node insert

CONDITIONS
Node is of type

ACTIONS
Mail to users of role

It works, but i need put in email text username. In data selector i have only "node" and "site" selector's, how can i get "account" selector?

add rules conditional module, now in actions you can add more conditions, in actions fetch entity by id, node-author, drill until you find UID, add a conditional, add an if, entity has field, entity-fecthed-author-by-id, select your field, now you have what you need, repeat as needed, for every field, a conditional, an if and your field. done.
Your rule will look something like this:


Changing the field separator for multivalue fields I have a problem which should have a simple solution, but I simply can't figure it out. Perhaps I'm overthinking it or missing some piece of information. Being new to drupal it's not unlikely at all.

I'm trying to output a list of links through a View. No matter which Format I chose (unformatted list, grid, etc.), Drupal never fails to add a comma between each link. I'm having a great deal of trouble removing this comma.

Setting a separator under Field Settings have no effect, but I guess that's only applicable if I had another list of links.

I have tried editting 'views-view-field.tpl.php' by adding the line:

<?php $field->field_associated_quicklinks->separator = ""; ?>

But it doesn't seem to work. PHP and I aren't on friendly terms, so I'm loathe to start messing too much with the scripts - unless I got some helpful tips from you guys.

All in all I'm stuck on this, and frustrated that I'm having this problem in the first place. Drupal shouldn't go around adding content to my output.

------ EDIT:
Well, after several hours and a few tufts of hair, I found this great vid: http://www.youtube.com/watch?v=sxZQqgvJk3sI believe it's exactly what I needed to know, but I still can't make it work.

I did as prescriped:
1) Copied the field.tpl.php file, removed the comment and changed the mark-up a bit.
2) I named the file 'field--field_associated_links.tpl.php' and copied it into the templates folder of my sub-theme.

I get no reaction whatsoever. Could it be confused by the fact that my field name starts with 'field' as well?

Any and all suggestions are very welcome!

Normally you can control this separator directly in the views field option in the multiple field settings.

Have you tried to change this ?


show a div before the title I'm using an accordion list. In my file views-views-accordion.tpl.php want to print a div before the title of each article. I'm using the latest version of drupal and views. Any idea?

You have many ways of achieving this:

You can either preprocess it inside template.php file. The title has a #prefix and a #suffix theme key when preprocessing it with hook_preprocess_node().
Install delta blocks and turn convert the page into block and place the block accordingly.


Add a jQuery hover effect to images in a View I would like to add a jQuery hover effect to a view of thumbnail images (the content type consists of an image field). The effect that I would like to add can be seen here:

  Code: http://www.freshdesignweb.com/responsive-portfolio-gallery-with-jquery-tutorial.html
  Example: http://elegantthemes.com/preview/Evolution/

It consists of an overlay that appears when the user hovers on an image. I would like the overlay to have links to the image itself (so the user can comment) and to open a larger version of the image in a lightbox.

I just cannot find an easy tutorial to add this. Anyone with good suggestions? Or with some time to show me the steps to implementing such an effect?

Thanks!

I would do it with adding a custom theme to that view How to apply theme to a view drupal 7 to make the views output to match with your tutorials HTML structure and add .js files as recommended.

When it goes advanced you can try creating a views style plugin so that you can add this jQuery effect directly from your views page.

see

How to create a Views style plugin for Drupal?

How to properly implement hook_views_plugins?


Validating form data that it is a weekday I'm trying to validate a custom form field from an Ubercart module (in the checkout process). The field would specify a delivery date. The delivery date must be a business day.

How does one determine if it is a business day or not?

Are there given functions within Drupal that provide which day of the week when a response is given? Or would native php functions be the route to go with?

date('w'[, $timestamp]);

gives you the days of the week as an integer from 0 (Sun) to 6 (Sat).

So you could check to see whether the chosen delivery date is 1 - 5.
I am not aware of any existing Drupal function to do this, but it's a fairly simple function to write oneself.


Have I understood correctly? - Drupal Slider\carousel modules Why in Drupal, so much is needed just to insert a picture into a slider?...

I understand that in the typical Drupal slider modules, we can't just upload a picture into the slider - We MUST choose from and existing photo in the site and it MUST also be an existing photo from an existing View... This is (allegedly) a problem because it forces one to upload the picture to somewhere in the site even if there is no such necessity and also forces him to use Views even if he has no need to.

Why all of this way just to use a picture and are there really no shorter ways to do image sliding in Drupal?

Please correct me if I was wrong in anything here.

There are a lot of options within Drupal. This is it's great strength, but comes with a steep learning curve for starters.

So there are a lot of modules to build a slider. Most sliders require a content type where you upload the image and views to make the list of images. This is not to make it hard, but to give you options on what to do with it.

If you want an 'instant' slider, check out https://www.drupal.org/project/content_glider. No views required.


sharethis module in drupal I am using Share this module in Drupal . In that when we click on Facebook, Linkedin the image is also inserted and linked to that social site but when we click on twitter,no image is pulled in.Kindly help me with this

Check out Twitter validator tool for possible reason. The Twitter specification may help you as well.


How to implement a button with different redirections? I'm setting up a job directory using Drupal 8, together with a team.
It is possible to see it here.

As you can see below, in a screenshot of the site, there's a button called "Add new job":

In a more visual way, this is what I would like to implement:

If the user doesn't have login:

User clicks button
User goes to create account

Else:

User clicks button
User goes to a specific / different page / view

Something is triggering me that we can achieve this like that using Rules, setting on action events, but I'm not sure how.

It can be that I am totally wrong and there's a more straightforward way to do this.

For example, if I was to implement this just with PHP, would redirect a button to one page and in that page, using user sessions sessions and if conditions, would define the content showing up.

I'm not an expert in Drupal neither I'm aware of all of its possibilities. So, any help is appreciated.

Point the button to a custom controller:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class ExampleController extends ControllerBase {

  /**
   * Controller for action button.
   */
  public function action() {

    // if user is not logged in, redirect to create a new account
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect('user.register');
    }

    // else return content or redirect to content
    return ...;
  }

}


Image field - Cant set up number of values I have 2 content types with image field.
Shop and product.

For shop i limited number of images to 1, on products to 10.

Somehow the number changes to 10 for shop and to 1 for products (sometimes product doesnt change at same time for shop but in the end it happens).
I noticed that it happens when i clear cache and run cron.
I change values back to 10 and 1, and it works ok till the next cron run (or cache clear).

Any idea why is this happening ? All other content types (about 20) are ok, no changes for image fields.

If you're using the same image field on two content types then the cardinality (number of values) will be the same across both.

You'll notice you have 'instance' settings and 'field' settings on the field edit form. The 'instance' settings are unique to that instance, and can be different for each entity type/bundle the field is attached to.

The 'field' settings are global to that field, and the cardinality is one of these global field settings. If you change it for one content type, it will automatically change for the other content type. The caveat to this is that if you have data in the database for those fields already, you might not be able to change the cardinality at all (the select list will be greyed out).

This is by design, and how the field system works (there's no way around it). If you need to have two fields on two different content types with different cardinalities, you need to create two separate fields.


Allow character variants in username I am trying to import some users from a phpBB forum and found an odd thing: in phpBB I have some users with weird characters in the username. Eg: Henriëtte .

The problem is that in Drupal I can't create 2 users with the username "Henriëtte" and "henriette". Apparently "Henriëtte" = "henriette" and this will give an warning saying that the username already exists.

Is there any way to import both usernames in Drupal? Thanks.

[LATER EDIT]

The database encoding is utf8_general_ci. Also, after further investigation the user_load_by_name() function is responsible for returning a valid user even if one letter is different (ë > e). Also, user_load_by_name will in the end use entity_load() to load the user object.

Found the answer.

The encoding should be utf8_bin not utf8_general_ci


Entity reference value from url in node add form block I have a content type book and another content type pages.
A page has a entity reference field to book.
Now, I want to allow users to create pages on the same page as book. So, I created a page add form using formblock module.

I would like to have the entity reference field auto generated and pointing to the book.

Is it possible?
Thanks. :)

Node Reference URL Widget can help you :)


Cached taxonomy menu block problem? I created a taxonomy menu block based on a vocabulary I have. It didn't work how I wanted so I removed it. I have created a view (page) that has the same URL as one of the links in the taxonomy menu block, and that URL displays nothing (which is what happened when it corresponded to a link in the TMB), even though it shouldn't - its preview displays a list of content items. If I modify the view's URL the content displays, if I set it back to what I want it to be it displays nothing.

I've cleared Drupal's cache and even removed the TMB modules, but I still get the same thing.

Am I right to think it's likely to be related to the TMB that I got rid of? And can anyone suggest any steps to getting the content to display on the URL?

Thanks,

Toby

I've resolved this, I think, but would be interested to hear if there are alternative solutions. I think the Taxonomy Menu Block was a red herring - it was just using the URL alias for the associated term references, which exist whether or not a TMB is used. My view had the same URL alias, hence the conflict; setting either alias to something else was all that needed to be done.


Forms API: 'file' or 'managed_file' type with multiple/unlimited values I've got a form that needs to have either a 'file' or 'managed_file' type field in it for uploading files via the form. Is there an attribute that can be set on the form item render array that will allow multiple/unlimited files to be uploaded via the one form item?

For example, when you add a new field via the admin UI to a content type, select the 'file' type widget and then in the field settings set the number of values to 'unlimited' - that's the sort of behavior I'm looking for in this file field via the forms API. Thanks in advance for any pointers!

If you are trying to build this functionality for a custom form using the Forms API, it may not yet be possible.  It's documented on Drupal.org to be an issue. See this discussion, the bottom talks about the problems with implementing AHAH with a file field.


Make Views pager count rows, not items? I have a view of events, grouped by month. Each month could have between 1 and 6 events. The pager is set to 10 items.

Example:

January
x x x
February
x x x x
March
x x
April
x

So if there are 5 events in April, the page cuts off after the first item. Even though paging can be used to navigate to the remaining events, this is misleading; it looks as though there is only 1 event in April.

So I wonder whether Views pager could work by row rather than item?

It sounds like you need a view of views. Try the module Views Field View.

I don't know if this is doable. But this is what I will investigate:

In your primary view you must create a month only field, and page on that. Then in your secondary view (which will become a field of the first view, and to which you pass the month as context) you return the dates for the passed in context of the month. You will then end up with a multi-value date field in the first view. You might have to do some rewriting of output  (Views PHP?) to get the dates as text or integer fields.

And if you get it right, remember to employ views caching as Views Field View adds a lot of database queries.


How to select nodes of a certain type, created by a certain user and which have reference field to a node equal a certain nid? function mymodule_get_nodes_by_user_referencing_nid($type, $userid, $referncenid) {
    return node_load_multiple(array(), array('type' => $type, 'uid' => $userid, ??? => ???));
}

I need a function that lists nodes by following this logic: give me all nodes of a given type which are created by a given user and which have a node reference field referencing a given node id.

Any ideas about such function (in PHP, not in Views)
)?

This code assumes you're using the entityreference module using field name "field_reference":

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition('type', $type);
$query->propertyCondition('uid', $userid);
$query->fieldCondition('field_reference', 'target_id', $referenceid);
$result = $query->execute();

$nodes = array();
if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}


Drupal not detecting the correct version number of a module? I am trying to transfer a site over, and run update.php.

Drupal is telling me that my system and menus modules are out of date. This is not the case - they're both up-to-date, in fact I downloaded the most recent ones and uploaded them to my public_html/sitename/modules folder.

Where is the version number stored, so that I can force Drupal to recognize that they are the correct module versions that Drupal is looking for?

Specifically for the menu and system modules.

This is in D7.

As Jimajamma in comment #2 pointed out it is worth to check whether there are older versions in renamed directories.

I had the same problem and error message with modules - after removing the backup below "sites/all/modules/old" the dependency check error in update.php was gone.


D8 Widget Column is missing on manage field page I haven't worked with Drupal for a long time and particularly I never worked with D8. Looks like the manage fields screen doesn't have widget column. Specifically I would like to use https://www.drupal.org/project/inline_entity_form widget for entity reference field, but I couldn't figure out where do I go to change widget type for the reference field.

See screenshot:
https://screencast.com/t/eZvspoNHTDQv

I'm sorry for a stupid question. I figured it out. It was under "Manage form display" screen. What got me confused was while googling for answer, I stumbled upon a few screenshots from an early D8 build which still had Widget Type column on Manage Fields screen and it lead me into thinking that something was wrong with my installation.


How does decode_entities() work? Let's say $node->field_description[LANGUAGE_NONE][0]['value'] contains 'We&#039;re in this together'.
This code doesn't output what I expect.
$node = menu_get_object();
if (isset($node->field_description[LANGUAGE_NONE][0]['value'])) {
  $text = strip_tags($node->field_description[LANGUAGE_NONE][0]['value']);
  $text = decode_entities($text);
}

instead of 'We're in this together', I get 'We&#039;re in this together'.
The full hook implementation is the following.
function MY_MODULE_page_alter($page) {
  // Provide list description.
  $node = menu_get_object();
  if (isset($node->field_description[LANGUAGE_NONE][0]['value'])) {
    $text = strip_tags($node->field_description[LANGUAGE_NONE][0]['value']);
    $text = decode_entities($text);
  }

  // Add metadata to describe site's content.
  $description = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'description',
      'content' => $text,
    ),
  );
  drupal_add_html_head($description, 'desciption');
}

The function decode_entities works as you expect.  It converts the HTML entity (&#039;) into a single quote and returns the decoded string.

However, that single quote will be expanded into an entity again at some point downstream, when the page is rendered.  This is what inserts (provided you spell "description" correct) the following into your page's <head>:

<meta name="description" content="We&#039;re in this together" />

I would not worry about this.  The above is a perfectly valid HTML meta-tag and will be interpreted correctly for SEO purposes, etc.


Programmatically delete a webform submission by sid without first loading it Drupal 8 project has a 2 webforms:

Webform "ABC"
Webform "123"

Explanation of the process:

When Webform "ABC" is submitted, a new "node" is created and the "Sid" used to create this node is recorded inside a "text" field (field_submission_sid) on this created node.

Now, when Webform "123" is loaded, the value of (field_submission_sid) is populated inside a 'text' element (submission_to_delete)... and when the Webform "123" is submitted, a custom handler will delete the submission of sid value = (submission_to_delete)

The custom handler is working but I believe there is a better solution... so please I need your help ?

Custom handler:

<?php

namespace Drupal\custom_module\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Delete a 'webform Submission' using its "SID" retrieved from a populated webform submission value.
 *
 * @WebformHandler(
 *   id = "Delete a webform Submission using its sid",
 *   label = @Translation("Delete a webform Submission using its sid"),
 *   category = @Translation("Entity Delete"),
 *   description = @Translation("Delete a webform Submission using its sid retrieved from a populated webform submission valu"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class DeleteSidWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Load 'submission' object from webform-submission populated data.
    //get (SID) from (submission_to_delete) text element available on the webform
    $sid = $values["submission_to_delete"];
    $webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);

    //Delete the Submission
    $webform_submission->delete();
 }
}

If you notice, I am loading the submission first then i am deleting it...

is there a better solution where I can delete the submission directly without first have to load it ?
maybe something like $webform_submission = \Drupal\webform\Entity\WebformSubmission::delete(submission_to_delete);

UPDATE:

I noticed if the 'webform submission' is not available (Ex: An admin deleted by mistake) so the value of $sid will be NULL and the below error is generated:

Error: Call to a member function delete() on null in Drupal\custom_module\Plugin\WebformHandler\DeleteSidWebformHandler->submitForm()

How to add an if statement to check if $sid value is empty then do nothing otherwise execute code.

Thank you,

You always need to load before delete, there is no "better" solution.

  I am affraid from affecting the performance of the website since the
  above handler will be executed a lot

Loading one entity at a time is no performance issue whatsoever.

$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);
// Check if submission is returned.
if (!empty($webform_submission)) {
  //Delete the Submission
  $webform_submission->delete();
}


Get User ID from a Profile Page to use in a View I'm creating Views blocks on profile pages such as drupalsite.com/users/testuser. I need to display blocks such as "Test User's Posts" and "Test User's comments." What is the best way to get the User ID of the profile pages' subject in order to filter the content based on this User ID?

In this case, /user/testuser is just an alias of /user/n where n is the user ID.  Which means the user ID is available in the unaliased URL, allowing you to do this.


How do I show the weather block based on Geofield on a Taxonomy Term The Weather module has a block to show weather based on IPs on a node defined by the geofield module. There doesn't seem to support if it is on a taxonomy term. How can I modify this code to support taxonomy terms?

   case 'geofield':
  if (user_access('access content')) {
    // Set up the node geofield weather block.
    if (arg(0) == 'node' and is_numeric(arg(1))) {
      $node = node_load(arg(1));
      $block['subject'] = t('Weather nearby');
      $block['content'] = '';
      $display = weather_get_display_config('default');
      $display->detailed = FALSE;
      // Get a list of all field names which are geofield fields.
      $geofield_field_names = db_select('field_config', 'fc')
        ->fields('fc', array('field_name'))
        ->condition('type', 'geofield', '=')
        ->execute()
        ->fetchCol();
      foreach ($geofield_field_names as $geofield_field_name) {
        if (isset($node->$geofield_field_name)) {
          // The node has geofield fields, determine if there's usable data.
          // First cycle through the language codes (will mostly be 'und').
          foreach ($node->$geofield_field_name as $language) {
            // Now cycle through the different locations.
            foreach ($language as $location) {
              if (($location['lat'] != 0) or ($location['lon'] != 0)) {
                $place = weather_get_nearest_station($location['lat'], $location['lon']);
                $forecasts = weather_get_weather($place->geoid, $forecast_days, $display->detailed);
                $weather[0]['forecasts'] = $forecasts['forecasts'];
                $weather[0]['utc_offset'] = $forecasts['utc_offset'];
                $weather[0]['name'] = $place->displayed_name;
                $weather[0]['geoid'] = $place->geoid;
                $link = _weather_get_link_for_geoid($place->geoid, 'default');
                $weather[0]['link'] = l($place->displayed_name, $link);
                $link = _weather_get_link_for_geoid($place->geoid, 'yr.no');
                $weather[0]['yr.no'] = $link;
                $weather[0]['station'] = array('distance' => $place->distance, 'bearing' => $place->bearing);
                $block['content'] = theme('weather_forecast_preprocess',
                  array('weather' => $weather, 'display' => $display));
              }
            }
          }
        }
      }
      // Do not show block if no lat/long information has been found.
      if (empty($block['content'])) {
        return;
      }
    }
  }

Here's a stab at it. You'll obviously need to test as I haven't tested it at all. Basically I added in some checks to see if it was a node or a term and then tried to test the fields for either one. Let me know if it helps!

 case 'geofield':
    if (user_access('access content')) {
        // Set up the node geofield weather block.
        if (arg(0) == 'node' and is_numeric(arg(1))) {
            $node = node_load(arg(1));
        } else if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
            $term = taxonomy_term_load(arg(2));
        }

        $block['subject'] = t('Weather nearby');
        $block['content'] = '';
        $display = weather_get_display_config('default');
        $display->detailed = FALSE;
        // Get a list of all field names which are geofield fields.
        $geofield_field_names = db_select('field_config', 'fc')
            ->fields('fc', array('field_name'))
            ->condition('type', 'geofield', '=')
            ->execute()
            ->fetchCol();
        foreach ($geofield_field_names as $geofield_field_name) {
            $geofieldname = array();
            if (isset($node->$geofield_field_name)) {
                $geofieldname = $node->$geofield_field_name;
            } else if (isset($term->$geofield_field_name)) {
                $geofieldname = $term->$geofield_field_name;
            }

            if (!empty($geofieldname)) {
                // The node/term has geofield fields, determine if there's usable data.
                // First cycle through the language codes (will mostly be 'und').
                foreach ($geofieldname as $language) {
                    // Now cycle through the different locations.
                    foreach ($language as $location) {
                        if (($location['lat'] != 0) or ($location['lon'] != 0)) {
                            $place = weather_get_nearest_station($location['lat'], $location['lon']);
                            $forecasts = weather_get_weather($place->geoid, $forecast_days, $display->detailed);
                            $weather[0]['forecasts'] = $forecasts['forecasts'];
                            $weather[0]['utc_offset'] = $forecasts['utc_offset'];
                            $weather[0]['name'] = $place->displayed_name;
                            $weather[0]['geoid'] = $place->geoid;
                            $link = _weather_get_link_for_geoid($place->geoid, 'default');
                            $weather[0]['link'] = l($place->displayed_name, $link);
                            $link = _weather_get_link_for_geoid($place->geoid, 'yr.no');
                            $weather[0]['yr.no'] = $link;
                            $weather[0]['station'] = array('distance' => $place->distance, 'bearing' => $place->bearing);
                            $block['content'] = theme('weather_forecast_preprocess',
                                array('weather' => $weather, 'display' => $display));
                        }
                    }
                }
            }
            unset($geofieldname);
        }

        // Do not show block if no lat/long information has been found.
        if (empty($block['content'])) {
            return;
        }

    }


how to change max upload size of media file I am using media module to add files to server and have given same access to others. Now I want to keep the upload size limit to 1 MB. Please let me know if any option to change this.

What have you tried, what are your limitations? You should be able to change your php.ini if you have access per this.


Memcache and form cache - is specfiying database for form cache still necessary? In Drupal 7, a typical setup for Memcache API and Integration was to add this into your settings.php:

  $conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
  $conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
  $conf['memcache_stampede_protection'] = TRUE;
  $conf['cache_default_class'] = 'MemCacheDrupal';

  // The 'cache_form' bin must be assigned to non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

  // Don't bootstrap the database when serving pages from the cache.
  $conf['page_cache_without_database'] = TRUE;
  $conf['page_cache_invoke_hooks'] = FALSE;

Note the importance of the form cache being told to still use the database.

For Drupal 8, the README says you only add:

  $settings['cache']['default'] = 'cache.backend.memcache';

Is there any need to leverage the database for forms in Drupal 8? What line would you add?

Drupal 8 does not have a {cache_form} table; in-progress $form_state got moved to the key-value store.  The KV store for forms defaults to the database (there are core classes to support database and memory for KV).  And the KV store and cache backends are different concepts in Drupal 8 (the former is for persistent data with expiration, the later is for ephemeral data with expiration), so you should be fine.


How do I change pager (# of items) for one page display in a view? I have a view that will have about 7 different display pages. Some of the pages will have a different amount of items displayed on that page.
When I'm on my Publication Page (display name) and change Use pager:Display a specified number of items | 3 items to 15, it changes it for all displays in this view.
How do I override it for this display only. Here is a screenshot of the page I'm currently on: https://ibb.co/8YJpC1d
I thought this would be something easy (probably is), but I honestly couldn't find anything online to help me.

I guess I answered my own question, when I clicked the left side Use pager:Display a specified number of items it let me select if I want to override for just that display.


Workbench Access field cannot be used for access control I have set up Workbench Access and Workbench Moderation and it is working in creating revisions for the Main Page Content section but when I go to add additional fields using the Workbench Access control field checkbox, I cannot enable the field and a message displays

This field cannot be used for access control

How is it possible to allow a custom field to be added to access control?  I've enabled the correct content type, set up vocabularies and set the Access control fields with the node reference field from the content type.

The fields were enabled all along, the main issue was targeting the problem.  Only my body field was displaying on the node draft. I had several other custom content fields in the node but they weren't displaying in the Draft.  The site is built using Context and Views so was I had to do was clone Draft versions of those View Blocks and View Blocks.  Setting that up can be a little confusing but I found good documentation here

Draft Revision Blocks