"Trying to get property of non-object" for image_get_info I have the following code:

  $imageinfo = image_get_info($newfile->uri, $toolkit = FALSE);

  $newrecord = array(
     blah blah blah
     'width' => $imageinfo->width,
     'height' => $imageinfo->height
    );

The width and height lines get the "Trying to get property of non-object" error.

If I print the contents of the $imageinfo array, it's this:

Array
(
    [width] => 630
    [height] => 315
    [extension] => jpg
    [mime_type] => image/jpeg
    [file_size] => 30334
)

I must be doing something stupid here.  What is it?

Always, always read the documentation first:

  Return Value

  FALSE, if the file could not be found or is not an image. Otherwise, a keyed array containing information about the image:

Emphasis mine.


Sorting view results by the number of matched arguments (contextual filters) I have nodes with tags on them. I also have a view of nodes with a contextual filter that can take multiple tags. I have it set to get nodes that match any, rather than all.

So imagine I have three nodes, Lorem, Ipsum, and Dolor. They have the following tags:

Lorem: foo, bar, baz
Ipsum: foo, bar
Dolor: foo

When the contextual filter "foo" is passed, of course all three come up. When "foo" and "bar" are both passed, all three also come up. Currently, they come up in no particular order, so passing "foo" and "bar" might give me this (depending on my other filters):

Dolor
Lorem
Ipsum

I want to sort by number of matched items, so passing "foo" and "bar" will bring them up in the order Lorem, Ipsum, Dolor or possibly Ipsum, Lorem, Dolor, but never with Dolor first. And if I pass all three terms I'd expect to see the only the order Lorem, Ipsum, Dolor.

This seems like a common thing to need, and yet searching has not yielded a ready-made solution. How would one go about implementing this with Views 3 in Drupal 7?

Following is one way to achieve the specified ordering

Add a relationship to taxonomy terms.

Turn on aggregation
Set the sort criteria to COUNT DISTINCT of taxonomy term reference field.


push jsonlog data to elasticsearch I have installed the module jsonlog on drupal 7, but there are no information on how can I push the logs to elasticsearch or kibana or logstash. How do I do that?

As JSONlog project page states:

  Logs watchdog events JSON-formatted to log files. Provides a Logstash/ElasticSearch-ready log source.

The module only does one thing: turn Drupal watchdog events into JSON-loggable files and writes them to whatever server dir you've configured for it.

Before using this module you will need to:

Setup ElasticSearch & Kibana. This is a separate task from setting up LogStash. It will depend on your service provider (this is off-topic for Drupal Answers).
Setup LogStash. This will vary based on whatever app server you're running Drupal on. You'll have to find instructions applicable to the app server running Drupal.


Views, how to construct multiple joins I have a node activity with fields referencing the node location and a node sport_type. As in, for each activity I need to add a location and a sport type.

On the other hand I also have a node admin with references to location and sport_type. As in, I can create an admin for each sport_type and each location.

How can I create a view which results in the admin when an activity nid is given?

In SQL I would write something like:

SELECT  admin.name
FROM    admin
JOIN    activity ON activity.location_id = admin.location_id
        AND activity.sport_type_id = admin.sport_type_id
WHERE   activity.nid = :nid

I try to create a similar query using the ui of views, where the activity_id would be passed in through the url path. I don't know how to implement the join though... Any tips? (Using Drupal 7)

What you're looking for is often called "siblings".

When sharing the same Taxonomy terms there are Contextual filters Has taxonomy term that can be used and this can work in a lot of cases.

But there are cases even with shared Taxonomy that needs to go a different route (possibly when using Aggregation or Multilingual sites). That second "sibling" route is also what you need to use when the connection is done through an Entity Reference field that isn't Taxonomy, like it is in your case.

The solution is done with the help of two Relationships and one Contextual filter.

Create the Content type Views showing Admin nodes. You first add the Relationship for your ER Location field, this introduces info about the referenced node into the Views. In your case this is the info about Location node referenced from Admin nodes.
Then you add the reverse Relationship to the first one, it will use the first Relationship by default, this is where the matching happens. The second Relationship introduces info about the content that is using that ER field. In your case this is all the Activity nodes that point to the same Location.
Add the Contextual filter for Node ID and make it use the second Relationship. Set it the usual way, default value and ID from URL, validate against Activity Content type.
If this is a Block Display set it to display in a theme region on Activity nodes and adjust its Contextual filter settings. Now when you visit an Activity node you will see listed all the Admin nodes that share the same Location ER.

Repeat the procedure for the second ER field Sport type. You will have 4 Relationships and 2 Contextual filters in the end. Don't build everything at once, test step by step and build it all for only one ER field first.

When building for the second ER field you can use the keyword all in Views Preview to "shortcircuit" the first Contextual filter so you can test the second one directly, without interference from the first one (you enter values into Preview separated with / for each Contextual filter you have, for example all/34 to bypass the first Contextual, all/all to bypass both Contextuals, or 34/34 to test for the Activity node with the NID 34).

This answer has a bit more details for a similar example:  Entity Reference widget selctor in view referring same reference


Calling Module function from jQuery and Ajax With every drupal site I make, I usually create a custom module that I use to hold different php functions and other things custom to the site I am working on. It usually only consists of a module_name.module and module_name.info. Additionally, I always have .js file in the theme to do any javascripts I might need. Pretty standard right? But I have now run into a situation where I need the two to talk to one another.

I know you can call a .php file and pass it data using .ajax in jquery. How would I envoke a function written in my custom module from the js file in my theme?

Hopefully this will help -- got this code from a Lullabot module development training.

It all revolves around a hook_menu callback.  The value in 'page callback' is the function that will be called, in this case it is: "menu_magic_page"

So Drupal looks for the menu_magic_page() function.

Your jQuery / AJAX call would then reference the value what's in $items['X'] where X is "magic" here.  So hitting http://example.com/magic would run the module function "menu_magic_page"

FWIW: the type/MENU_CALLBACK ensures it doesn't get added to menu's etc.  It just ensures Drupal is ready to process it.

Hope this helps.

/**
 * Implements hook_menu().
 */
