How to use between date query? I have 2 fields in a node and I'm trying to get the expired nodes set in "Start Date" and "End Date" field.

I'm using db_select to get the start and end date values.

How can I add a condition to check if the dates are in range?

Here's my current code:-

$query = db_select('node__field_end_date', 'ed');

$query->leftJoin('node__field_start_date', 'sd', 'sd.entity_id = ed.entity_id');

// Date values showing as a formatted date
$query->addField('ed', 'node__field_end_date', 'date_end');
$query->addField('sd', 'field_start_date_value', 'date_start');

The raw SQL would be something like this,

SELECT startDate, endDate
FROM YourTable
WHERE GETDATE() between startDate and endDate;

You might could do like this with db_select

$query = db_select('node', 'n');
$query->condition(now(), array(node__field_start_date, node__field_end_date), 'BETWEEN');

I hope it helps


Ionic Framework won't authenticate in browser (works in emulator) I've set up a simple Ionic Framework app which utilises Drupal 7 Services API to authenticate a user, before hitting some custom end points to retrieve data when logged in.

The issue I'm seeing is when running ionic serve to view the app in the browser: http://localhost:8100/#/auth/login.  I can successfully log in, but when requesting an endpoint, the user is not detected as authenticated.

Logging in successfully - see log debug:

However, when trying to access a custom end point - the user doesn't appear to be authenticated - the dblog reveals Anonymous (not verified), thus returning ["Access denied for user anonymous"] in the console. The dblog looks like so:

The odd thing is, if performing the exact same steps using POSTMAN or via the iOS emulator when running ionic emulate ios all works fine, see dblog now (this is when using emulator):

