How to check if an item exists in a Queue? While inserting items in a Queue how can I check if the item I am trying to insert is already present in the Queue?

The queue API doesn't have a method for this. It is very limited on purpose, as some queue systems might not be able to provide information like this.

The update module has its own wrapper to do this, by additionally storing all the task names in key value as well. See \Drupal\update\UpdateProcessor::createFetchTask:

public function createFetchTask($project) {
  if (empty($this->fetchTasks)) {
    $this->fetchTasks = $this->fetchTaskStore->getAll();
  }
  if (empty($this->fetchTasks[$project['name']])) {
    $this->fetchQueue->createItem($project);
    $this->fetchTaskStore->set($project['name'], $project);
    $this->fetchTasks[$project['name']] = REQUEST_TIME;
  }
}


Don't allow role to delete published content even its their own thanks for reading my question.

I am currently working on Drupal 8 site, please consider the following roles:

Admin - Can do everything
Publisher - can do everything the Admin can do, except set up and edit new
administrators
Editor - Can do everything the publisher can do, except Publish content to live
Writer - Can do everything the Editor can do, except Delete published content

I have managed to satisfy the permission for the roles Admin, Publisher, and Editor, now it seems the Writer one is tricky.

The only option seems like to Enable Delete own content for Writer, but that won't solve the issue if his article was already published, he can delete it.

Is there a module that can be solved by this? Or a better approach on how to configure permissions?

Regards,

Simply search for and disable the permission "Delete any content" for any / all content types for the role of "writer".

This is also a very handy module to help you find permissions https://www.drupal.org/project/permissions_filter


How do I programmatically know the jQuery version using a script or a hook? How do I programmatically know the jQuery version using a script or a hook?

I have used this script for getting the site's jQuery version.

