How do I add an 'order complete' from the Commerce module to the Rules events in Drupal 8? I need to add a new event to rules triggered by the successful completion of an order. The action is to grant a user a role which will expire in a fixed duration.

I've tried following the Rules documentation and adding a module with a *.rules.events.yml file. But modifying it to use the order_complete event which I got from this tutorial.

Unfortunately, even though it DID add an option to the events drop down, it doesn't trigger an action.

I've tried a grep through the commerce code for order_complete but it doesn't yield anything.

The action I've set to the rule is just to print a message.

After trying out combinations and with the helpful comments, the solution was to follow the Rules documentation but change the event to commerce_order.place.post_transition which I got from the tutorial.

The final code was to create a MODULENAME.rules.events.yml file and add the following code:

commerce_order.place.post_transition:
  label: 'Order has been completed'
  category: 'Order'

This created the option in the dropdown and allowed me to create the rule that triggered the action.


How to perform a redirect after completing a Quiz? I am using Quiz module. How can we redirect user to thankyou/someother page after clicking Finish button?

If using Quiz 7.x-5.x
Assuming you're using the 7.x-5.x-rc3 version of the Quiz module, you can take advantage of integration with the Rules module that this new release comes with.
To do so, have a look at the delivered rule, which looks like so:
{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      }
    ]
  }
}

After you enable Rules (and Rules UI, a submodule of it), just clone the above rule (using the Rules UI) and replace both Rules Actions with a basic "redirect" (a typical Rules Action) that fits your needs.
If using Quiz 7.x-4.x
For the 7.x-4.x version of the Quiz module, you may want to try the patch from fago (aka the Rules maestro ...), attached to issue # 1300420, which has a description like so (note the last phrase in it ...):

... adds basic rules integration to quiz. It includes an event when users have finished taking a quiz, a condition to check whether a user has passed a certain quiz and an action to clear quiz results for a user.
Patch works for me.


Render a Views table row ID using a field as the ID value I am trying to apply an ID to table rows in a view using a field as the ID value.

I've copied views-view-table.tpl.php template to my theme template folder and renamed it based on the view I am working with.

I'm using Commerce Kickstart2, and I would like to id the table rows in this view by the SKU of each product.

I added SKU as a field in my view and then render it as a class for the Views Row using replacement patterns for the row class of a table view. (See screen capture).

In my template this is the line that writes the row class:

<tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>

I would like to add to that the field SKU as a row ID: id="SKU Value Here".

I have tried a number of ways without success.

after running print_r($view->result); at the top of the template I get this:

Array ( [0] => stdClass Object ( [product_id] => 1 [commerce_product_sku] => sample1 [field_data_title_field_commerce_product_entity_type] => commerce_product [field_data_commerce_price_commerce_product_entity_type] => commerce_product [_field_data] => Array ( [product_id] => Array ( [entity_type] => commerce_product [entity] => stdClass Object ( [revision_id] => 1 [sku] => sample1 [title] => Product 1 [revision_uid] => 1 [status] => 1 [log] => [revision_timestamp] => 1423407240 [data] => [product_id] => 1 [type] => product [language] => und [uid] => 1 [created] => 1418869347 [changed] => 1423407240 [commerce_price] => Array ( [und] => Array ( [0] => Array ( [amount] => 1600 [currency_code] => USD [data] => Array ( [components] => Array ( ) ) ) ) ) [field_images] => Array ( [und] => Array ( [0] => Array ( [fid] => 1 [uid] => 1 [filename] => tote-1v1.jpg [uri] => public://tote-1v1.jpg [filemime] => image/jpeg [filesize] => 48075 [status] => 1 [timestamp] => 1418869347 [alt] => [title] => [width] => 860 [height] => 842 ) 1 => Array ( [fid] => 2 [uid] => 1 [filename] => tote-1v2.jpg [uri] => public://tote-1v2.jpg [filemime] => image/jpeg [filesize] => 52861 [status] => 1 [timestamp] => 1418869347 [alt] => [title] => [width] => 860 [height] => 1251 ) [2] => Array ( [fid] => 3 [uid] => 1 [filename] => tote-1v3.jpg [uri] => public://tote-1v3.jpg [filemime] => image/jpeg [filesize] => 96645 [status] => 1 [timestamp] => 1418869347 [alt] => [title] => [width] => 860 [height] => 1100 ) ) ) [title_field] => Array ( [und] => Array ( [0] => Array ( [value] => Product 1 [format] => [safe_value] => Product 1 ) ) ) [field_associated_product_diagram] => Array ( [und] => Array ( [0] => Array ( [tid] => 272 ) ) ) [title_original] => Product 1 ) ) ) [field_title_field] => Array ( [0] => Array ( [rendered] =>

If anyone can lend any insight into how to accomplish this, I would appreciate it.

Try this to add an id attribute with your SKU based on the $view->result output:

 <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?> id="<?php print $view->result[0]->commerce_product_sku; ?>">


Add js script to register page Like the title says really, I'm trying to add a script to my register page, I'm using Zen as my theme, and I've added a script into the .info file, and to just test that it works I have added an alert() function, and it runs on just about every page except the default register page, and I don't know why, it just doesn't call the script at all.

The longer version is that I have a bespoke Drupal site, not intended for public use, just for specific medical personnel to use for an event we have coming up. What the client has requested is that the user must tick a box declaring they are a healthcare professional before they can register. I have added a boolean checkbox to my register form, and set it to mandatory, but obviously Drupal will accept either checked or unchecked, I want to make it so that they have to check the box before they can register (it's just a legal compliance thing)

I wanted to try to do it via Drupals methods only, but my backup was creating a js solution which would set the register button to disabled until the box was checked, except it doesnt seem to work on the register page.

Can this be done?

If you make a checkbox required it should force the user to check it (if you have an up to date version of drupal core). See the issue here where that was fixed.

For older versions of drupal there was the checkbox validate module.

As for adding javascript in your info file. That will add it to every page.
So either the page it doesn't work on is using a different theme (and therefore a different info file), or there is a javascript error on the page that is preventing your code from running.

Check your page for javascript errors.

There is also the legal module, which allows you to set terms and conditions that the user has to agree to when signing up. The module handles the checkboxes.
It might not be right for you but it is another option.


Create dynamic textfield? I have a form builder containing the following code.

  $form['finput']['noreff1'] = array(
  '#type' => 'textfield',
  '#title' => t('No Reff1'),
  '#size' => 60,
  '#default_value' => $noreff1,
  //'#required' => TRUE,
  '#autocomplete_path' =>'noreff/autocomplete',
  '#ahah' => array(
      'event'   => 'change',
      'path'    => ahah_helper_path(array('finput')),
      'wrapper' => 'finput-wrapper',
     'method' => 'replace',
         'progress' => 'throbber',
  ),
  '#prefix' => '
', '#suffix' => '
',
  );

  $form['finput']['noreff2'] = array(
  '#type' => 'textfield',
  '#title' => t('No Reff2'),
  '#size' => 60,
  '#default_value' => $noreff2,
  //'#required' => TRUE,
  '#autocomplete_path' =>'noreff/autocomplete',
  '#ahah' => array(
      'event'   => 'change',
      'path'    => ahah_helper_path(array('finput')),
      'wrapper' => 'finput-wrapper',
     'method' => 'replace',
         'progress' => 'throbber',
  ),
  '#prefix' => '
', '#suffix' => '
',
  );

  $form['finput']['noreff3'] = array(
  '#type' => 'textfield',
  '#title' => t('No Reff3'),
  '#size' => 60,
  '#default_value' => $noreff3,
  //'#required' => TRUE,
  '#autocomplete_path' =>'noreff/autocomplete',
  '#ahah' => array(
      'event'   => 'change',
      'path'    => ahah_helper_path(array('finput')),
      'wrapper' => 'finput-wrapper',
     'method' => 'replace',
         'progress' => 'throbber',
  ),
  '#prefix' => '
', '#suffix' => '
',
  );

This code shows a fixed number of form fields (noreff1, noreff2, noreff3). If I want to dynamically increase those form fields, how can I do?

So, I just want to show one textfield for starting. If user not use
  that form, it doesn't show new form. But, if user input some value in
  that form, when user finish inputing that value (confirm by click
  enter button on keyboard for example), new textfield form showd up so
  user can fill new value, and so on.. – bandungeuy

I don't think there is a Drupal way to do that, but you can always do this with jQuery.

For example:

HTML

<form>

  First name:

  <input type="text" name="firstname" id="edit-first-name">

  Last name:

  <input type="text" name="last-name" id="edit-last-name">

</form>

jQuery

(function ($) {

   $('#edit-last-name-wrapper').hide();

   (function Forever(){

     var grabs = $('#edit-first-name').val();

     if (grabs != '') {
       $('#edit-last-name-wrapper').slideDown(1500);
     }
     // slides down and shows the last name field if the first name field is not empty
     else if (grabs == '') {
     // checks if the first name field is empty
       $('#edit-last-name').val('');
         // empties the last name field, since there is no first name
       $('#edit-last-name-wrapper').slideUp(1500);
         // slides up and hides the last name field

     }

   setTimeout(Forever, 1);

   })();

})(jQuery);

JS Fiddle DEMO


Does View UI restrict fields based on filters, etc In the Views UI, are the fields that you can add restricted by whats possible due to the filters, contextual filters, relationships etc? Eg if I set a filter to node type A, will the ui allow me to add fields that only exist in node type B?

In Views 3 in Drupal 6, the UI does not enforce any restriction of fields. (And it does tell you what content type(s) the field exists when you want to select one).  About the only restriction I can think of is the initial View type, eg, a node View restricts you to nodes, taxonomy restricts you to terms, users to users, etc.


How to change layout of profile2 page? I have no experience with php and I've been trying for hours to alter the HTML of a profile 2 (module which extends core profile functionality) page. How can I do this?

Ideally I'd like it so I can just alter the page and add things like:

<div>
    <?php print $name ?>
</div>

Thanks

You need to enable the Profile2 Page module in the modules list page.

Then you go to modules/profile2 and copy profile2.tpl.php, paste it into your template folder and there you can customize as you want using...

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

...or other variables you want.


Changing Exposed Filter Label in Views I have a view in Drupal 7 site that needs some editing. In particular, there are some exposed filters on that page that require their labels to be changed. How can I do that?

I cannot seem to find where to do that. From my understanding, the filters are innate to the Views module.

As @Kevin already suggested.

In the following image, Please, see the red circle. From that input text area you can change the Label. Are you looking something else?


Where are the DB settings located? i've been learning Drupal 7 using Acquia DevDesktop and i have several sandbox type website running on my laptop but now i'm trying to access the databases from the command line. but in the settings.php almost the only that's not comment out are at the bottom, where it makes reference to inc.'s like this.

if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) &&
file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] .          '/loc_rmywebsite_local.inc'))
  require($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] .     '/loc_mywebsite_local.inc');

but then when i do a search for these inc files locally on my laptop, nothing comes up, as if they don't exist. so
One, where are these files?
and two, find where the DB settings are for these local sites so i can start learning how use the command line, or maybe Drush.

yes, i should probably have written down these setting but didn't.

You can find DB Settings of Acquia DevDesktop locally at following location

  C:\Users\YOUR_USER_NAME\.acquia\DevDesktop\DrupalSettings\loc_mywebsite_local.inc

In above path Replace YOUR_USER_NAME with apropriate user name that you login on system. This path for Windows 7.


Drupal Coding Standards (request_uri) I'm trying to write a patch to make module Drupal coding standards.

And this one the complains that have and I do not know how to fix it.

  Line 148: the use of REQUEST_URI is prone to XSS exploits and does not
  work on IIS; use request_uri() instead [security_12]
      return "http" . (isset($_SERVER['HTTPS']) ? "s" : "") . "://" . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

Here is the function that is been affecting.

function module_get_url() {
   return "http" . (isset($_SERVER['HTTPS']) ? "s" : "") . "://" . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
}

I know that I need to implement request_ui but I'm not sure.

It should looks like this .... ?

   function module_request_uri() {
       return "http" . (isset($_SERVER['HTTPS']) ? "s" : "") . "://" . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
    }

Any help will be appreciated on how can fix this complain.

It means replace $_SERVER['REQUEST_URI'] with request_uri().

So module_get_url() needs to change slightly.

function module_get_url() {
  $uri = request_uri();
  return "http" . (isset($_SERVER['HTTPS']) ? "s" : "") . "://" . "{$_SERVER['HTTP_HOST']}{$uri}";
}


PHP error 500 when including a left join on a pager query in db_select() I've got a query which is causing a PHP error 500 whenever I add a left join:

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

Here's the query:

$query = db_select('my_table', 'mt')
         ->extend('PagerDefault')
         ->fields('mt')
         ->fields('u', array('name')
         ->leftJoin('users', 'u', 'u.uid = mt.user_id')
         ->orderBy('mt.my_table_id', 'DESC')
         ->limit($results_per_page);

$result = $query->execute();

The query is to be used with a table + pager. If I remove the jeftJoin() and respective fields() the query works perfectly. Can anyone shed some light as to why this might be happening?

Many thanks

The documentation says:

  Joins cannot be chained, so they have to be called separately (see Chaining). If you are chaining multiple functions together do it like this:

$query = db_select('node', 'n');
$query->join('field_data_body', 'b', 'n.nid = b.entity_id');
$query
  ->fields('n', array('nid', 'title'))
  ->condition('n.type', 'page')
  ->condition('n.status', '1')
  ->orderBy('n.created', 'DESC')
  ->addTag('node_access');


How can I alter ctools access plugin expectancies? How can I tell a access plugin to expect a different argument plugin? Surely there isn't a one to one ratio.

So I'm working with panels. I've written a custom argument plugin that will take the node name from the URL and send back a node context. The problem I'm having now is that since I have "Selection Rule" on my page variant that is looking for a node of a specific type. "Selection Rules" are indeed access plugins. So with this said, the "Node: type" access rule requires a "Node" type context.

I'm providing that... the only thing is when the plugin sets up it's access rules it's looking for the following argument:

What my plugin is providing for some reason I haven't found out yet is the following:
argument_node_name_1

node_name.inc is the name of my file, by which if I remember correctly what provides the system name because as far as I can tell is some magic provided by ctools.

I can however us the entity_id argument plugin and of course this all works, but then I don't get to use the node name in the URL.

Ok, so here is the answer...

The problem is that we were working on an existing panel page. We made the argument plugin in the middle of working on this page. So we went to "arguments" and switched out the correct argument with Node: Name instead of Node: Id which we had before.

What we didn't do was go through each of our variants and click "Save" on the "Selection Rules" tab. What was up was the old argument was still saved in those slots even though it didn't show up in the drop-down. It took me a while to realize this because I was thinking the "Access" handler settings were being "generated" vs being "stored". I literally worked my way back to the feature I made of the panel page hunting this down, and when I saw it... the UI to Feature translation started clicking in my brain.

In short, the feature I thought I needed isn't needed. All that was needed was to clear the fog of ignorance...

With that said, in an interface such as Views. If a handler such as this was to no longer be available, a "Broken" identifier would then show up. I'm thinking something similar would have clarified a lot here... or at least some kind of validation.

Added a bug report: https://drupal.org/node/2282539


Creating a fallback field to load conditionally So if I have a node type of Article. I have two fields on it:

field_image
field_secondary

If field_secondary is being used, I'd like for that to be shown over field_image. Can anyone help point me in the right direction how I'd go about this?

If field_secondary is also an image field, then you can check if it is empty in your Twig template:
For example, in node--article.html.twig:
{% if content.field_secondary is empty %}
  {{ content.field_image }}
{% else %}
  {{ content.field_secondary }}
  {{ content.field_image }}
{% endif %}

{{ content.without('field_image', 'field_secondary') }}

(Your actual template will have more HTML in it.)


How to get correct language code during installation? I am programmatically creating some content during installation of my profile and I need to set the language for this content, otherwise it will be in English(which my site is not) and there will be issues with visibility of fields.

What is the proper way to get the language code in which the site is being installed? The language manager service is returning English, which is incorrect.

Looks like getting it directly from config is working just fine:

\Drupal::config('system.site')->get('langcode')


how to use Profile information for payments I am using the customer_profile_type_ui as a way of displaying different checkout pages for different types of purchases. (this is the exact scenario which the readme file described as its use, and I followed it). But now I have an issue: payments. I am using the Authorize.net contrib, and it says in its home page -

  The Payment checkout pane must come after the Billing information checkout pane for Drupal Commerce to be able to populate the order used to generate transactions with a billing address before this module attempts to process payment.

When you follow the profile_type_ui readme, it says to use rules to disable all panes (which would include 'billing information' and then enable the appropriate profile pane. I followed this advice, because the billing pane didn't have all the fields I wanted.

When I looked at the email invoice (developer email), it did not have values for the billing information, as expected (or shipping, but I'm selling memberships, so we wont be using shipping).

The only possible thing I saw was a checkbox on the billing page settings page which said

  Enable profile copying on this checkout pane, helping customers avoid having to enter the same address twice.

but it didn't do anything. Any ideas?

It sounds like you're using a custom module with instructions that run counter to the Authorize.Net instructions. Is that what you mean by customer_profile_type_ui? I assume that isn't part of the core Commerce Customer module, so a link would be helpful, but honestly it looks like you've already answered your own question.

I don't really get why you'd disable the core Billing information checkout pane for having insufficient fields. If you add a field to your billing customer profile type, it will show up in the checkout form. What else would you need to do besides that?


Trouble sending redirect after logout I'm trying to send a redirect after logout, but it is not sending properly. I tried using the hook_user_logout in a module as follows:

use Drupal\Core\Routing\TrustedRedirectResponse;

function module_user_logout($account) {
  $redirect = new TrustedRedirectResponse($url);
  $redirect->send();
}

The send() call causes the page to crash with the message: "The __ page isn't working"

To resolve current issue we need to create RouteSubscriber
my_custom/src/EventSubscriber/MyCustomRouteSubscriber.php :

<?php

namespace Drupal\my_custom\EventSubscriber;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;

    /**
     * MyCustom Route subscriber.
     */
    class MyCustomRouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = parent::getSubscribedEvents();
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -300];
        return $events;
      }

      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('user.logout')) {
          $route->setDefaults([
            '_controller' => '\Drupal\my_custom\Controller\MyCustomUserLogoutController::logout',
          ]);
        }
      }

    }

Then add entry into my_custom.services.yml:

  my_custom.route_subscriber:
    class: Drupal\my_custom\EventSubscriber\MyCustomRouteSubscriber
    tags:
      - { name: event_subscriber }

Then create actual controller which will replace users module logout method.
my_custom/src/Controller/MyCustomUserLogoutController.php

<?php

namespace Drupal\my_custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;

/**
 * Class MyCustomUserLogoutController.
 */
class MyCustomUserLogoutController extends ControllerBase {

  /**
   * Logs the current user out.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to home page.
   */
  public function logout() {
    user_logout();
    $logout_url = 'https://google.com'
    return new TrustedRedirectResponse($logout_url);
  }

}

Hope it will save your time.

Thanks


How do I embed a custom node creation form inside a view I have these nodes : Company, Cars, Trucks (cars and truck have a taxonomy term to give it's type). Cars and Trucks have a field named Company wich refer to the Company node.

So i can locate the vehicle location on a map. I know how to create a form wich allow the company's administrator to add some cars (with this subject : How do I embed a node creation form inside a view)

But i want to give a field like "Select your vehicule's type" -> "Car" or "Truck" and it shows the right form to add a new vehicle.

I want too, restrict the selection of vehicules types by user group. Then me as an administrator i want to have the possibility to select all types of vehicle, but an user group like "Motorbike Company" can use only "Motorbikes" or allow "Truck company" to use "Trucks" and Cars".

And finaly, in Campany i've a field "Vehicles" and when the company's administrator add a new vehicle, i want it add too in the "Vehicles" field of the "Company" node.

Can you help me to did that ? I use Views and Display Suite. i'm novice with Drupal and i request your help :)

As you're using plain php (not really bestpractice) you can code it out yourself there, having a select changing a query-parameter for your view (self made contextual filter ..).
A more sophisticated approach would be hooking your view, hook_views_pre_render:

This hook is called right before the render process. The query has been executed, and the pre_render() phase has already happened for handlers, so all data should be available.
Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result.

Or create a custom page-callback (see hook_menu),
where you embed the view and add the form regarding your query param (or uri param).
You can check permissions with user_access.
You won't need to enable php execution with these approaches !


Does Google crawl Drupal sites in maintenance mode? I'm using Aegir to clone copies of my site under a subdomain name ie test.mydomain.com.
These copies are in maintenance mode to keep away spammers and prying eyes.
I then use these copies to carry out tests and development work before committing changes to my main site mydomain.com

But am I hurting my SEO by the existence of these cloned sites? Does google crawl a sites which has been put in maintenance mode? Will it penalize me for having so many dead end subdomains?

When you put a Drupal site in maintenance mode, non-administrators see the standard maintenance mode page (assuming you clear caches after doing so).  If you examine the response, you will see that it is sent back with a HTTP status code of 503, which from RFC 2616 is:

  503 Service Unavailable
  The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.

And from the Official Google Webmaster blog:

  If my site is down for maintenance, how can I tell Googlebot to come
  back later rather than to index the "down for maintenance" page? You
  should configure your server to return a status of 503 (network
  unavailable) rather than 200 (successful). That lets Googlebot know to
  try the pages again later.

So, that gives evidence that Drupal does the right thing, and that Google will revisit your site and index pages the next time it gets back a non 5XX status code.


Display Suite: Edit tab missing on user profile Using Display Suite (DS), I've overridden the user profile page in order to create a custom layout. However, the edit tabs that would normally appear when a user is logged in are no longer visible. How can I add them back?

I'm not sure if it's a factor, but I'm also using a custom-made Panels template within DS. Since I'm only using this layout on the user profile, I'm open to adding the edit tabs directly to the template, if possible.

I'm open to any methods that would be considered "best practice". Thanks in advance!

Further answers are welcome, however, I eventually found an easy solution to this issue. Because Display Suite supports tokens, I was able to create a custom field that outputted an edit button. Here's an example of the html I used: CUSTOM ICON.

In order to hide this icon from unauthenticated users, I enabled field permissions which is available when the Display Suite Extras module is enabled. Once enabled, you can adjust what fields are displayed for each user role in the permissions menu. Hopefully this is helpful to anyone experiencing a similar issue.


User organic groups for paid elearning courses? I don't know very much about the Organic Groups module.

I have a client that is interested in a course learning system and have that content restricted by groups. Each paid user would checkout and purchase this course.

Would organic groups be good for this particular feature?

You can set Organic Groups to be visible only to users of certain roles. And with the uc_roles module in Ubercart, you can create products which grant users a certain role.

There's also a module that makes it possible to sell Organic Group membership to one or more groups when a user purchases a particular product: UC OG Subscribe

Depending on what exactly the course learning system would be about, the og could be a good fit. Even without it, though, you can always restrict access to content through core roles, or ACL and the likes.


Trying to use Replace to change the output of value on a view using custom text I'm trying to figure out how I can replace underscores and a specific text using Replace on a Drupal 8 view custom text. In a template, I could use the following code to replace specific text.

{{ items.entity.getType|replace({'_': " ", "2": ""}) }}

what can I use on a view on custom text? I tried using {{ type|replace({'_': " ", "2": ""}) }} but it seems to show the text as plain text, not HTML markup.

have you try to use Rewrite results in views field settings? In Rewrite results there is an option Override the output of this field with custom text if you click on it it will let you change the output of this field to whatever you want.
plus there will be a Replacement patterns option which will show you a list of replacement tokens. also you can add some HTML if you want/need to.


Drupal 7, Is there a module that detects file structure changes? Recently one of my clients sites was hacked and hackers uploaded a few directories and files into the web root folder.

I'm looking for a module or a method that has the ability detect file structure changes in the web root of drupal and any sub folder. In the end I want it to be able to email me when files get added or directories get made.

There is quite a few:

https://drupal.org/project/md5check (7.x.1.0 - actively maintained)
https://drupal.org/project/hacked (7.x.2.0-beta -seeking new maintainer)
https://drupal.org/project/sentry_server (6.x.1.x-dev -  seeking co-maintainer)
https://drupal.org/project/file_integrity (abandoned)

I've included those abandoned and seeking new maintainers, in case you want to revive them or use them as starting points for your own project.

However, as noted by Clive, this is easier to set up and maintain outsite of Drupal.  Here  is a broad outline of what you need:

First, recursively run through every file and sub-folder on the server within the current directory of the script and generate a file containong the "master" hash for each.  Repeat this whenever you update your site by installing new modules, etc. or updating old ones.

Create a script (in your favourite scripting language) to do the following, and activate it with cron at regular intervals. Make sure that it is not remorely executable (store it outside the web root).

Load configuration file (list of files to exclude from scan, etc.)
Recursively run through every file and sub-folder on the server within the current directory of the script.
Generate a hash for each file and compare with the master hash
Alert (e.g. by email) if different.

Based on: How to detect if your webserver is hacked and get alerted. They also have a script (WebsiteCDS) that does this taht you can download.  I haven't used it, and can't vouch for the quality of their code.


Displaying taxonomy term list within another taxonomy term I have a vocabulary that list schools that users can select on registration and other vocabularies for books and courses, used on nodes.

Under each school's term page I would like to display a list of terms from Book vocabulary and other vocabularies and clicking on the any of the terms will list nodes with the term.

CT>Ucon

Books

textbooks
fiction
animes

I have thought of using panel to display school terms and then place a block of the book terms in a region in the panel, but I'm not sure how to go about it especially the URL. I would like the url to look like uconn/books/texbooks.

Additional info: Craigslist has similar nested categories. You have city category then under each city you have sale, services, community sections. This is what I'm trying to achieve. I want each school to have their own sub-categories listed under them.

Dee, I completely did not understand your question. But these code might help you.

/*To load a vocabulary*/

 $vocabulary = taxonomy_vocabulary_machine_name_load($machine_name);
 Example::$vocabulary = taxonomy_vocabulary_machine_name_load('book');

/*To get array of all term objects as a tree*/

$terms = taxonomy_get_tree($vocabulary);

/*To get children of all terms*/

foreach($term as $aterm) {

  $child = taxonomy_get_children($aterm);

}


A Real Estate Website Using Drupal My friend wants me to create a Real Estate Search Engine for him where Users can submit Real Estate Information so that others can view them ( by searching or any other method ).

I want to use Drupal because I have worked with it earlier. If there is a plugin/add-on for Drupal which can help me make a Real Estate Website, please do include a link in your answer to the plugin or module page(The Plugin or module should be free of cost).

Is there any other CMS which I can use ( Real Estate Plugin should be available )? or should I go with Drupal?

In Drupal, you will not find a specific "Real Estate Module". (Well, there is one, but it's a dev version for Drupal 5 and there's only 1 site using it :-)) Drupal modules tend to be more abstract: you take a module for building list pages, add a module for image handling, use a third module for send-to-a-friend functionality, etc. etc. The great thing about Drupal is that 99.9% of the time, you don't have to worry if those modules are compatible with each other. They just build on core concepts such as nodes, fields, menu's and users.

That said, I think you should be able to build a real estate site by combining the modules you need. This way, you will end up with a much more flexible system than a monolithic real estate plugin can ever offer.

I can't be really specific about which modules you need, because I don't know your exact requirements. For the basic functionality you don't even need additional modules; Drupal 7 core allows you to set up a content type (let's call it 'property'), add fields to the property content type (like an image field, price field, address field) and adjust permissions so logged in users (or anonymous, if you want) can create property nodes. Drupal core also includes basic search functionality.

After that, add contributed modules if needed:

Views to create all kinds of lists (plain, with filters, sortable tables, etc.)
Pathauto to create nice search engine optimized URLs
things like Location, Gmap and/or Locationmap (I haven't tried them yet in D7) for maps and geolocations

I recommend that you start building a basic site first and ask more specific questions when you run into them.


Why aren't nodes indexed when they are saved? Why aren't nodes indexed when they are saved?

As we all know, node_update_index is invoked by search_cron, which means that the search index is only updated as frequently as cron runs.

I am curious why _node_index_node isn't part of the normal node_save process, eg

if ($node->status == NODE_PUBLISHED) {
  _node_index_node($node);
}

Is there a good reason for this?  Since this function is defined by the node module itself, I don't see how it is a separation of responsibilities thing, nor can I think of a good reason for not doing this.

The related question would be, is is safe to wire up an action to fire when a node is created or updated?

I believe it is in the interest of scalability. Imagine you had a large, popular site with user-generated content. Imagine you had users saving a node (say, posted a question or answer) every 20 seconds. Imagine a node being indexed as well as submitted every 20 seconds. The site would become unusable very quickly. So it's much better to allow the indexing to happen independently of node submission.


User picture on multi site / multi database setup I have an unusual problem that doesn't appear to have a workable solution....

We have a multi-site setup that has a shared database for taxonomy and the users tables and it's related tables.

Each site then has it's own core database with content, permissions and file_managed.

We would like to keep the file managed table unique to each site, as the amount of images and video's expected will be significant over time.

This leaves us with one small issue in that the "picture" field in the user table is referring to a FID from the file_managed table. If I set my profile picture when on site 1, it works great. If I visit site 2, the same user table will return a FID from that site, which could and usually would be a completely different picture.

Has anyone had any experience in getting around this situation? We don't want to go down separate users for each site, and we don't want to have one file table for all sites.

Ideally I'd like to be able to hard code a url for the "picture" field in the user table, but I'm not sure if this is possible?

Any help is very much appreciated.

What I would do is:

Use hook_form_alter to add non-managed file upload to profile edit page.
Configure Drupal or webserver so that directory for these files was common, or so that all pictures would get uploaded to the "main" site's folder.
To a profile, I would add a link field. Configure it to be shared between sites, too.
In a submit handler (again, added using hook_form_alter) I would populate this field with the URL to uploaded image.


Field Collection vs. Entity View Modes with Field Group I have been using Entity View Modes to organize my fields, have different display types, and use Field Groups to add bootstrap-style wrappers around my content.

As often as humanly possible, I have views and panels render nodes with these view modes to keep a consistent look throughout the site.

I keep hearing about Drupal Field Collections, and have a basic understanding that it goes further and makes an Entity out of the grouped fields.  Seems like a different approach to achieve similar results. It has a lot more uses, but also a lot more open issues, and needs other modules to integrate with Views and Features.

I'd love to hear some thoughts on this.

Thanks,

Ji

Jim -

I love Field Collections because it allows me to create "structures" of fields that I can tie to multiple content types. You can still use Field Collections with Field Groups (in order to create field sets and the like). Would definitely recommend for projects with lots of content types / data that needs organization.


Routing match everything i want to match in a route a 'random' URL with a random sub path, fox example:

/example/1/a/b/c
/example/c3/s
...

i implement this route in my .routing.yml file

modulo.validator:
  path: '/example/{path}'
  defaults:
    _controller: '\Drupal\modulo\Controller\Controller::check'
  requirements:
    _permission: 'TRUE'
    path: '.+'

I write it following Symfony2 standard but it doesn't works, seems Drupal override requirements in path.

Take look to system.routing.yml

system.private_file_download:
  path: '/system/files/{filepath}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

why this doesn't work for me?

Any suggestion?

The reason that the route in system.routing.yml works is that it gets help by an inbound path processor service, which stores the filepath to a query parameter in the request:

PathProcessorFiles.php

<?php

namespace Drupal\system\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Defines a path processor to rewrite file URLs.
 *
 * As the route system does not allow arbitrary amount of parameters convert
 * the file path to a query parameter on the request.
 */
class PathProcessorFiles implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;
  }

}

