Order product ID field returns "0" in Views I have a View of type "Orders" for my Ubercart orders. I am trying to display the "Order Product ID" field value for each order product so that I can count those as distinct. I added the relationship "Order: Products", which makes the "Order Product ID" field available; however, that field is returning a value of "0" instead of the actual Order Product ID displayed in the database. How can I resolve this?

Here is an export of my view:

$view = new view();
$view->name = 'order_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'uc_orders';
$view->human_name = 'Order Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Order: Products */
$handler->display->display_options['relationships']['products']['id'] = 'products';
$handler->display->display_options['relationships']['products']['table'] = 'uc_orders';
$handler->display->display_options['relationships']['products']['field'] = 'products';
/* Field: Order: Order ID */
$handler->display->display_options['fields']['order_id']['id'] = 'order_id';
$handler->display->display_options['fields']['order_id']['table'] = 'uc_orders';
$handler->display->display_options['fields']['order_id']['field'] = 'order_id';
/* Field: Ordered product: Order product ID */
$handler->display->display_options['fields']['order_product_id']['id'] = 'order_product_id';
$handler->display->display_options['fields']['order_product_id']['table'] = 'uc_order_products';
$handler->display->display_options['fields']['order_product_id']['field'] = 'order_product_id';
$handler->display->display_options['fields']['order_product_id']['relationship'] = 'products';
$handler->display->display_options['fields']['order_product_id']['link_to_entity'] = 0;

Thanks!

I've also experienced this issue by creating hook_views_data_alter adding  the following code into it:

$data['uc_order_products']['order_product_id']['field'] = array(
    'handler' => 'views_handler_field_numeric',
);

I have noticed that the order_product_id had no handler so since the return of this field is the ordered product id I just went ahead and used the handler that comes with Views views_handler_field_numeric.

If you'd like, I bunched some additions related to the order product id field in my custom module in Ubercart-Add-ons.


Install.php available after xcopy deployment I created a Drupal 7 site with Sqlite on my dev machine. When I go to localhost/install.php it says: Drupal is already installed.

After deploying the whole bunch to shared hosting (windows) the install.php is available again although the site works. It is even available to anonymous users and when the site is in maintenance mode. What should I do to disable that? Or should I deploy another way?

What the installer checks for, is whether or not the settings file has database information for the site.

While this sounds simple in theory, and shouldn't lead to install.php being executed, there are many components involved.

There's DNS, which may or may not respond to various sub-domains.
There's the webserver configuration, which may or may not serve sub-domains, and may or may not re-write them before they hit Drupal.
Drupal, since 7, supports a sites.php file which can map domains to sites/ directories.
Finally, there's the sites directory itself, where Drupal can find a settings.php file, check for a valid $db_url, and decide whether or not to allow installation.

Due to the many components, and the technical complexity of setting them all up right, it's very easy to end up in a situation where install.php decides to allow installation. This should generally not be a problem, as anonymous users should not be able to create new databases, but it looks quite wrong regardless.

While removing install.php is a solution, it's technically hacking core, and makes future deployments needlessly complicated.

I normally do two things to counteract this.

The first thing is to run the site from a directory named after the domain, such as sites/example.com/ and make sites/default a link to the main site. This way, any unexpected domains being requested by Drupal will be served by the main domain.

Second, I always just block access to install.php completely on any production systems with this vhost file:

# ssh -L 8080:127.0.0.1:80 example.com
<Location /install.php>
  Deny from all
  Allow from 127.0.0.1
</Location>

<Location /update.php>
  Deny from all
  Allow from 127.0.0.1
</Location>

This ensures apache blocks access to both install and update. The comment at the top is a reminder for how I can open an ssh tunnel to the server so my traffic looks like it's coming from 127.0.0.1, thus allowing developers access to run update.php.

Something similar in IIS below. Note that I have not tested this. Someone with ISS experience, please update or comment so I can improve this part.

<location path="install.php">
    <system.webServer>
        <security>
            <authorization>
                <remove users="*" roles="" verbs="" />
                <add accessType="Allow" roles="Administrators" />
            </authorization>
        </security>
    </system.webServer>
</location>


how to add credits each month with rules? How do I add commerce credits to a specific type of user the first in every month? I cant seem to find a date field in rules-->add rule-->events

Check out Rules Example which is an example module showing how to integrate custom module with rules.

You can add a new parameter (e.g. condition - check if this is first day of the month) and perform all checks/actions you need there.


Clone a SelectQuery instance : what am I doing wrong? I've got a SelectQuery which I've created using db_select(). Then, after I've executed the query, I'm trying to clone it as I need to generate a few more queries based on the original one.

However, for some reason the clones I get from the original query doesn't seem to be clones. This is what I do.

// Create query
$q0 = db_select('track', 't');
$q0->fields('t', array('id','number','title');
[...]
$tracks = $q0->execute()->fetchAll();

// Clear fields on original query.
$fields = &$q0->getFields();
$fields = array();

// Clone original query. The below queries should not have
// any fields set as they just got cleared above.
$q1 = clone $q0;
$q2 = clone $q0;

// This gets weird. The queries $q1 and $q2 should be separate
// clones, independent of each other. So should their fields.
// However, setting fields on $q1 also sets fields on $q2.
$q1->fields('t', array('id'));

// Output : Array ( [id] => Array ( [field] => id [table] => t [alias] => id ) )
print_r($q2);

The fields() function on SelectQuery simply sets an array (see below). I thought that cloning an instance of a class containing an array would copy those arrays by value...and not by reference? Is this a special cloning "feature"?

protected $fields = array();

public function &getFields() {
  return $this->fields;
}

As you have seen in bug report #1671848 the special getters of these special drupal objects breaks the clone behavior. The problem is that by reference getter are used and this imply hazardous behaviors in PHP internals of returned values.

I think it will be quite very long until this bug get fixed. So one of the solution is to avoid such writings:

$fields = &$q0->getFields();
$fields = array();

This is not the way to empty something in an object. here the & is the fault. after such a write the internal array stored in the object is broken and the object record it as a reference, you've been breaking object encapsulation and bad things happen (sse the bug report). Use a setter, And if there is not setter to do that clone the queries before havinf any field added to the query (so it's empty).


"access ckeditor" permission missing - buttons inactive I have my ckeditor basically up and running. Users with the role 'editor' however can see and use it, but the buttons appear to be inactive. Just the "Source" and "Format" are accessible for editors.

And in under permissions > ckeditor I have no permission for "access ckeditor". Any help / pointers welcome! Thank you!

ps: Editors do have permission to use the related text format "full html".

Thank you for your suggestions. I suppose it probably is some permissions problem. I now granted the "Customize CKEditor appearance" permission for the role Editor and the toolbar is now functional. However it leaves me puzzled why this paprticular permission would trigger whether a user / role is allowed to use the toolbar buttons or not.

Customize CKEditor appearance
Allow users to customize CKEditor appearance.

Either it's a wording problem and granting that permission is the right thing to to – or I now actually have granted permission to customize the CKEditor appearance (as the wording would suggest) and I have a slight security problem However – i'll submit a request for support issue over at drupal.org and edit this post once I know more…
PS: Even thought this question might leave the impression – it's not my first time on drupal. It's just the first time I'm using CKEditor instead of WYSIWYG.


Update payment method pane with ajax I have the coupon pane, the order review and the payment info panes all on the same checkout page. When I add a coupon, an ajax callback is fired and the order summary is automatically updated to reflect the coupon, but the payment info pane is not updated.

I have a rule for two payment methods. One for non-zero order totals, and one for zero total orders. If I add a coupon that brings the total to zero, and then refresh the whole page, the rule action does apply and enab;es my 'free' payment method. However, it only works with a full refresh.

Is there a way to get the payment info pane to refresh during the coupon add ajax callback?

Otherwise, my customers see a zero total and they still see the payment info that requires them to put in a credit card to finish the order.

You may need to trigger a page refresh from the ajax?  I'm not entirely sure if you would be able to load the individual pane.


Error: Call to a member function addWhere() on array in hook_views_query_alter() I'm getting the error 'Call to a member function addWhere() on array' in my hook.
Any thoughts?
I just need to add WHERE clause to my query.

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implementation of hook_views_query_alter
 *
 * @param $view
 * @param $query
 */
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'search_filter' && $view->getDisplay()->display['id'] == 'block_1') {
    $field = 'node__field_country.field_country_target_id';
    $value = 'somevalue';
    $operator = '=';
    $query->addWhere(0, $field, $value, $operator);

Try to add your condition to conditions array in the where  $query->where like the following:

/**
 * Implements hook_views_query_alter().
 */
function myModule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() === 'search_filter' && $view->current_display === 'block_1') {
    $field = 'node__field_country.field_country_target_id';
    $value = 'someValue';
    $operator = '=';
    if (isset($query->where[1]['conditions'])) {
      $query->where[1]['conditions'][] = [
        "field"    => $field,
        "value"    => $value,
        "operator" => $operator,
      ];
    }
  }
}

Read this Article it's very useful.


Best way for implement 'Site Gate' I try to add 'site gate' to http://bartenderlab.it.
It's alcohol content so people under 18 are not allowed to view this site.

I created module with hook_init:

function gate_init() {

    $curr_uri = request_uri():
    if (strpos($curr_uri, '/gate') === FALSE) {

        if (! isset($_SESSION[GATE_SESSION_NAME])) {

            if (! isset($_COOKIE[GATE_COOKIE_NAME])) {

                    if(strlen($curr_uri) > 1) {

                        drupal_goto('gate', array('destination' => substr($curr_uri, 1)));

                    }
                    drupal_goto('gate');

            } else {

                $_SESSION[GATE_SESSION_NAME] = TRUE;

            }
        }
    } else if(isset($_SESSION[GATE_SESSION_NAME])) {

        drupal_goto('<front>');

    }
}