function menu_magic_menu() {
  $items = array();

  /**
   * This is a simple callback.
   *
   * This will create a path at http://example.com/magic. When visited, that
   * URL will trigger the "menu_magic_page" function.
   */

  $items['magic'] = array(
    'title' => 'Menu Magic!',
    'page callback' => 'menu_magic_page',
    'type' => MENU_CALLBACK,
  );

/**
 * Page callback for 'magic'. This is the function that will get called
 * everytime a user visits http://example.com/magic.
 */
function menu_magic_page() {
  global $user;
  return t('Hello, @username!', array('@username' => $user->name));
}


Drupal Commerce: Prices on Variations not displayed when selecting a variation I am using Drupal Commerce Kickstart 2.

When a user selects a value from the size drop down (variation), the price and other attributes do not update on the product display. I need to have something similar to this -> http://demo.commerceguys.com/ck/storage-devices/commerce-guys-usb-key. You'll see that when you select a memory size for the USB product the price will change.

Is this a built in feature for Drupal Kickstart or something they built through a custom module?

I have a product variation with a product attribute of Size (a user can select which size they want). I have product details such as SKU, Price, and Package.

I also have a product display set up by default, which displays my product variations as my Add to Cart form.

In the following picture you will see that even though I have 5 oz. selected all the details displayed are for the 10 oz. variation.

I need to know how to update these details based on which variation the user selects.

Any help on this is appreciated

This seems to work out of the box. There was a JQuery version conflict that was causing javascript errors.


How to programatically update existing user profile field in drupal 7 We are using Drupal 7 and the Profile2 module.

We create and add a value to a field in the profile using this code:

$profile = profile_create(array('type' => 'main', 'uid' => $account->uid));
$lang = LANGUAGE_NONE;
$profile->field_headline[$lang][0]['value'] = 'Software Engg';
profile2_save($profile);

How can we programtically update the user profile field 'field_headline'?

Please advice us.

You just need to load the user using drupal function

profile2_load_by_user($account->uid, $type_name = NULL)

$account->uid => user id

$type_name => one of the profile types of profile 2 if any otherwise NULL

   $profile =  profile2_load_by_user($account, $type_name = NULL)
   $profile->field_headline[$lang][0]['value'] = 'update Software Engg';
   profile2_save($profile);

For more information Click Here

Hope it will work for you!


How to reset Drupal's content cache / deleted content? I'm working with Drupal 7.44. I created some content, but then deleted those articles. However, when I go to add new content, Drupal still recognizes the title of my articles that I deleted (as I'm typing it appears as an autocomplete below the field). I'm not sure if this is still completely stored in the database or if it's just cached somewhere. How do I go about deleting this (preferably without completely having to re-install everything)?

Administration -> Configuration -> Development -> Performance and "Clear all caches" did not seem to work.

Thanks!!

Unless you are using some module that I havent heard of (certainly possible) to give autocomplete style info as you are entering a node title, then I think the functionality you are describing is actually something being done by your browser.

You can alter your form to add automcomplete="off" to your title field (see https://stackoverflow.com/questions/2530/how-do-you-disable-browser-autocomplete-on-web-form-field-input-tag)


How to get Drush to use alternative php.ini I'm trying to get Drush up and running on my webserver via SSH. I'm new to working with SSH so hopefully someone can help me work this out. When checking Drush's status it mentions that the disable_functions are not empty.

So I copied the webservers php.ini to the .drush file but it still uses the php.ini from the webserver and not from my .drush folder.

I tried finding a solution online but can't get this to work. A couple of thigs I tried are:

Using a drush.ini file. If I add this I is found by drush and shown in my drush status. But it doesn't solve the disable_functions problem. It also shows the webserver php.ini file. So it's the php.ini first and then the drush.ini.
I added export PHP_INI="/path/to/.drush/php.ini" to my .bashrc file and when I run echo PHP_INI it shows the right path but it doesn't solve my problem. I also did the source ~/.bashrc to reload the .bashrc. But this didn't help.

This is the complete drush status:

The following restricted PHP modes have non-empty values:            [error]
disable_functions. This configuration is incompatible with drush.
Please check your configuration settings in
/opt/alt/php56/etc/php.ini or in your drush.ini file; see
examples/example.drush.ini for details.
exec() has been disabled for security reasons preflight.inc:380      [warning]
exec() has been disabled for security reasons preflight.inc:425        [warning]
exec() has been disabled for security reasons preflight.inc:380        [warning]
exec() has been disabled for security reasons preflight.inc:380        [warning]
 PHP configuration      :  /opt/alt/php56/etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/bin/drush
 Drush version          :  8.0.3
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

Hopefully someone can help me getting this Drush installation to work.
Thanks in advance.

Zeb

Looks like you are using the Drush Phar, which does not support php.ini selection.  You must either:

Configure your webserver php-cli php.ini correctly (may not be an option if /opt/alt/php56/etc/php.ini is not writable)

or -

Install Drush via Composer per the installation instructions


Page cache works on local dev but not on production I've a Drupal 8.6.9 site running on Apache 2.4 and PHP 7.2. I've enabled the internal page cache, the dynamic page cache, and the BigPipe module in an effort to tease out some more performance.

I've set max-age to 1 day, under /admin/config/development/performance.

On my local development site (drupalvm, Ubuntu 16.04) I can see X-Drupal-Cache: HIT and a visible improvement in performance, but on the hosting server, also Ubuntu 16.04, I only ever see X-Drupal-Cache: MISS.

As far as I can tell, there's nothing amiss in settings.php on the live server, the Drupal config is identical, so there must be something amiss in the Apache settings, perhaps.

Has anyone come across this before where cache works on one environment, but not another?

My guess is during your testing you're visiting the page for the first time which would result in a X-Drupal-Cache: MISS (As you'd expect)

And as you've got the max-age set to 1 day your browser has now cached that response so no matter how many page visits you do for the next day you'll always see the MISS for that page (Because your browsers not going back to your server to get a fresh response) So other future users/different browsers could potentially be getting a HIT response after you've now forced drupal to create its initial cache

I'm only guessing here as I haven't tried myself but would seem to make sense. You could test it out by opening the same page in a different browser after you've got the MISS on your first browser to see if that 2nd browser is now seeing HIT


Disable translation of watchdog messages i have problem with drupal.
I'm using the watchdog function to save some log messages, but when i go to read them in the admin panel (admin/reports/dblog) they get detected by the T function and so i have a lot of unnecessary log entries inside the translate content page. Is there a way to disable the detection for that page?
Thanks

I made it like this:

function MYADMINTHEME_dblog_message($variables) {
  $output = '';
  $event = $variables['event'];
  // Check for required properties.
  if (isset($event->message) && isset($event->variables)) {
    // Messages without variables or user specified text.
    if ($event->variables === 'N;') {
      $output = $event->message;
    }
    // Message to translate with injected variables.
    else {
      $output = format_string($event->message, unserialize($event->variables));
    }
    if ($variables['link'] && isset($event->wid)) {
      // Truncate message to 56 chars.
      $output = truncate_utf8(filter_xss($output, array()), 56, TRUE, TRUE);
      $output = l($output, 'admin/reports/event/' . $event->wid, array('html' => TRUE));
    }
  }
  return $output;
}


/README.txt: UTF-8 Unicode (with BOM) English text, with CRLF line terminators I have been working on a Drupal.org project and I want to make sure that pass all the coding standards. For some reason I got these problem with the README.txt encoding and I dont know how to solve it.

 ./README.txt: UTF-8 Unicode (with BOM) English text, with CRLF line terminators README.txt

Bad line endings were found, always use unix style terminators
./README.txt: the byte order mark at the beginning of UTF-8 files is discouraged, you should remove it.

Can anyone tell me how to solve this problem ? I'm currently using Sublime Text 2 and I save my README.txt as UTF-8 Unicode with BOM and this did not fix my problem.

Here is the README.txt https://gist.github.com/darol100/e24059dbacc4f7e205ad
http://pareview.sh/pareview/httpgitdrupalorgsandboxdarol1002309319git

In Settings - User config, you should set

"default_line_ending": "unix",

Also, when saving file, select UTF-8 Unicode without BOM - that's exactly what you were told here:

  the byte order mark at the beginning of UTF-8 files is discouraged

Emphasis mine.

Taken from Fixing Sublime Text 2 line endings?


Sending a file in e-mail message body using Views Send I have a drupal site that holds thousands of client details. What I want to do is to create an emailer to send out campaigns to the clients.

So far I have a view set up to filter clients by company and using Views Send I can send all selected an email.

What I would like to do is to send a file in the email. Either that or be able to paste the data from the file into the email. The file is stored in my drupal site within a content type.

Does anyone know how I would be able to do this? To be able to select from a list which file to send in the e-mail message body?

take a look at the Entity Email Module:

The Entity Email module lets users create their own email templates
which can be used to send emails. Emails sent can also be recorded in
the DB if needed. Emails can be sent programmatically or by the mean
of the Rules module.
Main features:
Built on top of the amazing entity API
Allow token substitution
Templates can also contain attachments (PDF, TXT...)
Rules module support, so email actions can be triggered by any Rules
Supports the MimeMail module for HTML emails.
Build with the fields API Emails sent> can be recorded in DB

I don't know that it will integrate with Views on it's own, but you may be able to manually make it work the way you want.


How do I programmatically create a view whose structure is defined at runtime? I know I am able to create a view programatically here: "How do I programatically create a view?" - only this requires knowing the structure of the view (e.g. which fields / filters / relationships to use) already.

How can I dynamically create a view at runtime?  Either the view would get stored in the same place as typical views (in the views database) - or it could exist 'In code' except the code is dynamically generated.  E.g. is it possible just to create views ad hoc in hook_views_default_views()?

Ok - no answers and I've figured out two ways to do this.

1. hook_views_default_views()

One way is to define the view in hook_views_default_views() and then to rest the cache for instance with views_invalidate_cache(). These views end up being 'in code' but not actually set.  This didn't seem like the most desirable method for my use - but might be better for some applications.

2. save the $view

Create the view e.g. $view = new view(); and fill all the fields, and then $view->save() saves it to the views database. Keeping a record of the name of the view allows you to delete it later if necessary etc.


Assigning a badge to a user using Flag, Badges and Rules I am interested in assigning to user a Badge after he favourites 3 nodes. I want to do this with Flag, User badges and Rules.

How can I do that?

I would use the Goals module for this.

Create a 'Favorite node' task and a 'Favorited 3 nodes' goals.
Add an image to the goal. This is going to be your badge.
Create an 'Add to favourites' flag.
Create a rule that "records a task for goals" when a node is "flagged under 'Add to favourites'".
If you don't really need the User badges module, you can create an image field called 'Badge' for the users and use the following custom module (you can find more information here):

function MYMODULE_goals_completed_goal($goal_id, $uid) {
   $user = user_load($uid);
   $goal = goals_load($goal_id);
   $fid = $goal->goal_img['und'][0]['fid'];
   $img_title = $goal->goal_img['und'][0]['filename'];

   $edit = array();
   $edit['field_badge']['und']['0']['fid'] = $fid;

   user_save($user, $edit);
}

If you really need the User badges module, I think you can adapt the code a bit and everything should work fine.


Date module shows time field +5:30 ahead from input I am using Date module with date popup . And I am creating these node pro grammatically and saving dates to them like:

$node->field_task_time[LANGUAGE_NONE][0]['value'] = "2014-12-18 23:15:00";
$node->field_task_time[LANGUAGE_NONE][0]['timezone'] = "Asia/Kolkata";
$node->field_task_time[LANGUAGE_NONE][0]['timezone_db'] = "UTC/GMT";
$node->field_task_time[LANGUAGE_NONE][0]['date_type'] = "datetime";

The values in db are stored correctly but when I edit this node form the values in the date field shows 2014/12/18 and in time field it shows 4:15. i Don't know what's happening .

It seems as default behavior of date module if you check its documentation you can see:

Time zone handling

There are 5 different options for field Time zone handling:

Site's time zone - When entering data into the field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.

Date's time zone - With this option enabled, the date field adds a select box to explicitly specify the time zone for the date entered. When the date is saved to the database, it is not converted & the time zone information is saved with the date. When retrieved from the database, no conversion is performed and the date is displayed exactly as entered.

User's time zone - When entering data into the field, the data entered is assumed to be in the user's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.

UTC - When entering data into the field, the data entered is assumed to be in UTC time zone. When the data is saved to the database, it is converted to UTC (e.g. no conversion necessary). When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.

No time zone conversion - The date entered is not converted when saved to the database. When retrieved from the database, the data is NOT converted and is displayed exactly as entered.

so currently your settings are in site's timezone which is assuming that you entered date is in UTC hence the retrieved date is site's timezone which is UTC+5:30 switch setting s to No time zone conversion and you can see retrieved date as entered one.


Error handling with Drupal.ajax() First I am not very good in JavaScript so maybe I do not know some very basics... I apologize in advance.
I created a form where I want to save every change in single fields directly without the need to submit the form each time. Therefore I created a custom route which returns an AjaxResponse on successfull database savings as well as on any errors on the Drupal side.
But I want to be aware of any errors which may appear on the client side as well. $.ajax() has the function .fail() and .done() where I can do different things in my JavaScript when something went wrong. These methods are missing for Drupal.ajax(). Is there any way to react on errors when using Drupal.ajax()?
I tried
try {
  Drupal.ajax({url: path}).execute();
}
catch (e) {
  alert(e.name + ": " + e.message);
}

and built in some errors on my controller but all that happens is that the browsers console lists Ajax errors - no alert is shown to the client.

You can using like jQuery ajax. Because Drupal.ajax({}).execute() is a function and return the jqXHR.
 /**
   * Execute the ajax request.
   *
   * Allows developers to execute an Ajax request manually without specifying
   * an event to respond to.
   *
   * @return {object}
   *   Returns the jQuery.Deferred object underlying the Ajax request. If
   *   pre-serialization fails, the Deferred will be returned in the rejected
   *   state.
   */
  Drupal.Ajax.prototype.execute = function() {
    // Do not perform another ajax command if one is already in progress.
    if (this.ajaxing) {
      return;
    }

    try {
      this.beforeSerialize(this.element, this.options);
      // Return the jqXHR so that external code can hook into the Deferred API.
      return $.ajax(this.options);
    } catch (e) {
      // Unset the ajax.ajaxing flag here because it won't be unset during
      // the complete response.
      this.ajaxing = false;
      window.alert(
        `An error occurred while attempting to process ${this.options.url}: ${e.message}`,
      );
      // For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
      // so that calling code can take appropriate action.
      return $.Deferred().reject();
    }
  };

source
So in your case:
var ajaxExecute = Drupal.ajax({url: path}).execute();

ajaxExecute.done(function() {
    alert( "success" );
})
.fail(function() {
    alert( "error" );
})


How to add login form to the Access Denied page? I'm trying to add a login form to the access denied page, and wonder if this is possible via the UI.

Any suggestions/ideas?

Option 1: Use the CustomError module

The CustomError module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them. Some more details about its features (from its project page):

  Configurable page title and descriptions.
  There are no author and date/time headers as with normal nodes.
  Any HTML formatted text can be be put in the page body.
  The error pages are themable.
  Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
  Allows custom redirects for 404s.

You should be interested in the part about "Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.".

Option 2: Redirect to user/login using the Rules module

"Adding settings for the 'access denied page' and displaying the 'User login' block on that page" is indeed a solution that should work. However, you could take this a little step further, and enhance the user experience AbitMORE. By using a variation of the approach described in the answer to the question about "How to redirect anonymous users to login page using Rules module?".

To do so, assume the path of the "Default 403" page is set to "no_access" (via /admin/config/system/site-information, near the bottom of that admin page). Then create a rule using the Rules module, with as Event something like "After visiting node 'no_access'". So that the entire rule would look something like so:

Events: After visiting node 'no_access'
Conditions:

User has role(s) - Parameter: User: [site:current-user], Roles: anonymous user
NOT Text comparison - Parameter: Text: [site:current-page:url], Matching text: user/login

Actions: Page redirect - Parameter: URL: user/login

Should you want to do so, you could even add another Action to also display some (informational) message in the Drupal message area, with something like "You tried to visit a page for which login is required ...".

True, it might require you to enable an extra contributed module (Rules). But, as indicated by its growing popularity also, that module is probably already enabled in mostly any site (similar to the Views module), because there are dozens of use-cases for this module. Just 1 variation of this question: how about enhancing the user experience for "Page not found" in a similar way?

Option 3: Show User login block on dedicated page

Another variation, as an alternative to the Rules "Action" (to redirect to user/login), is to create some designated node, say with a path like "my_login_page_with_login_block". And then combine this with configuring the "User login" block (via admin/structure/block) like so:

Display that block in whatever theme region of your choice.
Use the "configure" link to the right of that User login bloc, to set the "Visibility settings" for "Pages". I.e. change the option for "Show block on specific pages" to "Only the listed pages", and specify the path (my_login_page_with_login_block) within the text box below it. If for some reason you don't want to use a path, then just specify node/nid (nid = id of the node) as the path instead.


set new content-type as product in ubercart When I install Ubercart, it creates a new content type ("Product"), and uses it for handling products.

Can I create another content type, and use it as product?

Yes, you can. It is a bit confusing the first time you try, as Ubercart terminology is different for some reason; they call it product class, but it is just a new content type.


Exclude exposed filter for one content type in my view I use leaflet map for displaying markers, like that :

My actual view -  filter criteria :

- Content published
AND
- Content - Has taxonomy term AND
- Content - Has taxonomy term AND
AND
Content type = 1 OR
Content type = 2

But now, I want display vectors with a third content type. It works without filters (taxonomy), and add all taxonomy terms to my third content, it's an ugly solution.

Do you have a solution ?

edit : drupal doesn't understand this setup

It looks like you want to make more distinct and/or groups. If using Drupal 7, here is a clear explanation of how to do it (see the accepted answer):
How can I do with Views and Drupal 7 what the Views Or module does in Drupal 6?

If using Drupal 6, the Views Or module can do the same thing.

If I understand your problem, the solution would be to put the first 2 Content Types in a group with the Taxonomy Term filters, then use a separate OR group for your 3rd Content Type.


Getting .info file not found in my custom module, even though it does contain an .info file I am trying to install my custom module, but the error I get is:

  modulename.tar.gz does not contain any .info files.

My module tar.gz file does indeed contain a .info file. I have installed other modules on the server, so I shouldn't have any permission issues.

The following is the content of the .info file.

    name = Module Name
    description = Initialization module for hl
    package = My modules
    core = 7.x
    files[] = modulename.module
    files[] = modulename.install
    files[] = modulename.inc
    files[] = includes/mydrupalusers.php

Mystery solved.

I traced back to the update_manager_install_form_submit() function in update.manager.inc.

When the file is uploaded, it is placed in the temp directory.  Drupal then creates a temp directory to extract the file into, using a unique directory name.  After the extraction, Drupal can't determine the module name any more, so it depends on the directory name in the archive. They commented on this in the code:

// Unfortunately, we can only use the directory name to determine the project
// name. Some archivers list the first file as the directory (i.e., MODULE/)
// and others list an actual file (i.e., MODULE/README.TXT).

I did not have my files tar'd in a directory.  So, I created a directory named after my module, moved the files into the directory, tar'd it up, and all is well.

Before

modulename.install
modulename.module

After

modulename/modulename.install
modulename/modulename.module


How to collect a list of file URLs using Rules and send a single email containing that list? I am using the Rules module to send an email when a content node gets saved/updated.

I have a basic node where users can upload a large number of files and enter an email address to notify someone about the change.

In this example, the Rules Action to Send Email is in a Rules loop, and I get one email per item in list. When I move Send Email to the left, I cannot access the "list_item" variable.

Rules Events:

After saving new content
After updating existing content

Rules Conditions:

Content is of type, Parameter: Content: [node], Content types: BasicPage
NOT Data value is empty, Parameter: Data to check: [node:field-email]

Rules Actions:

Loop
Parameter: List: [node:field-file]
List item: Current list item (list_item)

Send Email
Parameter: To: [node:field-email], Subject: Test [node:title], Message: [list-item:file:url], From: noreply@host.ca

Concatenating text in Rules was difficult when I did it. What I did was to keep two variables: a text array with a starting element value (such as "This is a digest:...") and a text value.

For each iteration of a loop over items to concatenate into a digest, etc. I set the text value to be the first item in the array ([array:0]) and then set the [array:0] value to be a concatenation of the text value and the new value from the loop. When the loop finishes, you know the [array:0] has the digest content.

I do not know why this couldn't work in a simpler way by concatenating the text value each loop directly or using two text values instead of an array. When I tried either of the other ways it only kept the last item or first item of what was being concatenated.


Can I set a CSS-class on the node in a view list based on a text field of the node? As I understand, I need a module like this: https://www.drupal.org/project/field_formatter_css_class but for Drupal 8

For example, I want to highlight one node in the views using CSS-class, how to do this?

PS

Finally I got necessary result:

/**
 * Preprocess function for views-view-grid.tpl.php.
 */
function themename_theme_preprocess_views_view_grid(&$vars) {
   foreach ($vars['items'] as $row) {
        foreach ($row['content'] as $item) {
             $subclass=$item['content']['#row']->_entity->field_fieldname;
             if(!empty($subclass[0])){
                $item['attributes']['class'][] = 'col-'. $subclass[0]->value;
             }
        }
   }
}

/**
 * Implements hook_preprocess_html().
 */
function themename_preprocess_html(&$variables) {
$node = load_your_node// Load you node here and add proper condition and type for following code
    $variables['attributes']['class'][] = 'page-node-' . $node->custom_textfield();
}


Drush installed and running; No Drupal site found even with uri specified After much trial and tribulation, I thought I had drush all ready to roar. Much excitement. But then, no joy...

Drush is working. The sites operate fine via MAMP. Regardless, a "drush cc all" command returns:

No Drupal site found, only 'drush' cache was cleared.                                          [warning]
'all' cache was cleared.                                                                       [success]

This question has stumped drupalcon attendees and very experienced developers. Any ideas?

I am on Mac OS 10.9.3
using MAMP (free) Version 3.0.5

Here is my drush status:

 Drupal version         :  7.29-dev
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database username      :  db_user
 Database name          :  db_name
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/MAMP/htdocs/mysite.dev
 Site path              :  sites/default

Have tried executing drush from /Applications/MAMP/htdocs/mysite.dev; from /Applications/MAMP/htdocs/mysite.dev/sites/default; and using drush cc all --uri=http://localhost/mysite.dev

Tried running drush from sites/default. Same result.

Please double check that all below points are addressed.

You're running drush in Drupal root folder or folder containing settings.php file.
The mysql command exists (and it's in your PATH).

Please note that the database command depends on your database driver set in your settings file (e.g. sqlcmd for SQL Server; for details check different classes in Drush's /src/Sql).

If the command is missing when running in any folder, make sure path to its binary file is added into your PATH system variable.
Your PHP has PDO extension enabled (check by: php -m | grep pdo or drush sqlc).
Your PHP has database extension enabled (e.g. mysqli) (check by: php -m | grep mysql).

To investigate what's exactly wrong, run drush with -v (verbose) and -d (debug) flags, e.g.

drush -vd status
drush -vd ev "echo 123"
drush -vd cc all

and check for any errors.

  mysql extension for PHP PDO is not installed. Check your php.ini to see how you can enable it.

Install database extension (e.g. mysqli) (as per above 4th point).

For MAMP, see: Drush does not work on my Mac

MAMP

Since you're using MAMP, make also sure you running the right version of php binary (check by which php) and it should point to /Applications/MAMP/bin/php/php5.X.X/bin/php. If not, please add the path into your PATH in your rc files (e.g. ~/.bashrc):

# For MAMP (OSX)
PHP_VER="5.6.10" # Or: 5.4.19/5.5.3 (check by: $ ls /Applications/MAMP/bin/php/php*)
export PATH="$PATH:/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php$PHP_VER/bin:/Developer/usr/bin"

XAMPP

For XAMPP for Windows, similar thing, add your C:\xampp\mysql\bin into your environment variable PATH.

Debugging

If your drush command fails for some reason, here are the suggested steps to debug drush (shell commands).

Install and enable PHP xdebug extension. Verify by php71 -i | grep xdebug.
Verify Drupal root, Settings File and Database are present in drush status.
Generate trace file:

drush ev "xdebug_start_trace(); drush_drupal_cache_clear_all(); echo xdebug_get_tracefile_name(); xdebug_stop_trace();"

or:

drush ev "xdebug_start_trace(); print_r(_core_site_status_table()); echo xdebug_get_tracefile_name(); xdebug_stop_trace();"

If xdebug is enabled for different PHP version, specify with DRUSH_PHP=/path/to/php.

If successful, trace output file should be printed at the end, so take a note of it.
Now open and check the trace file.
To test or compare drush output with clean Drupal, you can install new Drupal in empty folder by:

drush -y qd --no-server --core=drupal-8
cd quick-drupal-*/drupal*
drush status


right sidebar doesn't shrink in zen responsive theme I have a Zen 7.x.5.x Responsive subtheme with Right sidebar...

I know, I am new with all this responsiveness staff; but - I think the right sidebar doesn't shrink when I resize my browser....it just moves inside, staying about the same size....or may be I don't understand something....

so, I have made up my content area - it consists now from 2 blocks floating left and right; I put them width proportionally to content area : 67% and 33% - they resize, when I resize browser....but sidebar looks too big and not shrinking; even it seems to be set in percents from page's 1200px.....

Inspect the right sidebar element in your browser. Then select

<section class="region region-sidebar-second column sidebar">

in the DOM and it should give you the width as a percentage. This is proof that the sidebar is responsive. Now drag the browser window smaller and observe the media query changing at breakpoints and the percentage should also change. At mobile breakpoint the sidebars should be 100%.

Now look in your sub theme's sass/layouts folder for the file _responsive.scss

You will see snippets like this

$zen-column-count: 3;
...

#content {
          @include zen-grid-item(2, 1);
        }

        /* Span 1 column, starting in 3rd column from left. */
        .region-sidebar-second {
          @include zen-grid-item(1, 3);
        }

This is where the sidebar width is set in relation to the content area. In the above case it is 1 column wide starting at column 3. As there are a total of 3 columns it is 1/3 the total width.

You can change it here if you have compass set up and working and properly watching the folder for changes.


Suppressing another module's warnings Is it possible to suppress another module's warnings? My module calls another causing a warning to appear.

You could use the Disable Messages module for this. Here is a quote from its project page:

  Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

  Filter out messages that match a full text string exactly.
  Filter out messages that match a regular expression.
  Permissions to specifically hide all messages of a given type from any role.
  Disable all filtering for specific users.
  Disable all filtering for specific paths.
  Apply filtering only for specific paths.
  Debug system to get messages in the HTML without showing it to the end users.

Available for either Drupal 6 or Drupal 7 (and a DEV version for Drupal 8).


How to create a view to count comments per user? I am trying to create a view with a table that shows all the users and the total number of comments that user posted in descending order. I am not sure what I am doing wrong but I spent hours on this already...

Can anybody point me to the right direction?

The closest I got is I created a view of comments so far with the author name that I tried to aggregate. But I am getting all sorts of weird results.

I got it! Sharing my way ;)

What I did:

Created a view of comments of my type.
As fields, I added Author uid twice.
Set aggregation (COUNT) on the second Author uid.
Added a sort criteria for aggregated (Count) Author uid as descending.

woala... Wasn't that hard after all :)


What is the proper way to set up the front page? I currently have my front page set to a node/basic page through Configuration > Site information > Default front page. Will this cause Google to index both the home page and the default front page? I just don't want to get hit for duplicate content.

I’m worried because both were showing on the XML sitemap before I removed the default front page (droneswithcameras.com/search-best-drones-cameras). You can look at my site to see what I’m talking about. The default homepage is set to /search-best-drones-cameras.

Are the front page and home page essentially the same thing? It’s just strange to me that there are multiple URLs for the same page.

In Drupal 8 you can disable the /node route by disabling the view called "Frontpage", effectively eliminating the frontpage concept.


How to sort view by content type, using literal ordering, as second order-by clause In a view, I want to sort content by:

Collection (a taxonomy term)
Content type
Something else
Something else ...

I have this configured in the View UI and I want to leave most of it as it  is but for the content type ordering, I want to make this literal - I want to state the order exactly ("article", "page", "thingy", "other one").

For this in MySQL you would use FIELD()

I have tried using hook_views_query_alter and setting $query->orderby[1][field] to FIELD(node_field_data_type, "article", "page", "thingy", "other one") but I am running into exactly this problem: https://www.drupal.org/node/1382016#comment-12058755 In other words, the brackets and quotes are being removed so that it thinks it's one long field name (which of course does not exist) rather than treating it as a function call. It seems this did not happen in Drupal 7.

Is there a known way to get around this in Drupal 8?

Although there may be a method to do this via a query alter I was unable to find the correct solution. I was however able to find a solution.

Although we utilise search API heavily and we can use the content type relevance weighting we had a requirement to sort by a custom content type order and then by date, in addition some content types needed the same weight.

Our solution: Add a search weighting field to the required content types (e.g. integer 1-5) and include it in the index.  In the view add a sort filter for your search filter field.

You'll need to batch process or use views bulk operations to fill in existing node data and hide the field from content add / edit screens if required.

One added benefit of this method is, if the client wants to have a piece of content show at the top when it's in the result set they can manually amend the new field for it.


Apply multiple Content Type filters to Search Block Form in hook_form_alter() I'm trying to figure out how to apply multiple content type filters to the search results of the Search Block Form (not the normal search form). I've successfully filtered by current language and ONE content type. So far, here's what I have:

function mytheme_form_search_block_form_alter(&$form, &$form_state) {
  $manager = \Drupal::languageManager();

  $form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
  ];
  $form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . $manager->getCurrentLanguage()->getId(),
  ];
  $form['f[1]'] = [
    '#type' => 'hidden',
    '#value' => 'type:Insight',
  ];
}