if (typeof jQuery != 'undefined') {
// jQuery is loaded => print the version
alert(jQuery.fn.jquery);

How could i get the same by using some database query or hook programmatically?

you can use this code to get all installed modules list

module_load_include('inc', 'update', 'update.report');
$available = update_get_available(TRUE);
$data = update_calculate_project_data($available);
dpm($data);  // provides installed modules details as an array
dpm($data['jquery_update']['existing_version']); // provides jquery_update module existing version


Drush finding 3rd party module but can't install Have moneyscripts modules installed and drush does not update these 3rd party scripts but still I get a notification via drupal that update is required.

So I used drush up command but failed to update saying could not find download. Then I manually wget install the update but now if I drush up after manual install it won't stop trying to update the core.

How can I make drush IGNORE moneyscripts considering it can't install them anyway?

Or do I just have to select no everytime it asks?

Please see --lock, described in drush help pm-update:

--lock

     Add a persistent lock to remove the
     specified projects from
     consideration during updates.  Locks
     may be removed with the --unlock
     parameter, or overridden by
     specifically naming the project as a
     parameter to pm-update or
     pm-updatecode.  The lock does not
     affect pm-download.  See also the
     update-advanced project for similar
     and improved functionality.


In views, show the number of users who have subscribed to the organic group I am using the following modules
1. Organic Groups
2. Views

A content type called Course has been created. It has been set as an organic group.
It has group members(Users who have subscribed to the course).

I have created a view which shows the list of all the groups (Nodes of type Course).
In another column, I want to show the number of users who have subscribed to the group(course).

This is how to get the OG membership ID:s to start with.

Add new view. Show -> OG membership (important!)
Then in some display add a contextual filter -> OG membership: Entity id.
Provide default value -> Type -> User ID from logged in user.
Override title: %1's groups. Specify validation criteria -> User.

Now you have the list of ID's.

Next to get the actual titles of the groups (as the base table is OG membership, not node), Add a relationship -> Group Node from OG membership.
Add a field -> Content: Title. Relationship -> Group node from OG membership.

Now you get the titles too. For test add some filters and sort criteria.


Views header language in url I am trying to add a link in views header. I enabled multilingual module. Added a Global Textarea in the header. Then added

Click

I want to set the url as

Click

So the link may be

Click

or

Click

SELECTED_LANGUAGE_CODE is the language selected in the url.

English version of my site is http://example.com/en
French version http://example.com/en

You can use the token [site:url] which includes the languages prefix:

Click


Add a new field collection item to an existing field collection I have 1 field collection

Field collection: CKT Info child2
  machine name: field_ckt_info_child2

In that have 2 fields:

Field1: English CKT child2
  machine name: field_eng

Field2: Maths CKT Child2
  Machine name: field_maths_ckt_child2

I have set field setting "unlimited" to this field collection. Now I just want to add new field collection item in existing Field collection(CKT Info child2) programmatically. I have tried below code but it's not creating new field collection item.

function createFC()  {
   $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_maths_ckt_child2'));
   $field_collection_item->setHostEntity($node);
   $field_collection_item->set('field_maths_ckt_child2', "SET SUCCESS");
   $field_collection->save();
}

You can try code:

<?php

use Drupal\field_collection\Entity\FieldCollectionItem;
use Drupal\node\Entity\Node;

[....]

$node = Node::load(1);

$field_collection_items = $node->field_ckt_info_child2;
$fieldCollectionList = $field_collection_items;
if (count($fieldCollectionList)) {
 //update
  $field_collection_item = FieldCollectionItem::load($fieldCollectionList[0]->value);
}
else {
  //create new fieldconlection
  $field_collection_item = FieldCollectionItem::create(
    [
      'field_name' => 'field_ckt_info_child2',
    ]
  );
  $field_collection_item->setHostEntity($node);
  $field_collection_item->set('field_eng', 'HELLO');
  $field_collection_item->set('field_maths_ckt_child2', 'WORLD');
  $node->field_ckt_info_child2[] = ['field_collection_item' => $field_collection_item];
}

$node->save();


Views filter criteria date field is greater than current date I have a overview page with different events. Now it shows all events which were created. But I will that it just shows all the future events.

The content type has a datefield for the eventdate. I selected the field_date_event by the filter criteria but there I can not enter the token [current-date] or a dateformat like d.m.y.

How can I solve this problem?

You should be able to choose the Operator Is greater than or equal to, and the Value type set to offset with value Today:

This will include events happening today. If you want strictly from tomorrow you can choose Is greater than as the Operator.


Log profile 2 user info a separate log file When a user logs in, I want to log the user information from the Profile2 module in a separate file.

How can I achieve this?

The profiles2 docs state:

Thanks to the foundational entity API the module integrates well with Rules as well as Features.

Install the rules module (http://drupal.org/project/rules) and you should be able to access the profile data after he user login event. To log to the system watchdog with rules you need this patch: http://drupal.org/node/1349882#comment-6190164

This does not write to a separate file, but it would be trivial to extract your entries from the watchdog db table using phpMyAdmin.

And finally it does not require any coding.


Resizing a block on a drupal 7 website I have three blocks A, B and C on the home page on location Content Bottom. I have another block D I want to place at location A+B and I want to keep C at the same location. I will move A and B to another location on the layout. How to do that? Currently when I place block D at Content Bottom it only takes the space (and width) of block A and other two columns look Odd. Block D now shows up as a single long column. Not a developer, using Drupal for three years, always learning more about Drupal. I know a little bit about css files and css injector.

If I place block D at Tertiary Content location, it takes the whole width of the screen. It shows below the region for A, B and C.

The block widths are most likely controled by the theme CSS and it seems each block is given a third of the width of the container.

To change that and make one block take up two thirds of the container width you have to override the theme CSS. Exactly which selector and declarations to use depends on your particular case. You enter your overrides in the CSSinject or a similar module that overrides CSS through the interface.

If your theme is using floats, then you can find with your browser dev tools which selector was used to set that and the width, then use that same selector but with your own declaration override, something like:

.special-region .block {
  width: 60%;
}

If the layout method isn't floats then you'll have to adjust accordingly.

One other thing to consider is that this is most likely only code for wide screens, and it should be different for mobiles. Usually the mobile styles stack blocks one on top of the other so you won't have to do anything there, but you'll have to restrict your float to the same @media query as used by the theme, for example:

@media screen and (min-width: 900px) {
  .special-region .block {
    width: 60%;
  }
}

You can find out about which media query is being used through the browser dev tools.


Changing a Profile type Machine Name broke the Admin/People search I'm working on a Drupal 7 website in which there are several Profile types.
As part of a task, I had to change the "Label Name" and the "Machine Name" of one of them: specifically Professional Courses was changed in Professional School.

Later on, I've realised that this substitution have broken the search in the Admin/People page. Precisely, if the Administrator, from the Admin/People page, searches the users with the Profile type just mentioned, the search shows no results.
I've discovered that the View managing this page (Admin/People), has kept the old Machine Name in the query, which means that role has been cut out.

I’ve tried to fix this error by changing the query using the following code inside a views_pre_execute function in a custom module I've developed:

$query = db_select('users', NULL);
$query->condition('users.uid', array('0'), 'NOT IN');
$query->fields('users', array('uid', 'name', 'mail', 'status', 'created', 'access'));
$query->addJoin('INNER', 'profile', NULL, 'users.uid = profile.uid AND (profile.type IN ( \'master_school\', \'employee\', \'summer_school\', \'professional_courses\', \'digital_friend\', \'phd_school\', \'professional_school\' ))');
$query->orderBy('users.access', 'DESC');
$query->range(0, 100);

$view->build_info['query'] = $query;

However, this code changes the query inside the View, but didn’t fix the problem.
How can I fix this bug? Should I go back to the old Machine Name?
Thanks!

P.S. I'm using Profile2 and Administration Views modules.

I think this is a bug in Profile2 module.
I recreated your issue on a test installation and the same results happened.
After I inspected the database itself I found that the machine name was not changed in the table profile but correctly changed in profile_type table.
What you could try is to manually change the machine name in the profile table and see what happens then.
Also, it might be helpful to post your issue in Profile2 issue tracker, maybe they can fix this for other users.

Good luck.


Setting import to run every 15 minutes I am using Drupal 7.43, and I want to read my data from an external database every 15 minutes. My site is hosted on an Ubuntu server.

I am using Feeds importer with SQL parser. From import/feed_from_feed_db, all data is correctly imported; so, the importer runs correctly.

How can I set the feed importer to automatically run every 15 minutes?

For periodic import select As often as possible.

Then use Ultimate Cron and make the Feeds & Scheduler cron run every 15 minutes only, this way cron will not do other tasks that you don't need to do every 15 min.


Can I add a custom link to "Main Menu" via hook_menu? I'm trying to add a new link to the Main Menu from inside my module.

Currently, this code:

function custom_food_orders_menu() {
  $items['order_food'] = array(
    'title' => 'Order Food',
    'page callback' => 'page_creator_function',
    'access callback' => TRUE,
        'menu_name=' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

...adds the 'order food' link to the 'Navigation' menu. I tried setting the menu name to main-menu, but that does not seem to work.

Is this a limitation in Drupal? If it is, I'll adjust by creating a link to that page manually.

The correct code would be the following one; notice the commented line.

function custom_food_orders_menu() {
  $items['order_food'] = array(
    'title' => 'Order Food',
    'page callback' => 'page_creator_function',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',  // This is the changed line.
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

There aren't properties returned from hook_menu() (and generally from any hook used from Drupal core code) that uses the equal character.


How to print a CCK image field alt text in a node template? I'm trying to add the alt text from a cck image field in a Drupal 7 node template.  Getting the image style url is done, but I can't figure out how to just get the alt text.  This is what I have

<img src="<?php print image_style_url('160x160', $node->field_image['und'][0]['uri']); ?>" alt="????" class="thumbnail" />

How does one just output the alt text?

If you install the Devel module, you'll be able to use:

<?php dpm($node); ?>

It will provide all available fields that you could use. Another method might be to use theme('image') to help clean up your image theming.


What are the features of the Group module versus Organic Group module? To create groups in Drupal we have at this moment the Group module and the Organic Groups module.

From the Group module page:

  The Group module allows you to create arbitrary collections of your
  content and users on your site and grant access control permissions on
  those collections

From the Organic Group module page:

  Enable users to create and manage their own 'groups'. Each group can
  have subscribers, and maintains a group home page where subscribers
  communicate amongst themselves.

What are the features of Group versus Organic Group?

About

The Group module allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups.

Organic Groups allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...)

Group instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that). Groups can also act as a parent of any type of entity. Group provides an extensive API to attach entities to groups.

Advantages of Group as compared to OG

Group started in D7 only, taking full advantage of entities introduced in D7.
Group doesn't 'abuse' nodes by adding custom fields to them in order to make the module work.
Group does not allow you to have per-group roles or permissions. These are instead defined on the group type. So group types, group roles and permissions are configuration instead of content. Because of this approach, group types and roles exportable (with or without Features).
Organic Groups is commonly perceived as a huge module, which carries a lot of "legacy" from pre-D7 releases and makes it tougher to ever get upgraded to D8.
A D8 version of Group is already available (not so for Organic Groups).

Disadvantages of Group as compared to OG

As of today, Group only has alfa / beta releases (not any official release).
Even though some say it is self documenting, I think it is not (maybe because I don't want to digest the source code to find out what this module can do ...).
Not a lot of documentation available.
As of today, there is no group tag on drupal.SE, though there is an organic-groups tag, and there are already quite a few Group specific questions. Anybody interested in creating it (again), feel free to reuse my previously approved tag wiki and/or tag excerpt (no need for credits ...).

Integration with various modules

The Group module integrates with various other (popular) modules, including:

Rules, as illustrated in the answer to the question "How to bulk assign existing content to a group created with the Group module?".
Views, as illustrated in the answer to the question "How to show the content of a group on the group page when using the Group module?".
Pathauto.

The beauty, IMO, of these integrations are that they are more or less out-of-the box (not dozens of extra modules needed to make those integrations work).

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Podcast "Using the Group module as an Alternative to Organic Groups in Drupal 7 and 8".
What are the alternatives for the Organic groups module?

What people say about the Group module

Similar to what you see in the Group issue queue: most (if not all) people who know about Group just love it ...


Is it possible to use an image style with a path rather than a URI? I want to be able to send an image included in a custom module to the image_style theme like:

  $render_image = [
    '#theme' => 'image_style',
    '#style_name' => $imagecache_template,
    '#uri' => '/modules/custom/MYMODULE/default.png',
    ...
  ];

But '#uri' is expecting something in the format public:// . Is it possible to marshall a relative path somehow?

I'll expand a bit on what acrosman answered, only because I needed this exact same thing so hopefully this will help the next person who comes across this.

I'm working from preprocess_page and using a view to grab my images.

Like his answer make sure you add the ImageStyle:

use Drupal\image\Entity\ImageStyle;

Once I grabbed the view entity I was able to narrow down my image field and then work my way to the styled image.

$image = $entity->get('field_images')->getValue();
$image_entity = File::load($image[0]['target_id']);
$image_uri = $image_entity->get('uri')->value;
$style = ImageStyle::load('my_image_style');
$image_url = $style->buildUrl($image_uri);

So overall my whole function to grab the image from a View and apply a custom image style looked like.

function _mytheme_preprocess_page_front_projects(array &$variables) {
  $projects = array();
  $view = Views::getView('projects');

  if (is_object($view)) {
    $view->setDisplay('page_1');
    $view->preExecute();
    $view->execute();

    foreach ($view->result as $k => $v) {
      $entity = $v->_entity;

      // Grab image entity.
      $image = $entity->get('field_images')->getValue();

      // Load the first value for preview image.
      $image_entity = File::load($image[0]['target_id']);

      // Grab the uri of that first image.
      $image_uri = $image_entity->get('uri')->value;

      // Using ImageStyle you then load your style.
      $style = ImageStyle::load('my_image_style');

      // Use buildUrl to create the path to your styled image.
      $image_url = $style->buildUrl($image_uri);

      // Then I return the url as an image variable to grab in page template.
      $projects[$k]['image'] = $image_url;
    }

    return $projects;
  }
}


Large var_dump when looking at $variables This might not be the correct place to ask this question, please remove if it is wrong...

But, when I do a var_dump($variables) in one of my nodes I get a very large output that repeats several times... Is this just the way Drupal normally acts or might this indicate that there is something wrong with my site?

Thanks

Yes, it is normal as Drupal pass enormous amount of data trough functions and hooks using array. But for better answer you should provide more information.


Create rule to Set Default Value Here my query is that, I have created one field in product type "Time(Interval)" and another field created in Line item types "(Default Time)" field.
My requirement is when user saves a new commerce order, Product type (Time(Interval) field) value auto saves in Line item field (Default Time) value.
how we can do this, any idea.

You can implement hook_commerce_cart_product_add()
The product which user is adding to cart and the line item is available with in this hook. you can fetch the Time(Interval) field value from product and save it to line item.

function my_module_commerce_cart_product_add($order, $product, $quantity, $line_item) {
   $commerce_line_item = commerce_line_item_load($line_item->line_item_id);
   $product_time = $product->time_interval['und'][0]['value'];
   $line_item->default_time = $product_time;
   commerce_line_item_save($line_item);
}


How to require revision logging for certain users In Drupal 7, if a specific role modifies any content, I want to require that the user add message explaining the changes.  How can this be accomplished, either through an existing contrib module or custom code?

there is a Enforce Revision Log that will do this https://www.drupal.org/project/enforce_revlog module


Automatic copy node from Drupal A to Drupal B Drupal A and B are different domain (example: drupal A: www.aaa.com and drupal B: www.bbb.com)but at the same server.
At Drupal A, there are lot of fields, but I only need to send date field value to Drupal B (Everytime when it update or add new content). Drupal B will get date value and display at the content page. May I know how to do that?

I had tried Deploy (not working at all)
How to add data from one Drupal site to other?

I had tried aggregate but I send everything to Drupal B.

I need help. Many thanks.

For far my current solution is:
At Drupal B: php code connect drupal A database and get the date vaule. Echo to display at the content page.

I would solve the problem with either of the following

1) Write a 5 minute custom php script that would show the node ids and data value and then update the nodes with data value in the second database with a simple update query on field_data_field_<your-field-name> table based on entity id.

2) Use services 3 module to expose your data and then import that field with put method with only the field you want.


Drupal terms and arrays I am struggling a bit with the array structure of Drupal.

I am using PHP in a contextual filter inside views. I have the same vocab on both a content type and user via profile2. I manage to get the filter working for single term. The key is in how I return the values at the end of my function.

return $items[0]['tid'];

This returns 2, a correct tid on user profile taxonomy.

I can also get other values by using:

return $items[1]['tid'];

This returns 4, also a correct tid.

How would I be able to say?

return $items[ALL_ARRAYS]['tid'];

So that it would print all the term ids associated with that vocab?

My PHP code:

global $user;
$profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile) {
      if ($items = field_get_items('profile2', $profile, 'field_your_interests')) {
        break;
      }
    }
$tids = array();
foreach ($items as $item) {
  $tids[] = $item['tid'];
}
//returns nothing in view, not sure if a contextual filter can handle 'and'?
//return implode(',', $tids);

//This works with 1st value in array
//return $items[0]['tid'];

//This doesn't return anything
  return $tids;

There are a few ways you can do this, but this is probably the most straightforward:

$tids = array();
foreach ($items as $item) {
  $tids[] = $item['tid'];
}

// Return this if you want to use "or" logic
return implode('+', $tids);

// Return this if you want to use "and" logic
return implode(',', $tids);


How to install drush properly I am trying to install drush on my new computer and it's a mess
I'm on Mac Os High Sierra, with Mamp 5.3, PHP 7.2.14

I'm mainly interested in Drupal 7
On my previous computer, it was simple i just had to be on the htdocs folder and type : drush dl to download the latest Drupal 7 release

Now i had to install composer (v1.8.4) and then installed drush  using this command : composer require drush/drush:dev-master
I ended up with this version of drush (v9.7.0-dev)
When i type drush dl i get this message :

dl has been deprecated. Please build your site using Composer. Add new projects with composer require drupal/[project-name]. Use https://www.drupal.org/project/composer_generate to build a composer.json which represents the enabled modules on your site.

I'm no advanced user (obviously), i just need drush to have persmission to execute basic commands to install a new drupal 7, install, enable, disable modules..

Here's the result of $PATH

Mac:htdocs Mac$ $PATH
-bash: /Users/Mac/.composer/vendor/bin:/Applications/MAMP/bin/php/php7.2.14/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin: No such file or directory

Thanks

If you read the Drupal compatibility table in the docs, you'll see that the correct version for Drupal 7 is Drush 8. The installation instructions for Drush 8 are simple and clear, no Composer required - just download a phar file.

PS! If you are planning on maintaining Drupal 8 sites (with Drush 9) too, I recommend getting Drush Launcher.


How to add webform to existing content type? I have installed Webform and would like to add it to my custom content type. I have checked my content type under admin/config/content/webform and saved the webform settings but I still don't get the option to add a webform to my content type.

Go to Content type edit page : /admin/structure/types/manage/[ContentTypeName]. There you can see the webform under the Menu Settings. Just enable it from there. Adding screenshot :


ERROR:Cron run exceeded the time limit and was aborted. why? My Drupal installation's cron runs fail when run manually or by cron script.

I thought it might be the Simple News module, but I've disabled then uninstalled that and the problem is still present.

My PHP max_execution_time is set to 120 seconds, but only takes 2 seconds before I'm redirected to domain.com/user/1/edit with no error message is displayed.

When I look in the dblogs I can see:

  Message:    Cron run exceeded the time limit and was aborted.
    Severity:   warning

I have looked in the Apache logs and no PHP error is given. How can I debug in fix this?

Often a drupal_goto() call in a page or module will be sending the execution of the cron run off course.

This often happens when the core Search module tries to index a page with such a drupal_goto() call. The solution is to find that page (or module) and remove the call, or change it so it doesn't fire during a cron run.

Try installing Elysia Cron to allow you to run each Drupal cron task in turn to work out what's causing the problem. From there you'll be able to debug it or look for ideas on the Drupal.org issue queue.


PHP contextual filter code in drupal 7 'no query was run' I am using the contextual filter code in views to filter more options for the view, using this snippet:

$uid= $GLOBALS['user']->uid;

$result = db_query('SELECT users_node__field_data_field_agencyname.field_agencyname_nid as agencyid
FROM {field_data_field_agencyname} users_node__field_data_field_agencyname
WHERE users_node__field_data_field_agencyname.entity_id=:uid AND users_node__field_data_field_agencyname.deleted=0 AND users_node__field_data_field_agencyname.entity_type=:user',array(':uid'=>$uid,':user'=>'user'));

return $result->agencyid;

but no query is run shows up on the sql pane ?

How come?

I would suspect that no query is run because your code snippet isn't returning anything. The thing that jumps out to me is that you are trying to use $result as the first row returned by the query, however it is actually the entire result set.  For example, retrieving data from a DB usually look similar to the code below:

$result = db_query($sql);

// Iterate over the collection ($result).
foreach ($result as $record) {
  $agency_id = $record->agencyid;
}

In the example you posted above, you could use the following code snippet to pull a single field from the first row in the result set:

// This would return the agency ID.
return db_query($sql)->fetchField();

Take a look at the documentation of fetchField() for more information on how it is used.


Inserting previously uploaded images into WYSIWYG editors I'm having a photo sharing feature on the site where users upload photos which are saved as nodes.

I want to be able to have them insert any of their previously uploaded photos into articles nodes and comments.

I haven't decided on TinyMCE vs. CKEditor plugins yet.

I want to do the same for videos they have uploaded.
 I haven't tried IMCE yet but don't like the "windows explorer" like UI. Same with CKFinder

Our old community site has such a feature for the TinyMCE editor but I'm not sure how they did that.

If you're using the Media module, any image uploaded should be available in the WYSIWYG insert media library tab.


How do I use user_save() to add a new category? In Drupal 7,  there is user_save($account, $edit = array(), $category = 'account'). How do I create a new category for an existing account in Drupal 8?

Also, $user = \Drupal::currentUser(); and $user->save(); gives error as well. I need to attach a form element value to user object.

How to link a login form element to user account on logging in?

The category concept has been removed. So the answer is, you don't.

Not sure what you are trying to do, if you need a better answer, you will need to provide more details.

User is an entity with fields. There's nothing special about it, you change and save data in the same way like any other entity.


Ajax post with one parameter How can you pass / as part of a parameter in an Ajax call?

The address is http://studiga.delta-xray.co.uk/delete_favourites/%3Cspan%20class%3D%22remove-favourite%22%3E%26nbsp%3B%3C%2Fspan%3E%3Ca%20class%3D%22title%22%20href%3D%22http%3A%2F%2Fstudiga.delta-xray.co.uk%2Fproperties%2Fliverpool-property%22%3ELiverpool%20property%20Address%20line%201%3C%2Fa%3E%3Cspan%20class%3D%22address%22%3E%20Address%20line%202%20Town%20L2%206RE%3C%2Fspan%3E and I wanted just one parameter, but it is treating %2F as /.

function delete_favourites_permission() {
  return array(
    'access favourites content' => array(
      'title' => t('delete favourites via ajax'),
    )
  );
}

function delete_favourites_menu () {
  $items = array();
  $items['delete_favourites'] = array(
    'page callback' => 'delete_favourites_page',
    'access arguments' => array('delete_favourites_permission'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function delete_favourites_page($line) {
    echo $line;

    $result = "vvvv";
    drupal_json_output($result);
    exit();
}

echo $line; prints <span class="remove-favourite">&nbsp;.

How can I get it to work?

What I think you are trying to do is delete a record from the database, someones 'favorite', like a bookmark on content, perhaps.

Anyway, what you need is an argument in the URL, the best being an ID - even better if it is an entity id that could be provided as a loaded argument for you (like node/%node - the %node argument provides the loaded node instead of just node id).

Assuming the argument is simply an integer of a database record, you could do:

function delete_favourites_menu () {
  $items = array();
  $items['delete_favourites/%'] = array(
    'page callback' => 'delete_favourites_page',
    'access arguments' => array('delete_favourites_permission'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'delivery callback' => 'ajax_deliver',
  );

  return $items;
}

function delete_favourites_page($favorite_id) {
    // code to delete the favorite_id record
    $commands = array();
    $commands[] = ajax_command_alert('Favorite has been deleted.');
  return array('#type' => 'ajax', '#commands' => $commands);
}

However, your access callback should not be TRUE, that means anyone can hit this URL and there is no upfront access checking. I hope you are handling that in your callback, but ideally you should use permissions or a callback to perform more complex checking.

The ID will always be passed to the page callback function now, and you could perform the delete operation there.

The delivery callback has been set as ajax deliver, which tells Drupal the page will return ajax commands. The above code contains a very simple alert, which will fire when the callback is performed.

There is a decent amount more that can go into this when wanting to implement AJAX interactions via menu items and callbacks. But first you need to figure out / fix your URL structure so you can pass arguments and not strings / query strings, and you'll also want to implement access checking so only the user who owns that record (or admin) can delete it.


Private methods within a custom module I am grouping some shared functionality that will be used across multiple template files within a custom theme. I would like certain methods within this module to be accessible to the theme (ie. public) and certain modules only available to the module itself (ie. private).

I understand that modules in Drupal aren't classes, but I hate the idea of the modules 'private' functions being available across the site - it seems to unnecessarily pollute the global namespace.

Is there a way to hide/make private certain methods/functions within a module?

I understand that modules in Drupal aren't classes

Yes, however Drupal modules can certainly make use of classes, and many do.

You can use as many classes as you like.

Put your private functions in class definitions and access them that way.

Include the class file in your module.info file:

files[] = includes/MyModuleClass.class.php

You can use public and private variables in your class

public $public_var;
private $private_var;

Add private methods to your class

// Public
public function myPublicFunction(){
  $this->public_var = 'Public';
}

// Private
private function myPrivateFunction(){
  $this->private_var = 'Private';
}

Instantiate an object with

$options = array(); // example constructor params
$object = new MyModuleClass($options);

echo $object->public_var; // OK
echo $object->private_var; // Error

$object->myPublicFunction(); // OK
$object->myPrivateFunction(); // Error

More info in the PHP OO docs

http://php.net/manual/en/language.oop5.visibility.php
http://php.net/manual/en/language.oop5.php


Panels content wrapper I realised that this was a horribly verbose question, so decided to edit it and try again!

I am trying to find a way of wrapping a set of three (or more) Panels content areas with a div - is that possible?

You can definitely use the Panels Extra Styles module to wrap multiple panes in as many tags as you need.

On the first pane of your new group click the option cog and, under the Style section (which should read No style), choose 'Change'. Change the selected style to Wrapper:Raw and enter your opening tags in the text area 'Content prefix'. Leave the suffix area blank (as you don't want to close any tags yet)

Save the changes and then do the same with the last pane you want to group. This time close all the tags opened in the first pane by entering them in the 'Content suffix' text area.

Save and update your panel page and et voila! Your panes are grouped with your own HTML!


All images within my articles have a link of their own: why? The article content type has a field to upload images with the article text (body and teaser). I noticed that every image I upload gets its own URL after submitting the article, e.g. http://www.example.com/imagejpg.
This is messing up my Google SEO as each image has its own URL, and it is showing up in the search index for my domain.

Is there any way to stop these images from having their own URL?

All entities in drupal have their own page, you can use the Rabbit hole module to control what should happen when an entity is being viewed at its own page.
Inside module there is a sub-modules for each entity type, you have to install rabbit_hole and rh_file.


How to delete a content in a view with view rules? I got two views that displayed two different type of contents. Content A got a field "Title" and content B got the same field. I want to find and delete any number of content of type B that got the same title of a content A. I try to do this with view rules module with some view loops. I found some content B that got a title equal to a title of content. How to delete them?

Depending on your needs you could potentially use Views Bulk Operations (also known as VBO).


How to solve the strange behavior of content node in view I found one strange behaviour in views. Like if I click on a node title of a view table, it will take me to node page. If I click edit and save the content will save faster.

But in the view, which has an edit field link, if I click on the edit link, and try to save the same node it takes several minutes to save.

Can anyone know why is this strange behaviour is happening and how to resolve it?

Saving is perceived slower because after saving (with or without overlay) it automatically redirects you to the last page you were at. Since your view takes longer to load than a single node page, saving is perceived slower.

In conclusion, the actual saving takes the same amount of time, the difference is the view page load versus the node page load.


Is there a way to make aliases as short as possible? For instance, if you have three tokens, let's say [city], [state], and [country]
is there a way to do this:

/[city]-[state]-[country]

and then let's say there are three cities, Venice, in different places
the first, Venice, Florida, United States would get this url

/venice

the second, Venice, California, United States would get this url

/venice-california

the third, Venice, Italy would get this url:

/venice-italy

Notice that it does not cut an individual token, only cuts off the extra tokens as they are not needed (in the case of Italy, there is no state so pauthauto automatically skips this token).
From reading the documention, it looks like Pathauto's default behavior is to do this:

/venice

/venice-1

/venice-2

and so on... when what I want to do is make the first one the "venice" and any additinal ones get additial tokens as needed, so if Venice, Italy is first then they will get /venice

If there's a way to do this with pathauto, how would you do it?
If not, what's the best way to make a module that does this?
Can a module modify how pauthauto works without modifying pathauto itself?

thanks!

hook_pathauto_alias_alter is nearest to your query.

First parameter $alias will be newly created alias by pathauto. You would have to analyze it with some regex pattern for undesired pattern generation.

The second parameter will give you contextual picture of item in associated array.

module definitely be taxonomy_term
source system path of taxonomy e.g. taxonomy/term/<tid>

I think you will have pretty much to analyze the term and get its hierarchical info to update $alias variable.


How to make a logo resize properly in a responsive theme I am creating my first responsive website http://islamabadpools.com; I have used the Omega theme as a starter theme, and it works almost perfectly for the layout.

I used the absolute image module for adaptive images but it's not working for views banner slideshow.
I am also unable to make the logo responsive so I removed the logo from theme options.

I created a new article content, and added a logo as an image and given it a title logo; then, I created a view block with an article image field and filtered that with the title "logo"
and in field properties; in the view, I selected adaptive as the format.
Now my logo is responsive/adaptive but it's getting very small on lower screen sizes.

I repeated this for the quick assistance block displaying in the right corner of the header.

I just want to know what the right way to make the logo responsive is.

Add the following css to your site:

.view-logo img {
  max-width: 100%;
  height: auto;
}


One field (entity reference - paragraph) with two display modes I am having issue with displaying one field twice in my template having different display modes.

I have a content type basic page with field field_gallery (which is entity reference on paragraph). In template node--page--full.html.twig I want to render field_gallery twice. Once using default display mode and second using teaser.

<div class="container">
    {# this as teaser #}
    {{ content.field_gallery }}

    {# this as default or whatever #}
    {{ content.field_gallery }}
</div>

I tried do it using hook_preprocess_node, but could not achieve the result I want.

$variables['custom_display_mode'] = $variables['node']->get('field_gallery')
    ->view(array(
       'label' => 'hidden',
       'type' => 'teaser'
));

I do not want to use any custom module, I'm kinda new to drupal hooks and i'm sure that it must be possible somehow, to set custom variable and print it in my template.

Thanks.

An array with 'type' => 'teaser' is specifying a field formatter, but you probably don't have a field formatter with this name.

You need to add the view mode (display mode) as string argument to view():.

$variables['custom_display_mode'] = $variables['node']->get('field_gallery')
  ->view('teaser');

For more info see How to apply a Field Formatter to a node field programmatically?


How to display plain html I have inherited a drupal site with a few modules.
They're not exactly written according to best practices... they return html code instead of renderable arrays. In other words, they do this:

function custommodule(){
 $output = '<p> Some output. </p> <p> Some more output. </p>';
 return $output;
}

Instead of this:

function custommodule(){
   $args = array( arg1, arg2 );
   return theme('sometheme', $args);
}

The output is supposed to be displayed in the content region. However, since plain html is returned that is not wrapped in a node or anything like that, the output gets scattered all over my page... for example, the text Some output. appears above the navigation, Some more output. appears underneath the footer, etc.

By the way, the page-array has the returned markup (the $output from above) in this place:

page['content']['system_main']['main']['#markup']

Whereas for example a typical article would have its #markup in

page['content']['system_main']['nodes'][$nid]['body'][0]['#markup']

So I guess drupal doesn't realize I would like my output to be in the content region?

Is there any way I can safely render that unpleasant html?

Thanks a lot in advance!!

Once again, the problem sat in front of the screen ;)

Like @rooby said, there was a mistake in the html returned. A missing
 tag messed up my layout. Adjusting this solved my problem. Thanks!!

But to be able to influence the layout of custom html a bit more generally, I did this:

When a module returns output without first passing it through a theme function, it ends up in page['content']['system_main']['main']['#markup'], whereas in a normal page, there would be no #markup on this level of the page array, only elements like node, pager, #block etc. So finding page['content']['system_main']['main']['#markup'] means some custom code has been returned by some custom module.

So in my theme's template.php, I implemented

function mytheme_preprocess_page(&$variables, $hook) {
    if ( $variables['page']['content']['system_main']['main']['#markup'] ){
        $variables['page']['content']['system_main']['main']['#markup'] = '
' . $variables['page']['content']['system_main']['main']['#markup'] . '
';
 }
}

Thank you guys very much! Always awesome how good the feedback in the drupal community is.


Add entity reference field to content type I have 2 content type 1.Employee performance 2.Task

Task content type has a field that assign users to the task (Assigned To Users).Each employee has a node in  Employee performance content type and he is the author of the node. How I can add a select list field in Employee performance that display all the tasks that assign to the employee(author) by using entity reference field in view?

You would need to use the "Views: Reference by entity reference view" Mode.

You then need to have created an Entity reference view display to correspond to this. In this view you need to pass the current node author as an argument / contextual filter and show all the nodes you want to display there.

Select this view in the entity reference field's settings as attached, an that should do it.


How to configure the Total Subscription module? I'm taking a look at the Total Subscription module and have done the basic installation and configuration. But it's not evident how to get it to show up on any given node/page. I've been working from its documentation at https://www.drupal.org/node/2170825.

Any other suggestions about how to configure it?

The Total Subscription module has indeed some challenges related to finding out how to get it configured as it should be. Apart from its Community documentation (which you seem to have found already), the best I have found to far is a video tutorial (without sound though ...) that takes you through various admin screens. E.g. to show you some of the blocks related to this module.

Apart from that, to understand what this module is about, I find its readme.txt a bit helpful, as well as the module's project page. Here is a quote from it:

  Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.


How to sort the language detection methods In a two languages Drupal 7 site, I am using the following order of language detection methods:

URL
Session
User
Browser
Default

With this order, every time I visit the site as an anonymous user it comes in the default language.

Instead I would like to:

display the default language in the first visit.
if a language selection is made, display that language in the next visit

Is there a way to achieve this?

Well I think you are doing just fine, and don't get obsessive over this, it's ok!

the URL thing is the most important and should be always on top, I think session should be second since it can be generated via a request or parameter.

User I'm not sure since mostly users don't pay attention about their language preferences while registering on a webiste.

past these steps the rest doesn't really matter that much, but I'd put Browser the last one since it seems it can vary quite easy with plugins/extensions.


Programmatically creating multivalue field with a button of add another In the field ui, we can create a textfield with unlimited values. Which has button of add another, which when clicked added another field with a remove button.

I want the same functionality in my custom form. How will I create a textfield with unlimited values?

Here is a nice article on how to do it using Form API http://rapiddg.com/blog/use-ajax-support-multiple-item-values-custom-drupal-7-forms

Hope this helps.


Rule to loop over products with one specific SKU in Drupal Commerce cart I'm still a novice at Rules.  I'm using Drupal Commerce and have the Flat Rate shipping service enabled.  I'm using Rules to calculate a surcharge to the flat rate based on the number of items in the shopping cart.  So far this rule works.

However, I now want to modify the rule so that it only calculates the surcharge based on the number of products with a specific SKU.  All other line items in the cart, which may be other products, should be ignored for the purposes of this calculation.

If I was just coding this, I would put an if statement in the loop and look at whether the current line item has a specific SKU.  But I totally don't understand how to do that with Rules.

Thanks for any help.

Here is my current rule:

{ "rules_createspace_flat_rate_calculator_expedited_" : {
    "LABEL" : "CreateSpace Flat Rate Calculator (Expedited - US)",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_order", "commerce_line_item",     "commerce_shipping" ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value"  : "shipping" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-shipping-service" ],
          "value" : "ship_manuals_to_you_expedited_"
        }
      },
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "address_field" :     "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "country",
          "value" : "US"
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-line-item:order:commerce-line-items" ] },
          "ITEM" : { "order_line_items" : "Order line items" },
          "DO" : [
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "order-line-items:quantity" ],
                  "op" : "*",
                  "input_2" : "250"
                },
                "PROVIDE" : { "result" : { "shipping_volume_surcharge" : "Shipping Volume Surcharge" } }
              }
            },
            { "commerce_line_item_unit_price_add" : {
                "commerce_line_item" : [ "commerce_line_item" ],
                "amount" : [ "shipping-volume-surcharge" ],
                "component_name" :    "flat_rate_ship_manuals_to_you_expedited_",
                "round_mode" : "1"
              }
            }
          ]
        }
      },
      { "commerce_line_item_unit_price_add" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "1000",
          "component_name" : "flat_rate_ship_manuals_to_you_expedited_",
          "round_mode" : "1"
        }
      }
    ]
  }
}