Under /gate url is form with:

function gate_form_submit($form_id, &$form_state) {

    $post = $form_state['values'];
    $day = intval($post['gate_day']);
    $month = intval($post['gate_month']);
    $year = intval($post['gate_year']);
    $isRemember = $post['gate_remember_me'];
    if($day && $month && $year) {

        $allowed_age = (int) variable_get('gate_minimal_age', 18);
        $min_born_time = mktime(0, 0, 0, date("m"), date("d"), date("Y") - $allowed_age);
        $born_time = mktime(0, 0, 0, $month, $day, $year);

        if($min_born_time >= $born_time) {

            $_SESSION[GATE_SESSION_NAME] = TRUE;
            if($isRemember) {

                setcookie(GATE_COOKIE_NAME, sha1($born_time + srand()), time() + 60 * 60 * 24 * 7, '/');

            }
            $dst = '<front>';

            if(isset($_GET['destination'])) {

                $dst = $_GET['destination'];

            }

            drupal_goto($dst);
        }
    }
}

If checkbox for $isRemember is not checked user should only view site until browser close.

so I set:

ini_set('session.cookie_lifetime',  0);

in settings.php

But after restart browser gate page doesn't appear.

Also after user logout I am redirect to gate page instead of front page.

Please help.

Have a look at Disclaimer module; it seems to be the functionality you're looking for.


How to add more image styles to an image element in a content type I have a image field in my content type. In that field the images should be saved in two image sizes. As an example when I uploaded a photo it should save as two photos. One for 200x200 px and one for 360x360 px.

When I change the function settingsForm(array $form, FormStateInterface $form_state) in ImageWidget.php as below it applies to the all image tags in content types.

public function settingsForm(array $form, FormStateInterface $form_state) {

    $element = parent::settingsForm($form, $form_state);

    $element['preview_image_style'] = [
      '#title' => t('Preview image style'),
      '#type' => 'select',
      '#options' => image_style_options(FALSE),
      '#empty_option' => '<' . t('no preview') . '>',
      '#default_value' => $this->getSetting('preview_image_style'),
      '#description' => t('The preview image will be shown while editing the content.'),
      '#weight' => 15,
    ];

    $element['main_image_style'] = [
      '#title' => t('Main image style'),
      '#type' => 'select',
      '#options' => image_style_options(FALSE),
      '#empty_option' => '<' . t('no preview') . '>',
      '#default_value' => $this->getSetting('main_image_style'),
      '#description' => t('The main image will be shown when opening the popup.'),
      '#weight' => 14,
    ];

    return $element;
}

I need to do this only for a selected content types selected image field. Is there a way to do this?

Instead of altering the default field widget of the image fields, you should create an own custom field widget.

You may either extend the existing widget, or create it from the scratch by copying the image field widget's code to your own widget.

Then you will be able to just select that widget for your images that require two image styles to be selected, while other image fields can still use the default widget.

Edit:

For defining the different image styles for output to the end user (within your slider), you will be better off to creating a custom field formatter with according settings and output and choosing this formatter in "Manage display" of your content type. A good starting point once again is the existing field formatter.


How to proceed towards MySQL performance testing for Drupal? We have lots of Drupal sites installed on our server. Some of the sites do have lots of views and blocks configured on it.   Occasionally, one of such Drupal site (with lots of views and contents) suddenly becomes unresponsive or very slow. But rest of the Drupal sites with less contents appear to work fine during that time. We have to restart MySQL database in order to bring unresponsive Drupal site back to normal. We were thinking of setting up a periodic MySQL restart using cron.

This periodic restart option do not appeal to me very much. I want to find the cause of this problem. I suspect that it is mostly because of MySQL, but still it is a guess.

I am not experienced in the server performance issues. What is the best way I should tackle this problem? How can I confirm that it is a MySQL problem and not because of other? If it is a MySQL problem, what basic steps I should take to solve it?

First tool, that can be used, is Devel - it will show there's long calls have been made.
And there's many tools for perfomancing and tuning mysql in internet.


How do I get the modified field value of a VIEW I have a VIEW which pulls on the content field of a type. I specified I want the rewrite rules to trim to 25 characters with an ellipsis.

Unfortunately I also override the template (views-view-unformatted--XXX.tpl.php) and when I echo out the structure of the entire node and entity in template.php I see nothing of a modified field -- only the full data.

How do I adhere to the requirements of the field set in the VIEW?

I am not exactly sure of what your are looking for. When I need to change the output of a field I usually change the $view->result for the field in hook_views_post_execute.


Illegal choice error in views exposed filter select list My question is related to Drupal 7 Views Exposed Filter - How to Select all Taxonomy terms Upon adding new terms? however I have a different problem. I want to filter a view by users of specific roles and for that i have added the user field in views filter and exposed it.

The problem is that if i check "select all" in "options" and leave "Limit list to selected items" unchecked, the select shows "--Any--" as default selection and also includes any users added later but throws "An illegal choice has been detected. Please contact the site administrator" and does not load any views.

On the other hand, if i check "Limit list to selected items" in options it shows no error but then it will only load the selected users in options and not any user added later. The field "check_user" has a field collection relationship. How to solve this? Is this a bug or misconfiguration?

Using views 3.8 and Drupal 7.32

[EDIT]

I managed to remove the error by deselecting the "select all" option and checking all the users, this way the select list filter include the checked users in exposed filter and also any user added later. The select filter also provided "--Any--" option but when I first load the view, the first user in the list is automatically select instead of "--Any--". How to default the select filter to "--Any--"?

Don't choose select all option (it is a simple javascript effect to choose the values) or don't select any user from list. If you just choose expose the filter option it will display all the users list automatically.


How to execute some js code after click on exposed filter AJAX enabled submit? I have tried to update the input value of an exposed filter field before submit of the exposed filter through Js.

What I have tried

$('#edit-submit-phrases').on('click', function() {
  alert('check');
});

No alert message.

I also tried:

jQuery('#edit-submit-phrases').mousedown()

You can use the ajaxStart() function, to execute something before  Ajax request begins:

 Drupal.behaviors.<themename/modulename> = {
  attach: function (context, settings) {
    $('#edit-submit-phrases').on('click', function() {
      $( document ).ajaxStart(function() {
        alert('check');
      });
    });
  }
};


Accessing Drupal REST endpoint using Oauth 2 token I have successfully installed the Simple OAuth module on my website. I am also able to authenticate to it using Postman. I am getting the access_token and the refresh_token when authenticating. However, am not able to figure out how I can use this token to access Drupal's default REST endpoints or the endpoints provided by JsonAPI module.

I tried sending the token in the header with Authorization as key and Bearer {{the token }} as the value with no success. What is the right way to use the token for communicating with Drupal?

Just follow the steps given in https://dev.acquia.com/blog/decoupled-drupal-authentication-oauth-20, once you get the access token in postman you will also see tokens for the user details you have given at admin/config/people/simple_oauth/oauth2_token.  Just copy the access token from postman and add it to Access Token field of Authorization tab(New version of Postman) by selecting Type as oauth2 (Dont't use the access token from the path given above).

Also make sure in permission page under RESTful Web Services section you will see your custom api listed and permission for authenticated user was given.

I followed the same and it worked for me.


Dynamic menu links using menu token I'm trying to build a menu which has term id(tid) token in it to the views pages I have created. Menu links work when on taxonomy/term page but when menu links are clicked and url is changed to the views page, menu token can't get term id(tid) from that page, so menu links don't work. Basically menu structure is like this;

Menu on taxonomy page:

   views page 1 (url: /project/%1/venues) menu path: /project/[term:tid]/venues
   views page 2 (url: /project/%1/program) menu path: /project/[term:tid]/program

Contextual filter used: taxonomy term id from url where %1 is term id.

If I understand your scenario correctly, have a look at the Taxonomy Menu module.  This is what I use to create dynamic views, where the display is dependent on the menu item clicked.
(The menu passes in that value -- e.g., city name -- as an Argument/Contextual-Filter.)

Taxonomy Menu:

Custom Menu per vocabulary.
Uses the default taxonomy term path or custom paths.
Integrate with Views.
Integrate with Pathauto: use URL/path aliases.
Does not interfere with other menu modules.


Better way to manually load a view of nodes other than with "views_get_view_result" > "node_load"? I've got a d7 site on a shameful shared hosting account.

Since I am a pseudo haxxor, I want to load up my front page view and manually output all of my nodes.  My Front Page takes about 30 seconds to load in the worst case.  I am tears.

Here is what I am doing:

$view = views_get_view_result('main_feed');
foreach($view as $item){
    $node = node_load($item->nid,NULL, TRUE);
    /* assorted display code */
}

Any thoughts?  2.7 trillion thanks to all!

EDIT:

Well @Druplaist was right - this SHOULD work - after reading my own question I thought "If somebody else were asking this, I'd suggest that the problem was inside of /* assorted display code */ - and it is - probably some truncating method I grabbed.  It's still Drupal slow, but not 30 seconds till the server gets back to me slow.

Thanks for answering my stupid question, people!

Since you need to load all of the nodes on your front page, Not that much difference does it make how you implement it, whether using code or loading View in a page or block or ....

views_embed_view do the same thing and loads a View but it doesn't reduce the load size!

I recommend you to to use Ajax. The Views Load More module is exatcly what you need. This module

Provide ajax/no-ajax views load more
Works with views default ajax implementation, no hacks (check/uncheck ajax)
Supports the Waypoints module for loading on various points, Such as when the scroller is visable on the page.
Supports the Fade effect when loading new content.

Instead of loading all of your content, simply just load 100 or 200 of them then use Ajax to load more.

Views Show More module is another solution. This module