This service is registered in system.services.yml:

system.services.yml

  services:

    path_processor.files:
      class: Drupal\system\PathProcessor\PathProcessorFiles
      tags:
        - { name: path_processor_inbound, priority: 200 }

And the controller gets the file path from the query parameter added by the processor:

FileDownloadController.php

  public function download(Request $request, $scheme = 'private') {
    $target = $request->query->get('file');
    ...

You can implement the same approach for your route to match everything after /example/.


Display Google Search XML results onto site within HTML I have created a custom module to search the site using google site search and so far I have been able to get search results back in xml format and I need to have these results display on the site in HTML

Thanks for any help with this

We can use the Google Search Appliance module for this.

This will retrieve the results as HTML and there are custom search-result(s) theme templates which will allow us to theme as per our requirements


Organic groups, audience filter issue When adding groups under the 'audience' list box for Organic Groups, i can see ALL groups created by everyone. How can this be limited so the user only see's his/her groups created in the audience list box? Help is much appreciated!

The groups audience field is an entity reference field, which includes a setting to filter the groups using a view.
So first create a view that lists the logged in users groups, and use that in the groups audience field setting.


Send mail notification when node of given type gets created Use case: a small site where I want to warn all users by mail whenever a new content of a particular type is created. I thought I would try Rules+Actions to handle this.

I'm working on a vanilla Drupal 8 test site on my workstation, so there is just "Article" and "Basic Page".

I've installed the Rules module ok. I've looked at several videos explaining how this works in Drupal 7 and they looked reasonable straightforward. Now I'm trying to do something in D8 and finding it less than obvious.

Specifically, I've created the rule to fire when new content is created, and now I'm on a page editing Condition, where I want to specify that the node type is "Article". Using "Data selection" mode in the "Entity" field I select "node.type". This seems logical, but what on earth do I put in "Type"? No matter what I put I get a message something like this: "Data selector node.entity for context Entity is invalid. Unable to apply data selector 'entity' at 'entity' " - which is about as unexplicit as you can get.

Maybe I'm jumping the gun and Rules is not usable yet? Or maybe I've just not understood it at all...

But I would really appreciate if somebody could explain to me what seems quite straightforward in principle. How do I add a condition to my Rule that will cause the rule to fire only on a specific content type?

Answering the "what do I put in the 'type' box?" question, the answer appears to be the same as for D7 - that is, the same status you'd pass to drupal_set_message().

This gives you options of:

status
warning
error

As to the state of D8 and specifically D8 rules, I share your pain - and it's nine months since you asked the question!


How to translate !title field is required I want to translate '!title field is required.'.
I can see it in 'admin/config/regional/translate/translate' but if I put a translation, it will override the name/label of each field.

So it is taking '!title field is required.' as one string. But I just want to translate 'field is required' and field names separately.

For example a Name and Email required in a form should display same translation but replacing !title with the name of the field.

How to do that.

To change the field name, you have to translate !name field is required. . To do this, follow these following steps :

Go to admin/config/regional/translate/translate.
Search for the string !name field is required in the String contains textfield.
In search result, change the string for all the languages.
And then save it.

I hope it works.


How to add role selection field to the registration form? How can I add the role to registration form that users can choose their role?

I tested the Profile2 module and the Auto Assign Role module but they don't do what I want.

I want to add a CCK field in the admin/configure/account/fields.

Is there any module to add a CCK field to registration form for choosing the role?

If any module doesn't fit yoour requirement then you can use the  below code
 You can create any custom module or put this code in template.php of your theme.
 function testing_custom_form_alter(&$form, $form_state, $form_id){

if($form_id=="user_register_form"){
    $result = db_select('role', 'r')
                ->fields('r',array('rid','name'))
                ->condition('name',array('administrator','anonymous user'),'NOT IN')
                ->execute()
                ->fetchAll();
    $role   =   array();
    foreach($result as $userRole){

        $role[$userRole->rid] = $userRole->name;
    }

$form['role']['#type'] = "select";
$form['role']['#options'] =$role;
$form['role']['#required'] = 1;
$form['role']['#size']='auto';
    $form['#submit'][] = 'custom_assign_role';

}

}

function custom_assign_role(&$form, $form_state){
   $uid=  $form_state['values']['uid'];

    user_multiple_role_edit(array($uid), 'add_role', $form_state['values']['role']);

}

Hope it will help!


Basic custom module installation error - "...Controller does not exist in ReflectionMethod" I was following this tutorial to create an most simple custom module.

I have created files inside /modules/elevator_search:

And in the /src/Controller I've placed:

The /modules/elevator_search/evelator_search.info.yml:

name: Elevator Search
description: Moduł wyszukiwarki wind
package: Custom
type: module
version: 1.0
core: 8.x

The /modules/elevator_search/evelator_search.module is empty.

The /modules/elevator_search/evelator_search.routing.yml:

elevator_search.content:
  path: '/elevator_search'
  defaults:
    _controller: 'Drupal\elevator_search\Controller\EvelatorController::content'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

The /modules/elevator_search/src/Controller/ElevatorController.php:

<?php
/**
@file
Contains \Drupal\elevator_search\Controller\ElevatorController.
 */

namespace Drupal\elevator_search\Controller;

use Drupal\Core\Controller\ControllerBase;

class EvelatorController extends ControllerBase {
  public function content() {
      return array(
          //'#type' => 'markup',
          '#markup' => t('Hello world'),
        );
  }
};

It did show up under /admin/modules:

But when I try to install it I get an error:

  ReflectionException: Class Drupal\elevator_search\Controller\EvelatorController does not exist in ReflectionMethod->__construct() (line 123 of core/lib/Drupal/Core/Entity/EntityResolverManager.php).

Your class' name is "EvelatorController", the name of the php file of the class is "ElevatorController.php" - it is just a spelling problem


How to set the default value of remember me in the persistent login module to on? The persistent login module
gives a "Remember me" at login.

How to set this value default on?

It does not look like that module offers such a setting by default, so you'll have to change the option using hook_form_alter as well (in a custom module).

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {
  // I don't check for the specific form here, since we do have a specific element we can look for.
  if (isset($form['persistent_login'])) {
    $form['persistent_login']['#default_value'] = TRUE;
  }
  if (isset($form['account']['persistent_login'])) {
    $form['account']['persistent_login']['#default_value'] = TRUE;
  }
}

You will have to make sure that your custom module is run after the persistent login module:

How to update a module's weight
There's a module for that


Facebook Auto Post not working? I configure the facebook modules. I created facebook Apps and I gave facebook auth id and secret key and all. But I couldn't connect with facebook.  I got this type of Error?

You need to provide website URL on your app settings.

Step 1. Navigate to your app settings

https://developers.facebook.com/apps/[your-app-id]/settings/

Step 2. Under website section provide your website URL.

check this answer for Reference


How to create a link on a field in a custom template file I created a custom tpl file for the teaser of a node.
To print the fields i use render() eg:

render($content['field_subtitle']);

This all works fine but i would like for example that the rendered output of field_subtitle has a link to the actual node.

My workaround for the moment is to do something like this,

<a href="<?php print $node_url; ?>">
   <?php print render($content['field_product_subtitle']); ?>
</a>

This works but produces some nasty looking html with div's inside the .
So i was wondering if you could just add a parameter to the render function that produces a link to the node?

You will want to use a preprocess function in your theme's template.php file, so that you can manipulate the element's attributes before it is rendered.

For example, if you wanted to link a particular field to the node's page, you could implement template_preprocess_field() as such:

function THEMENAME_preprocess_field(&$vars) {

  $items = $vars['items'];
  $node = $vars['element']['#object'];

  $path = 'node/'.$node->nid;

  if($vars['element']['#field_name'] == 'TARGET_FIELD_NAME'){
    foreach($vars['items'] as $key=>$item){
      $vars['items'][$key]['#markup'] = l($item['#markup'], $path);
    }
  }
}

the l() function is a structured way to build a link within the Drupal API. In this example I have assumed that the field is only allowing plain text, but if your field allows HTML, you can pass extra variables to the l() function that will allow that.

You can access other node data in the $node variable I created, such as the node type, published status, etc. If you want to investigate all the variables available to you in this (or any) preprocess function or template, I would suggest installing the Devel module and printing out the variable you are interested in with the kpr() function. For example, you could add the following code to the preprocess function I created above:

kpr($vars);

and you would be able to see all of the data available for use in that function in an easy-to-read format.


Drupal 7 hook_fom_alter not working for custom fields I have added custom field for email address in my content type.
I want to assigned default email address to this field. Following is my code.

function request_order_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'request_order_node_form') {
    dsm($form);
    $form['field_your_email']['#default_value'] = 'sam@gmail.com';
  }
}