Your real challenge appears to be this part of your question:

  ... put an if statement in the loop and look at whether the current line item has a specific SKU ...

Here is how to get that to work:

your Rules Loop is inside a Rules Action (of course).
but in a Rules Action you cannot use a Rules Condition ... except if you also use the Conditional Rules module, so that's what I'd recommend you to do to do what you're asking for.
For an example using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?". As an alternative to using the Conditional Rules module, you can also try to rework the relevant part of your Rules Actions into performing a Rules Component. Because in a Rules Component, it is possible to also add Rules Conditions. For more details on using Rules Components instead of Conditional Rules, refer to the answer to "What's the alternative to using the Conditional Rules module?".

Easy, no?

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


Use custom variable in html.tpl.php for critical css I have built my current theme in my D7 site upon the Foundation theme, and with that comes a LOT of unused CSS that gives me a low score in Pagespeed Insights. I have tried different things, among others to use the Advagg module and it's submodule "Critical CSS". These modules does no good for my site unfortunately, despite repeated trials and despite safe settings etc. The screen goes blank and/or each page takes minutes to load. When I only use safe settings and critical css, the page speed score does not improve (and yes, all settings are done according to docs and I have spent many hours on trialling without luck).

So, instead I thought I would try to move this row in html.tpl.php:

    <?php print $styles; ?>
