Multiple Price for same product in commerce kickstart? I have installed Commerce kickstart. I have add the products.
Now my client asked Same product have two different prices. User will choose the price and pay it.

I am trying Commerce Donate module also.This module price for every product.

I need to change the price value for every product.

Might as well jump all in using Commerce Customizable Products and use this screencast to walk yourself through adding a line item type and a field to set the price.


How to get formatted total amount programmatically? I want to get the formatted total amount of my cart items.

I used the following code

$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$line_items = $wrapper->commerce_line_items;
$total = commerce_line_items_total($line_items);

It returns me $4000 instead of $40.00.

On shoping cart page it display $40.00. How can I get the price in this format?

I want this in commerce way not some custom php like number_format etc.

I had the same issue. I solved this issue by dividing the total by 100. You can see the total amount in the field_revision_commerce_total table. After dividing, I used commerce_currency_format($amount,NULL,NULL) to get the currency format.


Menu item path saved as node/nid instead of alias An alias supplied to the [Path] attribute of a Menu Link is converted to node/nid when saved, (along with a nice message: "The menu system stores system paths only, but will use the URL alias for display".)   This is implemented in core: function menu_edit_item_validate of menu.admin.inc.   (Drupal 7.22)

When moving nodes around between instances of the same site with node-export and uuid, node/nid is no longer valid, and results in menu links being dropped, or pointing to the wrong node.

A similar question was raised earlier:

How do I use URL aliases in menus?

But the solutions I think are for different use cases.  The suggestion of adding the alias and menu item together on node creation does not seem to work.   Our concern has nothing to do with how the node url is displayed.

UUID_path or maybe UUID_features seem to imply a solution, but if there is a resolution there, I don't understand it, and will appreciate any insight into how to handle this.

In the end, we need to have exportable menu links with path attributes that, one way or another stay, linked to an alias, regardless of nid.

Both nid and aliases are not guaranteed to be stable and unchanged, nid being a bit less prone to mutation. What you seem to really need, are UUID Links. It should allow you to store links by the unchangeable UUID, not localised nid.

There was also a sandbox project UUID Menu for just the case, but it seems it was never properly initiated.

The other approach is to export both content and menu as a Feature. This problem is in Features' issue queue and in UUIDs for Menu Links issue queue, unresolved yet. But in the second one patches exists.


How do I tell Drush where the root directory is? I have successfully installed Drupal 8 with Composer and I also installed Drush with Composer. When I use Drush, it says that the Drupal root is not found. I am passing the root, but it still says that.

How do I tell Drush where the root directory is?

I am using Drush from vendor/drush/drush/drush. I couldn't get vendor/bin/drush to work.

When I run:

$ composer create-project drupal-composer/drupal-project:8.x-dev drupal-project-test-site --no-interaction
$ cd drupal-project-test-site
$ vendor/bin/drush status

Then I see:

 Drupal version : 8.6.13
 Site URI       : http://default
 PHP binary     : /usr/local/Cellar/php/7.3.0/bin/php
 PHP config     : /usr/local/etc/php/7.3/php.ini
 PHP OS         : Darwin
 Drush script   : .../drupal-project-test/drupal-project-test-site/vendo
                  r/drush/drush/drush
 Drush version  : 9.6.0
 Drush temp     : /tmp
 Drush configs  : .../.drush/drush.yml
                  .../drupal-project-test/drupal-project-test-site/vendo
                  r/drush/drush/drush.yml
                  .../drupal-project-test/drupal-project-test-site/drush
                  /drush.yml
 Drupal root    : .../drupal-project-test/drupal-project-test-site/web
 Site path      : sites/default

Drush should be able to find the Drupal root for the site that it's contained inside without the use of --root or an alias. I'm not sure why vendor/bin/drush would not work. Perhaps try again with a new test project, and see whether you get the same results? Perhaps your install did not complete.


How do I force batch to use nojs? I am having trouble using batch. The problem is that on the client website, there is an error in the jquery file in the jquery_update module and I am not allowed to change this because I am just building a custom module for them. So, JS won't run and batch is locked.
I want to force batch to use do_nojs such that the page is reloaded using http meta. Is there any solution I can use for that?

I've run into the inverse problem using Pressflow. From that I have learned:

The js version runs if and only if the has_js cookie is set. If you are able to clear that cookie (and keep it away), you will be able to run batch.
When the cookie is not set, there is a query parameter in the meta refresh tag, namely op=do_nojs (and not op=do as is normal). If it is a batch you are trying to run and one for which you know the batch id, you may be able to force a nojs solution.

Based on that, if you are only having problems with tunning batches yourself, the simple solution is to disable js in your browser before starting the batch operation.


Subnavigation doesn't show with the Bartik theme I would like to have a menu point in my main navigation with sub-menu points.

I created a main point +Services with two points underneath it where I assigned the respective "Parent link".

The structure looks fine in the administrative interface, but I do not get the sub navigation points to show up or the mother point to drop down even though I selected "Show as expanded".

I placed two menu points under Services that do not show up.

Can anyone help in this matter?

Just set it as expandable in structure/menus.


Missing argument in hook_theme and Ilegal offset I have built hook_themes many times and never encountered this before but I am getting the following errors:

Warning: Missing argument 1 for geocoder_custom_theme
Warning: Missing argument 2 for geocoder_custom_theme
Warning: Missing argument 3 for geocoder_custom_theme
Warning: Missing argument 4 for geocoder_custom_theme
Warning: Illegal offset type in isset or empty in drupal_theme_access() line 53

I have tried clearing cache, renaming the hook, registry rebuild and nothing works.  I have another hook_theme in a different custom module that is basically the same thing but works completely fine.  Also if i simply return an empty array() it still does it.  Its like drupal doesn't send any values to my hook for whatever reason.

Code:

function geocoder_custom_theme($existing, $type, $theme, $path)
{
  return array(
    'geocoder_custom_before_me' => array(
      'variables' => array('string' => array()),
      'template' => 'geocoder-before',
      'path' => drupal_get_path('module', 'geocoder_custom') . '/theme'
    ),
    'geocoder_custom_after_me' => array(
      'variables' => array('string' => array()),
      'template' => 'geocoder-after',
      'path' => drupal_get_path('module', 'geocoder_custom') . '/theme'
    )
  );
}

That function is taken from Drupal as an implementation of hook_custom_theme(), not hook_theme(). Since the former doesn't get any arguments, PHP is complaining about the function declaring arguments for which it doesn't get any value.

The fix is changing the short name of the module from geocoder_custom to geocoder, for example.


See all nodes where user profile entity reference matches the same entity reference on the node I have the Profile 2 module where a user selects a zip code (which is an entity reference to the content type ZipCode)

The ZipCode content type has an entity reference to a Region content type.

Finally, there is a content type called Schools which has an entity reference to the ZipCode content type.

I would like to display all schools that match the region of the logged in user. Logically this means finding the user's region, and then all schools with the same region, through the zip code...

I can't for the life of me figure out how to do this. Any help would be appreciated.

The easiest way is creating a view for the School content type and add the fields you want to display on your list. Then add:

A reference to the entity that is common between the School content type and the ZipCode content type. If there is no connection between the two, you will also need to add a reference to the Region content type and then to the ZipContent type.
Add an argument or contextual filter for the user ID of the currently logged-in user and limit the number of nodes displayed.

Note: I have sometimes achieved the same result by creating a view (for users) referencing the content types and adding the desired fields.

This is a video about view arguments: http://mustardseedmedia.com/podcast/episode39.


After Drupal 7.32 should sql injection attempts create PDOExceptions? I have the Logging and Alerts module installed on a few of my sites. Yesterday I noticed a series of notification emails with the following data. These produced PDOException exceptions and so far as I can tell were unsuccessful at doing anything malicious.

This site was patched hours after SA-CORE-2014-005 was announced on 2014-Oct-15.

I simply want verification that these types of SQL injection attacks create PDOExceptions in Drupal, vs stripping the offending key/values from the injection attempt. Prior to the patch I wasn't receiving any such errors.

Email Title from LoggingAlerts module:
[] Error: PDOException: SQLSTATE[42000]: Syntax error or access...