Works both views ajax and no-ajax mode (developed mainly for the ajax mode).
Option for result display method. Can choose Append or Replace method.
Option to override 1st page or initial item count than others page.
Basic and advance animation system for result impression for ajax mode.
Ability to define custom animation timing.
Advance settings for content area and pager area selector. If default html

In the aggregate, create a View of all of the content types that their nodes must be included in the front page, include that view in the front page and use one of the above modules to use load more.


Does  Drupal have an AJAX solution for search results, preferably with Apachesolr integration? Specifically, I'm referring to being able to have the top 5 search results display as options in a drop down menu while the user types in a search query, somewhat similar to how node reference autocomplete works. It would be great to have such functionality work with Apachesolr.

Depending on your needs, there are a couple of solutions.  Probably the closest thing to Apple's Live Search feature is the Finder module.  It does not integrate with Apache Solr at this time, however.

I would also keep your eye on the Inline Ajax Search module as Solr integration is on the roadmap.  It might need some contributions to push integration through.

A third solution to try is the Apache Solr AJAX module.  It might not fit exactly what you are trying to do, however it allows for inline refreshing of the page when queries are entered and filters are enabled.


Upload multiple files (with multiple attr) in custom form: how to get files? I've made a form. Now I want it to upload files. I've made a form element to do that:

  $form['attachments'] = array(
    '#type' => 'file',
    '#title' => t('Attachments'),
    '#name' => 'attachments[]',
    '#attributes' => array('multiple' => ''),
  );

I've set #name and #attributes.multiple because I want to use the HTML5 multiple files upload thingie. They invented that for a very good reason. I assume Drupal knows how to handle that.

How do I get the files in the submit handler? I don't want to save them to the file system. I want to e-mail them.

Ofcourse (?) I can just query $_FILES, but even I think that's not right in a framework like Drupal.

Is there a better way?

I haven't tried HTML5 Upload yet, but it might help you out.


How do I change '|' to '-' in HTML page title? I wan to change the HTML page title: It is displayed as "pagename | sitename"; I want to change it to "sitename - pagename."

How can I do this?

I would have used existing $head_title_array variable like this:

<title><?php print $head_title_array['name'] . ' - ' . $head_title_array['title']; ?></title>

Reference: html.tpl.php

You can also do this with the Metatag module.


Cannot log in site despite having credentials from settings.php Ubuntu 16.04, Drupal 8 managed through ISPConfig 3.1

I'm trying to log in at mysite.com/index.php/user/login and I get bad username or password. I have copied and pasted from the settings.php file and everything.

This is a box that was setup for me by someone else who, when asked for the credentials, directed me to just get them from settings.php.

The only thing I can think of is that I'm somehow getting a site-login instead? But it's a fresh Drupal 8 install with no config.
Is there any other source for the password or alternate password for it?

I've tried going through ISPConfig and changing the database password there but it just breaks the whole site:

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

So I just revert to the snapshot.

Okay I see what happened now.

I was trying to login to Drupal and not to the database, but I was getting the DB password from settings.php.

On the Drupal sites I setup in the past I used the database user and password as the Site Maintenance Account’s credentials, so I’m used to them always correlating. Since someone else set this one up they put the user and pw to something different. It's probably a security hole to do it the way I was doing it so I guess I need to fix that.


How to assign roles to grant permissions to update particular pages? I have a menu like Publications, About us , Services and i want to assign a roles to the users like one user can update the content of about us and other can services means need to give permission for specific pages.

Is this is possible?

Some more details about what I'm trying to do: I do not want to give the permission to whole content type (that is not required). I want a user wise permissions like I have a role named ouroffice-user. Then under this I have a 10 users and I want to allocate different permissions to these 10 users like no. 1 have a permission to update the welcome content and no. 2 have a permission to update the about us page all users belong to single role that ouroffice-user.

The Group module allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

Group creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Group provides an extensive API to attach entities to groups.

For way more details about this module, such as how to configure it or available integrations with other modules, refer to my answer to "What are the alternatives for the Organic groups module?".

For this specific question you'd only need 1 Group Type, with 1 Group (of that Group Type) for each set (= collection) of "Specific Pages" (as in your question). BTW, available for either D7 or D8.

Have a look at the Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site". Even though it is about D8 (already), the key concepts of it are the same as in the D7 version. Maybe also review the answers to various questions around here tagged with the group tag.

Some more details about this part of your question:

  Some more details about what I'm trying to do: I do not want to give the permission to whole content type (that is not required). I want a user wise permissions like I have a role named ouroffice-user. Then under this I have a 10 users and I want to allocate different permissions to these 10 users like no. 1 have a permission to update the welcome content and no. 2 have a permission to update the about us page all users belong to single role that ouroffice-user.

Be aware that "roles" in the Group module are different from the typical (standard) roles in Drupal. For more details about the various roles and permissions that can be configured, refer to my answer to "What are the various roles supported by the Group module?".
Assume you create a custom Group role like "content manager". And you allow members with this group role to edit nodes of content type ABC.
From those 10 users (in your comment), those that correspond to your "no 1" should become members of some group (say titled Group no 1), in which they receive access to that Group role "content manager". And assume you create a similar group titled Group no 2, for those that correspond to your "no 2" users.
Using the gnode submodule you assign the nodes such as Welcome to the Group no 1 group and About us is assigned to the Group no 2 group. Note that it doesn't matter what the content types are (if they are the same or not), which is part of the beauty of the Group module.

Done ... really! Give it a try to get the idea ... those who try, love it ... after they get it ...


How to uncheck a checkbox programmatically? How can I uncheck a checkbox programmatically in Drupal 8.
I need this in an ajax call, when an option is selected, a checkbox must be unchecked

After a lot of trial and error, I found out:

Imagine a checkbox with name 'Coffee' has one option: ['Y' => 'I want an espresso'].