But I am not getting default value in my field.

Set default value in field setting and try this after that :

print $form['field_your_email']; //check where default value is

$form['field_your_email']['und'][0]['value']['#default_value'] = 'sam@gmail.com';


Is there a better way to get a uid in a block than using Input Format PHP? I need to make a direct link to page which needs the uid in the URL.

Can someone suggest a better way to do this in a block? Does Input Format PHP code open some unnecessary attack vectors? Are input filters or tokens in blocks possible?

<?php
global $user;
?>
.
.
.

   <a href="/user/<?php echo $user->uid ?>/fboauth?destination=stream">Facebook Deauthorize

This is a legacy site running 6.28 using FBOauth.

You should be creating your own block module for blocks that require custom PHP, custom PHP inside a form field is not very good security wise because of the way the PHP is parsed.

A custom block meaning

custom_hook_block() with the $block['content'] =>


Views block: select one item from each content type I am using a flexslider views block for the homepage of a site. There are content types such as news, articles, announcements... In that views block I would like to display the latest item of each content type.

I played around with the filter and sorting settings in the views admin panel but could not manage to list the items that way. I can either list the latest item -no matter what content type, or list the latest items of a certain content type -only one type. I tried to group the results in someway and that also was not what I need.

I found a related question but there seems to be no useful solution on that page.