Email Message Body:
admin@site.com  Mon, Nov 17, 2014 at 11:04 AM
To: admin@site.com
Site: https://site.com
Severity: Error (3)
Timestamp: 20141117 11:04:35
Type: php
IP Address: 128.xxx.xxx.xxx
Request URI: https://site.com/?q=user/login
Referrer URI:
User: Anonymous (0)
Link:
Message:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You
have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near ' 'test' AND status =
1' at line 1: SELECT * FROM {users} WHERE name = :name_0, :name_1 AND status
= 1; Array
(
[:name_0] => test3
[:name_1] => test
)
in user_login_authenticate_validate() (line 2149 of
/var/www/mysite/htdocs/modules/user/user.module).
$_SERVER => Array
(
[HTTP_HOST] => site.com
[HTTP_X_REAL_IP] => 198.101.235.xxx
[HTTP_X_FORWARDED_FOR] =>

... lots of more lines of email output ...

It is my understanding that in theory, yes, a compromised site from the particular vulnerability could lead to such behaviour. As Drupal.org recommends, in such cases you should treat your site as compromised and all next actions should be the appropriate for this case.

The fact that you patched the site shortly after the announcement, as you mentioned, is very important. As far as I have seen, most attacks are coming from scripts and it has not come to my attention any automated attack that would cause such behaviour (to my experience of course). This again is not reassuring, just a thought on the possibility for the nasty thing to have happened.

Apart from the obvious actions (see links below), I would definititely take a good look of the code that doesn't behave nicely. Also a good tool is always diff comparing to clean code. I would as well take a good look in the db. Last, there might also be a possibility that some contributed module has got issues with 7.32 or maybe anything else that might have been updated.

Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?

https://www.drupal.org/drupalsa05FAQ


Using multiple templates in a Drupal 8 module I have produced a simple Drupal module which provides a wrapper for a JavaScript library. I'm working on a separate module which will produce several pages of examples of the library and wrapper in action. These pages will each contain a two sections, the library, and description text and miscellaneous HTML.

What is the best technique to do this the Drupal 8 way?  I can imagine two strategies:

Each page will be a separate function within my controller. The function can first add two entries to the output array, the first will contain the data for the library, and the second the raw HTML and text.
In the second technique, I would place all the HTML and text in a twig template. Then I would add all the data for the library in the controller and add a reference to this new theme template as a second entry in the output array. I like the idea of this second strategy, but I don't know how to accomplish it. I've look at code for several Drupal 8 projects and read a few tutorials, and I haven't seen an example of this. The hook_theme function always contains a single return statement. How would I add a switch or if statement within hook_theme to determine which twig template to return.

If there is a third option that is even better, let me know.

hook_theme() returns a list of templates that will then be cached in the registry. You don't need conditions there, in fact, you can not, since it will be called only once.

Just return multiple templates and then reference them in your render arrays, like you already have to when using a single one.


Trying to replicate a view with no success I'm currently working on my drupal site and I have trouble replicating one view. This is the view I'm talking about.

I have replicated the drop down menu, the search bar "with the exception of a placeholder" and the list of episodes as well, but I'm having trouble replicating something where it autoselects/autodefaults the dropdown menu item based on the show name. (represented by the red arrow) I have tried everything, contextual filters, remember options, but nothing works.

Can you help me, I'm at loss of words here as to how to replicate it? Your help would be gratefully appreciated.

When you say, "autoselects/autodefaults the dropdown menu item based on the show name," what are you trying to do, exactly? What show name you are trying to auto-select? Is this view capable of showing shows with other show names? If so, and say you have ten shows in that list, which one do you want to be the default?

Are you trying to have links to that same view from different places in the site and you want a link on the Tech Guy page to automatically filter the Tech Guy shows, and a link on the Fictional Mister Podcast page to automatically filter to the Fictional Mister Podcast shows?


How to grant create and update permissions to a custom role? I have a new role as "Publisher". I want to grant Publisher 'create' and 'update' permission using code.

My .permissions.yml file looks like this :

'delete contact entity':
  title: Delete entity content.
'add contact entity':
  title: Add entity content
'view contact entity':
  title: View entity content
'edit contact entity':
  title: Edit entity content
'administer contact entity':
  title: Administer settings
'publisher contact entity':
  title: Publisher settings

I've used 2 functions to allow permissions.
The functions are:

 protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
// Check the admin_permission as defined in your @ContentEntityType
// annotation.
$publisher_permission = $this->entityType->getPublisherPermission();
if ($account->hasPermission($publisher_permission)) {
  return AccessResult::allowed();
}
switch ($operation) {
  case 'edit':
    return AccessResult::allowedIfHasPermission($account, 'edit contact entity');

  case 'update':
    return AccessResult::allowedIfHasPermission($account, 'update contact entity');
}
return AccessResult::neutral();  }

protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
// Check the publisher_permission as defined in your @ContentEntityType
// annotation.
$publisher_permission = $this->entityType->getPublisherPermission();
if ($account->hasPermission($publisher_permission)) {
  return AccessResult::allowed();
}
return AccessResult::allowedIfHasPermission($account, 'edit contact entity');   }

Now, If check sitename/admin/people/permissions, the role is created by it doesn't have a tick in the checkbox for edit contact entity.

PS: In @ContentEntityType, I've defined publisher permission as:

publisher_permission = "publisher contact entity"

You may grant your permissions on install time of your module with a simple config in config/install/user.role.publisher.yml (about this):

langcode: en
status: true
dependencies: {  }
id: publisher
label: Publisher
weight: 3
is_admin: null
permissions:
  - 'add contact entity'
  - 'edit contect entity'

Your code above is not a "grant", it's a runtime-check of users permissions.


Hide products from a view I know this may be very basic but I can't seem to figure out a way to hide a product that I've got set up in Drupal Commerce. I'm new to Drupal so thanks for your patience.

I am using the Expressa theme. In the product's edit screen, I go to 'Status' and choose 'Disabled' which prevents them from being added to carts (instead of Add To Cart, it displays 'Product Not Available' in the store) but it doesn't actually remove it from Product Display in the store. I've set the stock status to 0 on these products and made sure that they are not being displayed as 'Featured' yet they still show up.

Is there a simple setting where I can keep the product in the backend, in case I want to activate it later, but hide it from the store?

I've also navigated to the content list, found the list of content, checked all the relevant products and unpublished them.

Thanks for your help!

In Drupal Commerce, to prevent a product displaying on the front end you either.

Unpublish the product display node (the node referencing that product)
Remove the product from the product_reference field on the relevant product display node.


Why is hook_forms form callback not reached? In my custom_apps.module file I'm trying to implement the same form multiple times with different ID's and for that in a loop I call for:

drupal_render(drupal_get_form('driver_route_'.$delivery_nid, $args));

I have a hook_forms function:

function custom_apps_forms ($form_id, $args) {
    // If driver route form
    if (0 == strpos($form_id, 'driver_route_')) {
        // Call one of the multiple forms
        $forms = array();
        return $forms[$form_id] = array(
            'callback' => 'driver_route_form',
            'callback arguments' => array($form_id, $args),
        );
    }
    return array();
}

And the driver_route_form() function itself:

function driver_route_form(&$form_state, $form_id, $args) {...}

However for some reason the driver_route_form never gets called and instead I get this notices/warnings:

Notice: Undefined index: driver_route_55 in drupal_retrieve_form() (line 806 of /var/www/website/public_html/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'driver_route_55' not found or invalid function name in drupal_retrieve_form() (line 841 of /var/www/website/public_html/includes/form.inc).

It seems as if it's still trying to look for a function with the form_id not the one defined in my callback. What could be the casue of this? I have made sure the inside of custom_apps_form where the form is returned is reached.

Instead of:

return $forms[$form_id] = array(
            'callback' => 'driver_route_form',
            'callback arguments' => array($form_id, $args),
        );

You should have:

$forms[$form_id] = array(
            'callback' => 'driver_route_form',
            'callback arguments' => array($form_id, $args),
        );
return $forms;


How to get e-mail from Drupal.org about new Drupal releases? I have creates a account in drupal.org website. I saw this https://www.drupal.org/news link to know news about drupal.

Is there a way by which I can get latest updates in my mail without visiting the drupal site

Go to https://www.drupal.org/user , click on the "Edit" tab and from there, the "My newsletters" tab. This will allow you to subscribe to "Drupal newsletter" and "Security announcements".

Also to get notifications of Drupal core or module updates for a particular Drupal site that you run, go to Reports -> Available updates -> settings (/admin/reports/updates/settings) and enter your email address and the desired frequency (daily / weekly) and type (security / all) of updates.


Rules and Populating Content Fields I have a Temp webform with 2 fields, I have rules set up to, on webform submission, create an entity and then set a data value for the 1 field in my temporary content type.

Here is the rule. I have done this exact same thing on another site. The rule creates the entity successfully and pulls the title from the webform submission value of the title field, then when it moves down to setting the data for the second field in the content type it breaks. I am using [data:{component}-value] and replacing {component} with the machine name of the webform field, like I did with the title except it isn't assigning the content field the value I typed and submitted into the webform. Even using the same exact token as i did for the title it does not work. If i used a static just "asdf" to assign to the field of the content type that works, but it will not pull anything from the webform. Any ideas? I'm stuck here.

Add a condition, Entity has field: webform>field. I have to do that with entityforms.


Email sent to customer from Drupal has RED LOCK icon in the email I'm using Drupal Commerce. Overall it's working well. I have SSL setup and enforced so users HAVE to use 'https' (via .htaccess). I'm able to test fill out the form and it submits. PayPal gets the payment. We're happy. I get an email telling me a new purchase has been made (via Drupal at site:mail token).

The issue is, the user also receives an email from Drupal letting them know, you know, thanks for purchasing, etc. However, in the email to the person who purchased the product (in gmail specifically as that's all I've tested with) there is a RED LOCK icon next to their name/email at the top of the email. When hovered over it says 'bluehost.com did not encrypt this message'.

Now, MAYBE it doesn't really matter because i'm not sending them their credit card info back to them or anything, but it does LOOK disconcerting and I'd like it not to be there in their email. So I need their email to be encrypted.

I talked to Bluehost and they said it was an internal linking issue. The only link in the form is their email address that they put in (it's a custom field we setup).

Does anyone know how to encrypt their email address in the form before Drupal sends it to them? Or tokenize it properly perhaps is another approach since site:mail doesn't have that issue.

Here's the token I'm using to send them the email from Drupal:

[commerce-order:commerce-customer-billing:field-email-address]

Note: I'm using 'Send mail with Variable' action to send this email, if that's worth noting.

I've read both your questions regarding this issue posted here. IMHO the red lock is not a thing you can overcome by encrypting the contents of your mail before sending it via an unencrypted channel.

This issue is not directly connected to Drupal, but to your Drupals mail gateway. Obviously your mail relay is not supporting TLS mail forwarding.

I do suppose you are sending the mails using Drupals built-in mail functions. These functions do use the PHP mailing functions, which by default are set-up to use your hosts mail services.

If you are working with a root server and installed your mail server yourself (e.g. postfix on Unix), you have to digg into its configuration and make sure it is set-up to use TLS when connecting to other mail servers.

When you don't have direct access to these settings (e.g. on a shared hosting package), you can overcome this issue by creating a mail account with a third-party email provider that is using TLS (e.g. gmail itself). With this mail account you will also get SMTP credentials to use for sending mails from your desktops mail client.

In your Drupal, you can install and configure the SMTP module to use these credentials for letting Drupal send mails via this external mail provider. Please note that some mail providers have flood mailing prevention in place that do allow a certain amount of mails each time/per minute only. So you might additionally consider using Queue Mail and a Cron job to send your mails in batches.

Edit:
Drawback of the second solution is, that the mails received by your sites visitors may have been flagged as "x-forwarded" or have the third-parties mail provider email address as sender. Some mail clients therefore may mark the mails as spam.

So another solution for shared hosting: Ask your hosting provider to change the default mail server settings.


Random order at three-column Slick Slider I want to show random content on a slick slider which has three a three column layout (three content elements next to each other) on each slide.

If I set the views' sort criteria to RANDOM it will randomize the slides itself but not the content (the content and order on each slide remain the same).

Is there a way to randomize the content of each slide aswell?

I already found the solution:

The randomize option has to be enabled in the slick options instead of the view's sort-criteria.
We can either define a optionset to use it in different views (the optionsets have to be set at Configuration -> Media -> Slick) or we override the default-optionset in the view configuration itself (View -> Edit -> Format -> Settings next to Slick Carousel).


User profile fields translatable How can I make user profile fields translatable?

I'd like to be able to translate some fields into other languages.

If you are willing to use extra modules, instead of simple t() coding (as I do not believe this is possible for what you desire), install Profile2 and i18n Internationalization modules. Then, follow this guide in Profile translation and its documentation and that should set you straight.

Hope this helps.


URL for Created Services View? Apologies for the newb question, but: Is there a way to see the entire URL of a Services View I've created? I know it lets me name the path, however when I navigate to the URL, I get "View not found" (though the Views preview shows perfectly). I keep thinking maybe I'm just typing it in wrong? Right now, I'm navigating to:

http://domainnamehere.com/endpointname/views/viewname

Thanks all.

the right url will like domain/endpoint/services_url If you need to get any view the url will be like

domain/endpoint/viewname?display_id=block_id

More details found here


QR Codes with the Barcode module I am interested in creating barcodes from field data on-the-fly using the http://drupal.org/project/barcode module. As a rookie, could somebody explain to us how generally this is done and what is the best approach. For my working project example, I've already installed the said module and integrated a field into a Field Collection, but don't really want to spend more hours 'experimenting' to result on nothing. One idea I would like to explore is a QR barcode dynamically appearing on say a user home page (created via Views/Panels). Since my other interests are in music, a working example maybe a link to a band's website (i.e I create a 'Link' field in a Field Collection about a rock band, a visitor views the rock bands 'Homepage' on a D7 site, the link is dynamically shown as a QR code). This example is probably very common and portable across other content sites (trades, places of interest, 'Buy Now' links etc), but a decent 'how to/work through' or generalisation would be most welcome. Again, possibly it is something that can be done in Views or a case of backend PHP in a custom module (in which case I've a lot to learn). Thanks in advance.

It looks like a barcode is just a piece of encoded text from the .module file:

/**
 * Implements hook_field_info().
 */
function barcode_field_info() {
  return array(
    'barcode_field' => array(
      'label' => t('Barcode'),
      'description' => t('This field stores a barcode in the database.'),
      'default_widget' => 'barcode_textfield',
      'enable_tokens' => 1,
      'default_formatter' => 'barcode_default',
    ),
  );
}

So what you likely want to do is creating link fields that upon form submission pass their values onto the barcode field(s) as well. Then, you will show the barcode field(s) on any pages you want and hide the raw link field from the users view (unless their editing the entry).

You could look at the Rules module to automate this for you if you don't want to write a module (for example, when a new piece of content of type Foo, if field link is blah, copy field value to field my_barcode value). Look into the Form API to hide (with #access)the field_barcode values in the edit form (as they are dynamic end-user stuff).

The only thing that the Link field gives you over putting the raw url link in the bar_code field itself is extra form validation for free (for example, check it is a valid URL).


Where are the content types stored in the database? In Drupal 7 with this query:

SELECT * FROM node_type;

I can obtain the list of all my content types, now in Drupal 8 I can't find the node_type table.

I know that with this code:

$content_types = \Drupal::service('entity.manager')->getStorage('node_type')->loadMultiple();

$content_types_list = [];
foreach ($content_types as $content_type) {
  $content_types_list[$content_type->id()] = $content_type->label();
}

I can obtain the info, but where is this information stored now in the database?

It's configuration. Like any other config entity and simple configuration, it is stored in the {config} table.

But using the entity API is the only supported way to load that information, do not query that table directly.


Dispatch an Event when the a user logs I was looking into the new Events system for Drupal 8 and there's something I haven't been able to figure out.

I need to dispatch an event when a user logs something to the watchdog table using the new logging API.

// Logs a notice
\Drupal::logger('system')->notice($message);
// Logs an error
\Drupal::logger('system')->error($message);

https://www.drupal.org/docs/8/api/logging-api/overview

I already define a new Event in a custom module but I don't know what needs to be created so when a module logs/adds information to the watchdog table using the code above my event gets triggered.

Thanks

Once you get the event working, all you have to do is create an instance of the Logger Class in the Logger folder inside your module.

In here:
 /drupal_root/web/module/custom/my_module/src/Logger

And the class will be something like:

namespace Drupal\my_module\Logger;

use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;

class SendToEmail implements LoggerInterface {

  use RfcLoggerTrait;

  /**
   * Logs with an arbitrary level.
   *
   * @param mixed $level
   * @param string $message
   * @param array $context
   *
   * @return void
   */
  public function log($level, $message, array $context = []) {
    //Building the parameters for the email
    $params['level'] = $level;
    $params['message'] = $message;
    $params['context'] = $context;
    $this->sendEmail($params);
  }

  /**
   * @param array $params
   *
   * @return null
   */
  public function sendEmail($params = array()){
    //Variable declaration
    $module = 'my_module';
    $key = 'my_module_message';
    $to = "email@email.com";
    $from = "email@email.com";
    $language_code = \Drupal::service('language_manager')->getDefaultLanguage()->getId();
    $send_now = TRUE;

   $mail = \Drupal::service('plugin.manager.mail')->mail($module, $key, $to, $language_code, $params, $from, $send_now);
    return $mail;
  }
}


Field Collection vs Entity Reference How is field collection an advantage? You can do the same thing with a new content type pointing to the parent with an Entity Reference.

Maybe someone can break down some situations where each one would be better.

Say for Task -> Files, would field collection be better or a new content type with an Entity Reference?

Say for each file you needed more some other data about that file, sounds like a plan for a new type with an Entity Reference, but you can embed a field collection inside of a field collection.

I enjoy how Drupal has many ways of doing the same things, but I can't find much on how different or similar these two solutions are.

Maybe someone can help explain?

This is a question I make myself when facing new projects, Field Collection vs Entity Reference + custom entity or if the structure is simple, Field Collection vs custom field with several db columns / Multifield. Here's my opinion based in my experience.

Multifield is a great concept, it'd be a "lightweight" version of field collection, instead of creating an entity structure with relationships, it covers the simple use cases without creating the entity. It has a number of issues, though, such as not complete Features integration, not really multilingual etc (so if you plan to use this, contributions will be probably really welcome).

Field Collection is a great solution if you're doing a site that can be done just with a few tweaks here and there, it gives site builders a powerful tool to create complex structures without worrying much about the internals. It will basically create an entity that relates with the "host" entity by the ids, allowing to add fields to it and everything.
The disadvantages would come in the knowledge of the internals of Field collection that you need to perform complex operations such as managing a Field Collection with an Entity Reference on it, or migrate data. As it is a generic tool, it'd be fairly complicated to go one step beyond.

Another option you've got there is using ECK with Entity Reference, but my experience with this has been a disaster so far, I find it way easier to create the entity type by code without the helper.

It's a matter of what you need and what's the best fit for your project, if you've got the time and the developers to create entity types that relate with your data model through Entity Reference, you'll have more control over what's happening with your data structures, but then you're the "responsible" for that too.

After testing a while with all the solutions describe above, in my team we always go for the entity types + ER, but I can see that for small projects, without data migration or a complicated i18n setup, Field Collection is just the fastest way to go.


If a user does not have a role, keep redirecting them to the same form until they complete it? I have a form/node that I want all users to complete after logging in for the first time.  When the user completes the form (saves the node), they are automatically awarded the completed role.

If a user does not have the completed role, I want to keep redirecting them to the form no matter what links they click.

In Drupal 7, I could do this with Rules (event: content is viewed, condition: user does not have role, action: redirect).  However, in Drupal 8, Rules is still in alpha and I can't get it to work without crashing my site.  So what hook should I use to do this programmatically? (what's the hook for "user views a node"?)

You can use hook_entity_view, this is called when a user views any entity type, also hook_ENTITY_TYPE_view can be used if you want to redirect on specific entity type view like node.


What is the replacement of drupal_match_path()? What is the replacement of drupal_match_path() in Drupal 8?
The following function is removed from Drupal 8. How can I achieve same functionality in Drupal 8?

function drupal_match_path($path, $patterns) {
  $regexps = &drupal_static(__FUNCTION__);

  if (!isset($regexps[$patterns])) {
    // Convert path settings to a regular expression.
    // Therefore replace newlines with a logical or, /* with asterisks and the <front> with the frontpage.
    $to_replace = array(
      '/(\r\n?|\n)/', // newlines
      '/\\\\\*/', // asterisks
      '/(^|\|)\\\\<front\\\\>($|\|)/', // <front>
    );
    $replacements = array(
      '|',
      '.*',
      '\1' . preg_quote(config('system.site')->get('page.front'), '/') . '\2',
    );
    $patterns_quoted = preg_quote($patterns, '/');
    $regexps[$patterns] = '/^(' . preg_replace($to_replace, $replacements, $patterns_quoted) . ')$/';
  }
  return (bool) preg_match($regexps[$patterns], $path);
}

New PathMatcher service reports that the path.matcher service was introduced to deprecate most procedural functions in the path.inc file with its methods.
In particular, the equivalent of $path_matches = drupal_match_path($path, $patterns); is the following code.

$path_matches = \Drupal::service('path.matcher')->matchPath($path, $patterns);

The same service is used to check if the currently viewed page is the front page.

$is_front = \Drupal::service('path.matcher')->isFrontPage();

As usual, injecting the dependency is preferred over calling \Drupal::service().


Moved Site - Can't find original CSS for look other than in the ADVAGG I've inherited a drupal 7(I'm a beginner) site that had ADVagg installed. I added a stanza in my nginx config to take care of those files. What I'm running into is that there is a button on the original site that has a style which only exists in an aggregate file.  I can't find it in any other file in the enitre site. The docroot was zipped and sent to me. I'm just a little miffed as to why the site I've unpacked doesn't have the same styles as the one online currently.
I've disabled the ADVAGG as well with no change.
###
    ### advagg_css and advagg_js support
    ###
    location ~* files/advagg_(?:css|js)/ {
      gzip_static on;
      access_log  off;
      expires     max;
      add_header  ETag "";
      add_header  Cache-Control "max-age=31449600, no-transform, public";
      try_files   $uri @rewrite;
    }

AdvAgg is used to improve the standard Drupal Core aggregation.
Just disabling AdvAgg won't disable aggregation.
You will need to disable CSS aggregation under the Performance settings, then flush caches, and you should be able to inspect the button CSS again.


Clarity on Drupal caching? Drupal 8 uses Opcache, while most people still use APC for Drupal 7. I am not sure which of the two to use for a Drupal 7 site, because it appears there is no Opcache module for Drupal 7. There is this: https://www.drupal.org/project/opcache, but I don't think that will do the trick as it is a dev module.

Which of the two options should be used for Drupal 7? And if you choose Opcache, please suggest the best way to implement it, seeing as the module is in dev mode? Assuming I am using PHP 5.5 (i.e. a version that supports OpCache, which means it would be my preference as well).

Drupal 8 recommend using Zend OpCache (a PHP extension), which is enabled at server side, and it caches PHP code; it is not used for caching data.
For data caching, Drupal 8 automatically uses APCu without requiring third-party modules, if the PHP extension is enabled. See Several cache bins now use APCu caching by default, which states:

  In order to improve cache performance, Drupal 8 now has:

  A cache.backend.apcu service that site administrators can assign as the backend of a cache bin via $settings['cache'] in settings.php for sites running on a single server, with a PHP installation that has APCu enabled, and that do not use Drush or other command line scripts.
  A cache.backend.chainedfast service that combines APCu availability detection, APCu front caching, and cross-server/cross-process consistency management via chaining to a secondary backend (either the database or whatever is configured for $settings['cache']['default']).
  A default_backend service tag (the value of which can be set to a backend service name, such as cache.backend.chainedfast) that module developers can assign to cache bin services to identify bins that are good candidates for specialized cache backends.
  The above tag assigned to the cache.bootstrap, cache.config, and cache.discovery bin services.

  This means that by default (on a site with nothing set for $settings['cache'] in settings.php), the bootstrap, config, and discovery cache bins automatically benefit from APCu caching if APCu is available, and this is compatible with Drush usage (e.g., Drush can be used to clear caches and the web process receives that cache clear) and multi-server deployments.

So, if you are using APCu as data cache on Drupal 7 (which require installing a third-party module), keep using it; when you will port the site to Drupal 8, you will not need anymore a third-party module, to use APCu to cache data. That is why the APC - Alternative PHP Cache module doesn't have a Drupal 8 version.

The module you are linking just allows Drupal to report status information about the cache and reset the cache; it is not a module you need to use Zend OpCache with Drupal.


White screen of death but only on log in page? Ive got a copy of a site to work on locally. The instructions were to leave the settings.php how it is and just enter my database details into local_settings.php. Ive done this and the site works fine except except when I try and log in and go to the 'user' page at which point I get the white screen of death.

The site only works the the url doesn't have the https so this is the front page: http://mysite/

However when I try and 'user' to the end it redirect to https://mysite/user so it adds 's' to the 'http'.

Another quirk that may be relevant is that when I create a brand new site it works fine except that the admin log in doesn't work the first time. I have to use the 'Request new password' link to log in. After that I can log in and out fine.

Turns out I had to disable the secure pages module.


How can I add rows to grouping in views? I have a view that lists terms from two different vocabularies (Product Categories, and Traits). The Product Categories vocabulary looks something like this:

Sweet Corn

Type 1
Type 2

Onions

Type 3
Type 4

Popcorn

Type 5
Type 6

Each of these parent categories also have specific traits that are identified in the Traits vocabulary that looks like this:

High Expansion
Augmented
Celebrate

High Expansion is a trait of Popcorn, Augmented is a trait of Sweet Corn, and Celebrate is a trait of Onions. Traits are different from Categories, and must be defined in a separate vocabulary due to other definitions and functionalities on the site. So, I can't just make them children of the above parent terms.

I have a view that is a main landing page for the product categories that displays the icons for all the Categories and Traits, that the user can click to see a filtered view of products within the category clicked. I am grouping the view results by Parent term, but also need to include the Traits in the appropriate groups.

On my landing page view, I need to list the Traits under the appropriate grouping, so my landing page view should look something like:

Sweet Corn

Type 1
Type 2
Augmented

Onions

Type 3
Type 4
Celebrate

Popcorn

Type 5
Type 6
High Expansion

Is there any way to accomplish this type of grouping?

Thank you for your help!

The views Format Settings has your answer.  There is a drop-down for "Grouping field Nr.1" that does exactly this.

As it is, you have one "row" showing for each unique set of values because this is what mysql returns.  By setting this field grouping, Views will match up the values from the selected field and use them as headers for sub sections of your results.

If this is not a good enough match to your issue, please provide details on how it doesn't work and I can update the answer.

Continued:

The view is a tool for making a mysql query and then theming the returned result.  With this in mind, you need to craft a set of data relations and filters to get the appropriate data linkages for the ratios you want in your display.  This means you want the database handing you a field table like:

Category parent | product | category | trait

Sweet Corn | corn product 1  | Type 1  |  Null
Sweet Corn | corn product 2  | Type 2  |  Null
Sweet Corn | generic corn product  |  Null | Augmented
Onions | onion product 1 | Type 3 | Null
Onions | onion product 3 | Null  | Celebrate

Then once you have the dataset you need, you work on the theming side of the views tool.  Use the above mentioned Grouping field setting on the Category Parent.  This will make the sections with the parent titles as indicated in your question, but it might look like

Sweet Corn

corn product 1  | Type 1  |
generic corn product  | | Augmented

Then use the "exclude from display" on the product field, or actually remove it from the fields list.  I have it included here because it is needed to show the data grouping as I understand it in your question.  Finally, configure the "category" field with the link you want it to have and exclude it from display; use the "No Results Behavior" rewrite option on Trait to put in the token for the Category field, something like [field_term_category].  You should be able to find this token in the list of "replacement patterns" available in the Rewrite Results area.

You should now have a list of parent categories showing the linked sub categories and traits where you want them.  The "trait" field will either have the category or the trait in there, as it shows trait when trait is present, and category when not.  Be sure to uncheck the "hide if empty".


How to programmatically display a webform in a block based on user selection I am developing a module which generates custom blocks based on some configuration done by site admins in a module-specific config page. For each block I would like the admins to be able to nominate a webform (from a select dropdown), which would then be displayed in the block.

What I don't understand is how to match up the webform selection process with the webform display process. In the module-specific config page, I would generate the options by querying the node table for all nodes of type 'webform', display the titles of the webforms in the select element, and then save the nid of the chosen webform.

However this nid doesn't seem to be much help to me when it comes to my_module_block_view, where (as I understand it) in order to display a webform I need to do something like

$block['content'] = module_invoke('webform','block_view','client-block-N');

where N is the nid of the node to which the webform is attached, NOT the nid of the webform itself ? Incorrect statement - see correction below

So I'm unsure how to request the webform that the users have selected, as all I know about it is its nid?

What I'm seeing:

On my test Drupal, I have a webform with nid = 1, and content items of nid 2 and 3. Whether I specify 'client-block-1','client-block-1', or 'client-block-3' in my call to module_invoke, I am seeing no webform displayed.

Does anyone have any suggestions how I should proceed with this?

All help greatly appreciated.

CORRECTION

In the code example above, N should be the node id of the webform.

You're very close - the return from hook_block_view() is an array with keys content and optionally subject. Your current code example:

$block['content'] = module_invoke('webform','block_view','client-block-N');

Produces the equivalent of:

$block['content'] = array(
  'subject' => ...,
  'content' => ...,
);

When you put that through drupal_render(), it gets angry (because subject isn't a render array but isn't prefixed by #).

You're probably looking for:

$block = module_invoke('webform','block_view','client-block-N');

Or simply:

return module_invoke('webform','block_view','client-block-N');

(once N is substituted for the node ID of the webform).


PHP not Updating for Anonymous Users I have been running a personal dashboard on Drupal 7 for years (currently on 7.69). I rendered the dashboard in Homebox and some of the blocks use PHP (using PHP Filter) to get stock quotes, weather updates, etc.

I recently rebuilt the site in Drupal 8.8.1. I use Panels for the dashboard blocks since there is no Homebox for Drupal 8. I also added the PHP Filter module for my PHP blocks. I'll eventually put my PHP code in modules, but I'm going with PHP Filter for now. I'm using the included Bootstrap theme and caching is set to 'no caching'.

My problem is, everything runs fine when I am logged in as administrator -- the PHP code in the blocks executes every time I do a page refresh. However, when I am not logged in and I do a page refresh as an anonymous user, the PHP blocks do not update. In Drupal 7.69 the page will update for an anonymous user, which is the behavior I want. I've compared permissions between the two installations and everything looks the same. I must be missing something here.

Has anyone else used PHP Filter with Drupal 8 and run into this?

Looking at the code of the PHP filter:

class Php extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    $result = new FilterProcessResult(php_eval($text));
    $result->setCacheMaxAge(0);
    return $result;
  }

https://git.drupalcode.org/project/php/blob/8.x-1.x/src/Plugin/Filter/Php.php

it sets already a cache max age of 0, so you only need to remove the page cache for anonymous users by uninstalling the module "Internal Page Cache".


Mock a service while running a BrowserTest? I am trying to test the output of a controller that returns some information in a given page. This controller has a custom http client injected into it.

I want to create a BrowserTest that can navigate to a fake node, and then test for certain text or values. I also want to change the mock to return different values, so I can further test the output to account for those cases.

I tried:

    $client = $this->getMockBuilder('\Drupal\mymodule\Client\AuthorizeClient')
      ->disableOriginalConstructor()
      ->getMock();
    $client->expects($this->any())
      ->method('request')
      ->with('w12345', FALSE)
      ->willReturn([]);

    $this->container->set('mymodule.auth_client', $client);

But I get errors in the test that refer to the original class, and not the one I am trying to replace. I looked around in the core but wasn't really able to find what I was looking for. Does it make sense to do this? Is there a way to do a Kernel test to test responses from the route in question?

I could not quite get my mocked service to be used from the container as per the docs, so I resulted to doing this.

I don't really need a BrowserTest per se, as I just want to ensure the Response object contains what it should. I create a client mock and instantiate the controller object myself:

<?php

namespace Drupal\Tests\mymodule\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\mymodule\Controller\AuthorizeController;
use Drupal\node\Entity\Node;
use Drupal\file\Entity\File;
use Drupal\Core\File\FileSystem;

/**
 * Tests the AuthorizeController controller.
 *
 * @group mymodule
 */
class AuthorizeControllerTest extends KernelTestBase {

  /**
   * @var array
   */
  public static $modules = ['system', 'node', 'field', 'mymodule', 'file', 'mymodule_authtest', 'user', 'text'];

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();

    $this->installConfig(['node', 'user', 'mymodule_authtest', 'file']);
    $this->installSchema('file', ['file_usage']);
    $this->installEntitySchema('user');
    $this->installEntitySchema('node');
    $this->installEntitySchema('file');

    $module_path = drupal_get_path('module', 'mymodule_authtest');

    $uri = $this->container->get('file_system')->copy("$module_path/fixtures/pdf/foo.pdf", 'public://foo.pdf', FileSystem::EXISTS_REPLACE);

    $file = File::Create([
      'uri' => $uri,
    ]);
    $file->save();

    $node = Node::create(array(
      'title' => t('Test Paper'),
      'type' => 'working_paper',
      'language' => 'en',
      'field_id' => 'w12345',
      'field_paper_working_paper' => $file->id(),
    ));
    $node->save();
  }

  /**
   * Test different scenarios and responses from our controller.
   */
  public function testControllerResponse() {
    $node = $this->container->get('entity_type.manager')->getStorage('node')->load(1);

    $client = $this->getMockClient(1, 3, 3);
    $controller = $this->getAuthorizeController($client);
    $response = $controller->content($node);
    $this->assertContains('You’ve used 3 of your 3 allowed downloads for the year.', $response->getContent());
    $this->assertContains('Download Paper Anyway', $response->getContent());

    $client = $this->getMockClient(1, 3, 1);
    $controller = $this->getAuthorizeController($client);
    $response = $controller->content($node);
    $this->assertContains('You’ve used 1 of your 3 allowed downloads for the year.', $response->getContent());
    $this->assertContains('Download Paper Anyway', $response->getContent());

    $client = $this->getMockClient(1, 2, 1);
    $controller = $this->getAuthorizeController($client);
    $response = $controller->content($node);
    $this->assertContains('You’ve used 1 of your 2 allowed downloads for the year.', $response->getContent());

    $client = $this->getMockClient(0, 3, 3);
    $controller = $this->getAuthorizeController($client);
    $response = $controller->content($node);
    $this->assertNotContains('Download Paper Anyway', $response->getContent());
    $this->assertContains('Purchase Paper for $5', $response->getContent());
    $this->assertContains('Have Access? Login to Account', $response->getContent());
  }

  /**
   * Return a mocked client. Allow changing of some values to influence the
   * controllers response object.
   */
  protected function getMockClient(int $allow = 1, int $claims_max = 3, int $claims_used = 1) {
    $client = $this->getMockBuilder('\Drupal\mymodule\Client\AuthorizeClient')
      ->disableOriginalConstructor()
      ->getMock();
    $client->expects($this->any())
      ->method('request')
      ->with('w12345', FALSE)
      ->willReturn(
        [
          'allow' => $allow,
          'claims_max' => $claims_max,
          'claims_used' => $claims_used,
          'failed_reason' => NULL,
          'succeeded_reason' => NULL,
          'subscriber_id' => 12345,
          'subscriber_logo_url' => NULL,
          'subscriber_name' => "Test",
          'subscriber_type' => "SUBS",
        ]
      );

    return $client;
  }

  /**
   * Return a controller with a mocked client.
   */
  protected function getAuthorizeController($client) {
    return new AuthorizeController($client, $this->container->get('renderer'), $this->container->get('entity_type.manager'), $this->container->get('request_stack'), $this->container->get('logger.factory'));
  }

}

This seems like a valid approach and the cases are working, and executes much faster than browser tests. The mymodule_authtest contains a content type with a couple of field configuration files and example PDF file to use in this test.


How can I create a view that shows image file fields which do not have any data? I'm using Drupal 7 and I have a content type, Picture, which includes an image field.  Users use this to add image to the site.

Sometimes, however, there is no data on the server.  For example, if I copy the database from my production to my testing server, the image files will be registered in the db but they don't actually exist on the testing server, so the pictures cannot be displayed.

I would like to create a view that shows these images-- the data is in the DB, but the file does not actually exist.

I created a view for my content type Picture and added the following Filter Criteria

Image: fid- empty
OR File size- empty (Through File Usage: File relationship)

However, this does not show pics that exist in the DB but not in the filesystem.

Is there a way to do this in views, or is there no way to test if the file actually exists?

One way of going about this is using Views PHP. Add your file path as a field and exclude it from display. Add a Global: PHP filter with return file_exists($row->uri); as your filter code. This should return TRUE for files that do exist, and will remove those from the results, showing only files in your database that do not exist. Your current filter criteria are only checking the file_managed table in the database and are not going to be aware if the file exists.


How to add comma separated list for the select list check box field type For my one site, I added a select list(text) > check box field type to my content. When I go to manage display tab(using display suite module), in the format column column for the field, I see drop down field with 4 values ( css class, default, key, list). I selected list. Next to that I also see a geared setting where it allows me to make a comma separated list. When I go to front end, I see the values listed separated by commas. It works fine.

I am trying to do the same thing for my other site. But as for the drop down field, I only see default and key. Also, I don't see the geared setting icon to make it comma separated list. I am not sure what I did wrong on my second site. Both site have the same field type.

Please advise.

Do you have the Text list formatter module installed on the first site, but not the second site? That would provide the functionality you describe.


create menu filter price product salute you. I have one problem need your help. I want to create 2 menu list of product categories and product prices. there should be a link between two product categories menu to the product menu to display the products desired by the user. for example i have 2 menu after

categories:

dell servers
ibm server
hp server

price:
$ 100 to $ 500
$ 500 to $ 1000
$ 1000 to $ 2000

When I click on dell server it will display all the products dell server and when I continued to click $ 100 to $ 500 it will display the products of dell servers have priced 100 $ to 500 $. thank you

What you're looking for there is not a menu but faceted search, the best way to do this is to install and configure Apache Solr Search and Facet API.


Date popup field won't display in tableselect element I am attempting to embed a couple of date fields within a tableselect element, and after trying to use both textfield and date_popup field types, I can't get either to work. Here's my form function using textfields:

function language_dashboard_overview_form($form, &$form_state, $entity) {
  $form = [];
  $options = [];

  $header = [
    'language_locale' => t('Language Locale'),
    'status' => t('Status'),
    'staging_url' => t('Staging URL'),
    'start_date' => t('Start Date'),
    'end_date' => t('End Date'),
    'display_title' => t('Display Title')
  ];

  $translations = $entity->translations->data;

  foreach($translations as $locale => $locale_data) {
    // Get data for all the other fields here
    ...
    // Define start and end date text fields.
    $start_date = new DateTime($entity->field_locale_publishing_dates[$locale][0]['value']);
    $new_start_date = $start_date->format('m-d-Y');

    $end_date = new DateTime($entity->field_locale_publishing_dates[$locale][0]['value2']);
    $new_end_date = $end_date->format('m-d-Y');

    $start_date_field = [
      'data' => [
        '#type' => 'textfield',
        '#size' => 10,
        '#maxlength' => 10,
        '#default_value' => $new_start_date
      ]
    ];

    $end_date_field = [
      'data' => [
        '#type' => 'date_popup',
        '#date_format' => 'm-d-Y',
        '#date_year_range' => '0:+20',
        '#default_value' => $new_end_date
        ]
    ];

    $options[] = [
      'language_locale' => $locale_link,
      'status' => $status,
      'staging_url' => $stage_url,
      'start_date' => $start_date_field,
      'end_date' => $end_date_field,
      'display_title' => $title
    ];

  }

  $form['dashboard'] = [
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options
  ];

  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Submit')
  ];

  return $form;
}