To uncheck this selection, enter:
$form['Coffee']['Y'][#checked]=false


View inside display suite block field - contextual filter using display suite's block field, which i chose a view block.. so when i have view page ('parent' view) it list many nodes. each node has a field for block view ('child' view).

how do i get child view to filter its results by the node id it is being displayed with in parent view?  like a contextual filter, but not getting nid from url, but the node the block field is part of.

i like using display suite layouts, but need to rewrite the author field link. so i figure id make view to show the author and rewrite, then insert it into the node view mode as field. but i cant filter the child field how id like.

You should use Display Suite Dynamic Field instead of Block Field.

It allows you to select a view and pass the appropriate contextual filter arguments.

From Dynamic Field documentation:

  A dynamic field can be used in combination with the Views Content Pane
  submodule of Ctools to pass contextual arguments to a view. Steps:

  Install Ctools, Views, and Display Suite.
  Enable the Views Content Panes module and Views UI.
  Create a new view. Add a contextual filter--for example, node NID. Add a content pane display. Configure the "arguments" argument of the
  display to enable the exposed filter you added. For example, select
  "From context" as the source of the argument and "Content ID" as the
  context.
  Create a dynamic field.
  Under manage display for a given content type, configure the dynamic field to use the views content pane you configured.


FormState getValue on checkbox elements in hierarchical / tabular form structures broken? I can't seem to retrieve correct posted checkbox form element values using an array-style key in a call to the FormState::getValue method. If I flatten the elements into a non-nested structure, the getValue method works. But, I need to lay out the components using a table form element. The values that I get back (empty or "0") do not match the actual user-checked box states by the time they post in submitForm. I've also tried a zillion variants of reversed #parent array hints, #array_parent hints, #return_value, etc. It feels like there may be a bug in the getValues method in how it handles array-style keys? Or, am I doing something dumb?

class DataFsFolderSharingForm extends ContentEntityForm {

  // … stripped down to the bare essentials...

  public function buildForm(array $form, FormStateInterface $form_state, DataFsFolderInterface $folder = NULL) {
    // Documentation for for element attributes (eg: '#parents’, '#array_parents’, '#return_value’, etc):
    //   @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21FormElement.php/class/FormElement/8.2.x

    $form = [];
    $form['#tree'] = TRUE;

    // Show the current access settings as a table.
    //   @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Table.php/class/Table/8.2.x
    $form['access'] = [
      '#type'    => 'table',
      '#caption' => $this->t('Sharing Access'),
      '#header'  => [
        $this->t('User Email'),
        $this->t('View'),
        $this->t('Edit'),
        $this->t('Operation'),
      ],
      // '#array_parents' => array( 'access' ),
      // '#name' => 'access',
    ];

    // Non-nested element structure doesn’t break getValue method.
    $form['flat'] = [
      '#type' => 'checkbox',
      // '#name' => 'check-2',
      // '#return_value' => 1,
      // '#default_value' => 1,
      // '#array_parents' => array( 'flat' ),
    ];

    // Nested element structure breaks getValue method.
    //   @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Table.php/class/Table/8.2.x
    $form['access'][0]['view'] = [
      '#type'          => 'checkbox',
      // '#name' => 'check-1',
      // '#return_value' => 1,
      '#default_value' => 1,
      // '#array_parents' => array( 'access', 0, 'view' ),
    ];

    // ...more table elements added, who's rows are indexed by the middle integer array value...

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // The non-nested getValue returns the correct checkbox state (checked or unchecked).
    $checked = $form_state->getValue('flat');

    // The nested getValue returns the incorrect checkbox state (checked or unchecked).
    //  @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AgetValue/8.2.x
    $checked = $form_state->getValue(['access', 0, 'view']);

    // Also tried ['access', '0', 'view’ ]
    // Also tried ['view’, 0, 'access’ ]
    // Also tried ['view’, '0', 'access’ ]
    // Also tried setting '#parents’ form element attribute.
    // Also tried not setting '#array_parents’ form element attribute.
    // Also tried reversed version of '#parents’ form element attribute.
    // Also tried reversed version of '#array_parents’ form element attribute.
    // Also tried setting '#return_value’ form element attribute (using 1, 0, TRUE, FALSE, '0’, '1’, etc).
    // Also tried setting '#default_value’ form element attribute (using 1, 0, TRUE, FALSE, '0’, '1’, etc).
  }
}

Anyone still having this problem please allow collections of form elements using #tree set to TRUE. Its applied to the "parent" element, as the #tree property cascades to sub-elements. Use where you previously used in form calls. See D7 #tree and #parents on drupal.org.
Solution
Example for above case, change $form['#tree'] = TRUE; to $form['access']['#tree'] = TRUE; then the value will be obtained using $checked = $form_state->getValue(['access', 0, 'view']);.


Filedepot - Where is the file management interface? I have installed the module and additional libraries as required in the README but I don't see where the file management interface is. Can someone give me the link or point me to the right direction?

Looking at the hook_menu() implementations for Drupal 6 and 7 these two paths stick out:

Filedepot ( http://mysite.com/filedepot )
Filedepot Settings ( http://mysite.com/admin/settings/filedepot )

The rest of the paths defined are variations on the above, or AJAX callbacks, so I think one of those is the path you're looking for.


Setting date-based filter criteria in Views All,

I have created a Content Type which includes a field of type Date. I would like to create a Views filter such that only those nodes whose date falls within the current month are selected. Can someone please show me how to accomplish this.

Thank you.

I did some more digging and believe that the best approach is to use PHP Views. I installed the module, wrote my 'challenging' code, but am not getting the expected results.

For debugging purposes, I created the following output field code:

<?php
$field_forumdate = $data->_field_data['nid']['entity']->field_forumdate['und']['0']['value'];
$forumdate=strtotime($field_forumdate);
$currdate=time();
$nc = date('n', $currdate);
$nf = date('n', $forumdate);
$tflag = 'false';
if ($nc == $nf) {
  $tflag = 'true';
}
print 'Current month: ' . $nc . ', Forum month: ' . $nf . ', tflag: ' . $tflag;
?>

I created three Content types, and set the ForumDate fields to dates in October, November, and December. Looking at the preview, I see the following:

Current month: 12, Forum month: 12, tflag: true
Current month: 12, Forum month: 11, tflag: false
Current month: 12, Forum month: 10, tflag: false

Next, I created my filter code - which is identical to the above:

$field_forumdate = $data->_field_data['nid']['entity']->field_forumdate['und']['0']['value'];
$forumdate=strtotime($field_forumdate);
$currdate=time();
$nc = date('n', $currdate);
$nf = date('n', $forumdate);
if ($nc != $nf) {
  return TRUE;
}

The problem is that all three nodes are still being returned, i.e., the filter does not seem to be filtering. Please help!

Hope this will help,Create a view, Add a FILTER CRITERIA on content date field
select the following option

It will return all content which is lies on current month for the respective date field. Good luck


Impossible to update some modules via Composer I've updated a D8 website from 8.7 to 8.8.1 with SSH and composer.
For some modules (in SSH 3rd column is marked in yellow) it is not possible to update them. I understand that when they are marked in yellow some dependencies are missing?

The rest of the modules are updated successfully.

Below the list of modules that needs an update (3rd column is marked in yellow):

drupal/blazy         1.0.0-rc5 2.0.0-rc6 Provides basic bLazy integration for lazy loading and multi-serving images.
drupal/file_mdm      1.1.0     2.0.0     Provides a service to manage file metadata.
drupal/file_mdm_exif 1.1.0     2.0.0     Provides a file metadata plugin for EXIF image information.
drupal/file_mdm_font 1.1.0     2.0.0     Provides a file metadata plugin for TTF/OTF/WOFF font information.
drupal/slick         1.2.0     2.0.0     Slick carousel, the last carousel you'll ever need.
drupal/slick_views   1.0.0     2.1.0     Provides Slick carousel integration with Views.

In composer.json: slick and slick_views are added. Other above modules are not located in the composer.json:

{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "php": ">=5.6",
        ...,
        "drupal/field_group": "^1.0",
        "drupal/slick": "^1.1",
        "drupal/slick_views": "^1.0"
        ...,
    },
    "require-dev": {
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": ["load.environment.php"]
    },
    "scripts": {
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "enable-patching": true,
        "composer-exit-on-patch-failure": true,
        "patchLevel": {
            "drupal/core": "-p2"
        },
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/Commands/{$name}": ["type:drupal-drush"]
        },
        "drupal-scaffold": {
            "initial": {
                ".editorconfig": "../.editorconfig",
                ".gitattributes": "../.gitattributes"
            }
        },
        "patches": {}
    }
}

With these commands: nothing to install or update

composer update drupal/slick --with-dependencies
composer update drupal/slick

In the backoffice D8 (/admin/modules/update) it reports that field_group needs an major update.
That is not reported via SSH:

composer outdated "drupal/*"

I've tried to remove "field_group" to reinstall it:

composer remove drupal/field_group
...
composer require drupal/field_group
...
Using version ^1.0 for drupal/field_group

Why is it not using version: 8.x-3.0-rc2?

I've removed the vendor folder.
I've removed the composer.lock file.

What can I do to update the site to have the latest versions applied for the above list of modules? Simply removing and reinstalling is not working.

Major version changes contain breaking/incompatible changes in SemVer / Semantic versioning. If you would update them, it would break modules that depend on the old version. Therefore most projects lock composer entries to one specific major version number. Also doing a default composer require vendor/project - without denoting an explicit version number - will create an entry locked to the current major version number.

The common way for a major version change is to explicitly composer require a new major version, but this usually means manually doing extra upgrade/migration steps outside of composer.


How to pass data between operations of a single Batch? Is there any way to pass data between operations of a single Batch, when using Batch API ?

for an example, say I have $batch['operations'] as an array like this:

// Basic batch stuff to $batch here.
$batch['operations'] = array(
  array('my_initialize', $xyz),
  array('my_worker', $data),
);

// batch_set, process, etc.

function my_initialize($xyz, &$context) {
  // Can I process something here and pass it to
  // the operation 2 (my_worker) ?
  // May be some key in $context ?
}

function my_worker($data, &$context) {
  // How I can access some result from the my_initialize() function ?
}

I know I can set $context['sandbox'] but that's related to a second call if I set $context['finished'] = FALSE;

I'm currently storing data (it's some kind of chemistry formula which is expensive to store in the operation itself or calculate before batch_set) in $_SESSION in my_initialize and unset it in finished function but I'm curious is there any better way to do this.

Thanks David for your answer. But unfortunately $context['sandbox'] values were not retained through operations - they were retained through iterations of the same operation but not between operations.

Interestingly though, I found that $context['results'] values were retained between each operation.
I did a simple test using the following module:

<?php
function mytest_menu() {
  $items = array();
  $items['admin/content/mytest'] = array(
    'title' => 'mytest',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mytest_form'),
    'access arguments' => array('administer content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function mytest_form() {
  $form = array();

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

function mytest_form_submit($form, $form_state) {
  $batch = array(
    'title' => t('Working ...'),
    'operations' => array(),
    'finished' => 'mytest_batch_finished',
    'init_message' => t('Starting ...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'progressive' => FALSE
  );
  $batch['operations'][] = array('mytest_initialize', array('test data'));
  $batch['operations'][] = array('mytest_perform', array('different data'));
  $batch['operations'][] = array('mytest_perform', array('different data'));
  $batch['operations'][] = array('mytest_perform', array('different data'));
  batch_set($batch);
  batch_process('admin/content/mytest');
}

function mytest_initialize($d, &$context) {
  dsm($d);
  $context['results']['test'] = 'inti val';
  $context['test']['test'] = 'init val';
}

function mytest_perform ($d, &$context) {
  dsm($context);
  $context['results']['test'] = uniqid();
  $context['test']['test'] = $context['results']['test'];
}

function mytest_batch_finished($success, $results, $operations) {
  dsm($results);
}

After the batch finished, I could see the dsm()'d messages. voilà: values were retained.

http://i.stack.imgur.com/tkAXx.png

It seems like only $context['results'] was given to the next operation. Arbitrary keys ($context['my own key'] for example) didn't work.

Hope someone will find this useful :)

PS: *previous not previos (screenshot).


Add more and remove fieldset I created one content typa and I put one fieldset group through Field_group module, but I can't see settings to add more fieldset. I've 6 fields per fieldset. But I'm not able to do the same with fieldset. It can be done with particular field only.

You can add more fieldset by Add new group option available in Manage field page, please find the below screenshot..

And you can drag and drop the filed inside the fieldset as you required


Automatically Fill a Second Term Reference Field in a Node Based On Filled Value from a First Term Reference Field Given the following...

A vocabulary (let's call Vocab1) with terms that each have an added term reference field referencing a single term from another vocabulary (let's call Vocab2).
A node that has two term reference fields, the first for a single term from Vocab1 and the second for a single term from Vocab2

would it possible to automatically fill the second term reference field from Vocab2 based on what's is filled in the first term reference field containing a term from Vocab1?

Have look at the following modules

Reference field option limit

  This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

Hierarchical Select

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.


How can I limit the taxonomy terms of certain nodes? I have a content type that can have unlimited taxonomy terms. However those taxonomy terms should be unique to each node ID.
Since the user will create the taxonomy terms, should I write a "nid" field with each taxonomy term, or is there a better way?

Write a module that implements hook_node_validate. The implementation of that hook can check the integrity of the term associations by calling taxonomy_select_nodes and report any inconsistencies by calling form_set_error.

Beware of the limitations of taxonomy_select_nodes:

  This function requires taxonomy module to be maintaining its own tables, and will return an empty array if it is not. If using other field storage methods alternatives methods for listing terms will need to be used.


Is there any way to combine views block to homepage? Is there any way to combine views block to homepage?

Example:
I created different views blocks like team, about us, portfolio, services and sliders.

The first homepage has about us, portfolio and services.

The second homepage has team, services and sliders.

I can set one of them to front page without adjust the arrangement of views block in structure/blocks.

How do I make the changes of frontpage more efficiently with just change it to first homepage or second homepage?

I am not sure which Drupal you are using. But the procedure is pretty same for D7 & D8.

Normal Drupal Approach:

1. Create a block/views-block and set it's visibility to  as shown below, do it for all blocks which you want to show on front.

2. Go to Structures/blocks & place all views-blocks/normal-blocks under the content region as shown in following image, in order in which you want to display.

3. Front page: Now, all three blocks with their content are visible only on the front page as shown below.

For Second-home page: Do the same thing as above just apply the visibility to second-home-page url in the first step.

Using Panels module

You can use Panels module to get more settings, but if your purpose serves with above approach, do not add extra module in your site. But with Panels module, you can achieve any display setting what you can think of.


How to add placeholders in customized module? I am new to drupal, currently I am creating a new module for forms. Inside of module I have added the code as follows .

$form['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    );

In this case I wanted to use place holders for text fields. So how can I do ?

what do you mean by placeholders? a default value that prefills the textfield or some watermark text that disappears when you focus the textfield?
for a default value you can use the #default_value key in the text field definition.

for a watermark i recommend the Placeholder module. the module enables you to use a #placeholder key in your field definition.

cheers
j


How to theme title field Normally when I theme a field, I use a template suggestion in format field--fieldname--contenttype.  However, it doesn't seem to be possible to do this with the node title.  I've tried both of the following template suggestions:

field--title--contenttype.tpl.php
field--field-title--contenttype.tpl.php

Neither of them work (I've cleared caches).  The title isn't technically a field, since it's more like a property on the node object, so that may be the problem?

Is there any way to theme the title field?  It feels like I'm missing something simple.

N.b. I'm using panels and have dropped the node title pane into the panel but need to theme it differently.

You could use the Title module to convert your title to a proper field. Following that, your template file should work.


What's the default weight of a form's submit element? The following code is fairly standard for adding a submit button to the bottom of a form:

// Submit button.
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
);

It always appears at the bottom of the form so I assume it is assigned a 'heavy' #weight by default. Does anyone know its default value?

A submit button appears at the bottom of the form usually because it's simply added last in the form definition.

A submit button can still be placed anywhere and weighted using the #weight property.

The default weight is assigned automatically.

The relevant core code is in

form_builder

// Assign a decimal placeholder weight to preserve original array order.
if (!isset($element[$key]['#weight'])) {
  $element[$key]['#weight'] = $count/1000;
}
else {
  // If one of the child elements has a weight then we will need to sort
  // later.
  unset($element['#sorted']);
}

If not present the#weight property is calculated dynamically based on the count/item position while looping over the form element set.


Is there a drupal hook that I can use to redirect a user to an interstitial page for the first page view? If not then how can I accomplish this? I am currently in the process of developing a custom module that will redirect a user on entry to an interstitial landing page.  This page will closely replicate how forbes.com functions.  The landing page itself is a page template within the custom module that displays a view, an ad, and links back to the originally requested page. All of the pieces are in place and function as intended except for the hook when caching is enabled. After researching hook_boot, hook_init, and hook_page_alter, I have found that none of these are working when caching is turned on or in the case of hook_boot because drupal functions were not loaded when the hook was called.  I feel hook_boot is the closest solution at this point but after reading the comments in the api it was said that you shouldn't invoke any drupal modules inside of that hook. Is there a way I can detect if the user is anon without user_is_anonymous()? Should I write this hook without any drupal functions? Should I bootstrap drupal in hook_boot similar to how its done in the core module file statistics/staticstics.php?

Here is my code for hook_boot:

function my_module_boot() {
  // If anon proceed
  if(user_is_anonymous()){
    if(isset($_COOKIE['welcome_page'])){
      // do nothing
    } else {
      $cookie = filter_xss($_COOKIE['welcome_page']);
      // If user saw welcome page and has cookie- skip redirect
      if($cookie != 1) {
        setcookie('welcome_page', 1, time()+86400);
        $destination = drupal_get_destination();
        drupal_goto('welcome', array('query'=>$destination), $http_response_header = 301);
      }
    }
  }
}

My goal is to keep all of the code contained inside of the module. I'd rather not use any other contrib module at this point because my module is close to completion. This redirect should only get triggered if the user does not have the cookie and is anon.  Finally I do not want the site to appear before the landing page.

Thanks for any help.

Solution:

function my_module_boot() {

  if(isset($_COOKIE['welcome_page']) || isset($_COOKIE['welcome_page_admin'])) {
    // do nothing
  } else {
    $cookie = filter_var($_COOKIE['welcome_page'], FILTER_SANITIZE_STRING);
    // If user saw welcome page and has cookie- skip redirect
    if($cookie != 1) {
      $destination = '/';
      if($_GET['q']) {
        // Microtime for IE9 to properly redirect
        $destination = $_GET['q'] . '?a=' . microtime(true);
      }
      // Redirect and set cookie
      setcookie('welcome_page', 1, time()+86400);
      header("HTTP/1.1 301 Moved Permanently");
      header("Location: /welcome?destination=" . $destination);
      exit();
    }
  }

}

function my_module_user_login(&$edit, $account) {

  // Expires in one year for authenticated
  setcookie('welcome_page_admin', 1, time()+31556926);

}

Your suspicions are correct. If you want to do this server side on a cached page, you'll need to use hook_boot() and you won't be able call most Drupal functions because Drupal hasn't been bootstrapped at the stage that hook_boot() runs.

It seems to me that this is much better suited to client side. I would move this to a small js file (put it in the head if you're worried about the the redirect happening too late).


How to select nodes without taxonomy terms from a vocabulary in views? Is it possible to select all nodes that have no taxonomy terms from a vocabulary in views?

I tried the "is empty" option in the filter section, but it does not work.

I need to do that in views because I have to use VBO on the results of the query.

yes i think so.. for me it works when i select 'has taxonomy term' and next option 'is empty'


How to create Dynamic Routes I have been trying to create dynamic routes by using RouteSubscriberBase class.

I know we can create dynamic routes by using slug parameter in the URL. Similar to this method ( https://befused.com/drupal/dynamic-route ).

But I want is dynamic Routes not URLs.Similar to this method ( https://www.previousnext.com.au/blog/dynamic-routes-drupal-8-routesubscriber )

Here is the code I have written so far but I cant get whats missing in the code.

When I try to access http://example.com/custom-module/dynamic-routes/ it is available but when I try to access http://example.com/custom-module/dynamic-routes/tents I am getting Page not found Error.

I have Cleared cache before accessing the new URL.

DynamicRoutesAlter.php

<?php

namespace Drupal\custom_module\Routing;

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

/**
 * DynamicRoutesAlter Class.
 */
class DynamicRoutesAlter extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

   $products = ['cooking_gear' => 'Cooking Gear', 'tents' => 'Tents' , 'sleeping_bags' => 'Sleeping Bags','rope' => 'Rope', 'safety' => 'Safety','packs' => 'Packs'];

    foreach ($products as $key => $value) {

      $url = preg_replace('/_/', '-', $key);

      $route = new Route(
        // The url path to match.
        '/custom-module/dynamic-routes/' . $url,
        // The defaults (see the custom_module.dynamic_routes for structure)
        [
          '_title' => $value,
          '_controller' => '\Drupal\custom_module\Controller\DynamicRoutesController::productType',
          'type' => $key, //Not sure what type does ? Is it required? I have seen it as the syntax in the book Mastering Drupal 8 By Chaz Chumley, William Hurley
        ],
        // The requirements.
        [
          '_permission' => 'create ' . $value,
        ]
      );

      // Add our route to the collection with a unique key.
      $collection->add('custom_module.dynamic_routes'. $key, $route);

    }
  }

}

custom_module.services.yml

services:
  custom_module.dynamic_routes:
    class: Drupal\custom_module\Routing\DynamicRoutesAlter
    tags:
      - { name: event_subscriber }

custom_module.routing.yml

custom_module.dynamic_routes:
  path: '/custom-module/dynamic-routes'
  defaults:
    _title: 'Dynamic Routes'
    _controller: '\Drupal\custom_module\Controller\DynamicRoutesController::productType'
  requirements:
    _permission: 'access content'

DynamicRoutesController.php

  /**
   * {@inheritdoc}
   */
  public function productType() {

    $build['results'] = [
      '#markup' => $this->t('Controller to get Products List.'),
    ];

    return $build;
  }

DynamicRoutesAlter.php

Problem #1 - preg_replace() without pattern

$url = preg_replace('_', '-', $key);

The $url will be always NULL, because you are using preg_replace() without regexp, use instead str_replace() or write appropriate regexp pattern: '/_/'.

Solution #1

$url = preg_replace('/_/', '-', $key);

Solution #2

$url = str_replace('_', '-', $key);

Problem #2 - wrong variable mixing

$collection->add('custom_module.dynamic_routes'.{$key}, $route);

You are wrong with mixing variable and string. You want to concatenate it with the curly syntax. This is also incorrect.

Solution #1

$collection->add("custom_module.dynamic_routes.{$key}", $route);

Solution #2

$collection->add('custom_module.dynamic_routes' . $key, $route);

After you fix those problems, your code will work.

I'm also not sure about 'type' => $key,, why is that here? There is nothing about type route param.

P.s. as you mentioned itself, better use slugs.

UPD - all files

Check your files for mistakes.

custom_module.info.yml

name: Custom module
type: module
description: For https://drupal.stackexchange.com/questions/281728
package: Custom
core: 8.x

custom_module.routing.yml

custom_module.dynamic_routes:
  path: '/custom-module/dynamic-routes'
  defaults:
    _title: 'Dynamic Routes'
    _controller: '\Drupal\custom_module\Controller\DynamicRoutesController::productType'
  requirements:
    _permission: 'access content'

custom_module.services.yml

services:
  custom_module.dynamic_routes:
    class: Drupal\custom_module\Routing\DynamicRoutesAlter
    tags:
      - { name: event_subscriber }

src/Controller/DynamicRoutesController.php

<?php

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Returns responses for Custom module routes.
 */
class DynamicRoutesController extends ControllerBase {

  /**
   * Builds response for dynamic routes.
   */
  public function productType() {

    $build['results'] = [
      '#markup' => $this->t('Controller to get Products List.'),
    ];

    return $build;
  }

}

src/Routing/DynamicRoutesAlter.php

<?php

namespace Drupal\custom_module\Routing;

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

/**
 * DynamicRoutesAlter Class.
 */
class DynamicRoutesAlter extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    $products = ['cooking_gear' => 'Cooking Gear', 'tents' => 'Tents' , 'sleeping_bags' => 'Sleeping Bags','rope' => 'Rope', 'safety' => 'Safety','packs' => 'Packs'];

    foreach ($products as $key => $value) {

      $url = preg_replace('/_/', '-', $key);

      $route = new Route(
      // The url path to match.
        '/custom-module/dynamic-routes/' . $url,
        // The defaults (see the custom_module.dynamic_routes for structure)
        [
          '_title' => $value,
          '_controller' => '\Drupal\custom_module\Controller\DynamicRoutesController::productType',
          'type' => $key,
        ],
        // The requirements.
        [
          '_permission' => 'create ' . $value,
        ]
      );

      // Add our route to the collection with a unique key.
      $collection->add('custom_module.dynamic_routes' . $key, $route);

    }
  }

}


How to programmatically render a contact form in a theme in D8 How to get the side-wide contact form (feedback) individually displayed in a custom block or other page then /contact (e.g. frontpage)?

I've tried this code, but it is not working (are contact forms entities?):

// get default form
// get the entity object
$default_form = \Drupal::config('contact.settings')->get('default_form');
$entity = \Drupal::entityManager()->getStorage('contact_form')->load($default_form);

// get view builder
// render view
$view_builder = \Drupal::entityManager()->getViewBuilder('contact_form');
$full_output = $view_builder->view($entity);

Contact form is an entity, but you can't view it.

What you want instead is an add form of a contact_message with contact_form as bundle.

See ContactController::contactSitePage() (EDIT: API docs) as example:

$message = \Drupal::entityTypeManager()
  ->getStorage('contact_message')
  ->create(array(
    'contact_form' => $contact_form->id(),
  ));

// This works in a controller, use \Drupal::service('entity.form_builder') elsewhere.
$form = $this->entityFormBuilder()->getForm($message);
$form['#title'] = SafeMarkup::checkPlain($contact_form->label());

EDIT (thanks @nilsun): Note that entityManager is deprecated in favour of entityTypeManager.


How can I correctly include a (non-fragment) # in a URL? I need to build an external URL that looks like this:

https://searchapp.foo.gov/search-org/#/collection-name?q=search%20terms%20here

First thought is that /#/ is entirely invalid according to RFC 3986, unless I'm reading it incorrectly, but that's what I've been given. So I'm building it like so:

$base_url = 'https://searchapp.foo.gov/search-org/#/collection-name';
$options = [
  'absolute' => TRUE,
  'https' => TRUE,
  'query' => [
    'q' => $form_state->getValue('search'),
  ],
];
$url = Url::fromUri($base_url, $options)->toString();

Instead of the expected output, I find that my querystring is appearing before the #:

https://searchapp.foo.gov/search-org/?q=search%20terms%20here#/collection-name

I've tried using /%23/ instead of /#/, and that fixes the problem with the querystring being out of place, but creates a new problem by url encoding the %, so that I wind up with /%2523/.

I'm guessing this is a problem with hash segment handling. Is there a right way to handle a URL like this?

You are correct ... it is invalid to use the "#" for anything other than a fragment. That does not mean that someone doesn't have their web servers setup in such a way that "#" can be used in the URL itself.

  I'm guessing this is a problem with hash segment handling. Is there a right way to handle a URL like this?

To be clear, there is no problem with how Drupal is handling URLs ... Drupal is following the spec. I think your best bet in this case (short of yelling at whoever is giving you this URL for doing so) is to extend the Url class and replace the formUri method to handle your weird case.

Your other option is to do something really hacky like putting an easily replaced string in the URL and then doing a string replace at the last minute before displaying it.


How do I set up a More Link in a View's Pager? I have a View and am using the Pager to display a specific number of items, limited to 4. I want to create a "More" link to link to the rest of the items.

I've set my view up as such:

But no More link is appearing, even though I have more than 4 items and even though the helper information says:

  This will add a more link to the bottom of this view, which will link to the page view. If you have more than one page view, the link will point to the display specified in 'Link display' section under advanced. You can override the url at the link display setting.

I've looked through the HTML to ensure the link is not hidden by anything else. It's simply not present.

Would anyone know how to get this working?

You need to make display as page then only more will work. For more details https://www.drupal.org/node/450736.

You can also create block and activate ajax for better functionality. Show more/load more modules implements this sort of functionality. You can follow that.


Adding array of objects to javascript from PHP This is a part of my script in template file where php code is used to generate js field of objects:

<?php $count = count($events); $counter = 1; ?>

<script>
  var events = [

  <?php foreach($events as $event) { ?>

    {
      date: '<?php echo $event['date']; ?>',
      linkTarget: "_blank",
      content: "<?php echo $event['content']; ?>",
      class: "<?php echo $event['class']; ?>"
    }
    <?php if($counter!=$count) { echo ','; $counter++; } ?>
  <?php } ?>

  ];
<script>

I know that we can add js variable by drupal_add_js(array('myModule' => array('key' => 'value')), 'setting'); but how can we create the same js array as in example above in order not to use php code in js?

You can pass an array to JS like this:

drupal_add_js(array('my_module' => array('events' => $events)), 'setting');

In javascript you can get the values like this:

Drupal.settings.my_module.events;


Get whole node by post type Is there any way of getting a node by its post type? I've tried with the following code, but it doesn't really work.

$query = \Drupal::entityQuery('front_page_slider');

As far as I read on tutorials, it should work when the content type is front_page_slider. Instead, it returns an error.

  The "front_page_slider" entity type does not exist.

What you call post type is for Drupal a content type, or an entity bundle. The first argument of \Drupal::entityQuery() is the entity type that, in the case of nodes, is node.

The code you need is the following one.

use \Drupal\node\Entity\Node;

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'front_page_slider')
  ->condition('status', 1)
  ->execute();

$nodes = Node::loadMultiple($nids);

Note I added the condition('status', 1) line, which returns only the published nodes; if you are not interested only in the published nodes, you can leave that line off.

Furthermore, if you are executing the code without showing the result to the currently logged-in user, for example because it runs at cron time, you should disable the access check, and use the following code.

// Put the following line at the beginning of the file containing the code.
use \Drupal\node\Entity\Node;

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'front_page_slider')
  ->condition('status', 1)
  ->accessCheck(FALSE)
  ->execute();

$nodes = Node::loadMultiple($nids);

Differently, you would get only the nodes for which the currently logged-in user has access.
In the example of a hook_cron() implementation, that user is the anonymous user. Without the accessCheck(FALSE) line, the code would get only the published nodes to which anonymous users have access, which could be none, if the user permissions don't allow anonymous users to see nodes.

accessCheck(FALSE) is used by node_access_rebuild(), which contains the following lines. (Read the comment before the code.)

  // Disable access checking since all nodes must be processed even if the
  // user does not have access. And unless the current user has the bypass
  // node access permission, no nodes are accessible since the grants have
  // just been deleted.
  $entity_query->accessCheck(FALSE);


Remove the URL aliases that don't have a node I have been importing a lot of data using feeds, then deleting all imported items again when there were problems with the import. Unfortunately, the URL aliases for the pages do not seem to be deleted, so they are related to nodes that no longer exist. Is there any way to remove them, other than going through by hand?

A core bug causing this error was fixed for Drupal 8.2 and 8.3:

PathItem::delete() never runs because the path field type is a computed field in disguise

The fix for this problem, then, should simply be updating Drupal (...after having waited several months for this fix to be made and 8.2 released— but a satisfying answer now, i hope!)


Performance: Efficient use of EntityFieldQuery (with node_load OR node_load_multiple) to update thousands of nodes with/without conditions I have script that queries a system called Symplectic for publications of over 30 users (each authored over 300 publications). Most of the publications are authored jointly by more than one user. I have done the following using a combination of Entity API and other methods:

Programmatically creating publication nodes (with fields i.e. integer, text, lists, taxonomy terms, entity reference, etc).

I would like to avoid the following scenario:

Creating duplicate nodes of type publication

Every time I create a publication, I would like to check whether the publication already exist or not (most probably yes because, the users have authored so many publications together). I can achieve this when I am creating all publications at the same time :

I will lookup a structure the stores publication specific properties (i.e. Symplectic object id, doi, publication source id, last-modified-timestamp where source being pubmed, scopus, etc.). If not exist then create publications and update the structure, else reference the user to the already existing publication.

The actual use I am Concerned about is, Updating thousands of publications at a later date after they are created. I have the following options, which one do you think is most efficient:

Use EntityFieldQuery to query for all nodes of type publications (over 2500 nodes) at once, and store the properties useful for comparison in a structure. Use the structure to decide whether publication exist in Drupal, if no then create it, if yes then check for last-modified-date.
Use EntityFieldQuery with condition fields to check if a publication already exist in the Drupal system, if yes then check if update is avaiable, if no then create it. This method would require, N number of quries (2500 publication nodes would result in 2500 calls).
During initial create operation (when no publication node exists), create a structure and store the few publication fields that are expected to be unique (not timestamp) across all publications (i.e. symplectic object id, doi, publication source id, last-modified-timestamp), serialize the structure and store it in the file system. During update phase, load the structure from file system, unserialize it and use it to check whether a publication node already exist in the drupal system, if no then create it and update this structure, if yes then check whether update is required.

My worries in regards to above available options:

Loading over 3000 publication nodes (of course, EntityFieldQuery would retrun all nids, then I will have to use either node_load_multiple or node_load) - Is this efficient? Would I not face memory problems?
2500+ EntityFieldQuery does not seem to be the right choice due to query time. (Attaching conditions might increase the query time i.e. if symplectic id field of publication equals X)
This is my idea, I don't know if it makes sense.

I have Drupal 7 on CentOS 6.5, and a publication content type has the following number of fields:
boolean - 2
text - 20
Double field - 3
Taxonomy - 1
List 2,
title, body, etc.

What do you recommend based on your experience? I did have a look at Biblio module, it is not the way to go forward for our requirements.
I also know that $conditions parameter of node_load_multiple is deprecated in D7.

Sorry for long description, I tried to be as descriptive as possible.

If you can access the data via SQL then I think the Migrate module can do 80%+ of what you want with relative ease. Your hardest part may be either: 1) getting an SQL dump of the data you want from the remote system, or 2) build an SQL representation of the data from the data you can retrieve from the webservice using a Cron type task.