</body>

...to the bottom of the page just before the ending body tag. Then I would need to add the critical css in the head section.

    <head>
        <?php print $critical_css; ?>
...

But how can I pass a variable like $critical_css to html.tpl.php, that only contains the just necessary to show the page? Or is this not possible?

Instructions for the Critical CSS module:

Navigate to: admin/config/development/performance/advagg/critical-css

Under Add Critical CSS
- Select the theme that is your front page; usually the default is correct.
- User type should be set to 'anonymous' under most circumstances.
- Type of lookup, select URL
- Value to lookup, type in
- Critical CSS, paste in the generated CSS from running your homepage url
through https://www.sitelocity.com/critical-path-css-generator which is inside
of the 'Critical Path CSS' textarea on the sitelocity page.
- Click Save Configuration.


How do I show a translated the value of a content type in my template I have a bootstrap banner (jumbotron) on my site, which roughly looks like this:

{% if page.banner %}

 Welcome to foo.com

 we provide

{% endif %}

Now, instead of hard-coding the texts for h1 and h2 ... I went to  Administration > structure > content type and created content type called short texts and then to Administration > Structure > Content types
and added a content called site slogan and site description they both contain the values of h1 and h2.

Now, my question is how do I replace the text inside the H tags with a (translatable) text I created as a content?