With that, I get the fields, but no default value is filled in (and I've verified that the $start_date_field and $end_date_field  variables have the desired data).

If I try it with date_popup fields like so:

$start_date_field = [
  'data' => [
    '#type' => 'date_popup',
    '#date_format' => 'm-d-Y',
    '#date_year_range' => '0:+20',
    '#maxlength' => 10,
    '#default_value' => $new_start_date
  ]
];

$end_date_field = [
  'data' => [
    '#type' => 'date_popup',
    '#size' => 10,
    '#maxlength' => 10,
    '#default_value' => $new_end_date
  ]
];

I get no field at all in those columns. From the multiple items I've read on this, I'm adding the fields correctly to the tableselect. Is there something else I'm missing?

UPDATE: I discovered that for the text field, you use #value instead of #default_value. changing that shows my default date as desired. so the only remaining issue is that I can't get anything to show for a date_popup field.

I still can't get the date_popup element to work in a tableselect element, so I ended up going with text field and the jQuery_ui datepicker (included in core).

  $form['dates'] = [
    '#type' => 'fieldset',
    '#title' => t('Set Dates'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  ];

  $form['dates']['start_date_popup'] = [
    '#type' => 'date_popup',
    '#title' => t('Start Date'),
    '#date_format' => 'Y-m-d',
    '#date_year_range' => '0:+20',
    '#maxlength' => 10,
    '#date_label_position' => 'none',
    '#id' => 'apply-start-date'
  ];

  $form['dates']['end_date_popup'] = [
    '#type' => 'date_popup',
    '#title' => t('End Date'),
    '#date_format' => 'Y-m-d',
    '#date_year_range' => '0:+20',
    '#date_label_position' => 'none',
    '#id' => 'apply-end-date'
  ];

  $form['dates']['apply_dates_button'] = [
    '#type' => 'button',
    '#value'=> t('Apply Dates'),
    '#attributes' => array('id' => array('apply-dates')),
  ];

...

 'start_date' => array(
   'data'=> array(
     '#type'=>'textfield',
     '#value'=> $new_start_date,
     '#title' => 'Start Date',
     '#title_display'=>'invisible',
     '#name'=> 'start_date[' . $locale . ']',
     '#id'=>  'start-date[' . $locale . ']',
     '#attributes' => array('class' => array('datepicker')),
     '#size' => 10,
     '#maxlength' => 10
   ),
 ),
 'end_date' => array(
   'data'=> array(
     '#type'=>'textfield',
     '#value'=> $new_end_date,
     '#title' => 'End Date',
     '#title_display'=>'invisible',
     '#name'=> 'end_date[' . $locale . ']',
     '#id'=> 'end-date[' . $locale . ']',
     '#attributes' => array('class' => array('datepicker')),
     '#size' => 10,
     '#maxlength' => 10
   ),
 ),

and this JS behavior:

(function ($) {
  Drupal.behaviors.dashboardDatepicker = {
    attach: function (context, settings) {
      // Attach the datepicker to the selected fields.
      $( ".datepicker" ).datepicker({
        dateFormat: "yy-mm-dd",
        changeYear: true,
        yearRange: '-30:+30',
        minDate: '-0',
        showButtonPanel: true
      });

      // Add click handler for apply button.
      $("#apply-dates", context).click(function(event) {
        // Keep the form from being submitted.
        event.preventDefault();
        // Get the dates from the fieldset
        var startDate = $("input[id*='apply-start-date']").val();
        var endDate = $("input[id*='apply-end-date']").val();
        // Get the set of selected checkboxes.
        if(startDate) {
          $("table#locale-table").find("tr.selected").find("input[id*='start-date']").val(startDate);
        }
        if (endDate) {
          $("table#locale-table").find("tr.selected").find("input[id*='end-date']").val(endDate);
        }
      })
    }
  };
}(jQuery));


How to override node clone to its parents node? I am using node clone 7.x-1.0-rc2 module.It is creating clone for a particular node.Now if i published clone.How to override parent node with clone node. Is there any other way or module for doing this?

I am using workbench and my scenario is that i have three types of user contributor,validator and publisher. only contributor can create node and assign it to validator, now here validator can revert to contributor or assign to publisher.Publisher can publish this node or revert to validator.Now i am creating a clone of this node and again send it to contributor and contributor send it to publisher but when publisher wants to publish this clone so old content get update this clone node's content or delete old one and become this node as a parent node.

It looks that you are trying to implement elaborated workflow using node cloning approach.

I strongly suggest you to use Workflow module instead:

  This module allows you to create arbitrary Workflows, and assign them to Entities.

  Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state.
  You can set up the Workflow to alter states from form, page, comment and a special workflow tab.

  Transitions between workflow states can have actions assigned to them. In our example, we could assign an action so that when the story moves from the Draft state to the Review state an email is sent out. Another action could be assigned to the transition from Review to Published so that the node's status is set to Published (and becomes visible on your website).

It is there, it works, and it seems to cover all your needs in one, integrated solution. Even it's example use case is almost exactly like your use case here.

If you want to configure it at revision level more easily, there is also Revisioning, "a module for the configuration of workflows to create, moderate and publish content revisions".

  You use it in scenario's like this:

  Authors write content that prior to being made publicly visible must be reviewed (and possibly edited) by moderators. Once the moderators have published the content, authors should be prevented from modifying it while “live”, but they should be able to submit new revisions to their moderators.
  We shouldn't have to grant these roles “god-like” powers (e.g. D6's "administer nodes" permission) to implement this.


Where to check for node value constraints on services data receive I have a REST service to create nodes. On data receive, node.create is executed, but before actually creating the node I need to check some constraints like node type and other node values.

Is there any I can use?

To have more control on the node creation you need to write up your own service for nodes using  hook_services_resources(). By default you can control only the access for creating a particular node using permissions.

If you need to control node creation via node values, you need to go with your own services.


How to add the VAT on the selected products in Commerce Kickstart? I am using Drupal commerce kickstart. Can anyone tell me how to create the field for the VAT in the product creation form? I need a field for each product listed in the product form.

There is a module Commerce VAT for this purpose

  Commerce VAT module is an improved module for supporting VAT than the
  Commerce Tax module included in Commerce. If you are using Commerce
  VAT is is recommended you disable Commerce Tax.


How to have tpl for parent but not child? I want to override the template for just /user/ but not for /user/edit or user/anythingelse. Is there a way to do that?

For example, I made a page--user.tpl.php but it effects all of user's children.

You are editing in wrong template file. You have to make theme changes in user-profile.tpl.php.

For theme hook suggestions:

function themeName_preprocess_page(&$vars, $hook) {
  // Go to user page.

  // Requires devel module.
  dpm($vars['theme_hook_suggestions']);
}

There is a list of theme hooks in this page
Theme implementations is Drupal 7


How to set $base_url when running a site in a subdomain? I just uploaded a site to a remote server. The url is a subdomain: mySubdomain.myDomain.com.

The site just shows the front page. If I tried to navigate to other page (ex.: el-graner) I get this message:

Not Found

The requested URL /ca/el-graner was not found on this server.

I set the $base_url variable in sites/default/settings.php in this way, then clear all caches...but not working at all.

$base_url = 'http://mySubdomain.myDomain.com';

What are the settings I need to do when running a drupal site in a subdomain?

Have you tried clearing cache after uploading to remote server?

If it didn't help, you could try installing Global Redirect module. It may resolve your problem, or at least can help reduce the possibility of problems created by path aliases.


How to show the distance relative to the user's location? I'm trying to recreate a site, and one part of the content is supposed to show the distance relative to the user's location, like this:

Does anyone know of a way I can accomplish this?

You need to install the Geolocation Field module and the example submodule that comes with it.

In the examples you will find a view that made exactly what you need, and you only will need to clone and edit the view.

  Geolocation Field provides a field type to store geographical
  locations as pairs of latitude and longitude (lan,lng). The Drupal 8
  version also provides a views proximity search plugin. Geolocation
  Field can be used with all fieldable entities like nodes, users,
  comments, taxonomy terms, etc.


How to integrate content type to webform Drupal 7? I have a content type called "student".

now I want to set that content type as select option component in webform.

Are there any way to do so? thanks,

Tvphong, I think that the best way to go about doing this is by using a custom module so that you can then integrate that content type within the select list of preloaded options.

Perhaps this link can serve you well in this.

What I ended up doing is a slight tweak of this. So my custom module looks something like this (which is for location content types):

<?php

/**
 * Reference:  http://eureka.ykyuen.info/2012/04/11/drupal-7-dynamic-select-options-for-webform/
 * The following piece of code is based on the blog post above
 */
function webform_options_webform_select_options_info() {
 $items = array();

 if (function_exists('get_location_titles')) {
  $items['location_titles'] = array(
    'title' => t('Location titles'),
    'options callback' => '_get_location_titles',
    );
 }

 return $items;
}

function _get_location_titles() {
 $options = array();
 $type = "location";

 $result = db_query('SELECT nid, title FROM {node} n WHERE n.type = :tname', array(':tname' => $type));
 foreach ($result as $row) {
  $options[$row->nid] = $row->title;
 }
 return $options;
}


How to set node id as SKU id I am using drupal commerce for e-commerce site. When node(product) is created SKU id of the product must be node id. How can I achieve it. Thank You.

In Drupal Commerce products are entities, not nodes. If you're looking for a product's SKU to be automatically set to the created product's id, there's the Commerce AutoSKU module which allows you to use tokens (e.g. [product:product-id]) to automatically create SKUs.

One caveat from the project however:

  If you decide to use the [product:product-id] token, you should be
  aware that this will cause any new products to be saved twice. This
  shouldn't be an issue for most people, but if you have rules in place
  for when a product is saved, you may not want to use this token.


Generating hierarchic URI's based on taxonomy I was wondering whether it is possible to have a taxonomy whose URL's are based on taxonomy.
Example: I have a taxonomy list called 'Gallery type' which exists of the following items in which 'Pictures' and 'Movies' are higher in the hierarchy than the subitems:

pictures

pictures-2009
pictures-2010
pictures-2011
pictures-2012

movies

movies-2009
movies-2010
movies-2011
movies-2012

I also have a (gallery) content type in which it is obliged to select an item from the taxonomy list (actually a submitter should select two items: one main item and one subitem (e.g. 'pictures' AND 'pictures-2012'). Then I have made a view for every item in the taxonomy list so that every taxonomy term is a page that contains links to the pages that are created with the term as obliged option (I know that this is hard to follow, but please bear with me)

Example: I create a new gallery named 'Animals' and select the options 'pictures' and 'pictures-2012'. This gallery 'Animals' will be visible on the corresponding views, i.e. /pictures AND /pictures-2012. The page its URI however will be /content/animals. My question is then if it is possible to make the URI follow the hierarchy posed in the taxonomy. In this case it would be: /pictures/pictures-2012/animals

If anything is not clear, please do tell me! English is not my mother tongue, so forgive me if it contains a lot of syntactic and/or grammatical errors!

From the comments, this is one way how I would do this:

create a taxonomy vocabulary called gallery type.
create a taxonomy vocabulary called year.
populate them with the appropriate terms.

Then I'd create a view:

filter it on gallery type (or whatever content types are tagged by the above vocabs)
also filter it on all nodes that are published

In arguments (d6) or contextual filters (d7) I'd put in two arguments.  They would be taxonomy terms and you can select them from the dropdown list from taxonomy:

For the first, select taxonomy term and then in validation, select taxonomy and term again and restrict it to the gallery type vocabulary.
For the second select taxonomy term and then in validation, select taxonomy and term again restrict it to the year vocabulary.

Then, in the Fields, select whatever fields you want displayed.  For ease here, just select node title, but once in production I'd imagine they'd be title, a picture or image or two, a description, etc.

Now, create a page display in the view, and in the path enter

myfirstview/%/%

Change myfirstview to whatever makes sense on your website's hierachy.  What the two %'s do is substitute in the taxonomy terms above.

Save everything.

Now you have created a View that does all that hierarchy for you.  So, if someone goes to...

www.yourhost.com/myfirstview/movies/2009

...Views will create the page for you and display the title of whatever content has been tagged with both movies and 2009 (views takes the hardcoded myfirstview and substitutes in the movies and 2009 and then matches them against what content is tagged with those terms) and if they went to...

www.yourhost.com/myfirstview/pictures/2012

...Views would create a page of all pictures from 2012 doing the same logic.

What is nice is that you can then create a views that filter on only one of the vocabularies, eg,

www.yourhost.com/mysecondview/pictures

that would list all pictures

or

www.yourshost.com/mythirdview/2012

that would list all content from 2012

As you get more comfortable with Views you can then add all kinds of different sortings, eg, sort by posting or last edit date, sort alphabetically by title, etc, but this should get you on your way.  Just play around with the settings and hit Preview a lot.  You'd be amazed how simple it is once you get past the up front daunting nature of all the various options you have.


How do I redirect example2.com to example.com My website has 2 domain, example.com and example2.com.

example.com/node/1 and example2.com/node/1 are the same link.

How do I redirect example2.com to example.com.

When people open the linke example2.com/node/1, it will redirect to example.com/node/1

There are many ways to do this. I just give you the most straightforward (of course for me!) and simplest one.

In hook_preprocess_html use this code

THEME_preprocess_html(&$var){
      $host = $_SERVER['HTTP_HOST']. request_uri();
      if(strpos($_SERVER['HTTP_HOST'],'example2') !=false)
           header("location:example.com/".request_uri());
}

I can't test this code right now, but this is the main idea:

Get current url components separately, the host ($_SERVER['HTTP_HOST']) and what comes after it (request_uri()), if its $_SERVER['HTTP_HOST'] contains example2 as a substring, then redirect the user to example.com/request_uri()

For redirection you can also use drupal_goto or anything else you want I just gave you the pure PHP.


How to change upload destination from public to private when there are uploaded files in database? There are a few fields that uses public upload destination. I changed it globally right now, as far as I know it uses private upload destination from now.
But how can I change previously uploaded files' upload destination (programmatically)?

$dest = 'private://';
$file = file_move($file, $dest)

Change individual file from public to private and vice-versa


How can I set values in the $conf array using the admin interface? I am using the Journal  module and in order to limit the forms its text box appears on the form ids have to go into a $conf variable. The docs say it has to go into settings.php but I don't watch that.

$conf['journal_form_ids'] = array(
    'fivestar_custom_widget' => 0,
    'guestbook_form_entry_form' => 0,
    'imagefield_js' => 0,
    'img_assist_header_form' => 0,
    'img_assist_properties_form' => 0,
    'link_widget_js' => 0,
    ...
);

Is there a module that can accomplish this from the admin interface?
Can it be done through some kind of execute PHP form like with devel?

It has to be done from the admin

Sure, you can do this at devel/php if Devel module is enabled and you have access to Devel module's Execute PHP code.

The PHP to do what you want is

variable_set('journal_form_ids', array(
    'fivestar_custom_widget' => 0,
    'guestbook_form_entry_form' => 0,
    'imagefield_js' => 0,
    'img_assist_header_form' => 0,
    'img_assist_properties_form' => 0,
    'link_widget_js' => 0,
    // ...
  ));


Database connection onto an module i'm new into the world of Drupal, i'm a student comming from the Symfony ^^

I have create a module an i want to add an database connection for my module. In looking for an answer i have see the method getConnection of the Database class.

I have tried this onto my controller

$connection = \Drupal\Core\Database\Database::getConnection('moduleunicef','password');

for connection at my database called moduleunicef, i have see i need to modif my setting.php file.

/* /sites/default/setting.php*/
$databases['default']['default'] = array(
 'driver' => 'mysql',
 'database' => 'moduleunicef',
 'username' => 'theuser',
 'password' => 'password',
 'host' => 'localhost',
 'prefix' => '',

);

In result i have this error message (For security i have change the password and user ^^ )

  Drupal\Core\Database\ConnectionNotDefinedException: The specified database connection is not defined: root in Drupal\Core\Database\Database::openConnection() (line 366 of core/lib/Drupal/Core/Database/Database.php).

  Drupal\Core\Database\Database::getConnection('moduleunicef', 'password')
  Drupal\unicef42\Controller\PbRouteController->index()
  call_user_func_array(Array, Array)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
  Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
  call_user_func_array(Object, Array)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
  Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
  Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
  Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1)
  Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
  Stack\StackedHttpKernel->handle(Object, 1, 1)
  Drupal\Core\DrupalKernel->handle(Object)

So i have tried an over method into my controller

$connection = \Drupal::database();

the test of connection it's Ok but it's the base who i have input onto my setting.php file? or the drupal DataBase created for the install of the website?

I need some namespace onto my controller?

I'm using this one to swith and send a query

in the settings.php add

databases['customer_db']['default'] = [
  'driver' => 'pgsql',
  'database' => 'drupal',
  'username' => 'drupal',
  'password' => 'drupal',
  'host' => 'xx.xx.xx.xx',
  'port' => '5432',
  'prefix' => '',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\pgsql',
];

Then use when it's necesary

$db = \Drupal\Core\Database\Database::getConnection('default', 'customer_db');
print_r($db->databaseType());
$query = $db->query("SELECT * FROM customer");
...


Drupal 7: Two submit buttons and custom field validation I have a custom user registration form (D7). I added two custom submit buttons inside THEME_form_alter

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Sign Up')
  );
  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Sign Up & Take Survey')
  );