Assuming you can get an SQL version of your (by the way Migrate and what I'm talking about works on XML, JSON, CSV, text files ... and the framework supports "lists" of data from other sources -- but you'd have to develop some of your own Classes for exotic import sources ... I digress) ... migrate supports querying your objects like "I want to move item(s) from point A to B ... and either update or create them." as of Migrate 2.5+. Most people are comfortable with SQL or CSV files so I'll talk about that here. Being Object Oriented you're free to adjust Migrates behavior of course by extending a classes default behavior.

Once you have the SQL data you can use a Migration to import the data. By using Migrate 2.6's (stable release) track_changes option within a Migration class. The Migrate module will take the fields your migrating from point A to point B of your data and create a hash value of all the data. This hash value is used in subsequent calls to Migrate data to deem whether the given item should be created or updated from the data being fed into the Migration.

An example of this can be seen in this great little blog post:
http://timonweb.com/using-hash-value-trackchanges-to-detect-source-data-changes-in-migrate-for-drupal-7

The key excerpt enabling track_changes from the blog post is:

class ExampleNodeMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
   $options = array('track_changes' => 1);
   $this->source = new MigrateSourceSQL($this->query(), $this->fields(), NULL, $options);
}

I say SQL would be easiest for this approach because you could easily build a query for your migration that is basically SELECT id, doi, publication source id, last-modified-timestamp where source being pubmed, scopus, etc  FROM my_remote_data and  put $options = array('track_changes' => 1); and Migrate is basically doing all the work for you -- and should be very little PHP code to consume the data.