Any ideas how I can manage this?

That is easy. Simply create the most recent item for each content type on a different attachment display, and combine them all into the views block display. That is only way you will be able to achieve that


Updating duplicate Flags AND one or more Views blocks on a page on Flag click I have a page where I have several carousel views that can, at times, show the same item/node in each carousel. Such as a most downloaded and a most viewed. I have two different flags (bookmarks and cart) I need to update across the page as well as views blocks that lists out all of the flagged items for each of these.

So as I have been working on just how to do this I have run into some stumbling blocks. First of all I can hook into the flags JS API to initiate this, which is fantastic. I can even identify all of the flags of the type that has been acted upon which apply to the updated flag.

However I have ran into the following problems:

When looping through all of the identical items with say the bookmarks flag I don't seem to have a way to differentiate it from the other flags on the page that need to be updated. My concern is that by looping through all of them I will inevitably leave the flag I clicked on in the same state and all of the other duplicate flags on the page in the new state.

$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
  //Your code here
});
I want to prevent the flags JS from showing the popup messages on each click such as "item added to bookmarks" and instead pass that to jGrowl. I know how to generate it in jGrowl, I just need to figure out how to capture that message and show it my way.
Finally I need to update the related views block on the page when this is done. Say the bookmarks list block.

So what I would like to know is first, how do I deal with updating the same item's flag on multiple places on the page when it has duplicates?
Secondly I want to know how to capture that message and redirect it to my tool (jGrowl).
Lastly is how do I update a view block on a page with AJAX?

I want to do all of the updates without reloading the entire page.

Currently I am running this on Drupal 7 with Views 3 and using Nice Messages to generate system messages in a Growl-like format.

Thanks,
Patrick

I just ran into the same problem. This is how I handled updating duplicate flags on a page:

    $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {

        if(data.flagStatus == "unflagged"){
            $('.flag-favourite-' + data.contentId + ' a').each(function(){
                if(!$(this).find('a').hasClass('unflagged')){
                        ($(this).html(data.link.innerHTML));
               }
            });
        }
        else{

            $('.flag-favourite-' + data.contentId).each(function(){
                if(!$(this).find('a').hasClass('flagged')){
                        ($(this).html(data.link.innerHTML));
               }
            });

        }
    });

change out the term favourite with the machine name of you flag and it should work...


Drupal Commerce Sale Price On a Drupal Commerce project of about 2000 products, the client wants to set sale prices for some of the products. The client also wants to set a sale expiration per product so that after a certain date, the product is no longer on sale. Is there a module or technique that could accomplish this easily?