There doesn't appear to be any documentation about adding filters this way. But I did find this: NodeSearch::buildSearchUrlQuery. It appears that one should somehow be able to use OR and Negation in this, but I just can't figure it out.

I've tried this:

$form['f[1]'] = [
    '#type' => 'hidden',
    '#value' => 'type:Insight OR type:Event',
];

This just filters by the last one listed. I also tried this:

$form['f[1]'] = [
    '#type' => 'hidden',
    '#value' => 'type:Insight OR Event',
];

And this:

$form['f[1]'] = [
    '#type' => 'hidden',
    '#value' => 'type:["Insight","Event"]',
];

And none of these were working to filter in (or out) multiple content types.

Any help would be greatly appreciated. Or just pointing me to some documentation on using filters this way. Thanks.

So, I figured out how to make it work without actually finding any documentation. I just added a new filter for each content type I want to search:

$form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
];
// add filter for current language
$form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . \Drupal::languageManager()->getCurrentLanguage()->getId(),
];
// add filter for each full-page content type
foreach (fullPageNodeList() as $key => $full_page_type) {
    $form['f['.($key + 1).']'] = [
        '#type' => 'hidden',
        '#value' => 'type:'.$full_page_type
    ];
}


Can I include other template into template? I override template in my custom theme na (templates/block--[module]--[delta].tpl.php) and I would like to include other template (from the same directory) into this. Can I do it and how?