I've actually done this process most recently with the Migrate modules default support for CSV files with a Migration that results in 6 different Drupal content types built out from the CSV in dependant-order -- and objects are created/updated on-the-fly using track_changes every time the system does an sync from the remote system ... so it's doable via SQL or CSV easiest I think.

  random tidbit: my CSV file is like 40 columns of data and each
  sub-migration only cares about a limited set of columns in the csv
  file. So I tell each migration to ignore unwanted fields for that
  migration by using PHP's unset function in the prepare for the
  Entity being built. By unsetting the values the hash function only
  hashes the relevant data I care about for that single drupal object
  I'm creating with that migration.

Anyways... I hope this rant helps and offers you a path do this. I've used Migrate on and off for single table or larger migrations of data since the Migrate 1.x days ... it can be complicated to learn if you've never used it.


How do I access paragraphs with the JSON API? With the JSON API module, I am trying to access paragraphs.  In the JSON object it does not allow me to access the nested paragraphs.

How would I go about accessing the paragraphs with the JSON API?

*****Update with Solution*****

In the api call you need to have the correct URL format:  /jsonapi/{entity_type_id}/{bundle_id}[/{entity_id}]?_format=api_json.  The key here is to add this at the end of your the URL for the api call:  ?include={name of paragraph}.  For example:    /jsonapi/node/page?_format=api_json&include=field_testing_json_api
Once you have the correct API call, you need to go to the Drupal admin dashboard and go to people/permissions and under the Paragraphs Type Permissions section you need to grant access to view content to the specific paragraph you want the user to access.

2 steps required :)

create the paragraph(s) by doing a POST request, and receiving the revision ID of the created paragraph,
update the parent entity by assigning the paragraphs' revision ids to the paragraph field (entity revision reference field).

Step 1.

jsonbody = {
    'data': {
        'type': 'paragraph--study_history',
        'attributes': {
            'parent_id': localStorage.getItem('uid'),
            'parent_type': 'user',
            'parent_field_name': 'field_study_history'
        },
        'relationships': {
            'field_school_ref': {
                'data': {
                    'type': 'node--school',
                    'id': this.reg_selectedUni['id']
                }
            }
        }
    }
};

return this.api.apiPost('/jsonapi/paragraph/study_history', {}, jsonbody)

We are using our custom service api (ApiService.ts) which has the apiPost function that does exactly what you'd imagine :)
So the logic above should be easy to adapt to your own code.

Note that if you want to add more fields (text fields for example, you add them to the attributes section).

Step 2.
Here’s how we update the user, PATCH it to have the created “study history” paragraphs.

const jsonbody = {
    'data': {
        'type': 'user--user',
        'id': uuid,
        'relationships': {
            'field_study_history': {
                'data': [
                    {
                        'type': 'paragraph--study_history',
                        'id': schoolhist_info['data']['id'],
                        'meta': {
                            'target_revision_id': schoolhist_info['data']['attributes']['revision_id'],
                        }
                    },
                    {
                        'type': 'paragraph--study_history',
                        'id': unihist_info['data']['id'],
                        'meta': {
                            'target_revision_id': unihist_info['data']['attributes']['revision_id'],
                        }
                    }
                ]
            }
        }
    }
};
return this.api.apiPatch(this.endpoint.getUsers + '/' + uuid, {}, jsonbody);

Where this.endpoint.getUsers is /jsonapi/user/user.
This should be enough to get it to work, else comment and I can update.


Delete unused tables from the drupal database In my Drupal database I have so many field_deleted_data_XX and field_deleted_revision_XX tables. I have disable the revision entity but I want to delete these existing revision created tables, can I delete these tables directly or Is there any SQL script to delete unused tables from the database.

You can safely remove them yes. You can use drush to delete these tables: run drush eval 'field_delete_field("yourfield")' and run cron afterwards with drush cron.


How to keep the same vertical tab open on AJAX call? We're using vertical tabs on a configuration form for a ctools content type inside Panels. Inside most of these vertical tabs, there are "Add more" buttons, which use AJAX to add another item to the form. Essentially combine these two examples:

https://api.drupal.org/api/examples/vertical_tabs_example!vertical_tabs_example.module/7

https://api.drupal.org/api/examples/ajax_example!ajax_example_graceful_degradation.inc/function/ajax_example_add_more/7

We set the container around the whole form to reload the entire thing. The problem is that, on reload, the vertical tabs reset. We'd prefer it leave the element that the user currently had open open. Is there a way to do that?

We can save in $form_state html id current vertical tab.
Only, be sure, do not forget to set custom ids your tabs


How to display a date without hour, minutes, and seconds? I have created content type and installed Automatic Entity Label and generated the auto label using field tokens of:

field_id
field_DOB
field_Gender

After saving the content DOB format is displaying with time stamp           56u 2015-10-13 00:00:00 Male but here I want to show only something like this 56u 2015-10-13 Male.

I want to remove this 00:00:00.

While creating the field DOB I have chosen the following settings but still getting the hour, minutes, and seconds. How to remove this? Any suggestion?

Steps to achieve your requirement:

Goto /admin/config/regional/date-time/formats/add link, and add Format string as explained in the PHP manual.

Now add Date type and select the format you created.

Finally, go to content type Manage Display settings and add your newly created date format.
At URL /admin/structure/types/manage/page/auto_label, add token of the DOB field with the format you created by Browsing Available Tokens.


Views filter by taxonomy if not empty I would like to filter views block content by taxonomy. I have multiple content types on same block, and only one of them has taxonomy. The goal is to output all the nodes from content types with no taxonomy, and from certain term if content type has taxonomy.

Shorter: If content type has taxonomy, filter by it.

And not to be too simple: taxonomy is hierarchical and I would like to it work so, that nodes in child taxonomy would also appear when filtering by parent.

I could of course filter all the other terms out, but the thing is that client can add terms by himself. Therefore limiting the terms out manually is not the best solution.

I am using Drupal 7.22 and Views 3.7.

Use the views filter condition OR groups. Also make sure that the taxonomy relationship optional (uncheck Require this relationship).


Block form send email to recipients from a view We have a view which can be filtered.
We need a block which can be used to send a message with the recipients coming from the view.
Ideally this would be on the same page.
This would be used by anonymous users so the interface needs to be simple.
We have tried views send but the form is too complex to present to anonymous users.

Possibly an entity form where we can define the fields, user selects the recipients from the view, fills the simple block form and send.

Any ideas much appreciated.