This is my first week in Drupal, so I am a bit lost

You need to render either:

Fields
Variables created in a preprocess hook in mytheme.theme

Example, if you crated a field called Short Text (field_short_text), then in the node template for that type, you do:

{{ content.field_short_text }}

Except from the page template level (page.html.twig) you won't have access to the node render array.

If you create your own variables in a preprocess hook, you will need to call the translation service against that - it is better to let Drupal work normally for simple cases like these.

What you can do in this situation is create a View that has a node id argument, and either:

Output Views fields (meh)
Output that node in a designated view mode (best method)

Generate a Block display from that View, then place the block in the Banner region of your theme from Block Layout in the admin. If you are not familiar with Views, you should get familiar with it right now.

However, if you are trying to print the site slogan and site description, these are set under Admin > Config > Site Information, and should be available already as variables to the page template. I don't think there is a need to recreate what already exists, unless core doesn't translate site name, site slogan, site description but I am pretty sure it does.


Problems with EVA generated html I want to show a list of links to the 5 latest news on my homepage.

I learned that I can install the Views module to make a snapshot of a content type. I also use EVA to create a EVA field from the view and attach it to my homepage content type.

Then I can intercept the value of the view in my homepage_preprocess_node but the problem is that the value is a long string containing the whole list wrapped with html.

This is bad...

I want to have full control of the html. I tried different options but couldn't find a clean, basic, barebone option.

I am expecting a value that is an array of 5 objects so I can loop throught them and generate what ever html I see fit. The object would contain the field I asked (title) and a url to get to the news page.

Of course I can remove the html tags and rebuild the array from that long string but I don't want to do that if there is a better solution. I will use that view on the "press room" page also, so I don't want to have to duplicate code in two different preprocess_node functions

Nothing is simple in Drupal...

I wanted to add "EVA" as a tag for this question but it's not available.

That's because you are doing it the hard way. Why hardcoding everything when views does it out of the box? Views fields are extremely flexible and customizable. You may need to strip the views fields first (style fields and deselect whatever option you have - do that also with your format / html, unformatted etc). Usually, what I do is exclude from display and use views tokens in the last field of type Global text area. This way, the view only displays actually field values, with no html whatsoever.

To escape hard coding even for your content type display, try using display suite. It works smoothly with EVA as well.

I hope I got it right.

And... what is simple when you're trying to achieve complex structures? Is there any other platform delivering something like views OOTB?

There is some research to be done regardless choice of environment. And usually, the shortest, simplest way, is the way you know better.


how to display a list of OG content depending on user group membership? I've set up an OG Group type, and and OG Content type where I want to store some kind of articles.
I've provided fields where the author of an article can specify if an article can be:
1.  read by anyone, even unauthenticated users.
2.  read by all authenticated users, wheter or not they belong to a group to which the article is linked
3.  read only by users that belong to a group to which the article is linked.

I understand this has something to do with filters and relationships, but I can't get it to work....

Please help.... :-)

There is a pretty good tutorial of OG at https://drupal.org/node/1603460.

If you already know the basics and have provided proper access fields using the Organic groups access control module, you should next explore the views that come with OG and edit them to your liking.

Also the OG Extras module at https://drupal.org/project/og_extras has lots of stuff for practical use.


How do I create a form in a modal dialog with Drupal 7? There seems to be many solutions for implementing a modal dialog including Ctools, Colorbox, Simple dialog, and Ctools Auto-modal. I'm not sure which is the best to use for simple coding through the Form API to create popup forms in a modal dialog.

The big issue seems to be validation. Are there any best practices for creating a modal form in Drupal?

A good example for using forms on modal dialogs is in Ajax Login/Register module. You could see the module code and understand how it works(ajax_register is using ctools_modal).

Or you can render the form manually and use ctools only for the responses. For example:

mymodule.module:

function mymodule_form($form, &$form_state) {
  ...
  ctools_include('ajax');
  ctools_add_js('ajax-responder');

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'container',
  );
  ...
}

function mymodule_ajax_callback($form, $form_state) {
  if (!form_get_errors()) {
    $commands   = array();
    $commands[] = ctools_ajax_command_reload();

    return array('#type' => 'ajax', '#commands' => $commands);
  }

  return $form;
}

Now, you can anywhere render this form and show popup (using Twitter Bootstrap or Lightbox):

Show Form

<?php print drupal_render(drupal_get_form('mymodule_form')); ?>


Drupal Commerce product in-cart status info in Views How can I use information in Views about whether a particular product is in this user's cart? Particularly, how many times into a Views row for that product?

For example, on a view listing available products, I'd like to be able to stylistically differentiate the rows representing products the customer has already added to their cart, and/or show a field, empty by default, stating how many of that item are already in the user's cart.

I've looked at existing Commerce modules such as Commerce Views Display and Commerce Add to Cart Extras, but can't see anything directly relevant. I'm not sure how to proceed with creating something to do this short of writing a custom Views query which also loads the Commerce cart for each row, which I'd rather not do since I'm not sure how I could make it reasonably efficient.

Does anything exist to support this, or if not, is there a simpler/more integrated, less "reinventing the wheel" approach using the Views and/or Commerce API?

An ideal result would be a Views Field for commerce products outputting a simple number representing how many times a product with this product ID is in the cart. Turning that into all the above use-cases is easy (e.g. rewrite as a class product-in-cart-N then apply default styles to .product-in-cart-0, simply display the field with a label, etc etc).

I am not aware of any modules, that will provide the functionality that you described out of the box, but the snippets below will probably get you moving in the right direction.