Directory structure

sites\all\themes\
   my_name_of_theme\
        templates\
             block--views--front-page-block-1.tpl.php
             example-file-template.tpl.php

block--views--front-page-block-1.tpl.php (concept what I want to do):

<?php
     /* init $path (or maybe it is not needed) */
     include($path . 'example-file-template.tpl.php');
?>

You can get another drupal theme path with drupal_get_path('theme', 'theme_name'); and finally

<?php
     include(drupal_get_path('theme', 'theme_name').'/example-file-template.tpl.php');
?>


Can I get the absolute path to the frontpage in theme_preprocess_html? Is it possible to get the absolute path to the homepage or <front> eg: https://www.domain.com/homepage in the theme_preprocess_html hook? I tried global $base_url but it throws an error.

I used \Drupal::urlGenerator()->generateFromRoute('<front>', [], ['absolute' => TRUE]); from one of the comments in:

How to get the base URL of a site

Here is the entire working snippet:

/**
 * Implements hook_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {

  // Modify if we're on nodes
  if ($node = \Drupal::request()->attributes->get('node')) {
    // Get the node-type
    $nodetype = $node->getType();
    // Switch class for node-type
    switch ($nodetype) {
      case "landing":
        // prefetch frontpage from landing pages
        $frontpage_path = \Drupal::urlGenerator()->generateFromRoute('<front>', [], ['absolute' => TRUE]);
        $prefetchfront = [
          '#tag' => 'link',
          '#attributes' => [
            'rel' => 'prefetch prerender',
            'href' => $frontpage_path,
          ],
        ];
        $variables['page']['#attached']['html_head'][] = [$prefetchfront, 'prefetch'];
      break;
    }
  }
}


How to Make Sitcky Item in Select List? I've got a Select List, let's say Apple, Orange, Raspberry. TBD.

I need TBD to be sticky at top of the list, while the other items are sorted alphabetically.

Recommendations on how to approach this?

If it is an option you want to consider, you could use a convention for your select list values like so:

01-Apple.
02-Orange.
03-Raspberry.
00-TBD.

The sorted version of this list would look like so:

00-TBD.
01-Apple.
02-Orange.
03-Raspberry.

It's what I often do for any software where I somehow want to overrule the whatever sorting (eg to ensure my most often used folder names are always at the top) ... And it works in pretty much every OS I ever used (including mainframes ...)


Created flag for "add friend", set a View, works but there's a problem Ok, so now when a user looks at HIS profile, he gets the links to HIS list of friends, great!
However, when the same user looks at someone else's profile, he sees the links and they point to THAT user's friends - and I don't want that...

I'd like the 'friends' link to only appear if I'm seeing my own profile page; when looking at someone else's profile I shouldn't be able to see THEIR list of friends.

It sounds like your view is already set up with the proper Flagged: Node relationship and "User ID from URL" contextual filter.  If you edit the view and then edit the Flagged: Node relationship, you can try checking the box for "Only display if flagged by the currently logged-in user" and see if that helps you.

Keep in mind, this method will still display people that were flagged by both Person 1 and Person 2 (common friends, in other words).  Another solution would be to have a private profile page and a public profile page, with different views on each; you might want to look into the Profile2 module.


Using a Variable in a Rules Calculation I'm attempting to calculate an estimated shipping date on products with a turn-around time. Using a variety of fields on separate entities I've been able to get about 75% if the way. I run into a problem when attempting to perform the final calculation on my rule component. For some reason my calculated variable is not available on Input value 2 of the calculation when enabling data selection.

This is what my component looks like:

+ Set a data value:
  Parameter: Data: [order:field-due-date], Value: [site:current-date]
+ Add a variable:
  Parameter: Type: Date, Value: now
  Provides variables: Shipping Date (shipping_date)
+ Loop:
  Parameter: List: [order:commerce-line-items]
  List item: Current Line Items (line_item_list)
    + Apply an interval to a date:
      Parameter: Interval number: [product-display:field..., Interval period: Days, Date: [site:current-date]
      Provides variables: Line Item Date (line_item_date)

At this point I try to add an action "Calculate a value" to the loop; like this:

+ Input Value 1
  Data selector (Select data of the types Decimal number, Date.)
  -- line-item-date --
+ Operator
  Value
  -- max --
+ Input Value 2
  Data selector (Select data of the type Duration.)
  -- shipping-date --

I calculate this in order to overwrite the shipping date with the highest "line-item-date" in order to display an estimated shipping date based on the product with the longest turn-around time.

Here's my problem: the "shipping-date" variable is not available in "Input Value 2". I don't understand why the "select data of type" is "Duration" and not "Decimal number, Date"; although I assume that's where the problem is.

I ended up using a slightly different approach. Just in case somebody else is interested in this I'm posting my final solution here.

PROBLEM

"Estimate" a ship date based on the turnaround times of all the products in cart whenever a product is added or removed from the cart and at checkout (just in case the customer decides to check out days after adding the products).

Additional modules and fields:

Using the interval field module I added a "Turnaround Time" field to the product variation type.
I also added a date field to the order entity - "field-due-date".

RULES

I created 3 items under rules.

Reaction Rule: Set the estimated shipping date

+ Events
    + After adding a product to the cart
    + After removing a product from the cart
    + Completing the checkout process
+ Actions
    + rule set: Set the estimated shipping date
        // these settings ensure that you run through each and every line item, instead of just the current item; spend a long time doing that - over and over. :(
        + Line Item
          Data Selector: commerce-order:commerce-line-items:0
        + Order
          Data Selector: commerce-order
        + Commerce Product
          Data Selector: commerce-product

Ruleset: Get Line Item Turnaround Value
rules_get_line_item_turnaround_value
This rule gets the integer value of each line-item's turnaround time (in days in my case) and writes it to "line-item-turnaround-time" variable which is passed along to the next ruleset. I could probably have used a regular Rule instead of a Rule Set here.

Date Type
    Commerce Line Item, Line Item, line_item, Parameter
    Commerce Order, Order, order, Parameter
    Commerce Product, Product, product, Parameter
    Integer, Line Item Turnaround Time, line_item_turnaround_time, provided

+ Rule: Get the Line Item Turnaround Time as a Number
  Provides variables: Line Item Turnaround (line_item_turnaround)
    + Conditions
        + Entity has field
          Parameter: Entity: [line-item], Field: commerce_product
          //exposes the line item to the rule
        + Entity has field
          Parameter: Entity: [line-item:commerce-product], Field: field_turnaround_time
          //exposes the line item's product variation to the rule
    + Elements
        + Add a variable
          Parameter: Type: Integer, Value: [line-item:commerce-product:field-turnaround-time:interval]
          Provides variables: Line Item Turnaround (line_item_turnaround)
          //pulls the turnaround time as an integer
        + Set a data value
          Parameter: Data: [line_item_turnaround_time], Value: [line-item-turnaround]
          //write's the turnaround time to the "line_item_turnaround_time" variable

Ruleset: Set the estimated shipping date
rules_set_the_estimated_shipping_date
This rule pulls the turnaround time from a list of the line items in the current order, compares them and uses the largest value to adjust the estimated delivery date. Again, I could probably have used a regular Rule here instead of a Rule Set.

Date Type
    Commerce Line Item, Line Item, line_item, Parameter
    Commerce Order, Order, order, Parameter
    Commerce Product, Product, product, Parameter

+ Rule: Calculate the estimated shipping date
  Provides variables: Order Turnaround Time (order_turnaround_time), Conversion result (conversion_result), New Estimated Shipping Date (new_estimated_shipping_date)
    + Conditions
        + Entity has field
          Parameter: Entity: [line-item], Field: commerce_product
          //exposes the line item to the rule
        + Entity has field
          Parameter: Entity: [line-item:commerce-product], Field: field_turnaround_time
          //exposes the line item's product variation to the rule
        + Entity has field
          Parameter: Entity: [order], Field: field_due_date
          //exposes the current order to the rule
    + Elements
        + Set a data value
          Parameter: Data: [order:field-due-date], Value: [site:current-date]
          //set the order's due date to the site's current date. This does two things: 1. ensures that the shipping date is based on the exact time the order is completed, as opposed to a previously calculated value, or the order creation date. 2. rules fail if no value is set
        + Add a variable
          Parameter: Type: Decimal number, Value: 0
          Provides variables: Order Turnaround Time (order_turnaround_time)
          //set the base turnaround time to 0 so we have something to compare our line item turnaround times to
        + Loop
          Parameter: List: [order:commerce-line-items]
          List item: List of Line Items (list_of_line_items)
          //loop through a list of the current order's line items
            + rule set: Get Line Item Turnaround Value
              Parameter: Line Item: [list-of-line-items], Order: [list-of-line-items:order], Product Display: [line-item:commerce-product]
              Provides variables: Line Item Turnaround Time (line_item_turnaround_time)
              //runs the "Get Line Item Turnaround Value" and pulls the "line_item_turnaround_time" for the current loop line item
            + Calculate a value
              Parameter: Input value 1: [line-item-turnaround-time], Operator: max, Input value 2: [order-turnaround-time]
              Provides variables: Calculation result (result)
              //check to see if the current loop line item's turnaround time is larger than the value of the order-turnaround-time
            + Set a data value
              Parameter: Data: [order-turnaround-time], Value: [result]
              //if the current loop line item's turnaround time is larger than the value of the order-turnaround-time write it as the new "order-turnaround-time" otherwise keep the old value
        + Convert data type
          Parameter: Target type: Integer, Value to convert: [order-turnaround-time], Rounding behavior: Always up (9.5 -> 10)
          Provides variables: Conversion result (conversion_result)
          //converts the order-turnaround-time to an integer, just in case it's not, so we can apply it as an interval
        + Apply an interval to a date
          Parameter: Interval number: [conversion-result], Interval period: Days, Date: now
          Provides variables: New Estimated Shipping Date (new_estimated_shipping_date)
          //add the new "order-turnaround-time" to the "site:current-date[field-due-date]" to calculate the estimated shipping date
        + Set a data value
          Parameter: Data: [order:field-due-date], Value: [new-estimated-shipping-date]
          //write the new estimated shipping date to the field-due-date field on the order

Hope that saves someone a couple of hours.


How to display number of flagged comments for each author I am trying to copy the "thanked"-function seen in vBulletin forums. Here the author of a topic can thank the author of a comment and the number of comments a person have been thanked for is shown in the author pane.

I have used the Flag module to allow a comment-specific flag but I can't figure out how to display the count number of thanks for each user. I have tried to create a view and display it with views_embed_view but i don't know how to choose count for the specific author? I have also thought of using entityfieldquery but I don't think it can see which comments that are flagged?

Is there a solution to my problem?

Ok so I found a solution although I am not sure it is the best one. The problem was that the databases for the flag module only stores the comment id (when using a comment flag) and not the id of the authoring user. I am implementing the code in a PHP snippet in author pane template where the comment object isn't available. My solution was to do two queries:

$cid_array = db_query("SELECT cid FROM comment WHERE uid = :user", array(':user' => $account->uid))->fetchCol();
$thank_count = db_query("SELECT COUNT(*) FROM flagging WHERE entity_id IN (:cid) AND fid = 2", array(':cid' => $cid_array))->fetchField();

Thanks to Felix Eve for supportive comments


Is there a way to return "Drupal root" value that is faster than running drush status? I'm trying to add something to my shell that shows the current Drupal root value so that we can use drush use more, but the only way I can see to return the current Drupal root value is to run drush status which is quite slow

cd /path/to/drupalroot/sites/default
drush drupal-directory '%root'

On the old system I'm on right now, that clocks in at 3.5s, vs. 11.8s for drush status

If you are using site aliases, as tenken suggested, then you can do this:

drush sa --format=csv --fields=root


Should the Update Manager module be uninstalled when installing with Composer? Drupal 8 is installed with Composer and I use it to update. So I uninstalled the Update Manager module provided by the core.

Now when I go to /admin/reports/status, I have the following warning.

Should the Update Manager module be uninstalled when Drupal is installed with Composer?

Personally, I have Update Manager installed on all my live sites.

While I use composer to manage all of my sites, I am do not blindly composer update and push out.  I like to read changelogs and make sure I regression test thoroughly.

So, I have email notifications for updates turned on for all of my sites.  Most are set for daily notification for all updates, but a handful of internal-only sites (as in behind the firewall) set for security updates only.

Then I can test and plan what updates go out when during my maintenance windows.  Or for security updates, triage how critical they are to go out outside the normal windows.


Record image details for each image I wonder if someone could tell me how to add details for each image I have for my content on my Drupal 7.32 website (say title and description). For Example, I have a Content Type called Info, this has an image field which can have an unlimited number of images. When I upload the image I would like to also add details about the image. I remember seeing a Module that will allow that, but Ive been googling and I cant find it now. If this is not possible then I guess I will have to link the Image to another node and add the detail there. If you take a look at my About Us page on my website (http://www.caerleonlodgehillprimary.org/about-us), it has 3 images at the bottom, I would like to be able to show a title under each one, maybe some description too.

If you are customizing your theme and creating your own template files then this will help you.
This module can solve your problem for adding description for particular image.
https://www.drupal.org/project/image_field_caption
Just follow the installation guidelines and install it.
For title, just go to content type->edit link of image and then look for enable title field and enable that.
Yeah , you need to play a bit of with your codes, need to fetch data for title and description.
Thanks


How to import XML (using an API) via Feeds module? I have a client who uses a CRM that allows us to download data in XML format via an API. If I create a URL such as:

http://www.crmwebsiteurl.com/API/service.asmx/APISelect_XML?strCompanyAccount=client_name&strLogin=client_user_name&strPassword=client_password&strSessionID=&strTable=ClientTableName&strFields=ClientField1,ClientField2&strWhereClause=&strGroupByClause=&strHaving=&strOrderBy=

(and yes, all those empty queries/values in the URL must be as they are or the request will fail)

this URL will load an XML document in my browser, with all the content. I can then save that page (which automatically saves as an XML document) and then use Feeds and XML Xpath parser to import the data into Drupal, which all works perfectly.

The trouble is, I want to import the data directly, without having to download and save the XML file to my desktop. I know Feeds has an HTTP Fetcher, but I've tried what seems like every possibly configuration option (which really isn't that many) and I can get it to "successfully" import, but it always says there are no nodes to import (even if I've deleted all my nodes just to be sure). Obviously its not reading the XML file right.

I've seen other ways API's like to be authenticated and some tutorials on how to to those, but this (seemingly) simple authentication method (if a bit insecure) I haven't seen any tutorial on. And if I just use the entire URL (with the query, username, password, etc) in the URL field (Enter a Feed URL), it just always says "There are no new nodes".

I've also played with Feeds Import, Feeds HTTPFetcher AA, Web Service Client - but still haven't seemed to find anything that I've been able to make work.

Is this a unique situation? Or most likely I'm simply doing something wrong? Is there a tutorial I didn't come across that could help me?

You need todo more debugging. As 1 possible debugging example use Chrome Inspector to assure that properly configured, Feeds is requesting the correct URL to get the XML payload. you can do this by logging HTTP persistently before you hit the drupal admin page and recording what Feeds is issuing.

Compare that to hitting the URL by hand in the browser, or whatever steps you take. I suspect that Feeds has an API to alter the outbound request to the remote server and make it 1:1 with hitting the remote url by hand.

There are other HTTP session records you can use depending on your OS.


Can't set arguments to a view for displaying all data I use

$view = views_embed_view('export_emargement','page_1',$journee,$region,$produit);

it works well, but If I don't want to specify $region the view does'nt works.

Im my view admin if I set argument like this 797/62/24 it works

If I try 797/all/24 it works too!every data are displayed

In my code i try this, but it can't be parsed

$args = array($journee.',"all",'.$produit);
or
$args = array($journee.',all,'.$produit);
$view = views_embed_view('export_emargement','page_1',$args);

$args is an array that expects each field's contextual values to be passed in separately.

i think $args = array($journee, "all", $produit); ought to work.

you should only concatenate arguments into a string if its a multi-value single field situation and then I believe you join with '+' not commas.

EDIT

I missed what you were asking, if you have a contextual filter that is optional inside the view you can configure what happens when no value is provided (pick "display all results").

then when calling the view

as far as skipping an argument 'all' - the easiest way would be to move the order of the contextual filters so that the one that is allowed to be "empty" is last.

then instead of calling

$view = views_embed_view('export_emargement','page_1',$journee,$region,$produit);

call

$view = views_embed_view('export_emargement', 'page_1', $journee, $produit, $region);

or

$view = views_embed_view('export_emargement', 'page_1', $journee, $produit);

depending on if the user has selected a region


reCaptcha not working on webform I am using a Webform module to create a form to which I would like to add recaptcha. I've gone through the readme files for both captcha and recaptcha modules and all the configuration settings look fine.

The only thing I am unsure about is on admin/config/people/captcha general settings page.... I am trying to add a new form id to reflect my webform (webform-client-form-25) but it won't accept it. It says "Illegal form_id".

I've got the public and private keys set.

Skip CAPTCHA is NOT selected for any role.

From the view source:

How do I get the recaptcha working for my webform?

Since people may not check the comments for the answer:

Yaazkal suggested in comments try using webform_client_form_25

Hyphens(-) are generally translated into underscores(_) for machine names in drupal.


Why can anonymous users access private files using the system URL? I have a private organic group with a private organic groups post. I have properly setup my private files system. If an image is uploaded to the private folder an anonymous user can still access it with the following URL:

/system/files/private/assets/image.jpg

However they are given a Forbidden: You don't have permission to access this on this server when access the URL this way:

/sites/default/files/private/assets/image.jpg

My guess is that Drupal is not doing it's job in the first instance; as I haven't set up private file system properly and Apache is doing it's job in the second URL due to the htaccess file in there.

Any pointers?

/sites/default/files/private/assets/image.jpg will never work because of an .htaccess directive prohibiting direct access to that directory.

Beyond that, this strikes me as an issue with OG.  I'd try executing a module_implements('file_download') and have a look at what modules might be interacting with determining if a given file is accessible.


Display order of entity reference fields I have an entity reference field which references and displays multiple nodes on a Drupal 7 install.
I am trying to get them to display in date order (the date is a field on the referenced nodes).  The problem I have is that if a referenced node date is changed, or a new one created, the display order doesn't change.

I use a entity reference view to order the nodes on their date fields, which works when you manually edit the master node and then save it.  This then updates the order.  However this not a very practical solution.

I have tried creating a module which when referenced nodes are modified or created, it programatically loads and saves the master node using node_load and node_save.

However this doesn't trigger the referenced nodes to update their display order.

Does anyone know anything else I can try?

In case someone stuck on this, i have a solution for Drupal 8 (you can figure it out for 7):
In themename.theme add a preprocess funtion:

function themename_preprocess_field__field_entity_reference(&$variables) {
    usort($variables['items'], function ($a, $b) {
        $a = isset($a['content']['#node']) ? $a['content']['#node']->field_display_order->value : null;
        $b = isset($b['content']['#node']) ? $b['content']['#node']->field_display_order->value : null;

        // Do the comparison
        // This <=> operator only work for PHP >= 7
        return $a <=> $b;
    });
}


How to count the node of content type for corresponding entity reference field I am creating a report. I want to count the nodes of a content type saved for particular entity reference field.

So far I have worked with Views Aggregator and Forena Reports.

But I am not able find it. Can anyone help me on this please?

In Views, under Advanced, Use Aggregation - Yes.

Suppose you have content type A and B. B has entity reference field which refers A.
Now you have already created a view for content type A and added its relationship to B.

Now under Fields, Add a new field of the content type B(suppose body), change the label to Count set its aggregation settings to count.


Edit user profile template with module How can I edit the user profile template in Drupal 7?

I've created a module called sporthron in my project.

sporthron.module contains :

/**
 * Implements hook_theme().
 */