These render fine and both handle the registration equally well but when submit2 is clicked I want to redirect to a webform survey.

I added the following:

function tweakform_user_register_submit($form, &$form_state) {

  if($form_state['values']['op'] == $form_state['values']['submit2']) {
    echo 'Redirect to survey and populate fields with user details';
    exit;
  }

}

I refreshed the cache and this function does not seem to be invoked.

Alex

I'd suggest using the #submit property

For example:

$form['actions']['submit'] = array(
 '#type' => 'submit',
 '#value' => t('Sign Up')
);
$form['actions']['submit2'] = array(
  '#type' => 'submit',
  '#value' => t('Sign Up & Take Survey')
  '#submit' => array('custom_submit_for_this_button')
);

And then:

function your_form_name_submit($form, &$form_state) {
  // your logic for first button here; this is auto-called by Drupal
}
function custom_submit_for_this_button($form, &$form_state) {
  // your logic for second button here
}


How to modify attributes of fieldset-wrapper? It's similar and connected to How to modify attributes of  in form definition function? - This time I want to ask how to modify attributes of a
. HTML structure of a fieldset is:

<fieldset id="some-id" class="well-small form-wrapper vertical-tabs-pane">
  <legend>

      Lorem Ipsum

  </legend>

</fieldset>

I need class well-small directly on a fieldset-wrapper div. But if I apply it to a fieldset itself, it appears when you see it in sample above. When I move it one level down, well, there are only fields there, so it's one level too far instead of one level too close to the document root. Is there a way to conditionally add classes and other attributes directly from form building functions?