You'd write a function that gets all product IDs that are in the cart.

/**
 * Return the product_id values for all products in the cart
 *
 * @return
 *  An array of product ids
 */
function CUSTOMMODULE_get_products_in_cart() {
  $cart_product_ids = &drupal_static(__FUNCTION__);

  if (!isset($cart_product_ids)) {
    global $user;
    $cart_product_ids = array();
    $order = commerce_cart_order_load($user->uid);
    if ($order) {
      $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
      foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
                if ($line_item_wrapper->type->value() == 'product') {
                    $product_wrapper = $line_item_wrapper->commerce_product;
                    $cart_product_ids[] = $product_wrapper->product_id->value();
                }
      }
    }
        $unique_cart_product_ids = array_unique($cart_product_ids);
  }

  return $cart_product_ids;
}

For adding a class to the views row according to the quantity in the cart you'd implement hook_views_pre_render() and implement your logic there

/**
 * Implements hook_views_pre_render().
 */
function CUSTOMMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
        // get product_ids in cart
        $cart_product_ids = CUSTOMMODULE_get_products_in_cart();
        if (in_array($product->product_id, $cart_product_ids)) {
            // check how many times product_id is in the present in the array
            // do other stuff - apply class, etc.
        }
  }
}

Also, you'd probably want to change the "Add to Cart" button text to something custom if the product is already in the cart

function CUSTOMMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $cart_product_ids = CUSTOMMODULE_get_products_in_cart();
    if (in_array($product->product_id, $unique_cart_product_ids)) {
        // Product is already in cart
        // Change "Add to Cart" button text
        $form['submit']['#value'] = t('Add one more'); // your custom text and maybe a quantity of that product that is already in cart...
    }
}

I think using hook_views_pre_render() is the right way to go about this, but if there is more efficient or easier way I'd like for others to pitch in with ideas.

Hope this helps.


Is it possible to export arbitrary configurations? I'm trying to create feature modules for as much as possible, such as

my backup schedule (for the Backup & Migrate module)
my shortcut sets
etc. etc.

and I'm surprised how much can't be exported with Features.  Is there some way to do this?  Either with an alternative module, or with something that extends Features, or by hand-coding the feature module, or by dumping just a specific table from the database???

For some of the configurations/settings that aren't picked up by the Features module, there is the Strongarm module.

Strongarm gives site builders a way to override the default variable values that Drupal core and contributed modules ship with. It is not an end user tool, but a developer and site builder tool which provides an API and a limited UI.
An example of such a variable is site_frontpage. In Drupal this defaults to node, which ensures that the front page gets content as soon as some exists, but for many Drupal sites this setting is simply wrong. Strongarm gives the site builder a place in the equation - an opportunity to set the site_frontpage to something that makes sense for their site.

At the time this answer has been posted, the Backup and Migrate module wasn't yet compatible with neither the Features module nor the Strongarm module. See Make backup profiles and schedules Features exportable, (closed as fixed on May 6, 2013) for what exactly the issue was and which branch fixed it. The bug report doesn't contain any patch: The code has been developed in a branch different from the branch for which the issue was opened.


Sending emails in user migration I have some troubles with D7 migrate module and sending emails.

I made a migrate class to import users via CSV files. The import works well, all my users are created.
But I need to send emails when the new user is created.

So I have implemented the migrate complete() function in my class like this:

public function complete($entity, stdClass $row) {

    // some stuff here

    // Operation.
    $op = 'register_admin_created';

    // Send an email.
    _user_mail_notify($op, $user);
  }

It's here were troubles comes, I use the _user_mail_notify() function to shoot the mail to the new created user.

The process looks good, the mail logger module shows me the mail result, but in fact the user don't receive the mail.

I already try to create a user via the administration people menu and when a check the "Notify user of new account", I do receive the mail notification.

In Fact, the process that I have implemented in my migrate class looks like the process when you create a user manually via the admin interface and when you check "Notify user of new account".

I have to tell you that I also implement a mail interface, to be able to shoot emails with HTML / CSS. In this case, I just add a header and footer to the mail.
All emails sending via my custom mail interface are sent and render properly. Only the emails sending during migration process are not send.

If you have some ideas about that problem, or if you need more information don't hesitate :)

Thank's,

Vali.

Ok found it, the migrate module have a custom Mail Class that blocked all emails send during migration process.

The migrate Mail Class is

  MigrateMailIgnore

To bypass that migrate mail class you can simply do that :

public function complete($entity, stdClass $row) {

    // some stuff here

    // Bypass migrate MigrateMailIgnore Class
    global $conf;

    $conf['mail_system']['default-system'] = 'MyOwnMailClass';

    // Operation.
    $op = 'register_admin_created';

    // Send an email.
    _user_mail_notify($op, $user);
  }


How can I change the Available Menus to all, programmatically, for a specific content type? Hello I'm trying to alter a content-type's menu options by code, since there will be new menus that keep being created on the site and I can't keep going back to the content type to keep adding every single menu to the Available Menus. I should be able to set the default available menus to all, or all custom... but I can't figure this out. I'm looking at the function menu_form_node_type_form_alter and created a module to override, however nothing changes, and the Main Menu is always the default available menu. I'm actually trying to prepopulate the parent menu through the URL, which only works if the parent menu is checked as available, but it's not working for all the new menus because the parent menu is not set as available ... How do I override the default menu option for a certain content type so that the available menu checkboxes gets set automatically to all of the custom menus that were created?

Thanks in advance!

update:
still not figured out yet, but,
I went straight into the core menu module and modified this piece of the function above:

  $form['menu']['menu_options'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Available menus'),
    '#default_value' => variable_get('menu_options_' . $type->type, array('main-menu')),
    '#options' => $menu_options,
    '#description' => t('The menus available to place links in for this content type.'),

changing the 'main-menu' to a different name actually works straight from core but doesn't work when trying to override with my own module.

If I understand you correctly you want to change the available menus for node types when new menus are created.

You can implement hook_menu_insert to respond to new menu creation and you can use variable_set to add the new menu to the available menus for the selected node types.

E.g. this will add all new menus to the page and article node types:

function mymodule_menu_insert($menu) {
  $types = array('page', 'article');
  foreach ($types as $type) {
    $menus = variable_get('menu_options_' . $type, array());
    $menus[] = $menu['menu_name'];
    variable_set('menu_options_' . $type, $menus);
  }
}

If you already have created a bunch of custom menus, you'll basically need to call variable_set as in the example above.


How do I go to Checkout Page without product in cart? I am using Commerce Donate and configured it to show donation form on checkout page. That is what actually I need. Donation form, contact info and payment form on same page.

But we cannot go to the checkout page without having some product in cart.

How can I do that?

You can add the following code to a custom module:

/**
 * Implements hook_menu_alter().
 */
function YOURMODULE_menu_alter(&$items) {
  // Alter the default checkout callback to allow checkout without products.
  $items['checkout']['page callback'] = 'YOURMODULE_checkout_router';
}

/**
 * Implements hook_commerce_checkout_order_can_checkout().
 */
function YOURMODULE_commerce_checkout_order_can_checkout($order) {
  return TRUE;
}

/**
 * Displays the checkout form and create the user a cart if none exist.
 */
function YOURMODULE_checkout_router() {
  global $user;
  // Load the shopping cart order.
  if (!($order = commerce_cart_order_load($user->uid))) {
    $order = commerce_cart_order_new();
  }
  drupal_goto('checkout/' . $order->order_id);
}


Render Profile2 field out of Profile2 page Is it possible to render one of Profile2 fields elswhere on the page, in some node ?

I would like to present user with opportunity to edit only one field on custom link or node.

Thanks

Retrieve Profile2 Profile Data Programmatically

Implement profile2_by_uid_load() to get the data.

$profile2_data = profile2_by_uid_load($user->uid, 'profile_id');

$profile2_data will be an object containing all the data from profile_id for the requested user.

Retrieve Profile2 Edit Form Programmatically

module_load_include('inc', 'profile2_page', 'profile2_page');
$profile2 = profile2_by_uid_load($user->uid, 'profile_id');   // profile_id = machine name
$entity_form = entity_ui_get_form('profile2', $profile2, 'edit');
return $entity_form;


My page showing up with a title, but with the content div empty, but only for users I've created a new content type that has the default 4 fields (Title, Body, Meta tags, URL path settings) and one List(integer) that I added.  I called it "Basic page".

When I create a new Basic page node and put in some data, it will work as long as I'm logged in as admin.  If I log in as any other user, the page title will show up, but the body will be blank.

The content div for a user is actually completely empty.  The admin has content for it, but any other user does not.

New Test Page

I've looked through the user permissions for this node type, and that doesn't seem to be affecting anything (though I could have easily missed something).  The display isn't set to . I'm using Drupal 7.

It really sounds like a permissions problem. Do you (or did you) have field permissions installed?

If you do you will have to set field level permissions (which are separate) from node permissions. If you have field permissions viewing/editing a node does not mean a user can view/edit specific fields, you will have to specify these permissions in addition to the overall node permissions.


How can i allow users to give different responses to content types other than comments? How can i allow users to give different responses to content types other than comments? for example if i want users to be able give blog posts a "like" or "thumbs up/down" or something similar?

You could try any of these modules (with quotes included from their project pages):

Fivestar:

  ... adds a clean, attractive voting widget to nodes and comments and any entity.

Rate:

  ... provides flexible voting widgets for nodes and comments ("The cck model for voting with Drupal").

Vote Up/Down:

  ... allows votes on some Drupal entities and provides the base for implementing votes on other entities.


Add body classes to 404 and 403 error pages I need to add a body class to the page when either a 403 or 404 error is served, I'm not sure how to go about this. I'm using logintoboggan which sets the default 403 page to toboggan/denied so don't want to override that and break functionality.

Any pointers would be great.

For anyone working with Drupal 7, the function names and the way you pass variables are a bit different. The D7 solution for a 404 would look like this:

function MYMODULE_preprocess_html(&$variables) {
  $headers = drupal_get_http_header();

  if (isset($headers['status']) && $headers['status'] == '404 Not Found') {
    $variables['classes_array'][] = 'page-404';
  }
}

The drupal_get_headers() function from D6 is now drupal_get_http_header() in D7. The values returned are structured a bit differently. You can view the contents of the array with "dpm($headers);" if you're using the devel module.

Finally, additional class variables can be added as elements of the $variables['classes_array'] by assigning them to an empty index, which will then be added to the html body tag via the template_process() function.


How to assign role(s) for a new user based on node_field? I am in a process of finishing a workflow. I have done the most things with rules. To my surprise I found a feature is missing in this great module ...

I have created a content type called "my_cont_type". A content of this content type will be created only once by admin. A link will be provided for the admin to go and change the option whenever he wants.

It has a field called "my_field". It is a list box type where user can select multiple options. The options are "Role1" , "Role2", and "Role3".

On creating this content or after created admin can go and edit the same.
After edited the same from that time the new user who all registering or created they have to come under the corresponding role selected in that node. I have those three roles already in my application.

For example:

When Role1 and Role2 is selected the new user has to register with these roles1&2 enabled.
When Role1 and Role3 is selected the new user has to register with these roles1&3 enabled.
When Role3 is selected the new user has to register with only roles3 enabled.

Can I accomplish this using the Rules module?

I tried but I doesn't find any attributes regarding node or content type in condition when using the "After new user saved" event.

Yes this should be possible using the Rules module.

When trying to do so, make sure to add a Rules condition Entity has field (related to your my_field field). That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


Altering the type of a menu item to local task (tab) I've searched for hours but I can't find a good answer on how to alter the type of a menu item to local task (tab).

The private messages 7.x module (when aided by privatemsg_filter) exposes the following tabs (local tasks):

Inbox (/messages)
Sent Messages (/messages/sent)
All Messages (/messages/list)

There is a 4th menu item (/messages/new) which is currently a MENU_LOCAL_ITEM and I want to make it a local task as well. But how? And what is the best way?

The following hack worked, to create a new local task item with definitions identical to the original menu item except it's a local task. But is it the optimal way?

<?
/**
 * Implements hook_menu().
 */
function MOMODULE_menu() {
  $items['messages/newmessage'] = array(
    'title'            => 'Write new message',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('privatemsg_new', 2, 3, NULL),
    // 'file'             => 'privatemsg.pages.inc',
    'access callback'  => 'privatemsg_user_access',
    'access arguments' => array('write privatemsg'),
    'type'             => MENU_LOCAL_TASK,
    'weight'           => 5,
    'menu_name'        => 'user-menu',
  );

  return $items;
}


Change a normal submit 'input' type to 'button' type with button tag Is it possible in Drupal 8 to change a regular form submit button from Drupal into a button tag?

This is the output I need to achieve:

<button type="button" class="search-box__button">
  <svg class="icon search-box__open">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/build/img/svg-sprite.svg#icon-search"></use>
  </svg>
</button>

Well that was quick... I used my intuition and was able to accomplish it by doing the following:

In mytheme.theme:

/**
 * @param $suggestions
 * @param array $variables
 */
function mytheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#attributes']['data-twig-suggestion'])) {
    $suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['data-twig-suggestion'];
  }
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-results') {
    $form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_results_submit';
    $form['actions']['submit']['#attributes']['class'][] = 'search-box__button';
  }
}