function sporthron_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['user_profile'] = array(
    'template' => 'user-profile',
    'path' => drupal_get_path('module', 'sporthron') . '/templates',
   );
  return $theme;
}

And here is the path to the template :
/sites/all/modules/sporthron/templates/user-profile.tpl.php which contains :

<div class="profile"<?php print $attributes; ?>>
  <?php print render($user_profile); ?>
</div>

TEST

But this template is never used. Whatever edit I made is not applied.

And yes my module is enabled. Do you know how can I apply this template

Try to implement the hook_theme_registry_alter()

/**
 * Implements hook_theme_registry_alter().
 */
function sporthron_theme_registry_alter(&$theme_registry) {

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

  // Find all .tpl.php files in this module's folder recursively.
  $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
  // Iterate through all found template file objects.
  foreach ($template_file_objects as $key => $template_file_object) {
    // If the template has not already been overridden by a theme.
    if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
      // Alter the theme path and template elements.
      $theme_registry[$key]['theme path'] = $module_path;
      $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
      $theme_registry[$key]['type'] = 'module';
    }
  }
}


Search API- Force taxonomy terms to be indexed as one language I have a non-multilingual taxonomy on a multilingual site.  All of the terms in the taxonomy are in English.

However, since this is a taxonomy of locations, some of the translations of the names of states/prefectures are in the database as part of the general interface translations.