Commerce Sale Price provides per-product sale prices. Someone offered to provide exactly what you want but they haven't actually done so yet. The only thorny thing about achieving this is being able to work with Commerce's precalculated price system (you'll find some links on the Commerce Sale Price project page). At first you'd think this could all be done using Rules, but as I understand it, the system requires that a discount rule either be related to some global condition such as the date (which can get checked when a View is executed) or related to the product itself (such as an on sale field). The problem with your requirements is that the price is related to something external (the date) and something attached to the product. The only way I can see around this is by having a cron run that switches on/off the normal sale price flag based on the schedule fields (and causes the precalculated prices associated with that product to be updated).

For any of the precalculated stuff to work you'll need to follow the instructions on Sale Price's project page (you need to patch Commerce and use a sandbox module).

Addendum: Having said all that, if you don't ever need to use the precalculated price as a field in a View then I think you can do things entirely with Rules.


How to clear ALL cache, including field and filter caching of nodes and fields? I'm working on a text format filter module. Now, somehow Drupal keeps the node content in some cache that is not refreshed with drush cc all, which I would have hoped to "clear all cache". This is with Cache pages for anonymous users and Cache blocks disabled.

I wrote a little script that adds " " at the end of the node body, but even running that between two drush cc alls doesn't cut it, still with cache disabled.
It's really strange. If I go to a page I haven't accessed yet, it will show me an old version what was filtered.  So I'm tempted to now also let the script access the specific node over HTTP...

Is there an easy way to really clear all cache? I guess dropping and recreating all cache_* tables could cut it but that seems a bit convoluted.

"All" cache doesn't include the filter cache and if you are working with filters then that's the one you most likely want to clear.

You can clear the filter cache by truncating the cache_filter database table.

If you have drush at your disposal, you can run drush sqlq "truncate table cache_filter;" to get the intended result.

Please note, if you are using database prefixing you will need to add the prefix yourself, as the drush sql-query command executes the query exactly as provided.


How can I retrieve indexed facet options for a particular field using Search API? I currently have the Search API module configured with an Apache Solr server instance, and have created an index which indexes a custom entity.

I'm looking to somehow retrieve the options displayed within a Facet I have created for a particular field, to as options for a select field on a custom form. So in other words, the function a particular Facet would use to query Apache Solr when it is populated.

Does anyone know how I can retrieve this data using the Search API?

I've tried playing around with the example given in this very useful post on querying using the Search API. So far I've had no such luck retrieving the indexed Facet values as the appear in their Facet blocks.

Any help would be appreciated thanks.

I seem to have found the answer after some major trial and error, and some digging through the FacetAPI source code. The issue is linked to the same issue explained in the post
Display facets on non-search pages

I created a facet block in Views for each facet that I'm trying to access, and set them to "hidden" in the block settings within Views. Then by adding a block from my custom module directly below them in the same region, I was able to access the facet data using the following code:

$searcher = 'search_api@MY_CUSTOM_SEARCHAPI_INDEX';
$realm_name = 'block';

$build = facetapi_build_realm($searcher, $realm_name);
krumo($build);

The krumo output contains a render array for each facet you're trying to access, and all the facet options are available for you to access.

I hope this helps someone struggling with the same issue.


How can I produce a non-blocking process to modify newly created nodes of custom content type? I have a custom content type called a Scan where the only required field is ISBN. Nodes of this type are created when a user POSTs to my REST API endpoint with an ISBN number. That's all working fine, nice and quick (which it needs to be).

Now I want some additional process that -- in it's own time without blocking the API request -- goes over these newly created scans, querying an API (Google Books/ISBNdb/OpenLibrary) to fill out the other fields. I can confidently write the plain PHP to do this but I'm trying to learn how I would do this in the Drupal spirit?

I have learned custom modules so I've got an idea my code is going to sit in the controller (Yes?).
I have looked at Rules & Actions but these aren't working in Drupal 8 yet (Right?).
Cron seems to only run every few hours which would be too slow as I want my code to run within minutes of node creation.
I found hook_ENTITY_TYPE_create but not sure exactly how to create one? In my custom module?

Please help :-)

Disclaimer: I am new to Drupal and am self-teaching Drupal version 8. I am a senior PHP developer with a good understanding of good-old OO PHP but have just never done Drupal. Be gentle with me.

As an alternative to the cron job, this sounds like the queue system might be better.

The main difference is that in your hook_cron(), you have to execute queries to find data to process. With a queue, you listen to new entities being saved (hook_entity_insert()) and put them in your queue.

Then Drupal will manage the list of tasks (queue items) and will automatically invoke your callback for each of them. It will also handle time management and process the configured amount of queue items until the time you configure on your queue is up.

There are plenty of examples and blog posts to be found, this one seems pretty good: https://www.sitepoint.com/drupal-8-queue-api-powerful-manual-and-cron-queueing/. It seems to be very close to your use case, with a hook_entity_insert() than then does stuff with the new entities. It's pretty complete and does some more advanced things like a form where you can check the pending items and fire them off manually. You can of course skip that if you don't need it.


Route isn't being created for custom rest resource I'm attempting to create a custom rest resource, and have followed very many examples but I can't seem to get it to work. Every time I test it using https://www.hurl.it/ I just get a 301 error.

I'm using
http://example.com/myrest_test/1?_format=json
as the url as a GET request.

My format is as follows. I have a custom module called rest_test

Inside /rest_test/src/Plugin/rest/resource/MyRestTest.php I have

<?php

namespace Drupal\rest_test\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a resource for accepting rest calls
 *
 * @RestResource(
 *   id = "myrest_test",
 *   label = @Translation("My Rest Test"),
 *   uri_paths = {
 *     "canonical" = "/myrest_test/{id}"
 *   }
 * )
 */

class MyRestTest extends ResourceBase {
    /**
     * Responds to GET requests.
     *
     *
     * @param int $id
     *   The ID.
     *
     * @return \Drupal\rest\ResourceResponse
     *   The response.
     */
    public function get($id = null) {
        $response = ['message' => 'Hey this worked and this is the id'.$id];
        return new ResourceResponse($response);
    }
}

and inside a form.js file I have

 (function($) {
    $(function() {
        console.log('form.js executed successfully');
        jQuery.ajax({
            url: "/myrest_test/5",
        }).done(function(msg){
            console.log(msg);
        });
    })
 })(jQuery);

I receive the 'form.js executed successfully' message so I'm certain the javascript is running, but msg is empty. I've tried with the entire url instead of just the relative one as well.  I've also made sure I'm clearing the cache
But I can't seem to get any proper response. Is there something I'm missing? Why doesn't my rest resource response to my ajax calls?

UPDATE: Looking in the error logs it looks like I'm getting page not found errors for that rest call

UPDATE 2: When I visit directly in my browser I receive
/myrest_test/{id}

  {"message":"No route found for \u0022GET /myrest_test//234\u0022"}

UPDATE 3: After narrowing down the issue to it being a routing problem I found a similar question here No route found for custom REST resource however when I add

 *   uri_paths = {
 *     "canonical" = "/myrest_test/{id}",
 *     "https://www.drupal.org/link-relations/create" = "/myrest_test"
 *   }

I still encounter the same error

I'm not sure if there is a different lingering issue, but I was able to solve it
by using the REST UI module.

https://www.drupal.org/project/restui

Once I installed it I was able to see my route listed on the configuration page, but it was listed as disabled. After enabling the route from the configuration page it started working.


How can I attach a line item field to a custom checkout pane? How can I attach a line item field (as form element) to a custom checkout pane ?

I tried the following with commerce_line_item_save($line_item);

function MODULE_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
  //...
  //1st TRY, which in my opinion should be the right API fn ?
  global $language;
  field_attach_form('commerce_order', $order, $pane_form, $form_state, $language->language, array('field_name' => 'field_paxsup'));

Which returns

  Fatal error: Cannot access empty property in field.attach.inc on line
  208.

field.attach.inc on line 208  $items = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();

Precision: the custom checkout pane is working great with a basic field as below

$pane_form['nickname'] = array(
 '#type' => 'textfield',
 //and so on...
);

Got the answer just after posting : so the correct one is

field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode = NULL, $options = array())

First parameter

entity_type is the entity type you want to attach, not the one you want to attach to (see why non native english speakers have problems sometimes... Duh !).

Second parameter

entity expects an object , not a string ! Don't do