More info: I'm using the Drupal CORS module, with the following set up:
api/*|http://localhost:8100|*|Content-Type,X-CSRF-Token,Authentication, Origin, Cookie|true

On each request I'm passing the X-CSRF-Token.  I can't pass a Cookie as the console returns 'Refused to set unsafe header "Cookie"

My $http request looks as follows:

  this.getEventFeed = function(csrf, payload) {
    var api = FetchGlobals.getUrl();
    var deferred = $q.defer();
    var req = {
     method: 'POST',
     url: api + '/api/rest/event_feed/feed.json',
     headers: {
      'X-CSRF-Token' : csrf,
      'Access-Control-Allow-Credentials' : 'true',
      // 'Cookie' : cookie,
      'Authentication' : cookie
     },
     data: payload,
     // json : true,
    }
    console.log(req);
    $http(req)
    .success(function(data, status, headers, config) {
      var response = {
        'ok' : true,
        'data' : data,
      };
      deferred.resolve(response);
    })
    .error(function(data, status, headers, config) {
      var response = {
        'status' : status,
        'data' : data,
      };
      deferred.resolve(response);
    });
    return deferred.promise;
  };

EDIT: It appears to be an issue with the Cookie. As recommended here: https://www.drupal.org/node/1133084#comment-8433677 - I've added a new header called Authentication.  I can see from the dblog the user is succesfully being authenticated, however, I receive the error ["CSRF validation failed"].

Incase someone faces a similar issue, I managed to find a fix by:

Setting up an ionic proxy see: http://blog.ionic.io/handling-cors-issues-in-ionic/
Sending the Cookie with the headers as Authentication to bypass the issue 'Refused to set unsafe header "Cookie.  Then adding this code on hook_init() https://www.drupal.org/node/1133084#comment-8433677.


How to measure time taken for a Feeds processing (benchmarking)? Is there a way to measure time taken for a Feeds processing (benchmarking)? e.g. nodes / minute, time taken for last import. Similar to the statistics in Migrate UI?

The Ultimate Cron module will tell you how long the import takes and keeps track of time for each feed import.

In your feed Basic Settings, for Periodic Import, make sure you set it to As often as possible.

In Ultimate cron, jobs tab, Remember to run the scheduler cron job first, then the Feeds cron jobs

Once you have a number, you can manually do the math on how many nodes per second.

Note: the cron run speed will vary based on your server machine. A more powerful machine will get the cron job done quicker.


Subtheme for Subsite in Multisite I have a Drupal 8 Multisite setup with the following Folder structure:

themes

custom_theme

main_custom_theme

sites

site1

themes

subtheme1

site 2

So I want both sites to use main_custom_theme, but site1 needs to override one template (page.html.twig) with subtheme1. subtheme1 folder contains a subtheme1.info.yml as follows:

name: subtheme1
description: "Custom sub-theme"
core: 8.x
type: theme
base theme: main_custom_theme

I rebuilt all caches (Backend and drush cr, but drush cr might not clean caches of subsites?) but cannot select the new subtheme in Backend of site1.
What am I missing?

This is the Twig Debug output after using leymannx answer, subsites path is "leistungen"

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   * page--leistungen.html.twig
   * page--node--560.html.twig
   * page--node--%.html.twig
   * page--node--article.html.twig
   * page--node.html.twig
   x page.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/my_custom_theme/templates/main/page.html.twig' -->

I have a question that builds on this one... I published it appearently with a different user, without wanting to. Still new to not only reading stackexchange :)

If I try to do the same for the node of my content type, which is using a template named node--CONTENTTYPENAME.html.twig at the moment, I can insert a name suggestion node--NAMEOFSUBSITE.html.twig, which will then be used for ALL nodes. I'd like to insert a suggestion such as node--CONTENTYPENAME--NAMEOFSUBSITE.html.twig, for only this one nodetype.

How can I do that?

Thanx in advance!!

In Drupal 8 you are supposed to organize your themes and multi-site instances like in the following structure. I only highlight the relevant folders.

__docroot
  |__modules
  |  |__contrib
  |  |  |__devel
  |  |  |__views
  |  |__custom
  |     |__my_module_abc
  |     |__my_module_xyz
  |__sites
  |  |__default
  |  |  |__settings.php
  |  |__site1
  |  |  |__settings.php
  |  |__site2
  |     |__settings.php
  |__themes
     |__contrib
     |  |__bootstrap
     |__custom
        |__my_bootstrap_subtheme

So, if you want to create a sub-theme of a custom theme, you also have to place it inside docroot/themes/custom. Then it will appear in your back-end where you can enable it.

But what I would recommend instead of adding another sub-theme, is to simply add a template suggestion based on the multi-site instance name via hook_theme_suggestions_HOOK_alter. By that you can move on with only one custom theme (which is much easier to maintain in the end), and inside its MYTHEME.theme file you'll switch the page template for your certain multi-site instance like following.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $site_path = \Drupal::service('site.path');
  $site_path = explode('/', $site_path);
  $site_name = $site_path[1];

  $suggestions[] = 'page__' . $site_name;
}

Now you simply can place page--site1.html.twig in your theme's template folder and site1 will take this page template instead the default page.html.twig. (Source)

Tried it on a fresh D8 with Twig debugging enabled and it works just fine.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   x page--site1.html.twig
   * page--front.html.twig
   * page--node--1.html.twig
   * page--node--%.html.twig
   * page--node.html.twig
   * page.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/my-custom-subtheme/templates/page--site1.html.twig' -->


Installing require-dev dependencies from core/composer.json I understand the composer-merge-plugin allows the Drupal root composer.json file to load core/composer.json on runtime. I also understand require-dev will only pull dependencies for the root composer.json file (see this link).

How can I force one/all core/composer.json dependencies (including the required-dev ones) to be pulled if I want without hacking the root composer.json file e.g. with a composer require vendor/package?

By default, Composer will install also the development requirements, if you don't use the --no-dev option.
I ran  composer create-project drupal/drupal test 8.3.*@dev, and in the output of the command I could see the following:

  Installing drupal/drupal (8.3.x-dev
  8a84ec5556f354861f1ddc5d7a80081b91ca42df)
    - Installing drupal/drupal (8.3.x-dev 8a84ec5)
  Cloning 8a84ec5556 from cache
  Created project in test
  Loading composer repositories with package information
  Installing dependencies (including require-dev) from lock file
  Package operations: 76 installs, 0 updates, 0 removals

  [Omissis]

  Installing drupal/coder (8.2.11) Downloading: 100%
  Installing phpunit/phpunit (4.8.28) Downloading: 100%

If you downloaded the archived release for example from https://www.drupal.org/project/drupal/releases/8.2.7, which doesn't include the development requirements, you need to run composer update from the directory containing core and composer.json.
I tested composer update --dev after removing the vendor directory from the test directory created from the previous command, and I got this output:

  You are using the deprecated option "dev". Dev packages are installed by default now.
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Package operations: 76 installs, 0 updates, 0 removals


Redirect loop after installing SecureLogin module I have only just installed the SecureLogin module and after enabling it, I cannot access any user pages or forms that have been configured to enable HTTPS.

I only ever get 310 redirect loop errors.

Edit: I have managed to fix the issue by commenting out the $base_url configuration I had set up in settings.php . Now the site redirects correctly but still shows some unsecured content (styles and scripts from the header mainly).

I have managed to fix the issue by commenting out the $base_url configuration I had set up in settings.php. Now the site redirects correctly but still shows some unsecured content (styles and scripts from the header mainly).


How to create a parent content type which consists of other child content types? I want to create custom content type (parent) which consists of other custom content types (children). Is this feasible in Drupal 8? Or I should do it programmatically?

Example: I want to have custom content type called Task, and another custom content type called Subtask. When a user creates a task, the user has to complete some fields (id, name), and should then create some Subtasks which are children of this Task. For the subtask some fields are to be completed also. In the end, each task will have some data such as:

name = "task_one".
description = "this task should do ..".
subtasks = {"subtask_one","subtask_two"}.

For Drupal 8, it sounds like you are describing reference fields. You would want to:

Create your two content types
Add a reference field to one of them. The refence field would be of the type 'content'.
(Optional, but probably) Limit the types of content that can be referenced to only the other content type.


Using drush on drupal 8? Dursh works very well with my Drupal 7, but when I try running Drush on Drupal-8 directory it throws some error message,

$drush pm-list

Command pm-list needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment to run[error]
this command.
The drush command 'pm-list' could not be executed.                                                                                [error]
A Drupal installation directory could not be found

could anyone tell me the solution for this problem?

any help is appreciated. Thank you.

Which version of drush? https://github.com/drush-ops/drush#drush-versions has a nice table, but in short you need the master branch from github if you want to work with Drupal 8.


jQuery events are lost after form reload First I thought that this would not be a Drupal specific problem, but jQuery specific solutions didn't solved it. I hope you have some advices.

I have a form with lots of fieldsets. To find the right fieldset I've implemented a textfield as a filter with jQuery to show just the fieldset I want to see:

$(document).ready(function(){
    $(document).on('keyup','#textfield-filter', {} ,function(e){

        if($(this).val()) {
            var val = $(this).val()
            $('#myform fieldset').each(function() {
                if($(this).attr('id').indexOf(val) >= 0){
                    $(this).show();
                }
                else {
                    $(this).hide();
                }
            });
        }
        else {
            $('#myform fieldset').each(function() {
                $(this).show();
            });
        }

    });
});

That works on page load. But I also have a Drop Down Select Menu to select a complete different set of fieldsets. With a click on a button the entiry page is refreshed with the set of fieldsets, which was selected in the Drop Down Menu. But unfortunately, the 'keyup' event of my textfield is not fired after refreshing the page with the button.
As I said, I thought about a jQuery specific problem first, but the only solution I found was to attach the event handler for now and for the future, what I already did with $(document).on('keyup','#textfield-filter', {} ,function(e).

The form is rendered with the Form API. If necessary I can -of cause- give you my php code.

I would welcome very advice.

Many thanks!

Daniel

You need to use the drupal behaviors: if you run your code on ready function when the form is rebuilded on an ajax action all the handlers you have active will disapear because the item fields are replaced by the new ones.

This is the basic drupal behaviors template:

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

      // Execute your code

    }
  };
})(jQuery);

This way after a ajax, all you code inside this behaviour will be called again.

Maybe you will want to add .once() property to avoid execute some parts of your code twice.

Documentation: https://www.drupal.org/node/756722


Custom URL for entity create and view I am using ECK (Entity Construction Kit) to create my custom entities. Now I want to create custom url for various operation on my entities such as create (example.com/my-entity/create) or view (example.com/my-entity/view/custom-unique-field)

I have tried pathauto but it seems I cant define custom patterns for my own entities. Any help towards this step is highly appreciated.

Thanks,
Naveen

You can use the path (url alias) module for the create path. Since that's a single url, you can create a single path alias to change that.

It's a bit harder for your custom entities. You would have to create a custom module and integrate with path auto module to be able to create path aliases for the view urls of your custom entities. It's a lot of code, you can see how the path auto module does it for the node module. But be warned, it's not easy as there are many parts.

The gist of it is that you need to make some tokens available for the path system you are going to make, like the entity label and such. Then you need to create a function that can create an alias when given an entity. This is, however, a bit harder since you need to use the path auto API functions for this.


Field value empty in submitForm I've got a form field that is empty ("") when I submit my form and I cant figure out where I am going wrong. The field in question is reason - as in the reason why this record is being changed. I also include vid because that field is set and passed properly. Full source code of the relevant form here

Form:

public function buildForm(array $form, FormStateInterface $form_state, $part = NULL, $vid = NULL) {
    $form = array();

    //...

    $form['wrapper_form_fields']['reason'] = [
      '#type' => 'textarea',
      '#title' => '*' . t('Reason:'),
      '#value' => '',
      '#rows' => 2,
      '#attributes' => [
        'maxlength' => 250,
        'class' => ['js-modal-reason'],
      ],
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    $form['vid'] = array(
      '#type' => 'hidden',
      '#value' => $vid,
    );

    //...

    return $form;
  }

It appears to render out properly,

The parameter is passed in the HTTP request,

But when I dump it out in submitForm I get a blank value.

  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    $reason = $form_state->getValue('reason');

    echo "
";
    var_dump($reason);
    var_dump($form_state->getValues());
    echo "
";
    die;
    //...
  }

Output:

string(0) ""
array(7) {
  ["vid"]=>
  string(5) "78897"
  ["reason"]=>
  string(0) ""
  ["send"]=>
  object(Drupal\Core\StringTranslation\TranslatableMarkup)#1021 (5) {
  ...

Full source code of the relevant form here. One notable design decision is that most of the logic is in a parent class. I have a parent class InfusionCenterStatusForm that creates forms that will change the status of an instance of a content type. This base class is refined in child classes like InfusionCenterInactiveForm which will specialize the base form to set a record to be inactive.

You should remove the #value property. This is what is blanking it out. If you want it blank to start with, set #default_value instead.

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Textarea.php/class/Textarea/8.6.x


How to see all changes made by an admin Is it possible to somehow pull a report on an admins activity on a Drupal 7 site? I'd like to know for example any development changes, and settings changes, and database changes that an admin on a site has performed.

I've found some modules that help with that, but its too late to install them now.

Administration Notifications this is a simple module that can be used for communication of site changes/updates between the site designer/developer, and the site owners.

  if you maintain a drupal installation for another company, you can use
  this module to inform them when you have updated versions of the site
  (ex drupal 7.1 -> 7.2), updated modules on the site (i.e.
  Administration Notifications 7.x-1.0 -> 7.x-1.1), added new modules,
  or changed the site design in some manner.

or you can try Activity module.

  The Activity module keeps track of the things people do on your site
  and provides mini-feeds of these activities in blocks, in a
  specialized table, and via RSS. The module is extensible so that any
  other module can integrate with it. The messages that are produced are
  customizable via the admin interface and are context sensitive.


Module to show code and its output What I want to do is setup a "PHP filter" to run the code I'm told to run, and display the results as a normal page.

I also want to be able to have a way to show the code; many websites do it, and I was wondering how I could do so within drupal.
Maybe I could tabs in a content type (one for processed code, other for actual code), or an overlay with the PHP Text, or something to show the text in the "PHP Text Field" easily.

Further Description:
Say I have the following code as the body content of my page.

<?php echo "Hello World!" ?>

Who watch the page would see the code output ("Hello World!"); they would not see the PHP code that generated that output. I want something to display the code.

The output of the Geshi Filter module is the following:

I think that in your case, you can insert easyly your own PHP snippets in a common content type to be executed and displayed.

For run your own code from a node you can enable the PHP filter module (it is already in Drupal core, so you does not need download, just enable). this module allows embedded PHP code/snippets to be evaluated. And then, for syntax highlighting of your code, there are several alternatives of modules like:

http://drupal.org/project/geshifilter GeSHi Filter module, for D6 and D7. In this page you will find links to modules alternatives. I have tested this module in drupal 6. Follow the readme.txt instructions. According my test you can show your code (inside respective tags to show code) and run PHP code (copy/paste your code after your code to show, outside the tags to show code). this is an example:

<code type="php">
<?php
echo "hello world";
?>
</code>

<?php
echo "hello world";
?>

and this is the output:

http://drupal.org/project/wysiwyg_syntaxhl (for tinyMCE rich text editor) for D6. This alternative seems not listed in Geshi Filter page.

I hope this information be useful.


Commerce 2: Can Cash and Check payments be implemented? My client's business and website is primarily online purchases. However, there are instances when special customers or referrals come into their office and buy the product by cash or check.

My client wants those purchases to be recorded in the same database as online orders, along with the same captured contact information.

Is there a way to implement the checkout process so that certain employees with designated privileges can enter orders through the online store, but no request for payment information is required.  Or for those and only those privileged people an additional cash / check option is shown? (And the check option may also ask for additional info, such as the bank name and check number.)

You can do this by adding an additional payment gateway.

Add a role, Pay with Cash or whatever you want to call it.
Add a new payment gateway (at /admin/commerce/config/payment-gateways/add).

Name: Cash or Check
Plugin: Manual
Customer: Limit by Role: Pay with Cash role

The "Manual" gateway does not ask for any payment information, so orders with the manual payment selected (which only users with the Pay with Cash role will be able to select) will automatically be processed as completed when this payment method is selected.

If you want to record bank info for checks, you can make two separate gateways, one cash and one checks, and then customize the check gateway with additional fields.


What urls does a page manager intercept? The custom page is set up to intercept /sections/%section.  Will it intercept an URl such as '/section/section-1/articlename' or only '/section/section-1'

Regarding answer from Berdir:
How do I get a custom page to ignore C and respond based upon /A/B regardless of what C value is presented? In my case, C is the name of a specific article of type /A/B and those settings determine the format to be applied to the page through panels. Is there a wildcard?.

It should work the same as hook_menu() implementations and also react when additional path elements are passed to it.

Basically, when you have a request like A/B/C, the menu system first looks for A/B/C, then A/B and finally A until it finds a match.


How to programmatically assign/add new groups to the OG in Drupal Commons 6.25 How to programmatically add new groups to Organic Groups in Drupal Commons 6.25?  I have to do that for approximately 3000 groups. A preliminary test cycle that generates 50 will be the first step.

Which methods are preferable?

http://drupal.org/project/og_massadd
http://drupal.org/node/54979
http://drupal.org/node/1433036
http://drupal.org/project/devel

By the way, the images are stored in sites/default/files/imagecache/group_images_medium/group_images.

Questions that arise

Are the images, and the corresponding paths referenced in the database somewhere?
How can I do the mass-upload of the image and besides that, the mass-creation of groups?
Which tables of the tables of OG are necessary?
Is it enough to take the "og" table itself?

PS: An ongoing attempt with comments for Drupal 6 can be seen here: http://drupal.org/node/79874.

I am the author of og_massadd (which is quite buggy as it is now, unfortunately), but that module is only for adding users to an OG. But if I understand you correctly, you want to create the actual organic groups?

Doing this through PhpMyAdmin will probably be very cumbersome. You would need to add records to node, revisions, any CCK-tables (if your group nodes have CCK fields), og, og_uid (for group memberships) as a minimum. For addding content to your groups, you would need to add to node, revisions (CCK-tables if necessary) and og_ancestry.

It is a bit easier creating a group programmatically:

$groupnode = new stdClass();
$groupnode->type = 'gruppe'; // Group node type
$groupnode->status = 1;
$groupnode->uid = $owner_uid;
$groupnode->title = $title;
$groupnode->body = $body;
$groupnode->og_selective = $group_acces_level;
$groupnode->og_register = OG_REGISTRATION_NEVER;
$groupnode->og_directory = OG_DIRECTORY_CHOOSE_FALSE;
$groupnode->og_private = variable_get('og_private_groups', OG_PRIVATE_GROUPS_CHOOSE_FALSE);
$groupnode->{_integration_cGroupType}[0]['value'] = $cGroupType_content; // CCK field

node_save($groupnode);

if ($groupnode->nid) {
  og_insert_group($groupnode);

  // Set space (if spaces_og is used)
  //$ogspace = spaces_load('og', $groupnode->nid, TRUE);
  //$ogspace->controllers->variable->set('spaces_preset_og', $spacepreset);

  og_save_subscription($groupnode->nid, $owner_uid, array('is_active' => 1, 'is_admin' => 1));
} else {
  dpm('OG creation failed :(');
}


Increase Placeholder Length I have a webform that has a textarea input. I am trying to update the placeholder text. It seems to have a limit of 128 chars. Is it possible to update this to allow for a longer placeholder?

I created a ticket for this issue in the Webform module's issue queue and fixed the problem.

The best solution was to convert the placeholder input from a text field to a textarea so that you can now enter multiple lines of text as the textarea's placeholder.


What hook gets called at the formation of a form? (hook_form_alter called for adjusting a form) what hook gets called at the formation of a form.

I'm trying to add some additional mime types to form with id file_entity_add_upload but my hook_form_alter is getting called after these are validated, so attempts to upload them fails.

Update - added screenshot to illustrate the problem

Update 2
the mime types list in file_entity_get_upload_validators function in file_entity.pages.inc dictates what can be uploaded - see this screenshot

Specifically, in, file_entity_get_upload_validators, the line that populates the valid mime types with hard-coded values is (my screenshot didn't completely show the line):
$validators['file_validate_extensions'] = array(variable_get('file_entity_default_allowed_extensions', 'jpg jpeg gif png txt doc docx xls xlsx pdf ppt pptx pps ppsx odt ods odp'));

Update 3

It would appear that the actual checking of the mime type happens in core module "file", modules/file/file.js : if (!acceptableMatch.test(this.value)) {
        var error = Drupal.t("The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.", {
 I searched the error message shown in following screenshot in the code and file.js was a result - which looks like where the actual validation is taking place.

New error with Andy's answer - maybe it's me will look into it a little later.

Raised as an issue here:
https://www.drupal.org/node/2295671

There's this brilliant image on the Form API Internal Workflow in drupal.org, you can see the build process and structure. You've got callbacks such as #process and #after_build that could be useful for your use case.


How can I have node pages with Fivestar or comment fields cached properly? I was struggling with high page load time for my node pages when I realized that the problem was due to content pages not being cached (html render cache). The page is rebuilt after every single request. With some hit and trial, I realized that fields that have form elements, in my case, Fivestar widget and also the comment form at the bottom of the page prevent page from getting cached. Either of these fields cause this problem.
When I remove those two fields, page starts to get cached.
Has anyone else dealt with a similar issue? What is the best recommended approach to make sure the page continues to get cached?

I realized this was an issue because I was using the Honeypot module. Honeypot disables caching on all pages where there is a form. I updated the setting in the module to exclude node pages and it fixed the issue.


How to remove 'destination' query paramater from link URLs in Drupal 8 For some SEO related reasons, I want to remove the destination paramaters that are attached to the login and register link urls below nodes.

The Link-URLs look like this:

http://example.com/user/login?destination=node/55%23comment-form

But I want it that way:

http://example.com/user/login

For Drupal 7, someone has made it with:

function moon_url_outbound_alter(&$path, &$options, $original_path) {
 // here "moon" is my theme, use your own.
  switch ($path) {
  case 'user/login':
  unset( $options['query']['destination'] );
  break;
 }
}

Source: How to remove the Destination parameter from an URL in Drupal 7?

This source https://www.drupal.org/node/2238759 says, in Drupal 8 hook_url_outbound_alter has been replaced with OutboundPathProcessorInterface. But with the given example there, I don't understand how I could make it to unset the destination paramaters with my .theme file.

Can someone please help and tell how to unset the destination paramaters in Drupal 8 ?

Thanks in Advance!

Before proceeding, realize that although this might be better for SEO; it might be negative for user experience. Personally I'd hate it if I were to comment on a node and after the login I have to navigate back to that node. You might want to perform some session magic to redirect the user back to where he came from.

The answer to your question involves a custom module, with a Path Processor service. In addition to the default module files (mymodule.module and mymodule.info.yml), you'll need mymodule.services.yml and src/PathProcessor/MyModulePathProcessor.php.

The services file will expose your path processor to Drupal with this code:

services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\MyModulePathProcessor
    # Optionally provide arguments.
    #arguments: ['@config.factory', '@entity_type.manager', '@current_user']
    tags:
      - { name: path_processor_outbound, priority: -10} # Low priority acts last.

This 'subscribes' the class to the path_processor_outbound event.

The Outbound path processor should look something like this:

<?php

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MyModulePathProcessor.
 */