I have a search index in Search API that indexes the taxonomy terms (field reference on a node) as type taxonomy term.  Somehow, Search API is sometimes picking up the translations when it is doing the index, so I get results like this:

Tokyo (50)
東京 (25)

These are both Tokyo, just some of the entries are converted into Japanese.  The only thing I can think is that the author language is set to Japanese for the nodes that are coming up as Japanese.  However, when I display the data in a view, all of it shows up in English.

So, how can I force Search API to ignore translations when indexing taxonomy terms?

One workaround: since I didn't need the translations in my case, I could go to the Translate UI screen and search for them and delete them one-by-one.  A real pain, but at least it cleared up the problem.


How to alter the Views field Format drop-down menu I am exporting some XML feeds using Views. One of these fields needs to look like this:

<image>http://example.com/path/to/myimage.jpg</image>

I am storing my image in a CCK field. When selecting that field in Views, these are the options provided:

I don't need an teaser, full node, editable something, or HTML formatted link, just the path to the image. How do we alter that Format selector?

If your content type is blog, for example, and it has a CCK image field, create a relationship from your blog content type to the image content type.

Create a new field in the View and select the field_image from the image content type, make
sure to select the relationship you created:

And select URL to file from the Format dropdown:


Relation Between Drupal Commerce Line items and Products I am making a website in Drupal 7 and Drupal Commerce with some custom modules. Now, I have a set of Products.