CSS and JS workarounds are out of the scope for me. I know how to work around it. Now I'm asking to know how to do it directly in PHP.

Looking at theme_fieldset the fieldset-wrapper class is hardcoded and that div doesn't take any additional classes from the $variables array.

So looks like the only option is to override theme_fieldset in your template.php of the active theme. If your conditional variables are present in $variables then you could do the logic straight in the theme_fieldset override function (replace mythemename with the name of your theme)

function mythemename_fieldset($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend>' . $element['#title'] . '</legend>';
  }

  // Condition/logic here
  $class = '';
  if($variables['....'] == '....') {
    $class = ' well-small';
  }

  $output .= '
';
  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . '
';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }
  $output .= '
';
  $output .= "</fieldset>\n";
  return $output;
}

Otherwise, a more elegant solution (by @Mołot) would be to supply use drupal_attributes like so:

mythemename_fieldset(&$variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend>' . $element['#title'] . '</legend>';
  }

  $element['#wrapper-attributes']['class'][] = 'fieldset-wrapper';

  $output .= '
';
  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . '
';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }
  $output .= '
';
  $output .= "</fieldset>\n";
  return $output;
}


Is there a module that can create a Taxonomy out of the installed modules? Is there a module that can create a Taxonomy out of the installed modules?

I want to create simple configuration tracking system and need to make my modules one of the taxonomies.