class MyModulePathProcessor implements OutboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($path == 'user/login') {
      unset( $options['query']['destination'] );
    }
    return $path;
  }

}


Multiple Context block order / weight I have 2 Contexts set up that each place a block in the same region.

There are times when both these contexts will happen at the same time and as such both blocks appear together.

Currently when both appear they are not in the order I require, is there a way of weighting these across contexts?  I know the weighting works within a context however this is not what I need at this point.

Currently using:
Drupal 6.22,
Context 6.x-3.0

UPDATE:

Hi All,

This post appears to get quite of interest but I'm afraid I don't use Drupal anymore or have any time (or sites) to check these answers.  If any answer gets enough interest and appear to be right then I'll happily mark it correct but I can't actually verify anything.

This patch worked for me. Enable the patch at admin/build/context/settings.

There is a lot that gets discussed after that comment and one contributor even created a module. I haven't read much of the other comments, implemented the module nor any of the patches posted after the one I referred to above.


Site really slow for registered users When I look at the devel query logs of my website I see that views takes up most of the loading time. Anonymous loads of my page are much faster compared to registered loads but how come? Isn't views loaded the same way for every user?

Views supports caching the query and the rendering.

If you have page caching enabled then it's obviously much faster and views isn't involved at all.

There is no silver bullet to improve performance, try to install xhprof to find out where your bottlenecks are.

Using a different cache backend like memcached can help a lot, for a start.


Show Block only if it's a front page and GET variable is set I am setting up a block in Drupal 7 to "show block on specific pages" through PHP.

What I want is that if it's a Front page and there is a GET (listed) variable, only then it shows the block otherwise not.

Hence, the block would only be shown, if the url is www.site.com/?listed=true

I tried this, but it doesn't work:-