The Products are,
 - Product 1
 - Product 2
 - Product 3
I have two line items. Lets say Product Sizes. And product weight.
Each have select or another module implemented. I have followed the concept of Randy Fay's Screencasts.
http://www.commerceguys.com/resources/articles/237

http://www.commerceguys.com/resources/articles/238

Now with each line items the cost of the product changes.
As per the screenscasts, the process will be,

Create Line Items
Create Products
Create Product Display and add a Product Field Reference to it.
Then it will display the line item in the product display page.

But, I am not creating the Product display. This is going to be via the custom module. So can you tell me from the coding point of view, what is the relation between a line item and a product. So that I can list all the created line items for a displayed product.

It sounds like you are confused.

Short answer:
Line items has a reference to a product.

Explaination
Line items are only used when you add something to your order (cart), they have a relationship between the order and the product and hold data like price quantity, but can hold additional data, like the address (in case of subscriptions), which a unique each time you buy something.

If you have product attributes like size or weight, you probably want to store this on the product, since a products with different sizes and weight should be different products (A S size t-shirt is not the same as a L sized t-shirt).

So it really sounds like you are doing this the wrong way.


Node Hierarchy and active menu trails I'm trying to use Node Hierarchy module together with the Menu Block module to create blocks in different regions of my site.  My problems is that when a child path is active, the parent path doesn't highlight.

An example of what I want is the path http://example.com/exampleparent/childnode1

My main menu is on the left side of the screen, like so:

Home
Example Parent  <-- active parent
About

And the child menu is on the right side of the screen, like so:

Child Node 1 <-- active child
Child Node 2

But when I'm viewing the child node the parent isn't "active" (bold, in my example).

Is there an option I'm missing, or does the Menu Block module not work the way I think it does?

The problem was not that the modules failed to act correctly.  The problem was that the theme I was using did not have any CSS for the active-trail class that is provided.

To be thorough, there are two classes that get applied to menu items.  The active is only for the exact menu that you're at.  The active-trail class gets applied to all the parents of the current menu.


Drupal 8 Custom Twig Templates not being loaded I am working on a website which has pages with dynamic google maps, which has made it necessary for me to make use of custom page templates. I ran into a issue earlier today and been trying to find a way around it for hours now:

I have two pages that I need to create templates for(lets call them /dash_a and /dash_b). I created a twig template saved as page--dash_a.html.twig which loads correctly when I navigate to the page on the website. Now I created the page--dash_b.html.twig but it doesn't load the template on this page surprisingly. It actually uses the page.html.twig template. I have tried the following:

Cleared all caches numerous times
Deleted the page /dash_b and recreated it
Disable Caching on the website
copied the content of page--dash_a.html.twig into page--dash_b.html.twig, cleared cache and refreshed page just to be sure there is no error in my twig file.
Created another page /dash_c and created a corresponding page--dash_c.html.twig to see if it will work but that too didn't work.

None of these could resolve my issue. Please what else is there to do to resolve this issue as it has robbed me of a whole day's work already. Any help will be appreciated.

P.S.: I am very new to Drupal and this is my first website on the platform, but I have used DNN extensively in the past.

Can we start easy? I think 9 times out of 10 when my templates dont load it's due to file naming issues. Do the file names match what's in the database as your content type machine name?

One thing that has happened to me a couple times is I hit enter too soon when creating content in drupal. That ajax just needs a little time to catch up and fill in the machine name. Too soon and your dash_c page could actually be named dash_

Do you have devel enabled? Can you see the *FILE NAME SUGGESTIONS when you "view source" of your webpage?


How to redirect all node aliases to ? I created a module with a hook_menu() to redirect every $items[%node] to drupal_goto('<front>'). Is it possible to do the same for every alias path and how would I do that?

The background is that it's a one-pager with all nodes displayed only on the <front> page. No single node should be viewed. Nevertheless every single node has a Facebook Like Button and so has to be like-able/share-able with Facebook. But that's another story, on the whole.

Using the Rules module you can implement a rule that looks like so:

{ "rules_redirect_all_node_aliases" : {
    "LABEL" : "Redirect all node aliases",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "my_homepage" } }
    ]
  }
}

It will redirect any path starting with node/ to a path named my_homepage (adapt that path to fit your homepage path).

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function.

Note: A variation of this rule could be to replace the Rules Condition with something like "if the current path is not my_homepage" (in which case the same Rules Action will redirect to my_homepage.


How can we use form directly without using drupal form handler I want to post a html form into block as content and wanted to submit the form to a page.
where I will need to get the form values using $_POST and do some process on it.

How can i do that without using drupal_form(), drupal_form_submit() handlers.

Any way we can achieve it.

Thanks.

If your goal is to just get the HTML output of an existing drupal form then this will get you there:

$form = drupal_get_form('drupal_form_id');
$form['#action'] = url('mypath');
print render($form);

Replace 'drupal_form_id' with whatever registered Drupal form you want and url('mypath') with whatever URL you want to post to.


Custom Validation while adding a term under taxonomy I want to use custom validation while adding a term. I used form alter and #validate function it's not working.Default validation function under taxonomy module is working but my custom validate function is not.

Here is my code

  function lms2_validate_form_alter($form , &$form_state, $form_id){

    if ($form_id == 'taxonomy_form_term'){
      $form['#validate'][] = 'lms2_validate_term_validate';
    }
  }

  function lms2_validate_term_validate($form ,&$form_state){
      drupal_set_message('hello');
  }

In Drupal 7, if you go through hook_form_alter.

It uses $form as a reference. You need to use & before $form.

/**
 * Implements hook_form_alter
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_form_term':
      $form['#validate'][] = 'mymodule_taxonomy_form_custom_validate';
      break;
  }
}
/**
 * Implements hook_form_validate
 */
function hook_taxonomy_form_custom_validate($form, &$form_state) {
  //validation goes here
}

Let say if your module name is lms2_validate then use:

function lms2_validate_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $form['#validate'][] = 'lms2_validate_term_validate';
  }
}

function lms2_validate_term_validate($form, &$form_state) {
  drupal_set_message('hello');
}


My events are not displayed in calendar Here I have a problem with Views and Calendar modules.
I created test events with a date field.

I configured a view for Calendar with the date field, but no events are displayed ...

How to?

And if possible, how to remove the link on the month names?

thank you very much

Hi you could use event_calendar module.. The calendar module only display calendars value. It is not display any event on it... So we are going for event calendar module. It gives various option for display the events and also provide the event content type..


Filtering the terms of a specific vocabulary How do I get all the taxonomy terms of a specific vocabulary? If a page has terms coming from 2 vocabularies (e.g. "Software" and "Hardware"), how do I display the terms coming only from the vocabulary "Software," and not from "Hardware"?

In a view, to filter terms from a page tagged with more than one vocabulary, so that only the terms from, say, Hardware show, you would:

under Format, change the default 'Content' format to 'Fields'
under Fields, add a 'Taxonomy: All Terms' field
scroll down to the 'More' section and click
you should see a screen like below, which allows you to filter terms to a single vocabulary (or more, if needed)
http://img850.imageshack.us/img850/9266/filtertoonevocabulary.png


Adding a delete button to node edit form I need to add a delete button to a node edit form, so in case I open a edit form of the node I want to have a possibility to delete it as well.
This edit node form is genereted from a view using Link to edit Content and displayed in modal window, which adds the following markup to the page.

Link to edit node

How can I programmatically achieve this in Drupal 8?

There is a "Delete" Link right to the "Save" Button. If you can't see it, you're missing the "delete content of type x" permission.
If you need the Link styled as button, use the matching css classes of your theme.