In input--submit--search-results-submit.html.twig

{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<button{{ attributes }}>
  <svg class="icon search-box__open">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/themes/custom/mytheme/build/img/svg-sprite.svg#icon-search"></use>
  </svg>
</button>

Form still submits and functions as expected. Is this the general approach or at least acceptable? I will go with this unless there is a better way.


Refreshing a block using AJAX I am trying to apply the example from [the Flag API page][1] to refresh a block dynamically via AJAX. I am looking into customised jQuery code because my block is created via a module, not a view.

I have implemented the callback in the .module file and it works. It is when I try to copy blockExistsOnPage() where I fail. It talks about a component module which is necessary for the execution of the code, but this module is obsolete for drupal 7. I think that I stumble on the definition of var domId. This is my JavaScript code.

(function ($) {
 $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
   alert('Object #' + data.contentId + ' (of type ' +
   data.contentType + ') has been ' + data.flagStatus +
   ' using flag "' + data.flagName + '"');

    if (data.flagName == 'myflag') {

        if (blockExistsOnPage('mymodule', 'mymodule_blockid')) {
            refreshBlock('mymodule', 'mymodule_blockid');
        }
    }
  });

// Attempt at refreshing the block
function blockExistsOnPage(module_name, block_id) {
  var domId = module_name + '/' + block_id;
  return $('#'+domId).length != 0;
}

function refreshBlock(module_name, block_id) {
  var domId = module_name + '/' + block_id;
  $.get(base_url + 'node/' + $nodeid + '/' + block_id, null, function(newHtml)  {
    // Replace the old block with the new one.
    var domElement = $(newHtml).insertAfter('#'+domId);
    $('#'+domId).remove();
    if (Drupal.attachBehaviors) {
       Drupal.attachBehaviors(domElement);
    }
 });
}

edit: I am trying to use a $.ajax request instead. It seems cleaner, but I am struggling to get my relative address of the type node/[nid]/module_name/block_id. Should I modify the block_id in the menu hook? Or should I find a way to create a url in the jquery:

module hook menu:
    function get_involved_menu() {

// Ajax Callback. Returns updated content of block
$items['block_id'] = array (
 'title' => 'Content of module_name block',
 'page callback' => 'module_name_createcontent',
 'access arguments' => array ('access content'),
 'type' => MENU_CALLBACK,
 );

return $items;
}

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

  $.ajax({
     type: "POST",
     url: 'module_name/block_id',
     success: function (data){
        $('div.get-involved-divblock').html(data);
     }
   });
 });

the code below returns an empty block. If I am on node '57', and I put instead

 url: '57/module_name/block_id',

Then it returns the content. How can I make it a relative path? How do I obtain the node id in the jquery?

depending on how your module is setting up the block, you could look into Block Refresh:

  Block Refresh allows an administrator to configure a block to refresh
  it's content via 3 different methods: automatically via a timer (eg
  every 30 seconds) , manually via a 'refresh' link, and once on page
  load.

  Block Refresh uses jQuery/AJAX so the refresh happens
  "behind-the-scenes".

  Block refresh can be handy to serve fresh content in certain blocks on
  otherwise cached pages. You can opt to bypass drupal's cache for the
  refresh callbacks for each block.

Edit

I just ran into this exact problem and developed a simple little approach that works nicely:

using Block Refresh

set up each of the blocks you want to refresh as manual - this would normally cause a link to appear in each block allowing a click refresh

create some css to hide the ugly links:

.block-refresh-button
{
    display:none;
}

then add a simple jQuery click to force block refresh to do all the work for you - this can be modified appropriately as necessary:

jQuery(".flag-wrapper").click(function()
{
    jQuery(".block-refresh-button").each(function()
    {
        jQuery(this).click();
    });
});

I found this will refresh ALL blocks on the page set up with block refresh, including Views.


drush @sites command doesn't work The command drush @sites status doesn't do anything.

The full command obtained for the process is:

  /usr/bin/php /home/myuser/.config/composer/vendor/drush/drush/drush.php --php=/usr/bin/php --php-options= @sites status

This is my enviroment:

Drupal:  8.2.4
Drush:  8.1.7

The "drush site-alias" command says me:

@site1
@none
@site2
@self
default
site1
site2

I have a setup for Drupal multi-sites with subdirectories, the aliases file is:

~/.drush/aliases.drushrc.php

<?php
/**
 * @file
 * Site alias for all sites
 */
$root = '/var/www/html';

$aliases['site1'] = array(
    'uri' => 'multisite.local/site1',
    'root' => $root,
    'path-aliases' => array(
        '%dump-dir' => '/tmp'
    ),
);
$aliases['site2'] = array(
    'uri' => 'multisite.local/site2',
    'root' => $root,
    'path-aliases' => array(
        '%dump-dir' => '/tmp'
    ),
);

The full output of the drush status command is:

 Drupal version                  :  8.2.4
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database port                   :  3306
 Database username               :  db_user
 Database name                   :  db_name
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :
 Default theme                   :  bootstrap
 Administration theme            :  seven
 PHP executable                  :  /usr/bin/php
 PHP configuration               :  /etc/php.ini
 PHP OS                          :  Linux
 Drush script                    :  /home/myuser/.config/composer/vendor/drush/drush/drush.php
 Drush version                   :  8.1.7
 Drush temp directory            :  /tmp
 Drush configuration             :
 Drush alias files               :  /home/myuser/.drush/aliases.drushrc.php
 Install profile                 :  standard
 Drupal root                     :  /var/www/html
 Drupal Settings File            :  sites/default/settings.php
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Private file directory path     :  private/default
 Temporary file directory path   :  /tmp
 Sync config path                :  sites/default/files/config_BrLQsjBr6VkcTEyCkzkY-es-hzISWg4d3oV2EEEoqh-UZMLBJWDiDaq78TIWm-lBbVi-aPHISw/sync

"@sites" is no longer available with Drush 9. I presume this what is being used with Drupal 8 here.