<?php
if ( (drupal_is_front_page()) && ( !empty($_GET['listed'])  ) {
  return true;
}
?>

any idea?

You missed a closing bracket. Try this:

<?php
if (drupal_is_front_page() && !empty($_GET['listed'])) {
  return TRUE;
}
?>

or

<?php
if (drupal_is_front_page() && isset($_GET['listed'])) {
  return TRUE;
}
?>


Why does Drupal (8) not discover my custom taxonomy term template? Following the instructions on how to create a custom template for taxonomy terms I managed to add a template suggestion for a particular view mode of the taxonomy term entity by using hook_theme_suggestions_HOOK_alter:

function linkup_theme_suggestions_taxonomy_term_alter(&$suggestions, $vars, $hook) {
  if($vars['elements']['#view_mode'] == 'teaser') {
    $suggestions[] = 'taxonomy-term--teaser';
  }
}

(linkup is the name of my custom theme)

This seems to work as I can see the template suggestions when I print the twig debug information:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'taxonomy_term' -->
<!-- FILE NAME SUGGESTIONS:
   * taxonomy-term--teaser.html.twig
   * taxonomy-term--15.html.twig
   * taxonomy-term--group.html.twig
   x taxonomy-term.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/content/taxonomy-term.html.twig' -->

But for some reason Drupal does not pick up the template which is located in themes/linkup/templates/taxonomy-term--teaser.html.twig

I think the naming is correct (unlike Drupal 7 in 8 you dont need to fiddle with underscores to match dashes in file names)

If I add a template called taxonomy-term.html.twig to the theme then that is discovered.

Am I missing some of Drupal 8's logic to discover the custom template?

You need to use underscores in your suggestion (but continue to use dashes in your template file name):

/**
 * Implements hook_theme_suggestions_HOOK_alter() for taxonomies.
 *
 * {@inheritdoc}
 */
function HOOK_theme_suggestions_taxonomy_term_alter(&$suggestions, $vars, $hook) {
  if($vars['elements']['#view_mode'] == 'teaser') {
    $suggestions[] = 'taxonomy_term__teaser'; // note underscores
  }
}

you could also leave out your condition and do:

/**
 * Implements hook_theme_suggestions_HOOK_alter() for taxonomies.
 *
 * {@inheritdoc}
 */
function HOOK_theme_suggestions_taxonomy_term_alter(&$suggestions, $vars, $hook) {
  $suggestions[] = 'taxonomy_term__' . $vars['elements']['#view_mode'];
}


How to programatically change file user owner I'm using drupal services module. I can upload files through web services but the problem is all created files has the same owner, that is, the user of the web services. I would like to change this user but I don't know how to do it.

I have been searching in drupal api functions (file.inc), but I haven't found a function to change this. How could I change the file's owner?
Thanks.

I don't know of a module built to handle this, but you could build something easily enough to do it:

the DB table file_managed handles files, and includes a uid field which is the user ID of the file 'owner'

This could be modified in a custom module, but a MAJOR WARNING that I don't know what potential damage this could cause to other elements of the site, perhaps someone with more experience with the DB could add some advice in this regard


How to display fields of an entity reference field? My content type have an "entity reference field" related to another content type.

The only option I have is to display a link to the entity.

How can I display other fields from this entity?

You can choose rendered entity instead of label.

After that click the options button (cog wheel) and choose the view mode of the rendered entity.

You can go the referenced content type's manage display and modify the chosen view mode to display the fields that you want

NOTE
you can enable more display modes from manage display > Default > custom display settings

and can also create your own view mode by pressing manage view modes on the bottom of the same screen


Course as a Product in Ubercart I'm trying to understand how course connects to product in ubercart.

There is a module called Course Ubercart, and I'm trying to create my courses as ubercart products with no luck.

Here's the description of the module:

Course ubercart 7.x-1.0-beta3   Supports Course as an Ubercart product and restricts enrollment to paid courses.
Requires: Course (enabled), Chaos tools (enabled), Universally Unique ID (enabled), Views (enabled), Views Bulk Operations (enabled), Entity API (enabled), Rules (enabled), Entity tokens (enabled), Order (enabled), Product (enabled), Image (enabled), File (enabled), Field (enabled), Field SQL storage (enabled), Store (enabled)

How am I supposed to use this? I have tried creating new products, looking to see if there is anything in the course content type UI for it, and I see absolutely nothing.

Just  putting my comments in as answer...

https://drupal.org/node/2106647

How to make custom content type as product in ubercart drupal 7?

You have to create content type as product. Thanks


Restricted access on reference field type? I've created a new field in Drupal 8, the field type is an Entity Reference and the type of item is set to Field Storage.

When I edit my page, I select the node I want to reference, save and publish, but nothing shows on the page, when I go back into edit, the field it says:

  – Restricted access –  (node.field_field_name)

What's going on?

The reason you see that is that you don't have view access to field storages.

In Drupal Core, there is no access control handler for them because they're managed behind the scenes and never really edited/viewed/deleted. That happens automatically through field configs.

You can add implement hook_field_storage_config_access() (look for hook_ENTITY_TYPE_access() for documentation) and allow view access to your users. But....

  I'm trying to find a way to create an index for a content type based off of several of the fields found on each page.

I don't understand that. I'm not sure you're on the right track and before spending time to implement access control, I'd try to confirm that.


forcefully / manually remove content type Is it possible to manually remove a content type?

I've packaged it in a feature and now the content type is no longer needed; it's been deprecated. I'm unable to delete the content type after disabling the feature in the features panel and in the modules page.

If you have devel install then go to sitename/devel/php and execute the following code.

node_type_delete('content_type_machine_name');

else you can run the same code inside hook_init() of your custom module.
Hope it helps.


Adding fees at each payment I am using Commerce Fees module, as I want to add 5% as fees at the time of purchase.

I have added a fees type, and created a rule for this.

My Problem is that I whenever I go to checkout page where I have added some products such that my total order price is 1000, so I should be getting service tax of 50, but I am getting it to be 52.63 instead.

I am attaching my rules export, please help.

 { "rules_5_service_fees" : {
 "LABEL" : "5% Service Fees",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules", "commerce_fees" ],
 "ON" : { "commerce_fees_order" : [] },
 "DO" : [
   { "data_calc" : {
       "USING" : {
         "input_1" : [ "commerce-order:commerce-order-total:amount-decimal" ],
         "op" : "*",
         "input_2" : "5"
       },
       "PROVIDE" : { "result" : { "tax" : "Calculated Tax" } }
     }
   },
   { "commerce_fees_apply" : {
       "entity" : [ "commerce-order" ],
       "fee" : "service_fees",
       "amount" : [ "tax" ],
       "currency_code" : "USD",
       "include_tax" : "0"
     }
   }
 ]
 }
 }

Not as much of an answer as it is a recommendation. You should be doing this at the price calculation (per product) level, not order level. Not doing this can mean you're taking into account the taxes, shipping, other coupons/discounts, etc.


Web service with application-level and user-level authentiation I need to create a Drupal site (D6 or D7 are both OK) with an API. The Services module is the obvious choice, but I couldn't yet figure out if it is possible to do what I want.

My site will contain users and a list of mobile apps that are known to the site. Every user has an 'activity log' on the site (probably a view of nodes where type = activity and user = current user). The users can use one or more of those apps on their mobile devices. When a user does something with an app, the app should connect with the site through the API and write a message (ie. create an 'activity' node) in the user's activity log.

As far as I can see, I will need two levels of authentication. On the application level, the mobile app should identify itself as one of the known apps. On the user level, the user must log in with his username and password, to make sure that his actions will end up in the correct activity log.

I have not yet figured out the best way to do this with Services and related modules. I hope someone can tell me:

if it can be done;
which version of Services I need;
which related modules could be used for authentication;
how to configure them.

Thanks!

Under D6, using Services 3.x

It may be more easy to consider that:

User authentication should be handled directly by Services (OAuth/API/Session)
Using an specific mobile app is a Permission:

in your module, in the resources definition, add a access_callback & access arguments:

Code:

/**
* Implementation of hook_services_resources().
*/
function mymodule_api_services_resources() {
  return array(
   'myresource' => array(
     'retrieve' => array(
       'callback' => '_mymodule_resource_retrieve',
       'access callback' => '_mymodule_api_access',
       'access arguments' => array('Use registered mobile app'),
       'access arguments append' => TRUE,
       ...

add corresponding permissions in a my_module_permission() hook:
Code:

/**
* Access callback for the resource.
*
* @param string $op
*  The operation that's going to be performed.
* @param array $args
*  The arguments that will be passed to the callback.
* @return bool
*  Whether access is given or not.
*/
function _mymodule_api_access($op, $args) { ... }

And then return false if the mobile app is not registered...


I want to import my youtube videos to drupal when I upload a video in YouTube It will sound stupid but what I want to do is I want to get YouTube videos to my drupal installation.

The challenge is one of my clients he wants to see if he can do like while he is walking and liked the video he can upload it somewhere(preferably YouTube) and it comes up in Drupal as field of node.

Is this possible in Drupal ? I am using version 7.

Social Content module allows you to automatically import Youtube videos as nodes. It provides an easy-to-use graphical user interface where you can map node fields with the fields provided by the Youtube API.

To just display Youtube videos, you could map a link field to the Youtube Embed URL, and then output it with Link iframe formatter module (for example).


Change Login Form:Username to Select Text Is it possible to change the login form? Specifically the Textbox for username to select text?

Let's say I have 4 users named: User1,User2,User3,User4 and when select text is clicked. All users will be listed as a choice?

PS: I'm very new to drupal detailed help will be appreciated.

Yes we can do it using function hook_form_alter(&$form, &$form_state, $form_id) {}

Just include this function in template.php of your theme or in you module.

If you theme name is "testtheme" then replace hook with you theme name(testtheme).

OR
you can include it in your custom module. If you have custom module with name "testmod"  then just add this code in your module and replace the hook with your module name (testmod)

function **hook**_custom_form_alter(&$form, $form_state, $form_id){

    //Get the users  from database or keep it static according to requirement
    $users  =   array("user1"=>"User 1","user2"=>"User 2","user3"=>"User 3");
    if($form_id=="user_login"){
    $form['name']['#type'] = "select";
    $form['name']['#options'] = $users;
    $form['name']['#required'] = true;
   $form['name']['#size']='auto';

    }

    }

Don't forget to clear drupal cache.
Hope it will help!


How to avoid certain variables from being cached? I've spent days trying to figure this out and really hope you guys can help me out here.

Let's say, I’ve created a list field on the user entity called field_render_array with the options:

Render array 1
Render array 2

There is a controller called RenderArray which should:

Return render array 0 if field_render_array is not set.
Return render array 1 if field_render_array is equal to render_array_1.
Return render array 2 if field_render_array is equal to
render_array_2.

I’ve been trying to achieve this using a controller like:

<?php

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

class RenderArrayController extends ControllerBase {

  public function content() {
    $user = \Drupal::currentUser();
    $field_render_array = $user->get(‘field_render_array’)->value;

    if (!isset($field_render_array)) {
      return array(
        ‘#markup' => ‘You haven’t set your preferred render array.',
      );
    }
    else if ($field_render_array == ‘render_array_1’ ) {
      return array(
        ‘#markup' => ‘Your preferred render array is 1',
      );
    }
    else {
      return array(
        ‘#markup' => ‘Your preferred render array is 2’,
      );
    }
  }

}

The problem is that the value of $field_render_array is getting cached. This comes across as a bug for end-users as the render array doesn’t immediately change after changing the value of field_render_array.

Is it possible to somehow avoid certain variables from being cached or is there another solution to achieve the same thing?

If the variables come from the current user, then add this cache context to the build array you return:

$build['#cache']['contexts'][] = 'user';


Theme expanded menu item? Does anyone know how I can theme the entire li output for an expanded menu item?

For instance, the output is

I want to change the output to:

Is there a way to theme this output, like there is a way to theme specifically the expanded menu item output, like there is to theme other li outputs, such as below...?

function theme_menu_tree__main_menu_link($variables) {
  return '
'.$variables['tree'].'
';
}

My current code

function theme_menu_link__main_menu(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    foreach ($element['#below'] as $key => $val) {
      if (is_numeric($key)) {
        $element['#below'][$key]['#theme'] = 'menu_link__main_menu_inner'; // 2 lavel

      }
    }
    $element['#below']['#theme_wrappers'][0] = 'menu_tree__main_menu_inner';  // 2 lavel

    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'],     $element['#localized_options']);
  return '
' . $output .
  $sub_menu . "
\n";
}

You can get the complete (main) menu tree with this in your THEME_preprocess_page

  // Get the entire main menu tree
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Add the rendered output to the $main_menu_expanded variable
  $vars['main_menu_expanded'] = menu_tree_output($main_menu_tree);

Then you can pass that to a theme function in your page template:

<?php print theme('links__system_main_menu', array(
  'links' => $main_menu_expanded,
  'attributes' => array(
    'id' => 'main-menu',
    'class' => array('nav', 'navbar-nav'),
  ),
)); ?>

I've been using the function below to create a Bootstrap ready dropdown menu - you can clearly see how the submenus are themed by checking the $link['#below'] part of the array.

    /**
     * Implements hook_links__system_main_menu().
     *
     * @param array $vars
     * @return string
     *  Themed HTML for bootstrap 3 ready main menu.
     */
    function YOURTHEME_links__system_main_menu($vars) {
      // Get the active trail
      $menu_active_trail = menu_get_active_trail();
      // Initialise our custom trail.
      $active_trail = array();

      // Get current path
      $dest = drupal_get_destination();
      if (is_string($dest['destination'])) {
        $paths = explode('/', $dest['destination']);
        // Loop through and add all active paths
        foreach ($paths as $path) {
          // Read previous element added to active trail (using array values
          // preserves original array).
          $safe = array_values($active_trail);
          $previous = array_pop($safe);
          if ($previous) {
            $active_trail[] = $previous . '/' . $path;
          }
          // Or this is the first one
          else {
            $active_trail[] = $path;
          }
        }
      }

      // UL classes
      $class = implode($vars['attributes']['class'], ' ');
      $html = '
';

      // Iterate links to build menu.
      foreach ($vars['links'] as $key => $link) {

        // Check this is a link not a property.
        if (is_numeric($key)) {
          $sub_menu = '';
          $li_class = array();
          $a_class = array();

          // Check if link is in active trail and add class.
          if (in_array($link['#original_link']['link_path'], $active_trail)) {
            $li_class[] = 'active-trail';
          }
          if ($link['#original_link']['link_path'] == end($active_trail)) {
            $li_class[] = 'active';
          }
          // Check if last element in list and see if LI contains actual link
          $link['#attributes']['class'][] = strtolower(str_replace(array('& ', ' '), array('', '-'), $link['#title']));
          $link_title = $link['#title'];

          if (isset($link['#localized_options']['attributes'])) {
            $link['#attributes'] = array_merge($link['#localized_options']['attributes'], $link['#attributes']);
          }

          // Check if we have a submenu.
          if (!empty($link['#below'])) {
            // Check if lvl 1, if higher do other stuff
            if ($link['#original_link']['depth'] < 2) {
              $li_class[] = 'dropdown';
              $link_title .= '';
              $link['#attributes']['class'][] = 'dropdown-toggle';
              $link['#attributes']['data-toggle'] = 'dropdown';
            } else {
              $li_class[] = 'dropdown-submenu';
              $link_title .= '';
            }
            // Theme submenu
            $sub_menu = theme('links__system_main_menu', array('links' => $link['#below'], 'attributes' => array('class' => array('dropdown-menu'))));
          }
          // Build classes string
          $classes = '';
          if (!empty($li_class)) {
            $classes = ' class="' . implode($li_class, ' ') . '"';
          }
          $html .= '
' . l($link_title, $link['#href'], array('html' => 'true', 'attributes' => $link['#attributes'])) . $sub_menu . '
';
        }
      }
      $html .= '
';
      return $html;
    }


How do I get the uid of a node? I am trying to get the user ID associated with a node using this code in Drupal 7, without any luck:

$uid =  $node->uid;
echo "uid: " . $uid;

$uid doesn't have any value in it.

I want to get it so that I can count the number of my members' posts.

$node = node_load('NID');
$uid = $node->uid;
$sql = "SELECT nid FROM {node} WHERE uid = $uid";
$result = db_query($sql);

$number_of_rows = $result->rowCount();
echo "uid: " . $uid;
print "
$node->name has submitted $number_of_rows source code / articles.
";'

I tried putting it in a display suite module under fields. I also tried putting in a page content type.

That should work. Try making sure that you have a properly loaded node object.

$node = node_load('NID');
echo $node->uid;

It is possible that if the node was created by an anonymous user that the $uid would be zero and thus wouldn't print.


Help installing rpx module I'm trying to use the RPX module and I get as far as step 5.

I've installed and enabled the plug

checked permissions

and selected "visitors"

Then i get here.

  Visit admin/config/people/rpx and enter your Janrain Engage API key.* This API key must be entered for the module to function properly.

I find that the path admin/config/people/rpx doesn't exist.

I'm running Drupal 7.12 with RPX 7.x-2.2

Is this a common problem, does anyone know how to fix it?

The page you are referring to, admin/config/people/rpx, is defined in the module named Janrain Engage UI, machine name rpx_ui. You need to have it enabled for the path to be registered.


sharing code in custom module I have a small module that basically contains a controller and a block plugin. I cannot figure out how to include a class in both of them

The files are located in sites/all/modules/my_module. That directory contais

$ ls -R
.:
config/  my_module.info.yml       my_module.links.menu.yml  src/
css/     my_module.libraries.yml  my_module.routing.yml

./config:
install/

./config/install:
my_module.settings.yml

./css:
hello_block-layout.css

./src:
Controller/  Plugin/  Utils.php

./src/Controller:
MyController.php*

./src/Plugin:
Block/

./src/Plugin/Block:
MyBlock.php

The problem is the namespaces:
MyController.php has namespace Drupal\my_module\Controller and
MyBlock.php has namespace Drupal\my_module\Plugin\Block

I can use the class definition in Utils.php for one of the two, if I insert a require_once in the file (with the whole path, use of .. seems not to be working) AND I use the same namespace in it.

So if MyController.php starts with

<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;

require_once '/home/rdgon/public_html/sites/all/modules/my_module/src/Utils.php';

and MyBlock.php starts with

<?php
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;

require_once '/home/rdgon/public_html/sites/all/modules/my_module/src/Utils.php';

and Utils.php starts with

<?php
namespace Drupal\my_module\Controller;

then the class is used by correctly by the controller. But then MyBlock.php complains about not finding the class, because the namespaces don't match.

My question: is it possible to share (include) a class definition by several components of a module? What location should I use for the shared code and what is the proper way to include it? (using the full path of the file cannot be the way to go)

thanks in advance, Ruud

If you want the class declared in my_module/src/Utils.php to be made available to any PHP script, add this at the top of that script file:

use Drupal\my_module\Utils;

This of course assumes that you're following the correct PSR-4 standards for naming: make sure that mymodule/src/Utils.php exists, and contains one single class named Utils, with namespace Drupal\my_module at the top.

See PSR-4 namespaces and autoloading in Drupal 8 for a more in-depth explanation.


Drupal Commerce Line Item Revisions Has anyone seen a module capable of providing line item revisions? I am calculating the cost of a custom line item type via rules. It is essentially a booking and may need to be altered in the future.

I am therefore looking for some information from anyone who may have had a similar issue? This is what I need.

Every time I recalculate the price of a line item on an order to create a new revision.
Always display the latest revision to the user.
Provide a view showing other revisions in the admin panel.

The line item entity doesn't have revisions, so you would need to add this for all line items. Which means, you need to alter some of the very core of Drupal Commerce. It's possible, but maybe it would be better to store bookings in a custom table and save a reference on the line item instead.


spamspan not working, how to apply patch? http://drupalcode.org/project/email.git/commitdiff/523cd0d

This is the link to the patch but looking up how to apply a patch I understand the command to use in terminal but I don't understand how to dload the patch?

What type of file is it saved as? and do you apply within modules folder or sites folder?

There's nothing too sophisticated about a patch file -- you can copy the commit code in the above link to your clipboard and paste it into a text editor. This link might make it easier:

http://drupalcode.org/project/email.git/patch/523cd0d

Then, you want to save your new file in the same folder as the module file you're trying to patch (based on the path in the actual patch file) and run the patch script as outlined here:

https://drupal.org/patch/apply


Price by multiple attributes in Commerce I need to dynamically alter a price based on the value of two attributes in Commerce. I'm quite new to commerce so not exactly sure how to achieve this. Using rope as an example, the price needs to vary based on both the length of the rope and it's diameter. I know I could create a line item for each length if that was the only variant, however due to both length and diameter being variable this becomes more of a challenge.

Anyone have any ideas?

It will probably have to be done with custom Rules.  If the price is calculated predictably via different measurements/attributes, you can use the Rules Event of Calculating Sell Price of Product.  Conditions could vary, but a custom Action or Action set is probably going to be needed to calculate the price, and then set the price to the calculated value.

Maybe check out this link for an example of dynamically changing product prices.

http://www.drupalwoo.com/content/blog/drupal-commerce-and-rules-changing-product-price-dynamically


List of Views add-on modules Is there anywhere that I can find a list of add-on modules for the Views module?  If I search for "Views plugins" or "Views add-on", the search just picks up on "Views" and returns a million results that contain "Views".  I was hoping to find a list of things like "views_conditional", "views_or", etc.

You can either use google (or some other search engine if that's your thing), or drupal.org search.

On the drupal search pages you can filter by modules and by the "views" category, among other things.

For example, see https://drupal.org/search/site/views?f[0]=&f[1]=&f[2]=im_vid_3%3A89&f[3]=drupal_core%3A103&f[4]=sm_field_project_type%3Afull&f[5]=ss_meta_type%3Amodule&solrsort=iss_project_release_usage+desc

Other than that there are no secret ways, just persistent searching.


Get delta value of Multifield How do I get the delta value of a multifield in a View template? I need to get the delta value in the Row output View template.

<?php foreach ($row->field_my_field as $data): ?>

  <?php if ($data['raw']['value'] == 'o'): ?>
    // Output nothing, or placeholder, whatever
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>


Change labels of date select fields I'm using the Form API to create a Date of Birth field with  lists for month, day and year.

$form['dob'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of birth'),
    '#default_value' => '',
    '#date_format' => 'm-d-Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '-100:+0',
    '#required' => TRUE,
);

Sine the default value is blank this outputs the following:

How can I alter the labels? Specifically I want to get rid of the '-' characters so it looks more like this

There might be better way to do this, but one method would be to run an #after_build function that will alter the first '' placeholder date label option to your liking. For example:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['dob'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of birth'),
    '#default_value' => '',
    '#date_format' => 'm-d-Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '-100:+0',
    '#required' => TRUE,
  );
  $form['dob']['#after_build'][] = 'MYMODULE_myform_dob_after_build';
}

// Alter the date component option so the first placeholder element has the new label.
function MYMODULE_myform_dob_after_build(&$form, &$form_state) {
  $form['day']['#options'][''] = t('Day');
  $form['month']['#options'][''] = t('Month');
  $form['year']['#options'][''] = t('Year');
  return $form;
}


file pattern name for content type What is Drupal 8 file pattern name for a specified content type?

Suppose I have  a Movie content type. What is the pattern name for its page? Is it page--node--movie.html.twig?

This is what your looking for.

The Drupal 8 code is the following one.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $suggestions[] = 'page__' . $node->getType();
  }
  return $suggestions;
}


Image field causes #access to reset to default I am using ajax to show/hide a field based on a date field. I set the default access to TRUE. If the user selects a date of birth over 18 years old, $is_younger and consequently the access switch to FALSE.

function mrpeanut_form_record_node_form_alter(&$form, &$form_state, $form_id) {
    // some other stuff here
    $is_younger = TRUE;
    $values = !empty($form_state['values']) ? $form_state['values'] : array();
    $dob_date_combo_element = &$form['field_dob']['und'][0];
    $dob_date_combo_element['#ajax'] = [
      'callback' => 'mrpeanut_form_record_node_form_minor_agreement_callback',
      'wrapper' => 'minor-ajax',
      'effect' => 'fade',
    ];

    if (!empty($values['field_dob']['und'][0]['value'])) {
      $dob = new DateTime($values['field_dob']['und'][0]['value']);
      $now = new DateTime();
      $age = $now->diff($dob)->y;
      $is_younger = $age < 18;
    }

    $form['field_minor_agreement']['und']['#access'] = $is_younger;

This is working great until the user selects and uploads an image on a separate image field. Then, $is_younger switches back to TRUE, regardless of whether they are over 18 or not. I can't seem to figure out why.

I think the error is happening on this line:

if (!empty($values['field_dob']['und'][0]['value']))

After I upload an image, I get this error if I try to watchdog the value.

  Notice: Undefined index: field_dob in
  mrpeanut_form_record_node_form_alter()

I think $values is getting overwritten after the image is uploaded and therefore date of birth can't be calculated again and it reverts back to $is_younger = TRUE.

Here's my callback:

function mrpeanut_form_record_node_form_minor_agreement_callback($form, $form_state) {
  $commands = array();
  $commands[] = ajax_command_replace('#edit-field-minor-agreement-wrapper', drupal_render($form['field_minor_agreement']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

I would try refactoring your code, so that the part that produces the value of $is_younger first checks whether the triggering element is the field_dob field.

As an example:

// some other stuff here
$dob_date_combo_element = &$form['field_dob']['und'][0];
$dob_date_combo_element['#ajax'] = [
  'callback' => 'mrpeanut_form_record_node_form_minor_agreement_callback',
  'wrapper' => 'minor-ajax',
  'effect' => 'fade',
];

// Were we called by the #ajax-ified element?
if (isset($form_state['triggering_element']) &&
  $form_state['triggering_element']['#name'] === 'field_dob[und][0][value]') {
  $values = !empty($form_state['values']) ? $form_state['values'] : array();
  $is_younger = TRUE;

  if (!empty($values['field_dob']['und'][0]['value'])) {
      $dob = new DateTime($values['field_dob']['und'][0]['value']);
      $now = new DateTime();
      $age = $now->diff($dob)->y;
      $is_younger = $age < 18;
  }
  $form['field_minor_agreement']['und']['#access'] = $is_younger;
}
// Initial form loading.
else if (empty($form_state['input']) {
  // Place initial loading logic here for field_minor_agreement.
}


Display users who flagged content In my Drupal 7 project I have users of role A and B respectively. Users of role A can create content and users of role B can flag it.

I'm building a view that displays on A users' account page their content and names of B users who flaggd it.

I have created a view Content (not User) and added relationship Flags: Content flag and consequently field Flags: User uid to display together with content related fields.

In view block I use Grid format. Same content information is displayed several times per each user who flagged it, like  bellow

Content title QWERTY
Users uid  who flagged 1

Content title QWERTY
Users uid who flagged 2

Content title QWERTY
Users uid  who flagged 3

How can I display content information only once and users who flagged in one field separated by comma?

you need to edit /drupal/sites/all/themes/MYTHEMENAME/template.php
then add the following code.
function MYTHEMENAME_preprocess_views_view_fields($vars){
      if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['id'] != 1){
        $vars['fields']['title']->content = '';
      }
    }

What this code is saying is if your row is not equal to (!=) 1, then don't display anything. Thus, it will print your title only for row 1.

replace MYTHEMENAME with your actual theme name.

replace VIEWNAME with your view's name. example: flagged_content

replace DISPLAY with your view's machine name. You can find this by editing your view, then under Advanced -> other
examples: block, block_1, page, page_1 or default. It's default if you're using your master view.

For user's separated by comma you would have to use css for that.
JS FIDDLE EXAMPLE
PS: I think you would have to change it from grid to html list for your view.


views_embed_view use to append new HTML from view Using drupal 7, I have a view that created an aggregated table like this:

Animals  44

Plants 25

I want that when user clicks on 'Plants', on the same view, without refreshing, the list of the 25 plants (coming from another view) comes out, appending the HTML to the Plants div.

I think that views_embed_view might be the solution. I am on the right track? how do I specify on which DIV the generated view should be appended to?

thanks

You are on the wrong path.

Install the Views Megarow Module. Then create another view that will list the respective Animals and Plants together. Set the path as well, in this example I will assume a path of

megaitems/%

Note the argument.

Then add a contextual filter of 'Content: Type'. When the filter value is not in the URL, display content of no results found. Verify that it works by typing the content type (animal or plant, ie the machine name of your content) in the preview contextual filters section at the bottom. It should only show the nodes for the specific content type that you type in.

Back to the original view, select the Format as Megarow table. Add a field 'content type', and set its display to hidden. Move this field so that it is the first field in the list. Then add a field Megarow links. In the megarow settings, there is a section 'Links'. Add this:

View|megaitems/[type]

This will now create a link which when you click on it loads your content using AJAX. You might have to adjust your view slightly as you are using aggregation.

Good luck!

I have just created this view with aggregation active and views megarow does not play nice with it. But all is not lost. Install Views Field View also. Then create a new view wherein you embed a field of a view. This field must then use the view of your aggregation and append as an argument that is passes the node type again. Then in you original aggregated view you have a contextual filter by type and you do your aggregation as normal. This aggregated view will then return your aggregation result per content type to the new view, and in the new view you add your megarow field.


How to add translation of all content? I am adding Arabic translations to an English website. For every article node, I need to individually translate each node.

Is there a way to add translations in one go?

The customer will update the content, but I need to create the initial translation of more than 500 nodes.

You can get all nodes, then with a foreach create a translation for each node.

$nodes = \Drupal::entityQuery("node")
//->condition('type', 'my_custom_type') //use this for specific content types
->execute();

$nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);

foreach ($nodes as $node) {
  //Creating the translation Spanish in this case
  $node_es = $node->addTranslation('es');
  $node_es->title = 'Mi prueba!';
  $node_es->body->value = '
El cuerpo de mi nodo.
';
  $node_es->body->format = 'full_html';
  //Saving the node
  $node_es->save();
}

You can add some fields like title and body, or just save.


How to change date repeat display format I am using date module & date repeat API but now i want to change repeat date format.Now repeat date is display in "Repeats 5 days " but i want to show only "5 days " instead of "Repeats 5 days"

Similar question was raised before. There is still no way to override the format of the Repeat rule via theme functions. The answer that was given for the linked question provides a possible workaround (quoted below).

  you may override theme_date_repeat_field(), which calls
  date_repeat_rrule_description(). You could call your own version of
  that function to customize the display.

  This would leave the contrib modules untouched, but you would be
  duplicating some effort and have more code to maintain.

There is an active issue for Date Repeat sub-module - Make Repeat Date Format/Display More Flexible which did not receive enough attention.

You can also patch the date_repeat.module directly and keep track of it during updates, but that is obviously not a desired way to go about this.

The function that constructs the output of the string you need to change is

function date_repeat_rrule_description()

check $output variable - that is what you are trying to modify.


Embedding content in external website I'm new to Drupal (and SE) and am looking for a way to embed Drupal 7 content in an external website.
D6 had modules for that (web widget and embed widget).
How can I do it in D7?
Thank you!

Web Widgets now has a Drupal 7 release, so it might be worth trying it out.


Is "parent" supported in aliases? Is the "parent" key supported in Drush 9? It isn't in the example file here https://github.com/drush-ops/drush/blob/master/examples/example.site.yml or drush docs:aliases and I am trying to get a bastion working off of the Drush 8 docs (https://docs.drush.org/en/8.x/bastion/).

Can anyone confirm it should pickup a "parent" key?

edit: I see here http://api.drush.org/api/drush/examples%21example.aliases.drushrc.php/master that "parent" was deprecated before the switch to YAML in Drush 9 so maybe it is called something else now. Not sure how to specify merging key values in YAML.

parent is not supported in Drush 9 aliases, but there are a couple of facilities that you can use.

Variables such as ${env.home} or ${foo.bar} can be used to inject environment and configuration values from Drush configuration into alias files.

An environment named common in any sitename.site.yml file will have its attributes copied into every environment defined in the same file.


How limit access to a paragraph type by role, like it is for content types? The permissions page at /admin/people/permissions provides very fine grain control over which actions people can do with specific content types. How can I  add all paragraph types under this permission system? We have a paragraph type that is reserved only for special cases, and we don't want anyone but a certain custom editor role creating/editing them.

I've searched for a few contrib modules, but many are not updated (or just plain abandoned) with little documentation.

Simply enable the Paragraphs sub-module Paragraphs Type Permissions. It provides CRUD permissions per Paragraphs Type.

http://cgit.drupalcode.org/paragraphs/tree/modules/paragraphs_type_permissions/paragraphs_type_permissions.info.yml?h=8.x-1.x

  Allows users to configure permissions for individual Paragraphs
  types.


how to display a link on a node view page? I want to display a link on a node view page just like the "Add new comment" link.
How should I do this?

I think it can be done through hook_node_view(),  but how can I use this hook?

In your implementation of hook_node_view(), add an element to the $node->content array. The element should be a renderable array as expected by drupal_render().


"Click to show" text at pages How can I implement "click to show" some text data at pages?
Also I need to save log in database about events.

I've found tiny module Field Value Loader (Show field on click).

Any suggestions about how to implement this?

Checkout these modules:

qTip (Stylish jQuery Tooltips):

  qTips are stylish tooltips that can be configured and styled (more to come in later releases) to fit nearly any website's design. You can look at demo here.

Field Tooltips:

  Field Tooltips provides a user interface for adding tooltips to fields. Field Tooltips includes three important features:

  A simple administration interface for adding tooltips to fields.
  Support for all field types.
  Support for HTML tooltips.

Beauty Tips:

  The Beautytips module provides ballon-help style tooltips for any page element by integrating the BeautyTips jQuery Tooltip plugin by Jeff Robbins with Drupal. It provides an API for adding custom beautytips as well as some built-in features. Admins can enable rollover balloon-help style tooltips for text fields within forms. It also supplies hover tips for Drupal help links and advanced help links.

  Most importantly, it allows developers to add their own custom beautytips popups to their site without having to delve into jQuery.


Need help with Block Caching I run a flash card game embedded as a block in a Drupal 7 site.

Below that main block I display 3 further blocks for the winners of the previous and current week and top 7 best players:

And these 3 blocks are really dragging the performance of my web site (loading page is taking 5-10 seconds more than without them). I'd prefer them to be cached every 15-30 minutes because the weekly top 7 doesn't change often.

How could I do that - without jeopardizing my main block with the game? I.e. the main block contains flash vars specific to each user (his authentication hash) - this one block may not cached and served to any other user.

Below is my code:

pref.info -

name = Pref
description = Pref module
package = Pref
core = 7.x
files[] = pref.module

pref.module -

function pref_block_info() {
  return array(
    'pref_main' => array(
      'info' => t('Display flash game for auth. users'),
      'cache' => DRUPAL_NO_CACHE,
    ),
    'pref_winner' => array(
      'info' => t('Show the winner of the last week.'),
      'cache' => DRUPAL_NO_CACHE,
    ),
    'pref_leader' => array(
      'info' => t('Show the leader of the current week.'),
      'cache' => DRUPAL_NO_CACHE,
    ),
    'pref_top' => array(
      'info' => t('Show the top 10 of the current week.'),
      'cache' => DRUPAL_NO_CACHE,
    ),
  );
}

function pref_block_view($block_name = '') {
  global $user;
  $viewer_id = $user->uid;

  if ($block_name == 'pref_main') {
      .... # may not be cached
      return array(
        'subject' => '',
        'content' => '...here I return the .swf file + user-specific hash...');
  } else if ($block_name == 'pref_winner') {
      .... # should be cached
  } else if ($block_name == 'pref_leader') {
      .... # should be cached
  } else if ($block_name == 'pref_top') {
      .... # should be cached
    $result = db_query("
select u.id,
        u.first_name,
        u.female,
        u.city,
        m.money,
        u.login > u.logout as online
from pref_users u, pref_money m where
        m.yw=to_char(current_timestamp, 'IYYY-IW') and
        u.id=m.id
order by m.money desc
limit 7
");
    $i = 0;
    $list = array();
    foreach ($result as $record) {
      $list[] = user_link($record) . ($i++ > 0 ? '' : '&nbsp;&raquo;');
    }
    $theme_args = array('items' => $list, 'type' => 'ol');
    $content = theme('item_list', $theme_args);
    return array(
      'subject' => 'Семерка лучших',
      'content' => $content,
    );
  }
}

For module caching I probably should enable it in the /admin/config/development/performance and then use some other constant instead of the DRUPAL_NO_CACHE (but which one to take from the includes/common.inc)?

A simple solution would be to cache the output instead of caching the block. This would be done in your hook_block_view implementation.

It could look like this:

...
$cache = cache_get('pref_pref_leader', 'cache_block');
// Return cache if possible.
if (!empty($cache) && isset($cache->data) && !empty($cache->data)) {
  return $cache->data;
}

// no cache, generate the output.
...
$content = ...;
$block = array(
  'subject' => 'Семерка лучших',
  'content' => $content,
);
// Cache for 30 mins.
cache_set('pref_pref_leader', $block 'cache_block', time() + 1800);
return $block;
...

See documentation for

cache_set
cache_get


How to create grouped filters based on integer range? I'm developing a recruitment website which will allow users to filter jobs by salary. It has been designed so that the filter is grouped into salary ranges like this...

I am using the Range module in order to add a range field to my job content type (essentially just two text boxes). The idea is that the admin can enter in any 'from' and 'to' integer (doesn't have to be a value that matches one of the filters e.g. £20–25k). Instead the query should be able to adapt and show any matching results.

The issue I have is that because I essentially have two fields saved there doesn't appear to be any simple way of grouping filters. I have attempted to use the Global: Combine fields filter but this only works with strings, not integers.

I've also attempted to add the Salary range filter included with the Range module under the Filter criteria heading of my view but this doesn't appear to work either. Here is a screenshot of what I attempted (I'm assuming that the Range module doesn't actually store the integers in-between the 'to and 'from' fields so I guess this wouldn't work. I'm also not sure that separating the values with commas is valid either).

The only method I can think of would be finding a way of adding the two fields together to create one total integer which would then allow me to use the standard is-between operator available when filtering a single field in Views.

Thanks in advance.

You might try the Contextual Range Module: https://www.drupal.org/project/contextual_range_filter

According to the documentation, this allows you to make a contextual filter based on a range (as opposed to just a single field value).


How to broadcast a message to several Drupal web sites? I have several Drupal installations and I want somehow, to send a message that would be displayed in all of them at the same time, in a block for example.
The scenario could be that the server will be down for maintenance, so I want to show a message on the admin section alerting this.

My first thought is trying to use something related with RSS Feeds, but if anyone has experienced the same situation any feedback will be appreciated

There are a number of ways to accomplish this, but I wouldn't recommend using Feeds for system wide alerts because of issues with the way Feeds locally caches the source RSS based on how often or infrequently it changes.  This also requires maintaining redundant content types, views, and nodes across several sites.  While this could be done with a Feature, there are much simpler ways to do this.

One extremely simple option is to configure each site to with a block that embeds an iframe from a centralized messaging site that isn't even running Drupal.  Update the HTML of the message and it will be shown everywhere. When you are done, update the HTML to no longer display the message. Of course this will require a layout that allows the space for the message to always be there, but empty when there is no message.  Not ideal.

You could accomplish the same thing without the empty space in the layout by including an external javascript that inserts the message when the .js on a main site is updated, but that is getting less simple and could be impacted by each site's javascript aggregation and caching issues.  Not ideal.

For a solution that is only slightly more complicated, but far more efficient and doesn't require any scripting knowledge, implement https://www.drupal.org/project/sharedblocks.  This module allows you to define a View driven block on a the site used to generate the messages as shared and subscribe to that block on every site you'd like to display the messages.  This has the added bonus of being able to configure the messages as a content type that are archived so you have a system history as well.  Just add either an expiration time or a checkbox to limit the message's active state and filter the View so it returns nothing if there is no active message.  The result of an empty block from the parent site on the child sites is the block isn't displayed at all so no need to deal with the space an empty iframe creates.  The cache and cron settings for Shared Block are configurable.

UPDATE: Just reviewed the https://www.drupal.org/sandbox/cecrs/2340909 to be promoted to a full project.  The module is currently limited to a single alert, but the alert is displayed using a block that can be shared across multiple sites.  I've opened a feature request to change that to define an Alert entity, even without that Site Alert + Shared Block is a great solution.


How do I create new Message Templates? I am using Drupal 6 with the Open Atrium distribution, as for now I am able to send email notifications every time I post or edit a news. However I'd like to create more message templates, specifically I'd like to use a different template based on the news tags. For instance if I publish a news with "gallery" tag I want to use a dedicated template and so on. Any idea on how I can accomplish that? Many thanks.

Previewable email templates is a good module and supports Rules and Tokens.

  The Previewable Email Template (PET) module lets you create email
  templates, with token substitution, which can be previewed by the user
  before sending. The emails can be sent to one or many email addresses
  in a flexible way, and the recipients may or may not be Drupal account
  holders (users).


Printing individual components of comment-form in comment-wrapper.tpl In my comment-wrapper.tpl.php I was doing

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

which worked fine. But to render  the comment-form according to given theme, I tried doing this:

<div id="comments" class="<?php print $classes; ?>"<?php print $attributes; ?>>

   print render($content['comment_form']['author']);
   print render($content['comment_form']['field_email']);
   print render($content['comment_form']['comment_body']);
   print render($content['comment_form']['actions'['submit']);
   print drupal_render_children($form);

 if ($content['comments'] && $node->type != 'forum'):
     print render($title_prefix);

<?php print t('Comments'); ?>

     print render($title_suffix);
endif;

This code is printing all the components of the form  but the submit button is not working as it should. When I click the submit button it is not giving any reaction. Do I need to add any more lines of code to make this comment form work  ? Thank you.

You forgot to render hidden form fields that are required for the correct work.

Just add this line of code after outputting all visible form fields:

<?php
  print drupal_render_children($form);
?>

Also if you output form elements outside form template you need manually add {form} tag
In your case you will get

<form id="comment-form" class="comment-form" accept-charset="UTF-8" method="post" action="<?php print url('node/' . $node->nid); ?>#comments">
<?php
  print render($content['comment_form']['author']);
  print render($content['comment_form']['field_email']);
  print render($content['comment_form']['comment_body']);
  print render($content['comment_form']['actions']['submit']);
  print render($content['comment_form']['actions']['preview']);
  print drupal_render_children($content['comment_form']);
?>
</form>


Generating a taxonomy I have a list of items that I need turned into a taxonomy. My list looks something like this:

Apple
    Apple 1a
    Apple 1b
    Apple 2a
    Apple 2b
    ...
    Apple 192b
Banana
    Banana 1a
    Banana 1b
    Banana 2a
    Banana 2b
    ...
    Banana 96a
....
More Items
    More Items 1a
    ....
    More Items 300b

Anyway you get the idea. Creating new terms for each of these isn't going to work in this case , it'll take days. Is there any way to bulk create from a text file like this?

If you can get your terms into CSV format you can use the excellent Taxonomy CSV import/export module:

  This module allows you to import or export taxonomy from or to a CSV (comma-separated values) file or with a copy-and-paste text.

It has support for importing hierarchical trees like yours, and even supports drush.

It also has good documentation to get you started.

EDIT

You could also try the Taxonomy import/export via XML module which does the same thing but for XML (if you find it easier to get your data into that format). It's only in dev release at the moment but its worth a try.


Creating a view that shows all events and the users that have signed up for each event I am using the Signup module, and I am looking to create a view that shows all events and the avatars (default Drupal user picture field) of the users that have signed up for each event.

Here is a mockup of what I am trying to achieve. I have everything but the avatars so far.

View Mockup

See export of the View I have so far

Doing something like this is pushing views to it's limits. You want to pull in a lot of data and group it by the node id. I'm not sure if all this is possible through the views interface, though I believe it will be possible with the engine that's running views.

Instead of trying to achieve this rather complex view, which may become something, that's hard to modify, you could do this quite easily using more and simpler queries. Such a simple solution could look like this:

You could create a simple view, which display all the info except the signups. (Node title etc)
Signup already has a view, which will display the people that signed up for an event. With a little bit of modification, you could make it show the avatar of the users that has signed up for an event. Then you could embed this view in either a preprocess function and/or a template for the view you created in step 1.
You're done.

The ideal thing would be to create all of this in a single view, but sometimes you have to think about what the cost will be compare to the gains. I doubt you will be able measure any performance differences, unless you list hundreds if nodes with signups. But the time you save doing it this way is quite a lot.

This is the same with views itself, it's inefficient, but nothing important (for most sites) and it allows us to save lots of time, not having to code queries, theme functions etc.

Update:

Embedding a view with arguments (like node id) is pretty simple:

$html = views_embed_view($name, $display_id, $arguments)

Or in your case

$html = views_embed_view('signup_user_list', 'default', array('nid' => $nid));


File Upload Field not working I just tried to create a simple mandatory file upload field in a custom form like this:

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

  $form['#attributes'] = array('enctype' => "multipart/form-data");

  $form['pdf_file'] = array(
    '#type' => 'file',
    '#title' => $this->t('PDF File'),
    '#description' => $this->t('PDF files only'),
    //'#multiple' => TRUE,
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
  );

  return $form;
}

And that did not work.

When submitting a file (no matter what kind of), i get this error all the time:

"PDF File field is required."

Does anybody have an idea what I am doing wrong?

I am using Drupal 8.2

Try removing the required line. Updated code:

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

  $form['#attributes'] = array('enctype' => "multipart/form-data");

  $form['pdf_file'] = array(
    '#type' => 'file',
    '#title' => $this->t('PDF File'),
    '#description' => $this->t('PDF files only'),
    //'#multiple' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
  );

  return $form;
}

Update: As upload fields can not be required in PHP, just make it required in JS/jQuery

Add this code to a JS file:

$( "#target" ).submit(function( event ) {
  if( $(".pdf-file-field").files.length == 0 ){
    alert("Please add a file");
    event.preventDefault();
  }
});

Note: Instead of "event.preventDefault()", you should also be able to use return false.


How can I add language selection to the user profile in "my account" settings I'm currently allowing users to switch language with the "Language switcher" block, but I would like have this as part of the user profile that is managed with the "My Account" settings page.

Is it possible to add this as a field? Adding a field is no problem, but can I make it refer to the language setting that is normally controlled by the language switcher block? I'm using Drupal 7.

The language setting is already present in the account settings page, I was misguided by the first part of the description "This account's default language for e-mails, ..." and skipped over the rest that read "... and preferred language for site presentation." doh!


Drupal 7 module for Password Complexity Rules For a Drupal 7 site the customer would like to implement the following (see at bottom) Password Complexity Rules.  Which of the below rules are possible to implement and what would be the best module to use for these rules?

The password must be at least 12 characters (network enforced)
The password must contain both upper and lower case characters: a-z, A-Z (network enforced.)
The password must contain numbers and punctuation characters as well as letters: 0-9, !#$%^&*()_+|~=`{}[]:";'<>?,./@ (network enforced.)
The password should not be or contain a word in a dictionary
The password should not be a common usage word, such as:

Names of family, pets, friends, co-workers, fantasy characters, or sport teams
Birthdays or other personal information, such as addresses and phone numbers.

You can implement this bit of the rules

  The password must contain both upper and lower case characters: a-z,
  A-Z (network enforced.) · The password must contain numbers and
  punctuation characters as well as letters: 0-9,
  !#$%^&*()_+|~=`{}[]:";'<>?,./@

anything extra is pushing it, plus it is difficult to enforce

You can use this module Password policy for implementing it

  This module provides a way to specify a certain level of password
  complexity (aka. "password hardening") for user passwords on a system
  by defining a password policy.


How do I add a customer ID field in Ubercart? I want to ask for the customer to enter his ID when he buys something.
Is it hard to add a new field apart from the default: name, phone, address, etc?

You want to add a field to the checkout process? There are two modules that do that. uc_webform_pane allows you to create webform nodes that integrate into the checkout process. uc_cck_pane allows you to integrate cck nodes into the checkout process.


Show list of users based on taxonomy term (D7) I have a taxonomy vocabulary "Department". In the user account I have a taxonomy term reference field with this vocabulary. So each user can be assigned to one or more departments. I used the module Taxonomy Meny to show the taxonomy terms in my main menu.

Now I want to show a list of users when I click on a department in the menu. Does anybody have an idea how I could do this?

Thanks.

You're right Mohammed, I should be using views.
Use a view with a filter on the department field and then create a link to the view page in my main menu.
I was overthinking this way too much.


Core search, use wildcards by default I've been trying to Google my way out of this one but I can't seem to find a solid solution for using wildcards by default for the core search module. Only things I can find are patches which aren't really looking like totally stable. And I want my customer's multi-lingual production site to be as stable as possible.

So, the current situation is as follows:

When I search for foo I will get only foo as result.
When I search for foo* I will be getting foo and foobar as result.

What I want is:

When I search for foo I will get foo and foobar, regardless of language.

Is there any way to elegantly solve this. I'm prepared to solve this with a custom module for example.

I've always used the Porter Stemmer module to handle that, it works a treat.

This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.
The process of stemming reduces each word in the search index to its basic root or stem (e.g. 'blogging' to 'blog') so that variations on a word ('blogs', 'blogger', 'blogging', 'blog') are considered equivalent when searching. This generally results in more relevant search results.


Username display overidden by customer profile name If a user has a customer profile (i.e. ever filled out a shopping cart) the name in the profile is used everywhere their username is displayed.

This results in a lot of confusion for our moderators/admins.  Because when they go to lookup a user in admin/people they're looking for the username that the user logs in with.  But what's displayed is their "nice" name from their shipping address.  I need to undo this override because it's way too confusing.

It doesn't look like anyone is doing this through theme_username().  Where is this display override happening?

Found it!

commerce_kickstart_user_username_alter() is overwriting usernames with the name provided in their addressbook.

I implemented my own hook_username_alter() to simply return $account->name.


Show profile2 fields on users page through panels I would like to select profile2 fields on users page.

Elements:

Profile2: artist + fields
User: role artist

If the user is being viewed is an artist the panel should show its fields.

Actions:

Created the profile2 for a custom user (if I do not panelize the user/%user page the user can view the profile2 fields).
Activated the user_view pane
Added relatioship with profile 2
Now the profile2 fields appears on the UI.
Select the field header_img
Save the pane

I must have forgotten something because the profile (panelized) fields does not show any content of the profile2 fields..

Attaching some screenshots!

Thanks!!

It looks like you are doing it ok, but there is an issue related that you can check at https://www.drupal.org/node/1011370#comment-9332247.

If you update to the latest dev version of profile2, it should work, and you could select the profile context and the profile type.


How can I make a view block of related products? I have read through the issue queue and read all kinds of documentation and made all kinds of settings in Views Contextual Filter and no luck at all. What can be the definitive way to make a Views block of related Commerce 2 products?
My products are tagged to taxonomy terms of which the taxonomy vocabulary is referenced on the product. I now tried to make a Views block to make contextual filter such that if viewing a product you can find a block of other products belonging to same taxonomy term.
No settings are working.

This patch solved this issue, https://www.drupal.org/project/commerce/issues/3015347#comment-13310494