In relation to existing configuration management systems I got a suggestion here Is there a module for tracking changes to a Drupal site's configuration? so any other existing options for configuraton management should be answered there.

I have decided to use a combination of 3 modules to accomplish the task.

Views System, Views Data Export and Taxonomy import/export via XML

Views System is a Views module that lists all the installed modules and themes. Views Data Export enables the output of Views System to be exported as XML or CSV which Taxonomy import/export via XML can then import into a taxonomy.

A module which can update taxonomies from feeds would be nice, there is probably a module for that, but these will do for the time being.


Views - Edit, view, delete node in dropdown In facebook, on every post, there is a little arrow in the corner with content about that post.

Is there a Drupal module which allows me to achieve this?

What I want to do is:

I have different content types which a user can add.  I want to add the 'edit node', 'delete node' and 'view node' link into a small dropdown which allows the user to choose any of these options by clicking on the icon.

This can be achieved through contextual links. You can add new links through a custom module or with the Custom Contextual Links module (CCL).


Reference dialog hyperlink configuration Can anyone please direct me on how to configure References Dialog so that instead of just returning the titles of my node as plain text, they are returned as hyperlinks?

AFAIK, References Dialog only add links for add/edit/search.

If it's the display of a referenced node that you want to change, just change the field's format (under Manage Display) to "Title, as link".