More information here:
https://github.com/drush-ops/drush/issues/3019#issuecomment-334503217

  Drush 9 no longer supports executing a single command on multiple sites with alias lists (@A,@b,@c) or @sites. Neither of those syntaxes are available in any context. You may still use drush sa @group to see all aliases in a group; that is the only context in which Drush recognizes alias lists.


site created using drush arr failing with missing index.php I am using drush archive to copy a live site to a test environment.  The test environment is on my local machine, the live site is on a hosted platform.

The arr command seems to complete successfully and the new database config is correctly appended to settings.php, the files are all restored to the appropriate directory on my local machine and the database is created and populated.  So far, so good.

If I navigate to the default page  http://localhost/~drew/site2, the home page is displayed, but it is clear that the CSS is from my theme is not available - I think that this is because the CSS was compressed and cached on the live site, so I can probably ignore that for now.  If however, I try and navigate to any other page, I get an HTTP 404 saying localhost://~drew/site2/index.php not found yet when I check the filesystem, it's definitely there, and the web server can clearly see it because it created the home page earlier when I navigated to the default page.

I do use pathauto and have set explicit path names for my pages on the live site - could this be broken in some way when restored?

Thanks

I think you problem is likely that you need to set the RewriteBase in the .htaccess file.  Edit your .htaccess, find the line that looks like

# RewriteBase /

And add a line under it that reads

RewriteBase /~drew/site2

then clear Drupal caches, and try your site.


How to specify AND, OR with dynamic query I’m trying to create a dynamic query, the query logic conditions needed are: AND, and OR.

The main query will include two sub queries.

The ConditionInterface::condition documentation states that:

  If called with 1 parameter, it should be a ConditionInterface that in
  itself forms a valid where clause. Use e.g. to build clauses with
  nested AND's and OR's.

I cannot find the example to build clauses with nested AND’s and OR’s so I’ve done some digging through the ConditionInterface API Reference (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21ConditionInterface.php/interface/ConditionInterface/8.6.x)

I found a function conditionGroupFactory (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21ConditionInterface.php/function/ConditionInterface%3A%3AconditionGroupFactory/8.6.x)

The conditionGroupFactory function appears to be what I need, however I cannot find any implementation examples.

Could someone please explain the implementation of this function.

$result = $connection->select('inventory', 'inv');
$result->fields('inv', ['part_number']);
$result->condition('inv.visable', 1);
$result->conditionGroupFactory('AND')->condition('inv.part_number', $queryOne, 'IN');
$result->conditionGroupFactory('OR')->condition('inv.part_number', $queryTwo, 'IN');

Note: $queryOne, $queryTwo; Are of type SelectInterface.

My Objective SQL Statement:

SELECT inv.part_number
 FROM inventory AS inv
 WHERE inv.visable = 1
 AND (inv.part_number IN (SUBQUERY_1)
 OR  inv.part_number IN (SUBQUERY_2));

I don't have the same structure of your table  but i test it with the following statement it works:

SELECT *
 FROM `node__body` AS n_b
 WHERE n_b.`deleted` = 0
 AND (
 n_b.`revision_id` IN (32,6,17)
 OR  n_b.`langcode` IN ('fr')
 );

here is the code snippet for your case:

  $query = $connection->select('inventory', 'inv')
    ->fields('inv', ['part_number'])
    ->condition('inv.visable', '1', '=');
  //- Set Or Query group
  $group = $query
    ->orConditionGroup()
    ->condition('inv.part_number', [SUBQUERY_1], 'IN')
    ->condition('inv.part_number', [SUBQUERY_2], 'IN');
  //- Add Or group
  $query->condition($group);
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);


How do I get the last available hook_update_N() for a module? I'm having trouble getting a custom module to install and update successfully.  I'd like to examine the database for the modules update_N numbers. Is that possible? If it is, where do I look for it?

They're in key/value storage, which in the database would be the key_value table. Look for entries with a collection of system.schema, and a name matching the machine name of the module you're interested in.

Through the API, it's a bit easier:

$current_version = drupal_get_installed_schema_version('name_of_module');


Configuring an Entityform with a term reference field I have an entityform that users use to upload pdf files. On the form there is a 'Term Reference' field (select list) that lets them choose the type of document that they are uploading, e.g. 'letter', 'contract', 'invoice' etc...

These entityform submissions are then displayed as a view with the 'term reference' field displayed next to a link to the uploaded document.

My problem is that when I click on the term reference the term's page is not populated with the entityform submissions that have been labeled with it.

Add new view that shows content of type: entityform submissions.
Add a field Entityform Submission field 'Document type'
Set the path to /taxonomy/term/%
Add a contextual filter, entityform submission 'Document type' and 'provide default value' - 'taxonomy term ID from url'

Done.


Drupal8 Oaut2 add a grant type “password” to client I work on Drupal8 project and created Rest API, everything works fine until I want to add Oauth2 when I try to get a token I got an invalid grant type error.

This is the error code:

{
    "error": "invalid_grant",
    "message": "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.",
    "hint": "Check the configuration to see if the grant is enabled."
}

This is the url that i called:

http://myserver/oauth/token?grant_type=password&client_id=6db9da8d-b831-4381-b279-381bc5a57e90&scope&username=webmasterrest&password=webmasterrest&client_secret=$S$EamACyfemGWic74kmkwUvphMmr9FL132KC297mI1GEkTKhyBJyAo

I added a client, but I can't add a grant type "password" to this client, any help please?

To add Oauth 2 authentification
Install the module using Composer: composer config repositories.drupal composer https://packages.drupal.org/8 && composer require drupal/simple_oauth:^2. You can use any other installation method, as long as you install the OAuth2 Server composer package.
Generate a pair of keys to encrypt the tokens. And store them outside of your document root for security reasons.
openssl genrsa -out private.key 2048
openssl rsa -in private.key -pubout > public.key

Save the path to your keys in: /admin/config/people/simple_oauth.
Go to REST UI and enable the oauth2 authentication in your resource.
Create a Client Application by going to: /admin/config/services/consumer/add.
Create a token with your credentials by making a POST request to /oauth/token. See the documentation about what fields your request should contain
(Not shown) Permissions are set to only allow to view nodes via REST with the authenticated user.
Request a node via REST without authentication and watch it fail.
Request a node via REST with the header Authorization: Bearer {YOUR_TOKEN} and watch it succeed.
From this

NOTE: I user drupal/simple_oauth version 2.x because i got an exception n version 3.x


Querying the database via a url and displaying the results? Some background context:
I have created a custom form, which inserts data into several tables when submitted. In fact, five new records are created in the node table on submit. A new record is also created in several other other tables, which are all related to these five newly created records in node. One of these node records is the root of everything: from the nid you can access all the related records

The aim:
Now, I'd like to be able to enter a url, like example.com/record/1, and for the '1' to be used as the nid from which to get this root node record from the database, and all its related records, and to display it all on a page.

The question:
How can I do this? I have looked into node_load and menu_get_object, but I can't find any documentation which describes the process of querying the database, using information in the submitted url, and displaying the results on a page.

Thanks

Direct answer to your question - you can get the parameter from the query string a number of ways:

use the arg() command (not recommended as best practice)
use the $_GET string, provided by PHP
use drupal_get_query_parameters

Any of these methods would get you the nid from the query string (in your example, 1) - you could then us db_query or node_load to load the data for this record and output it as desired but thats too much work.

Much easier way to do this is to use the views module and add a contextual filter. Setup a basic view and then configure however you like (ex - display full node / teaser or views, etc). Set the path to

record/%

where the percent sign indicates a variable you are going to pass to the contextual filter. Next, under advanced options

select 'contextual filters' and 'add'
search for and add one of type 'content: nid'
on the next screen choose 'provide a default value' of type 'raw value from url', then select the url argument you want to use which in your case is '2'

Views will handle the querying for you and take care of sanitizing the input, and dealing with the output on the way.


Is there any way to find broken images across an entire site? A number of images appear to be missing from within body fields of a site. It may have been like this for a while, so it's hard to say why. Folder/file permissions and paths are correct. The site was never moved and oddly, its only happening on some images and not all. Is there any way to detect which ones are missing on an entire site (40,000+ nodes)

You can try the linkchecker module.   It does check the source of <img> tags in the body, however it doesn't do it perfectly like it does for <a> tags.

If <img> have alt text, it thinks it is fine, even though the link is broken
<img> with links like "sites/testing/file/image.jpg" are returned not broken, links like "/sites/testing/file/image.jpg" are returned broken
External links work pretty well.

Your best bet is to use Xenu’s Link Sleuth project  (windows freeware)

Additional resources:
Here is a comparison of the link page modules.  Maybe you can find something else.
Broken Link Checker thread on drupal.org


How to get fields definitions of a vocabulary in drupal 8/9? I needed the field list related a vocabulary item.I was able to list the fields related to a content type by using like this:
\Drupal::entityManager()->getFieldDefinitions('node', 'article');

But I can't find a way for the vocabulary items.

\Drupal::entityManager() is deprecated, instead you should use \Drupal::entityTypeManager. From the docs:

Deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal::entityTypeManager() instead in most cases. If the needed method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the deprecated \Drupal\Core\Entity\EntityManager to find the correct interface or service.

This is especially relevant here as the getFieldDefinitions() method has moved to a different service, entity_field.manager.
With all of this said, you can use the same method to get taxonomy term fields as any other bundle. As documented in this related answer:
$entity_type_id = 'taxonomy_term';
$bundle = 'article_tags';

// Load the field definitions for any bundle.
$my_bundle_fields = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions($entity_type_id, $bundle);