What drush version I can use that doesn't require composer? I try to use drush on the server that is behind corporate firewall, and downloads from many sites are blocked. In particular, when I run "composer diag", it hangs for the long time on the line "Checking http connectivity to packagist: http://packagist.org/" and then prints "The "http://packagist.org/packages.json" file could not be downloaded: failed to open stream". I saw similar blockage when trying to use wget with a number of URLs, including ftp-origin.drupal.org/files/projects/.

So how far back should I go to get the version of drush that doesn't use composer and will not try to update itself on the first run? I understand that some functionality will be missing, but at least basic functions like "drush cc", "drush en", "drush dis", etc. I will be able to use.

I believe any version on this page that is released as a phar file:
https://github.com/drush-ops/drush/releases

Super old versions of Drush (unsupported) were not released as single phar files. The current version of drush (version 9) seems to be geared to released/maintained via Composer only; and no longer Pecl or other distribution channels.


How to restrict field permissions to referenced user? I have a submit-review process where submitters choose their reviewer. The reviewers are linked By User Reference module. Submissions are public but have an Accept/Deny review button implemented with Button Field which only should be accessible by referenced user.

Workflow fields submodule seems to accomplish that behavior but unfortunately I can't get it to work with Workflow. There is an incompatibility of versions and maintenance seems not to be very active.

So I try to build my own solution using hook_field_access() like that:

function MYMODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  if ($op == 'view' && !empty($entity) && ($field['field_name'] == 'field_accept_review' || $field['field_name'] == 'field_decline_review')) {
        // is current user == node reviewer?
        return ($entity->field_reviewer == $user->uid);
    }
}

Do I have to use user_load() before getting to the uid of the linked user?

I assume field_reviewer is an user reference field with only a single value allowed. If so use the following to get the referenced user's uid which is directly stored in field_reviewer array in submission:

// is current user == node reviewer?
if (!empty($entity->field_reviewer)) {
  $reviewerId = $entity->field_reviewer['uid'];
  return ($reviewerId == $user->uid);
}
return FALSE;


How can I display a message when "add another item" on an Inline Entity Form Multiple field is clicked? In Drupal 8 inline entity form is there a "form_alter" or "submit handler" or some type of ajax callback for when a user clicks "add another item"?

What I would like to do is display a message to the user when they click "add another item" on a Inline Entity Form Multiple field.

Struggling to find the right path.

You can do this using JS. Add a click event listener on the Add item button. When the button is clicked you set a message.

Something like this should work:

$('.add-item-class').on('click', function () {
  const messages = new Drupal.Message();
  messages.add('You clicked the add item button!');
});

Make sure you have Drupal available in your JS file by adding it as a dependency in your libraries file.

js:
  path/to/js-file.js: {}
  dependencies:
    - core/drupal
    - core/jquery

Please note that the Drupal.Message() was first introduced in Drupal 8.7, so if you use an older version it would not work.

Another possible solution is to create a route that sets the message, using \Drupal::messenger()->addMessage('').

Your controller will do like this:

\Drupal::messenger()->addMessage($this->t('Your added an item!'));
$messages = ['#type' => 'status_messages'];
return new JsonResponse(['message' => Json::encode(\Drupal::service('renderer')->renderRoot($messages))]);

And your JS file like this:

$('.add-item-class').on('click', function () {
  $.get('/path/to/your-route', function (response) {
    $(context).find('.region-highlighted').prepend(JSON.parse(response.message));
    setTimeout(function () {
      $(context).find('.region-highlighted .messages').remove();
    }, 5000);
  });
});

This appends the message to the highlighted region and removes it after 5 seconds. You can place it anywhere you want.


Viewing ID of organic group? I am trying to display the ID of the group the user is currently viewing. I created a block, and added the following PHP code into it:

<?php
$group = og_context();
if ( !empty($group) ) {
   print "$group->nid";
}
?>

Problem is, when I run it, I get the following error:

Notice: Trying to get property of non-object

Any idea why this is happening, and how to fix it? Seems like it should be easy enough of a task.

In Drupal 7 the NID is the group ID so you could just output $node->nid.


How to use user wildcard in a custom path? I have configured my user path alias pattern as consultant/[user:name]. Now I need to have one custom path from my custom module as consultant/[user:name]/job. Here is my  code in hook_menu.

 $items['user/%user/job'] = array(
'title' => 'Apply for job',
'page callback' => 'job_application_page',
'access arguments' => array('access content'),
'file' => 'job.pages.inc',
'type' => MENU_CALLBACK,

);

I want the url as follows

For user Joan the path should be consultant/joan/job. But this is not working, giving an 404 error page

Do I miss something? Please advise.

You've picked user_load as your wildcard's load function - that takes an ID, and loads a user object. Your requirement is to load by username, which will work differently.

A function ending with _load doesn't exist for that, so you'll have to create your own:

$items['user/%MYMODULE_user_name/job'] = array(
...

function MYMODULE_user_name_load($name) {
  return user_load_by_name($name);
}


How do I manually group content? I have created a wishlist in which those nodes are showing which are flagged,
Wishlist working fine

The next task is to create favorite groups. That is, the user must be able to create groups of favorites, being able to edit a name, for example “summer recipes”, and assign recipes to the group.

What i have tried so far i have created a another content type "Create Group" which is automatically get flagged on creation by Using hook_node_presave().

Now flagged nodes(Groups) are also showing in wishlist then i have added draggable views into the existing wishlist view for grouping content by drag and drop by changing order.

But after changing order ,the changed order is not shaving into database,i think its a module issue which is not compactible with views relation.

Is there any alternative like is it possible to add custom select list in group content type which will show list of flagged node per user .

You can group existing flagged content into smaller groups through the Content type Group you created with the help of Views display type Entity reference.

Create Content Views listing nodes that user might flag, don't create Page nor Block display, then when you save the View add the Display Entity reference from the Add dropdown.
Under Format: Entity Reference list Settings choose Content: Title as the Search field

In the results you should now see a list of node titles that can be flagged.
Add a new Relationship Content flag from the Flag category and configure it:
Tick Include only flagged content
Flag Bookmark (or whatever the name of your flag is)
By Current user

This will now filter out only the nodes that are already flagged by the current user. You are probably logged in as admin so you will now only see nodes that admin has bookmarked.
Adjust other views settings (Pager for example to show all items), No results behavior to You haven't bookmarked any content yet and save the View.
Edit your Group content type and add a new Reference field that references unlimited number of Content (nodes).

You'll probably want to make it a Required field

Under Reference type Reference method choose the Views you created in the first step. You will only see views displays of Entity reference type here.

A new option will appear View used to select the entities. Choose your exact views display here.

There are no arguments to pass, leave that empty (it is done through the flag relationship).
On the Manage form display settings for that field choose Check boxes/radio buttons.

Now when your users go to create a new Group node, they will be able to choose from a list of nodes they had already flagged:

In case you need your users to control the order in which the selected nodes appear in the Group you can change the field widget to Autocomplete, that way the choices can be reordered:

but this way the users have to search for node titles. You can help them by duplicating the views into a Block display and displaying it only on Create/Edit Group pages so users can see which title to search for.


File upload with ajax and without upload button Is there any example how to set up form element with type file to upload it via AJAX and without upload button. I want to be same as stackexchange.

These modules can help you

HTML5 Drag & Drop File

  HTML5 drag & drop + HTML5 file upload with XHR2. Allows the user to
  drag & drop files into a Image/File Field and uploads it immediately
  behind the scenes. In theory it should work for as many files as the
  field allows.

  Requires jQuery >= 1.5.2 (jquery_update has that)!

  It's a start...

Enable
Works for all managed_file fields
You can disable per field in the field instance config

  There's a settings form under Config > Media where you can change the
  upload method from Series to Parallel (much faster, but slightly
  riskier). If you dare, try it out. I've experienced (although not for
  a while) the full entity form being submitted by a file upload.

  If you're uploading A LOT of files, you might encounter the server's
  max file/POST size limit. I've no solution for that yet.

Drag'n'Drop Uploads(you can use dev version,I am using it and work;) )

  The Drag'n'Drop Uploads module adds the ability to drag an image from
  your local filesystem, drop it onto a node body textarea and have the
  file automatically uploaded and referenced in your node.

(maybe you just need some custom jquery coding, first hide upload button then fire upload button programmatically in your js)

Plup

  Plup module enables uploads to file fields using the popular plupload
  library. It does not require any other modules to work, but the
  plupload library must be downloaded separately (version 1.5.8 is the
  last supported version).

  Please note that you must remove the "examples" folder from the
  downloaded plupload library to avoid introducing a security
  vulnerability.

  The original developer is no longer maintaining the module, and I will
  only minimally maintain it until Media 2.x has a stable release that
  works with plupload and multiform, after which I expect to migrate to
  those modules.


How to inject User class as dependency? How to do I inject Drupal\user\Entity\User class as dependency? I could not find service name in service list.
 for example:

$user = User::load($this->currentUser->id())

for this code I want to call like this

$user = $this->user->load(($this->currentUser->id())

when injecting in Controller. How can I achieve this?

You don't have to inject services in the controller, because ControllerBase already provides the services needed. So this should work:

$user = $this->entityTypeManager()->getStorage('user')->load($this->currentUser()->id());

For other services not included in ControllerBase, see How do I use dependency injection on \Drupal::moduleHandler() to a Controller?


Added fields are not displaying while creating the user I am new to drupal and I have added few more necessary fields to the user create page [i,e in configuration->people->account setting->manage fields],but the added fields are not displaying while creating the user[i,e admin->people->add user]
but its displaying while editing the created user, I have searched to figure it out from last 1 week but no luck for me. if anyone know the reason for not displaying please help me. I have attached the screen shot too.Thanks in advance.

this is a similar questions on Drupal answers. I would remove this one as i considered duplicated.

Adding fields to user registration form