You can use Views Send module for that.

  Views Send enables you to send mass mailing from a View.


Drupal 7 Captcha in all webforms or per content type webforms I am on D7.

I have a content type that is webform enabled.

Requirement
I need to implement captcha for all the webforms for nodes of this content type.

Problem
In D7, you are supposed to give the form_id in the settings page to get captcha in the form, however I will have loads of forms with all different form_ids.

I am using the Captcha module.

Is there any way to implement my requirement?

You could add the following code to your template.php

if (strstr($form_id, 'webform_client_form')) {
        $form['my_captcha_element'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'image_captcha/Image',
        );
    }

this should be placed inside the yourthemename_form_alter


How to add tabs to panels setting page? I want to add additional vertical tabs (marked with red) in screenshot, but have had no luck with google or documentation.

How does one add tabs here?

Those vertical items are internally called "operations" and are implemented by task_handlers plugins although some of them are hardcoded in page_manager. You can see some examples in:

ctools/page_manager/plugins/task_handlers/http_response.inc
panels/plugins/task_handlers/panel_context.inc

You may also find more info in page_manager_render_operations()  docstrings.


How to Create Membership Groups for Products? I'm exploring if the latest release of Drupal Commerce (using Commerce Kickstart 7x-2.38) will work for my Apparel eCommerce requirements. We need membership to groups (which will be corporate accounts or schools) that will present authenticated users a selection of apparel products using corporate or school logos and of course special pricing. I've looked into both Organic Groups and Membership Entities and neither seem to be the best solution. Any ideas?

Another alternative to look at is the Group module, which is an alternative to Organic groups ...

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Cant login to my sites on AWS but I CAN login with the same database on my local machine I've loaded two different Drupal 7 sites on Amazon Web Services (AWS) Ubuntu instances. They both work fine and are configured mostly correctly.

The only problem is, I can't login to either site using my Drupal username/password combinations! (either site). I've double and triple checked my passwords/making sure CAPS LOCK isn't on, etc. I cleared cookies and even tried the permissions suggestion given in this article.

No matter what I do when I try to login to either site on AWS I get a silent login fail. No errors, the browser just reloads and prompts me to login again. I know the username/password work because on my local machine for both sites I can login easily using the same database.

Note: I, of course, imported the databases for both projects so they SHOULD have the same user data.

Anyone know what else I can try?

Well, I fixed it. I had to run the following command:

sudo a2enmod rewrite


How can I set the default value for a Media form element? I am using Media 2.0 and a media field in a custom admin form.

I am trying to set the default value as described on
https://www.drupal.org/project/media/issues/1158760#comment-12656764, but `#default_value = array('fid' => 1234); doesn't work.

How can I set the default value for a Media form element?

After some digging in the media module, this is the working notation:

'#default_value' => 12345,

Plain and simple...


Displaying the filefield file's size How can I get the filesize (eg, 2.12 MB) of a FileField upload?

I tried this from a views row template but I get an error message (function.filesize]: stat failed for ..filename..):

// this correctly gets the result
// /sites/example.com/files/CIRS_manual_test.pdf
$file_field = '/' . $field->original_value;
print "Download chapter as pdf: ';
print filesize($file_field) . '';

I've tried using the full path /www/..., but get the same error message. I know the path is right because I'm able to load it in my browser.

Are you talking about getting the actual filesize or just formatting the size?

If the first, you can add a relationship to the {files} table in your view so that you can pull in the filesize column.  IIRC, you add a relationship to the fid and then you will see File: Size in the fields.  This will not work, though, if you manually overwrite the files via SFTP, etc.

You are getting the error because of the difference between the web path and the actual filesystem path.


Drupal Commerce Product SKU pane not showing after upgrade After performing an upgrade of a Drupal 7 site (core and modules), including Drupal Commerce, the Product SKU pane is not showing up on my panels page.  I'm able to add it to my panels page and there are SKU's for the product.

Why is this happening?

SOLUTION:  I've found setting the View Mode to "Product List" makes this appear correctly.


Using a view result as allowed_options in a text(list) field I have a set of values that are created in a different node, and I would like to use them as the allowed values for a field in another node. So, I have a view that collect the values and I have a hook_allowed_values function to create the allowed_values list. My function is:

function hnbuilder_fheq_allowed_values(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable){
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
        $nid = $node->id();
    }
    $view_id = 'default';
    $args = $nid;
    $result = views_get_view_result('outcomes',$view_id,$args);
    return $result;
}

My problem is that my views_get_view_result is not returning anything. I get the correct $nid, and pass this to the views...result. The view, on its own, works fine. But if kint($result), I get nothing.

I've updated the config for the field, to make it call the hook_allowed_values function.

What am I doing wrong?

Here's what I ended up with...

function hnbuilder_fheq_allowed_values(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable){
    $node = \Drupal::routeMatch()->getParameter('node');
    //kint($node->bundle());
        if ($node instanceof \Drupal\node\NodeInterface) {
            $thisnid = $node->get('nid')->value;
            if($node->bundle() != 'qualification'){
                $nid = $node->get('field_qualification')->target_id;
                }
        }
        $args=[$nid];
        $values = [];
        $view = Views::getView('outcomes');

        if (is_object($view)){
            $view->setArguments($args);
            $view->setDisplay('default');
            $view->execute();
            foreach($view->result as $rid=>$row){
                foreach ($view->field as $fid => $field ) {
                    $values[$rid][$fid . '-value'] = $field->getValue($row);
                    $my_options[$values[$rid]['field_fheq_code-value']] = "[".$values[$rid]['field_fheq_code-value']."]- ".$values[$rid]['field_fheq_description-value'];
                }
            }
        return $my_options;
    }
}


Theme inheritance : blocks placement not inherited I have a "Father" theme, and a "Child" theme that inherits from Father.

Css and templates are well inherited, it's ok, but blocks placement (Structure > Blocks) won't inherit.

Is it supposed to ? If it is, do you have any idea for this to work ?

Note : I have the same custom regions defined in each .info file.

Many thanks.

Block placement per region is unique to each theme. Putting the search block in "right_sidebar" for theme_a doesn't put the search block in "right_sidebar" for theme_b.


Drush 6.6.0 Site-Install fails with 'No database to operate on.' I am having some problems running drush site install through Puppet.  When it comes for puppet to execute the following command I get an error.  It appears as though the database URL is being truncated and then some non-verbose error tells me SQL cannot execute?  If I try to install the site via the web-UI it works without any issues.  I can connect from this machine using mysql client and the username/password.

[root@site:/var/www/html/drupal]#
#-> /usr/bin/php /var/webdeploy/src/composer/vendor/drush/drush/drush.php \
site-install -y -r /var/www/html/drupal \
--db-url=data.rds.awsdomain.com/dbname \
--db-su=user \
--db-su-pw=password \
--account-name=admin \
--account-pass=admin \
--account-mail=mail@example.com \
--site-name="site name" minimal

You are about to CREATE  the 'ata.rds.awsdomain.com/dbname' database. Do you want to continue? (y/n): y
Unable to generate CREATE DATABASE sql for                         [error]
No database to operate on.                                         [error]

Your --db-url is not in the correct format.  Use this instead:

--db-url=mysql://USER@data.rds.awsdomain.com/dbname

Replace USER with the account used to access the database.  If this is the same user that you have specified with --db-su, then the --db-su option is not necessary.  Drush will not go the other way (fill in the "ordinary" user from the privileged user specified via --db-su), though.


How to prevent dynamic library definition from being cached? I have a use case where i want to dynamic add library  , Attributes of library will vary with page. In my case the $callback will be different depending on the page.

$libraries['sample.my-lib'] = [
    'js' => [
      '//maps.googleapis.com/maps/api/js?'.$key.'&callback='.$callback
       => [
        'type' => 'external',
        'attributes' => [
          'async' => "true",
          'defer'=> 'true'
        ],
       ],
    ],
    'weight' => '2200',
  ];

The above code works but when i navigate to different page i have to clear the cache to get updated value of $callback.

I have tried hook_library_info_alter but library definition is still cached.

How can i work around it to make my use case work.

You could trigger Drupal::service('library.discovery')->clearCachedDefinitions() every time, but that seems like a painful workaround performance-wise. All library definitions for a particular theme seem to be stored in a single cache entry library_info:$activeTheme, which doesn't allow any more finely grained invalidation.

Would the range of values of "callback" allow you to loop through them and define a separate library for each one you use, and then attach the specific one you need? The JS gets loaded on demand, so only the attached library would appear on each page.

foreach (static::CALLBACKS as $name) {
  $libraries['sample.my-lib.' . $name] = [
    //...
  ];
}

Or maybe it would be possible to call the appropriate callback from a single main function (possibly setting the callback via a drupalSettings attachment), allowing you to put a fixed value in the Google Maps API URL?


How can I update the field of the entity? I have an "Question" entity, and I need to updates its 'key' field (of string type):

My code isn't working:

  $storage = \Drupal::entityManager()->getStorage('question');
  $query = $storage->getQuery();
  $query
          ->condition('key', $key);

  $entity = $query->execute();

 $entity -> set ('key', 'new_value');
 $entity->save();

It returns the error Fatal error: Call to a member function set() on a non-object

The QueryInterface::execute() method returns either an integer or an array, not an object. It is a good idea to check api.drupal.org (if you don't use an IDE), or let your IDE do the work for you with intellisense.

It probably would be easier to use loadByProperties, which loads the entities for you. However it is definitely useful to get the query object, but you need to call loadMultiple.

$entities = \Drupal::entityTypeManager()
  ->getStorage('question')
  ->loadByProperties(['key' => $key]);

if (!empty($entities)) {
  $entity = reset($entities);
  $entity->set('key', 'new_value');
  $entity->save();
}