field_attach_form('commerce_line_item', 'my_line_item_type' ...

but :

$line_item = new stdClass();
$line_item->type = 'line_item_liberte';

field_attach_form('commerce_line_item', $line_item, $pane_form, $form_state, $langcode, array('field_name' => 'field_paxsup'));

In checkout pane context, load the line item

function MODULE_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {

  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  field_attach_form('commerce_line_item', $line_item, $pane_form, $form_state, $langcode, array('field_name' => 'field_paxsup'));
  //...


Delete locked fields, programmatically I have upgraded a website to drupal 8 that I found a field created and I need to delete that field as it became useless.

The field is locked, and this prevents me delete it from the interface.
I tried to delete it using field_purge_field(), but it didn't work either.

The answer for How to properly delete fields, programmatically? didn't work for me.

Edit:
I tried that piece of code but didn't do any thing

$field = \Drupal::entityManager()->getStorage('field_config')->load($entity_type.$bundle_name.$field_machine_name);
field_purge_field($field);

How do I delete fields that result locked? How do I unlock them before deleting them?

Purging is the second step, after the field was deleted. field.module should do that automatically for you.

A field config is an entity, you delete it like any other entity:

$field->delete();


How do I allow iframe embeds to a particular domain? I see that Drupal now automatically adds the 'X-Frame-Options: SAMEORIGIN' header. However, the client would like to give explicit permission to allow a iframe embed to another site.

How do I allow iframe embeds to a particular domain?

https://www.drupal.org/project/seckit

you can set security level and also set exceptions


How to invoke a search api from drupal site for Ubuntu Unity lense? I'm creating a simple Unity lense for my college site which is based on Drupal, but I don't know how to adapt this command for Drupal API. Please help, it's python.

  We now create our query url, using the Wikipedia opensearch API url = ("%s/w/api.php?action=opensearch&limit=25&format=json&search=%s" % (self.wiki, search))

I'm using template to write lense following Wikipedia example http://developer.ubuntu.com/2012/04/how-to-create-a-wikipedia-unity-lens-for-ubuntu/. I don't know python but Im familiar with C. This Drupal API calling is the only problem I have to successfully develop a lense. Please help!

Your site is running Drupal 6.26
http://en.ict.edu.rs/CHANGELOG.txt

The Unity Lense does not require OpenSearch. You essentially just need to Curl your search results page with a querystring and parse out the search result links.

Eg, send a Curl request with:
http://en.ict.edu.rs/search/node/example

You could show some answers easily that way for any drupal site. You could setup a custom View for searching your content as well if you wanted, or even install the Services module and make a small dedicated search api.

I'm actually running Ubuntu 12.04 here and installed the Lense stuff which looks neat -- but I'm too busy to code up a small example, sorry. Hopefully these thoughts will point you in the right direction.

EDIT: alot of the code is really there already when you start your Lense project. You just need to tear through the results from /search/node/KEYWORDS_HERE you get from the request in Python ...


Why didn't the Drush command bam-restore work? I'm a new admin of a Drupal site (core 7.38 on an OpenSUSE 11 server). Yesterday I ran Drush up to update VBO to 7.x-3.3 and suddenly I could no longer access the site. The homepage displayed the site's header/logo with the generic error message "The website encountered an unexpected error. Please try again later." I tried accessing /?q=user and some of the other pages via their clean URLs, but nothing worked.
The server was working fine and I was able to access the tar.gz archive created that morning through the Backup & Migrate module. So I followed instructions I found online for restoring from a Backup & Migrate archive (using bam-restore) but it failed. Drushcommands.com says bam-restore accepts three arguments: source, destination, backup id. I entered the parameters but got another ambiguous error message. Subsequently I found different instructions that avoided the bam-restore command and opted for mysql commands.

Why didn't the bam-restore work?
 Is there a way to get more specific error message or access what's actually going on with Drush in a specific circumstance?

First, I would have run drush up drupal, updates only Drupal core, no third party themes or modules. To do a restore, try drush archive-restore


How to make a stacked flexslider slideshow carousel I would like two ad blocks showing the same randomized content, but without duplicates.

I could just use two different blocks, with different flexslider options, (both starting on different images and moves by two), but that only works with even number images and can not be randomized.

Right now, I'm trying to make a carousel showing two images, and trying to restrict the container to a size that they form two layers. The problem: flexslider still moves on to white space, as if it was still one long layer.

Thank you for your time.

Got it to work, but using views slideshow. I just clicked "View Action Advanced Options" in the action setting, setting it to two slides. I also renamed the flexslider library and made sure that I downloaded the full version of cycle. And that's it!


Do contrib modules have to be set to expose settings variables to Strongarm? I'd like to push everything into Features for the sake of versioning and migration of my site configuration.

Does a contrib module have to be purposefully set up to expose its configuration variables to Strongarm?

Looking at strongarm_vars_load I can see that it loads all variables in the variables table using ctools_export_load_object regardless of any special consideration (other than variables already controlled via strongarm in features).

When I've used it in the past I've never had to specifically define the variables for strongarm to use.


How to get the unrendered contents of a block I have a template file in which I would like to restructure the output of a block item (the applicable block changes depending on the page you are on). Basically what I want to accomplish is to list the items that will be rendered in a region, pick out the one I want and then modify how it will be displayed. What would be the best way to accomplish this? Can I do this through the template file?

Thanks.

The solution I went with is to use the template_preprocess_block() hook as it allows me to render the items as I see fit. The issue with using the block.tpl.php file is that it does not give you access to components that is used to render the block (as by this point in the process, it is already rendered).


Aggregator module block shows up only to registered users I am using the aggregator module for D8, I have created a few blocks with feeds from various media outlets. The problem is that the blocks show up only to registered users of the site. How can everybody see them?

Thank you.

Have you checked the role permissions on the blocks? On block layout, you should be able to click on Configure. This should take you to the administration screen for the block in question. There you should see a tab layout with an option for Roles. Do you have items there checked?


How do I style a navigation block menu? I am having a pretty base navigation menu in d8 .But compared to d6 its style is pretty basic . How can i have a decent navigation menu ?

navigation menu in d8

navigation menu in d6

How can i have a styled navigation menu in d8 ?? I blurred it because content not to be exposed ;) .

You can style it by writing css that target the elements of the navigation menu. If you use the inspector in your browser you should be able to figure out what classes the menu is wrapped in so you can properly style it.

If you are using a custom theme you can start by adding a css file to a css folder. In this case I named mine style.css.

/path/to/custom/theme/css/style.css

.menu li{
    background: blue;
}

Then I came up with a name for my css library in mytheme.info.yml

name: MyTheme
description: My custom Theme
type: theme
core: 8.x
libraries:
  - mytheme/global-css

regions:
  header: 'Header'
  content: 'Main Content'
  footer: 'Footer'

Then I made sure that the library included our style.css file.
In mytheme.libraries.yml I had

global-css:
  css:
      css/style.css: {}


Google Store locator Store Phone and Store Web not visible I am using Google Store locator module for my Drupal 7 website.

I have used version 7.x-1.1. But when I test my page the Phone number and website are not visible on the frontend?

If you can see there http://litebook.eu/store-locator/json in the browser you can see the data is added (store phone and store web).

Why are those fields not visible on the frontend?

Thanks

There is a patch you can apply that should fix your issue.

Check out the thread here https://www.drupal.org/node/2383773 and the related thread here https://www.drupal.org/node/2528458

This one https://www.drupal.org/node/2528458#comment-10125006 will take you straight to grabbing the patch, the top two will give you the context of what happened.


How do I load the node create or edit form? To load the login form I am using the following code.

$form = \Drupal::formBuilder()->getForm('Drupal\user\Form\UserLoginForm');

I would like to load the form to create or edit a node. How can I achieve this?

Copying partially from an answer that I gave here: How to alter $form_state before render a form?

To get an add form, you can have to do something like this:

$values = array('type' => $node_type);

$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($values);

$form = \Drupal::entityTypeManager()
  ->getFormObject('node', 'default')
  ->setEntity($node);
return \Drupal::formBuilder()->getForm($form);

Edit: Somehow I missed that you said edit. You do exactly the same then, except that you don't create a new $node, you load the one you want to edit and then use that.

As written there, this is based on the entityblock_form module, so if you need this in a block, you can also just use that module.


Drupal 7 - Ajax form in modal window I try to create modal window with form (from page /node/add/page).
Try this

hook_menu() {items['mypath']=...} + callback (where echo drupal_render($form); exit();)

//form has many elements from different modules (node + inline register)

Next

get rendered form via ajax (form has action 'mypath')
plug jquery.form.js to the form

Submit

Server returns full page and i'm sure that new page material doesn't save even if i change action to '/node/add/page' instead of 'mypath'

What i do wrong?

It's hard to tell what you doing from your description. A better description could possibly yield better answers.

One possible problem could be that the form needs to be loaded on the page the it is submitted on. This is required for the validate and submit handlers to be processed.


The directory sites/default/files does not exist I received the "The directory sites/default/files does not exist" error on a 7.43 install. In this situation, Drush is not available so I am doing a browser install.

I had this error once before in 2014 according to my notes. I don't know whether it's specific to the server I'm on or a general issue because I've done setups on other servers and don't remember seeing that particular error. In the previous situation, I noted that I changed the permissions on default to 777. I am always loathe to set much of anything to 777 so I am wondering whether it needs to be kept at 777 or is there some point after setting up the site that I can switch it to something more secure.

Your perms should (arguably) never be 777 on anything, but your exact situation will dictate that. 755 is often more appropriate for writeable folders, 644 for writeable files, but it depends on how your server is configured, and who owns the files.

You do need to create the sites/default/files folder manually, before the web-based installation can proceed, and your web server user must be able to write to that folder. You also need to create sites/default/settings.php, make it writeable, then remove those write perms once installation has completed. Drupal's status report will tell you about this if you haven't already done it.

There's not a lot more to it, just make sure the perms on all your files and folders are sensible for all the users that can interact with them. Securing file permissions and ownership has the full details, I'd recommended reading and fully understanding that page before going any further.


How do I alter a field content before saving the form? I have two fields, Transaction type and Amount. I would like to change the value saved by Amount depending on Transaction type.

e.g.

Transaction type == deposit , amount is a positive value.
Transaction type == withdrawal, amount is a negative value.
Transaction type == tax , amount saved is a preset percentage of the value input.

You can do it inside a hook_form_alter in a custom module.

function module_name_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'your-form-id'){
    if(your conditions){ // single or multipe if condtions based on your requirement.
     $value = 'value based on your condition';// your value based on condition.
    }
   $form['your-field-name']['language'][0]['value'] = $value;
  }
}

Hope this will help you


Is the Workflow module a Symfony component? In Drupal 8.5, is the Workflow module a component from Symfony?

I ask because I thought it might help me to learn the basics from the Symfony Workflow component, but looking at the core directory and the composer.json file I saw this.