attach image to poll choice I have a polls module that comes with drupal 7 enabled, But I need to attach an image filed to a choice, so when users add a choice to pull they get to add an image to it not to the node itself. is there a way to add this image?

I just got Advanced Poll with the sandbox module Advanced Poll Field Image to do the trick!


How to split configurations in features to minimize conflicts I need to put all configurations of a site to features. Some say that it is not a good idea to put all of the site configurations in one big feature. I have also experienced strange behaviour of the features ui when I tried it once.

My question is what kind of rules I need to implement on splitting the configurations between multiple features, to fulfil one important thing: Every small configurations, every new strongarm variable, or field, etc should be completly clear where to put to, to avoid confuse and conflicts in the future.

What I try to do is to build up features in layers. At the bottom most layer you put all the things that do not depend on anything else in your features, such as contrib modules, site settings and the like.

At each layer you add features that depend on the layer below, trying to avoid cross-dependencies. Each feature should be as standalone as possible apart from its depndencies on lower-level features.

It's difficult to achieve perfection, though, because a new feature may affect things you have already configured. For example if you install the field permissions module for a specific need, that'll add extra settings to fields you have already configured. So that module effectively becomes a dependency of sorts even though logically it isn't.


Calculating quiz score for validation I'm not using the Quiz module; I am using Webform and Drupal 7.

I have created a quiz that, if passed, assigns the user a new role. Currently, I use validation rules to simply prevent wrong answers from validating; all questions must be answered correctly before the user can proceed.

I need to change this to allow users with a score of 80% or higher to proceed to the next quiz. I know that I can do that with the quiz module. However I also need to be able to show correct answers for missed questions only to users who scored between 80% and 100%. Those scoring below 80% may not see any answer key.

What is the best way to go about this?

I am solving this problem by disabling Quiz and using only Webform, and writing a custom module that does the following:

use hook_form_alter to catch webform submissions
compare them to fields in an answer key

answer keys are of content type 'answer key'
they have a node reference field that references a webform

calculate percent that match
display a message depending on score

if 80% < x < 100% display answers
if 80% < x return that the quiz was passed
if 80% > x tell them they failed and redirect them back to the quiz page to re-take the test.


Switch theme per user upon login I'd like to switch theme per user upon user login success in my drupal 6 site. I need to check username of a particular user to change a particular theme for that user.
Is there any module around to accomplish this?
Or, do I have to write a hook like

function mymodule_init(){
    global $custom_theme;
    global $user;
    // check username here.
    $custom_theme = 'garland';
}

But, I'm finding a module which have admin interface so that I can define usernames as much as I can.

Try the Themekey module which allows content, user, or role -specific themes.


Can't choose content type anymore I installed the Webform module on my drupal 7 install and now, when I select to create new content, I don't get asked to choose the content type (basic page, article, webform) anymore. Where is the setting for this? I need to be able to choose which content type I want to create.

Thank you!
Ron

This is caused by a hiccup in the node menu rebuild after installing a new module. If you run into this issue, its likely due to one of three problems, which you can address in the following order:

Clear full cache, forcing the content menu to rebuild
Go to the menu options under /admin/structure/menu/manage/navigation and look for your add content menu items and make sure they are disabled
If these two fail, then there is probably an error in your build that is preventing the menu from rebuilding correctly - check in your error logs for any issue there and address.


Problem in deploying Drupal 8 application I am trying to deploy a Drupal 8 application to another folder from development.
Using PGSQL as database server.
I have database named xyz.
I am copying that database to another one named abc.
The problem I am facing:
When I use old database xyz for new code base, it is running fine.
But, when I use abc, which is exact copy of xyz, it is showing error.
Following is the error I am facing:

Array
(
    [%type] => Recoverable fatal error
    [@message] => Drupal\Core\Render\Markup Object
        (
            [string:protected] => Argument 1 passed to Drupal\Component\DependencyInjection\Container::__construct() must be of the type array, boolean given, called in /PROJECT-PATH/core/lib/Drupal/Core/DrupalKernel.php on line 890 and defined
        )

    [%function] => Drupal\Component\DependencyInjection\Container->__construct()
    [%file] => /PROJECT-PATH/core/lib/Drupal/Component/DependencyInjection/Container.php
    [%line] => 119
    [severity_level] => 3
    [@backtrace_string] => #0 /PROJECT-PATH/core/includes/bootstrap.inc(552): _drupal_error_handler_real(4096, 'Argument 1 pass...', '/Applications/M...', 119, Array)
#1 /PROJECT-PATH/core/lib/Drupal/Component/DependencyInjection/Container.php(119): _drupal_error_handler(4096, 'Argument 1 pass...', '/Applications/M...', 119, Array)
#2 /PROJECT-PATH/core/lib/Drupal/Core/DrupalKernel.php(890): Drupal\Component\DependencyInjection\Container->__construct(false)
#3 /PROJECT-PATH/core/lib/Drupal/Core/DrupalKernel.php(465): Drupal\Core\DrupalKernel->initializeContainer()
#4 /PROJECT-PATH/core/lib/Drupal/Core/DrupalKernel.php(655): Drupal\Core\DrupalKernel->boot()
#5 /PROJECT-PATH/index.php(23): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#6 {main}
)

The website encountered an unexpected error. Please try again later.

Can somebody please help me solving this.

EDIT:

I have correctly changed settings.php file for new code base and also changed the correct database name.

The error indicates that Drupal is failing at boot(). Check if your DB connection settings in settings.php that is located in the sites/default directory points to your new database.


How do I get an instance of AccountInterface in my Unit Test I want to write a Unit test. But the class I want to test has a AccountInterface dependencie Injection.

When I try to get the AccountInterface Object I get:

  Drupal\Core\DependencyInjection\ContainerNotInitializedException:
  \Drupal::$container is not initialized yet. \Drupal::setContainer()
  must be called with a real container.

My test looks like this

<?php
namespace Drupal\mymodule\test;

use Drupal\mymodule\MyModuleQuery;
use Drupal\Tests\UnitTestCase;
use Drupal\user\Entity\User;

class MyModuleQueryTest extends UnitTestCase {

  protected $user;

  public function __construct() {
    $this->user = \Drupal::currentUser();
  }

  public function testResult() {
    $MyModuleQuery = new MyModuleQuery(1, $this->user);
    $countUser = $MyModuleQuery->mymodule_get_user();
    $countNode = $MyModuleQuery->mymodule_get_node();
    $bool = FALSE;
    if (!isset($countNode) && !isset($countUser)) {
      $bool = TRUE;
    }
    $this->assertTrue($bool);
  }
}

You most likely want to mock your dependencies rather than trying to instantiate actual objects because a unit test should only test the class it describes. However this is not always as convenient.

In this case you are trying to call the \Drupal::currentUser static method which is dependent on the dependency injection container. An empty container can be created and used for the test, and test doubles available for it.

protected function setUp() {
  // use Drupal\Core\DependencyInjection\ContainerBuilder;
  $container = new ContainerBuilder();
  $account = $this->prophesize('Drupal\Core\Session\AccountProxyInterface');
  $container->set('current_user', $account->reveal());
  \Drupal::setContainer($container);
  $this->user = \Drupal::currentUser();
}

However you do not actually need the container, and can just use the test double.

public function testResult() {
  $accountProphecy = $this->prophesize('\Drupal\Core\Session\AccountProxyInterface');
  // Mock some methods.
  // $accountProphecy->getUserName()->willReturn('admin');
  $MyModuleQuery = new MyModuleQuery(1, $accountProphecy->reveal());
}


Drupal 8 Valid_url() In Drupal 7 we use valid_url, but what is the replacement in Drupal 8 for it?
I tried it but it the function is undefined. Finally I found the solution, see my answer.

Visit this to find an answer of this question.
https://drupaltreasure.blogspot.in/2017/04/drupal-8-validurl.html

The content of the provided link:

First, include class namespace use Drupal\Component\Utility\UrlHelper;
then use this function, No need to create the object because it is a static function so we can call it by its class name: UrlHelper::isValid($url, $absolute = FALSE);

Parameters:

$url : The URL to verify bool

$absolute: Whether the URL is absolute


"Article" html tag in body of Basic Page content type: what template is rendering this? When creating a basic page, then previewing that page, here is a sample mark-up from the browser:

Name

iOS &amp; Android Developer

I had pasted the basic html ul/li/dl etc in the source code view using the ckeditor, saved then viewed the page in a browser.

Don't know why a
 tag was wrapped around content within established html tags but my main question is where to find what template that is adding the
 tag as well as the nested structure of the extra
 tags

I've looked in the template files within modules and Zen (my parent theme) but I haven't found anything yet. Where is the
 tag being generated? I think that would help me find the full mark-up.

I always clean that part in node.tpl.php, that's the default template for nodes if you don't have one for each content type. So i would try changing the article tag for a div tag on that file.
You can make sure that it works cleaning all caches from your Drupal


Rhythem Theme for Drupal Commerce Hi does anyone here use Rhythm Theme for Drupal Commerce. I have a problem when I upgrade to the latest version of commerce in that when I go to create a Product Display it only lists 10 products instead of the many products I have. Not sure if this is a problem with commerce or with the theme I am using.

This is actually due to a change in Commerce 1.13 that we didn't have a great way to overcome initially. (More information at: https://www.drupal.org/node/2697017). The issue is with the settings for the product reference field on your node type. If you edit it, you'll find an options list limit setting that you can increase to see the more complete list of products again. Sorry for the regression. :-/