"symfony/class-loader": "~3.4.0",
"symfony/console": "~3.4.0",
"symfony/dependency-injection": "~3.4.0",
"symfony/event-dispatcher": "~3.4.0",
"symfony/http-foundation": "~3.4.14",
"symfony/http-kernel": "~3.4.14",
"symfony/routing": "~3.4.0",
"symfony/serializer": "~3.4.0",
"symfony/translation": "~3.4.0",
"symfony/validator": "~3.4.0",
"symfony/process": "~3.4.0",
"symfony/polyfill-iconv": "^1.0",
"symfony/yaml": "~3.4.5",

In the replace section, I noticed the following line.

"drupal/workflows": "self.version",

No, the Workflow module is not a Symfony component.

As for what you found, the first list are the Drupal core dependencies, which include its dependencies from Symfony components.
Under the replace section, you just find a list of Drupal core modules. You can understand they are modules because they are listed as drupal/<module machine name>, while the Workflow component would be listed as symfony/workflow.


Rules: get content created by user account being cancelled? Case: using Rules module, when a user account is cancelled, create a new node of type Archive and (a) copy select data from that account to the new node of type Archive, and (b) copy select data from a single node of type XYZ authored by the cancelled user to the new node of type Archive.

I have this rule:

EVENT
After a user account has been deleted
CONDITIONS
None
ACTIONS
Create a new entity
(set data values here)
Save entity

In Actions, the new node created is of type Archive. In between creating and saving this new node, data values are set (i.e. "Set data value") on it. The values are derived from the account being cancelled.

However, how can I access a node of type XYZ authored by this account, and use that to also set data values on the new node of type Archive? There seems to be no way to access the fields of XYZ in the Data Selector. The available fields pertain only to the account, and not to content authored by that account.

As a comparison, in Views I would establish a Relationship to open up access to fields of related entities. What's the equivalent in Rules?

Thanks

You can use the Views Rules module, as further detailed below.
1. About the Views Rules module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of your "node of type XYZ authored by this account" (as in your question). Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

3. Create a rule using the view of display type 'Rules'
Adapt your Rulew Actions, using these guidelines:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each node contained in your Views loop (I seem to understand you will only have one), perform whatever Rules Action that fits your requirement, using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed).


What to do when translation imported using Locale has an inappropriate translation? I used Locale module to translate Drupal to my national language. But some words' translation is not appropriate. How can I change the translation of some words?

Go to  Administer -> Site building -> Translate interface -> Search (d6) or Configuration -> Regional and language -> Translate interface -> Translate (d7). You will see a search box. Simply search and edit string you think should be edited.


translate product type title I am working on a drupal commerce site which needs to be multilingual.

The problem I am facing is that I cant translate the title field of product types.
For example if I create a new product type called "Fruits" I want to be able to translate that title to other languages enabled on my site. I did replace the default title with a title field using the Title module but I still cant find my "Fruits" string to translate.
Thanks

You should use node to display the product since commerce doesnot provide a product display page.

Then by replacing the title for that content type allows you to translate the product title.

To create product node page while creating the product in commerce form you can make use of inline node form provided by using Inline entity form module


Roles and Permission creation programatically inside module I am trying to create drupal 8 roles and permissions programatically. My current approach is to have a module that when install it will generate those set of roles and permissions defined by the  module. It would be more like a background Module, where no form is needed or anything. My problem lies that I really don't know where to start the the roles creations since no form is needed, I mean should I create them inside a hook?, if so which hook?, any other place?

I really don't know if this is the best approach, still a newby on drupal 8. Any suggestions will be greatly appreciate it.

Thanks in advance

Create the roles on your development site and grab the configuration for them and place them in:

<modulename>/config/install

When the module is installed it will import that configuration. hook_install is deprecated for installing configuration with a module.

Remove any uuid information from the export as it won't be applicable in most sites.

If you are unaware how to export/import configuration in drupal 8, you should read:
D8 Configuration Management

edit: Just as an aside fact, you can in theory write your own config.yml files however until you are very familiar it's easier to just create the role, and export it.


Make a gmap view embeddable on another site The website I'm building has a google map view. I want to provide a code snippet to site visitors to let them embed this gmap view on their own site. Does anyone know of a way to accomplish this in D7?

I saw this question over at the SO main site, but it appears to be D6-specific since Embed Widgets doesn't have a D7 release and Web Widgets only has an abandoned D7 release. So I'm wondering if there's another way to do this.

You could create your own iframe: http://www.iframehtml.com/

You will most likely want to create custom page output so that you aren't including extra regions from your site. You can do so by creating a custom html.tpl.php template (might not be necessary) and page template for the map.


Rules to create an autoresponder for a Webform submission? I need to create a Rule to create a autoresponder email for a Webform submission.

This is: the webform has only the "email" field. When the form is submitted the rule should fetch the the 'email account' entered in the email form field and send an email to that account. That's all.

I already enabled the Webform Rules module but I see to way to fetch the email value from the rule I created.

What am I missing here?

You do have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

So in your case, you should be able to get it to work using something like [data:email-id] (assuming that's what corresponds to the "email field" in your case).

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform)
the 2nd attempt explains what to do in case of Webform.

The above is a good start, but not sufficient to achieve your goal (= "When the form is submitted the rule should fetch the 'email account' entered in the email form field", as in your question).
However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your [data:EmailAccountField-value-raw] (and with an appropriate data type). I'm assuming your eMail field in your webform has a machine name like EmailAccountField (adapt to fit your machine name).
In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).

PS: I'm assuming this question is about D7.


date in spanish webform component coming out in day month year , need month day year My webform in english shows  the date component as month day year.
but when I translate it to spanish it shows the date as day month year.  How can I modify the format for dates when in different languages?

FOUND THE ANSWER: go to /admin/config/regional/date-time/locale/es/edit and change the date format to month first for the long, short and medium dates

Posted on behalf of Diana that can't do it due to reputation limits.

Go to /admin/config/regional/date-time/locale/es/edit and change the date format to month first for the long, short and medium dates.


How to show pop up message "Are you sure ......?" with "OK" button before save the content I have a image field on profile content type. And when users try to save the content without uploading images I would like to show pop up confirmation message "Are you sure you want to save your profile without photos?"  with "OK" button. And I need the content to be saved only after the users click the "OK" button.

I thought I could do this with Rules module however it look like there is no action for showing popup message with "OK" button of confirmation.

Is there any way to achieve this?

The custom way to do this would be to use hook_form_alter to add some jquery into the form you are targeting that would bind to the submit action of the form and execute some javascript function (ex. an alert) if a form field value is not filled out.

The key library for this is the jquery validation library here:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

There are also a couple modules you could try and install that implement this library and offer direct integration with your field through the form api. I've used this one:

http://drupal.org/project/clientside_validation

To achieve a similar validation effect as what you're looking for.


How can I point to an internal anchor using core menu? We have a navigation menu created using Drupal's built-in menu system. One of our menu items has the path set to "node/100770#digital-anchor," but when the menu is rendered, it strips off everything to the right of the node ID. I've tried this suggestion (using a named id), but the issue isn't that the browser is ignoring everything the node id; it's that Drupal is actually stripping off everything after the id when the menu is rendered. If I look at the rendered source in the browser, it just isn't there.

How can we point to an internal anchor (or named element, if you believe that anchors are deprecated) using the default menu?

I don't think you can do that through the UI.

However, you should be able to specifify it with menu_link_save() in a module, for example in a hook_install() implementation. See the options key.

Looking at url(), something like 'fragment' => 'digital-anchor' should do the trick.


Is it possible to change the view type form "content" to "content revision"? I created a view with several displays.
The view type is CONTENT.

But now I need to change the type from CONTENT to CONTENT REVISION, without to be constrained to rewrite all the displays.

Is it possible?

Technically speaking, the type of a view corresponds to the base table against which a database query is executed. This means that it sets the stage, so to speak, for the data that is going to be collected. All fields, filters, sort options etc. are configured in relation to that starting point.

Since changing the view type would mean changing the base table, you would be replacing the foundation your view is built on. This a tricky thing to do, because the data you are collecting may not relate to the new base table as it did to the old base table. (In a more radical example, imagine turning a Content view, which retrieves the node ID, into a User view. That would break because users do not have a node ID.)

So is it completely impossible? Maybe not, especially because node and node revisions are somewhat similar. When you look at the exported configuration (YAML markup) of a "Content" view, you will see a line base_table: node_field_data. In a "Content revisions" view you will find the line base_table: node_field_revision. If I had to try this (disclaimer: I never did!), I would do the following:

Duplicate the view I want to change (so I don't lose the original) and save it without changing anything
Go to /admin/config/development/configuration/single/export to get the config YAML of the duplicated view
Copy the config and paste it into a text editor
Change base_table: node_field_data to base_table: node_field_revision
Delete the duplicated view
Copy the edited YAML from your text editor and import it via /admin/config/development/configuration/single/import
Hope that the import doesn't generate errors
Go to the configuration screen of your newly imported view, see if it reports problems, and try to make it work

Good luck. When you do try the above, I would love to read if it worked for you.