Ubercart-based POS / Kiosk I have a Drupal 6/Ubercart 2 website with a desktop-specific theme. I intend to create a POS/Kiosk theme for the site, to be used when the site is accessed via a tablet (and possibly via smartphone). That theme would be bare-bones... a couple of Views showing products, probably the AJAX cart module, and very little informational pages. The POS concept would involve a kiosk with an ipad that public customers in a retail location would be able to use to place orders right then and there.

I suppose I just want to see if anyone out there has done a setup like this, or whether anyone has any ideas on things to avoid, issues that may be encountered, etc. Ideally, the end result of this port would be a recipe of sorts, that everyone else could use for similar situations.

So far, potential issues I have come up with are:

Must auto-log out users upon successful order completion. Is there a way to do this in Drupal/Ubercart via stock settings or an existing module?
Some type of auto- or manual-logout for when a customer walks away from the POS without completing the order (so that the "next person up" can start with an empty cart, or can at least easily clear the cart and start their own shopping experience). I suppose this can be accomplished with a large "Click here to start a new session" button that would basically be a "rebranded" log out button...
...I'm hoping other viewers of this question might be able to point out any other issues I may not have thoughts of yet.

Looking forward to any input anyone out there may have!

I'm working on a similar problem.  I have an ubercart based shopping system that a customer wants to have available on a public computer in his store.  We need to change themes, branding etc and auto-logout users.  His users will also be ordering from home, so we have to identify that particular computer and change the behavior and look of the site when we know they are ordering from the in-store kiosk.

Kiosk module that may help

This module allows an administrator to put selected computers into "Kiosk Mode".
"Kiosk mode" simply means that a given computer will have an extra flag set for template files, which allows a themer to exclude certain page elements, such as off-site navigation.

I'm installing this on my test server and we'll see how well it goes.  I'm hoping to figure out how to get that variable (if $kiosk) into ubercart checkout conditions and trigger some actions based on it.  It seems like themeing is pretty easy with this module but as for changing behavior, I'm not super sure how it will work.

Please let me know if you find any magic bullets as we're both trying to do a similar thing and i'd be great to share a solution.

UPDATE: I've been working with kiosk mode module (drupal 7 version) for a bit and have been able to create custom rules by calling the kiosk_is_kiosk function defined in the module. Simply use custom php condition in rules with this code:

 return kiosk_is_kiosk();

And you can have different workflows for kiosk terminals than for regular on-line users.  So for example, once an order is finished the kiosk will log out the user, but not a person using the same site from the home.

-Zachary


can't unassign role from user I am working on a site which uses someones custom module which makes some modifications on the user account page as well as his profile pages.

On this site, I registered myself as a user and logged in and found that I was assigned to all roles, even administrator. When I tried unclicking the checkboxes on the user page to unassign roles, it didn't work, the roles stayed the same. I tried this while logged in as the user himself and also as the admin.

What types of things could be causing this issue? Where should I look?

As per my understanding, there are custom modules from which it is updating.

Try searching hooks like hook_user_insert(&$edit, $account, $category) and hook_user_update(&$edit, $account, $category) from custom modules. I hope they might have written a piece of code to update the roles.


How to prevent edit or delete of some content by its author depending on an approval status field? Here is a screenprint to illustrate part of my current implementation:

This is what I want to achieve:

If the value of 'Admin Status' is not "Approved", then the author can still edit or delete his/her own content.
If the value of 'Admin Status' is "Approved", then the content can not be edited by the author.

I have tried a lot, even using the Rules module, but nothing works for me.

Any suggestions about how to get this to work?

You can get this to work with the Rules module by using Event System > Drupal is initializing, combined with a Rules Condition related to the URL for the edit or delete operation.

Disallow edit

The rule you'd need for disallowing 'edit', is a variation of the rule I included (in export format) in my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

These are the changes to that rule to make it work this case also:

The paths containing node should be extended by adding /edit at the end (I'm assuming that's how the URL for your edit link looks like).
Add a (1st) Rules 'Condition' like "If Author id matches the uid".
Add a (2nd) Rules 'Condition' like "If Admin Status is Approved".
Change the "Message" (in the Rules 'Action' to something to indicate that the edit is not allowed because Admin Status is Approved.
Modify the Rules 'Action' to fit your own requirements, e.g. to issue a redirect to some 'help page' with more details about this.

Disallow delete

Should you also want to disallow 'delete' by the author for "Admin status" = 'Approved' (which is not what your question currently says however ...), then create another rule in which you use a similar approach as for 'edit' (as described above), just replace all 'edit' by 'delete'.

Combine both rules

It should be possible to consolidate the 2 suggested rules above, using "OR" within Rules. Know however that this is a very little harder to get it to work. So learn to walk (= get it to work with 2 separated rules) before you want to learn to fly ...

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.

Note: your question does not say what should happen (what is allowed or not) when a user who is not the author tries to edit or delete something with 'Admin Status' = Approved. If such scenario is possible in your setup, then you might have to further enhance the Rules Condition I suggested accordingly ...


How do I rewrite Solr search results to show related entity reference field? 1: I have two node types: "Plants", and "Pests". related using a field in the plants node type called "affecting_pests".

How do I modify the solr Search result view; in the case of a Pests result, to display " name of pest==>affected plant " in the results title, and instead of link to pest page, redirect to the parent plant that the pest affects?

Assuming you are using the apachesolr module, implement hook_apachesolr_search_result_alter() in a custom module. The function you create will receive the $document object that you may modify. You will have to add logic in there to locate and load the appropriate related entity.


Drupal Commerce - Sort products in view priced lowest to highest This seems like it should be super simple. I'm trying to sort my products by price (from lowest to highest) in my view, and no matter what I do, nothing seems to work. See below the setup of my current view. At the moment, the below settings give me the lower priced products first (e.g. it shows products ranged $4-9 before products ranged $50-90), but they're all mixed up (e.g. $4, $7, $4, $9...) when it should be $4, $4, $7, $9...

I hope that makes sense.

It isn't clear to me why you're sorting based on some sort of standard deviation here (or why you're using aggregation at all). If you really just want to sort a list of products by price in a taxonomy term, you should just keep aggregation off and sort on the price directly.

If you need aggregation on, you're going to need to explain the intent behind this sort method.


LimeSurvey RemoteControl JSON_RPC API from Drupal Has anyone used LimeSurvey's RemoteControl JSON_RPC API PHP script from Drupal to connect to LimeSurvey in a different server?

I have tried the PHP Example in https://manual.limesurvey.org/RemoteControl_2_API#Example_and_helper in my local instance to export a survey responses and it works perfectly fine.

I have now copied the script to my Drupal folder (installed library jsonrpcphp through composer) in a Test server and trying to connect to Limesurvey in a different Test server; and I am unable to get the connection right.

I have updated the filename, base URLs, username and passwords for the Test instances. Not sure If it is something to do with "https" in the URL? URL for Local instance was "http". Because the script breaks at get_session_key line.

Any help with this will be appreciated! Please drop a comment if more info is required.

SSL certificate in the Lime Survey test server was expired. Renewed the SSL cert.


Two JS files attached to one module Alright, so I have two files which should be added to a module. This is the way I do it:

$form['display']['#attached'] = array(
    'js' => array(
      array('data' => drupal_get_path('module', 'test_module') . '/js/test_module.js'),
      array('data' => drupal_get_path('module', 'test_module') . '/js/common.js'),
    ),
  );

Now my test_module.js file looks like this:

(function ($) {
Drupal.behaviors.test_module = {
  attach: function(context) {
    console.log(Drupal.settings);
  }
}});

And js works fine because I get data from Drupal.settings object. However, the second one is totaly the same and console.log does not work. Here's how it looks:

(function ($) {
    Drupal.behaviors.test_module = {
      attach: function(context) {
        console.log("test data");
      }
    }});

Why the second file does not work?

Don't duplicate the attach function.

(function ($) {
Drupal.behaviors.test_module = {
  attach: function(context) {
    console.log(Drupal.settings);
  }
}})(jQuery);

If you have used this for 1st JS

(function ($) {
Drupal.behaviors.test_module_2 = {
  attach: function(context) {
    console.log("test data");
  }
}})(jQuery);

Then you can use this for 2nd JS as the attach function should be used only once


Add as a particular role while creating an account in Drupal 7? In Drupal 7, I have a role named as "blogger". When user goes to blog site and created an account then a role should set by default as "blogger" rather than "authenticated user". How to do this? Any Suggestions please.

Adding my comment as answer. If every user is a blogger then the easiest way I see is not to have it as a separate role at all; instead assign similar permissions to authenticated user.

Or you could change the role of the user by implementing hook_user_insert():

function MODULE_user_insert(&$edit, $account, $category) {
  $account->role = 'blogger';
  user_save($account, $edit = array(), $category = 'account');
}


How can I display existing node content in its node form? I have several fields that need to be translated and it would be best if the translator sees the to-be-translated content right beside the translation field.

In a standard node form, it shows that field as an input text area field for updating purposes but I don't want the translator to touch that or be able to mess with that.

I want the translator to 'see' the rendered display of that "to-be-translated" field next, under or above the text area field for the translation on the node form. How to do that?

I'm not very strong in php so if you give advise with php, please be thorough.
Thanks in advance!

One way that I recently found was by using panels where you can actually place different components in different places. These components would then be either the rendered to-be-translated field beside the translation field. So you could say that this is a solution but I'm not very sure if this is going to require me to do this for each and every role differently or if panels could only be used to kick in only when a specific condition is met i.e. user has 'translator' role.


how do I open a custom module form in colorbox popup? I am creating a form in custom module, and I need to show this form in a view. How do I show this form in a color-box popup?

I have created a custom block to render this form, but I don't understand how to show this form in a view page, inside a popup.

I am suggesting you to use chaos tools for modal popup form. Its easy to implement and integrate into Drupal 7. I already used in my several sits.

You can find a great example of Ctools modal form at here


Cannot see page content? I'm building a custom theme for Drupal 7.xx, which is part of my internship.
I've been developing this theme for quite a while now, but I still consider myself an absolute beginner when it comes to theming for Drupal.

During the process, I've ran into quite a few problems which (luckily) I've been able to solve with the help of google (including Drupal Answers) so first of all thanks for that!

One of the problems I seem to be unable to solve, is that I cannot see the page content anywhere. So far I've added all content of the pages in blocks, which I've assigned to be rendered out by a region called 'cont_page_block', and which I have declared in my .info document.

To clarify: When I add a new page, I fill in the page title and body, but it doesn't appear on the page. Also, when I add a news article, I can see the teaser on my 'news summary' but when I try to click on it (which works though) it redirects me to a new page (URL states ?q=node/xx) which is, ofcourse, empty.

Here's the code I use in my page.tpl.php file to render the region:

   <div class="cont_page_block">    <?php print render($page['cont_page_block']); ?>
                                    <?php print render($content); ?>               </div>

And here's the declaration of my regions in my .info file:

regions[cont_page_block] = content-page-block
regions[content] = content

Am I missing a line of PHP code in my page.tpl.php file?
Any help would be greatly appreciated!

Try using:

<?php print render($page['content']); ?>

Edit:
To further the above, if you want to see the action links/titles/tabs you can print those by:

<?php if ($title): ?>

 <?php print $title; ?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>
      <?php if ($tabs): ?>

 <?php print render($tabs); ?>

      <?php endif; ?>
      <?php print render($page['help']); ?>
      <?php if ($action_links): ?>

        <?php print render($action_links); ?>

      <?php endif; ?>
      <?php print render($page['content']); ?>
      <?php /*?><?php print $feed_icons; ?><?php */?>


What is the most drupally way to add a slide show (as a block? So I can reuse it in multiple places) I'm very new to Drupal 7, and just getting started.

I'm looking to add this slide show on my site:
http://jquery.malsup.com/cycle/int2.html

The "Manual and Auto Advance
(hover to pause, click to advance)" one.

What is the best way to do this?  My understanding is that Drupal 7 already supports a lot of core jquery stuff.  So, in which drupal file would I add the code

$('#id_name').cycle({
    fx:     'fade',
    speed:   300,
    timeout: 3000,
    next:   '#s3',
    pause:   1
});

If this plugin is not already supported, then in which drupal file would I add the jquery cycle declaration, and where would I install those files?

More importantly, I am asking these operating under the assumption that I should make this a block, so that I could conceivably show this slideshow in multiple places on my site.  Is that a good strategy, or is there something better?

If the content you want to use is already in nodes then you could use Views and Views Slideshow (which uses the cylce plugin you linked to).

With views you can create a block which can be re-used wherever you want in the site.

Learning how to use Views is one of the best things a new user to Drupal can do, it'll provides a lot of nice tools in a point and click interface.


Save a webform as draft? I want to save a webform as draft for logged in user. I read somewhere that this a default feature but not able to find out. I could not find this option "Allow users to save a draft" in the form settings(Using Drupal7 and webform 3.13). Please suggest.

There is indeed a "Save as Draft" button in webforms. Check the permissions with "allow users to save draft" in the permission page.

There has been an issue reported here with the same problem as yours.


How to make download file link to open form and mail the download link to email? My flow is like that.

I have scroll-able list of download links for Private files.
When user click on Download File link it will show Form to gather
some data like first_name, last_name, email and Phone.
after submission Link will be forward to email Id specified in form
with KEY will check Once download the file link will be expire.
Second Mail goes to admin and Data will be stored to system as Sales
Lead.
File will be get to User.

I have created Views to List all the Files as a Block and  Link added to download file using yourdomain.com/get/file/1

Is there any suggestion for that or specific module tutorial available so, I can check...

There is simple solution for this.

You need to create a form using custom module and link download file with that form. When user click on download file link, it will redirect user to form.

In the form submit, you can send mail to client with download link and admin also and can perform other task too.

If you want to expire download link after once download, you can save the counter of download in database. You need to create link for download in your custom module and in page callback of that link, you can check if its already downloaded or not.


How to interpret kint output I have installed devel kint module on my drupal 8. Everything is fine with the module.

But my problem is how should I interpret the output of kint correctly. Especially when I want to render field within file entity.

Here is the scenario:

I have a form created with YAMLForm in my front. In that form user can upload image.
User submit the form.
When I debug data with kint, I can see the url of the image, but I am
unnable to display it thru .

Please find below a screenshot of the kint output

I have tryied with the following but no chance :

{{ file_url(data.picture['#value']['#file'].entity['#values'].uri['x-default']) }}
{{ file_url(data.picture.0['#item'].entity.uri.value) }}
{{ file_url(data.picture.entity.fileuri) }}

I've Googled for hours but couldn't find any clues.

Thanks in advance for your help.

You can't load protected values. So kint is not much help here.

But you can try this, load directly the uri value:

{{ file_url(data.picture['#value']['#file'].uri.value) }}


How to store information in session for anonymous user in a site without a user with uid=0? In our system for some reason, we have deleted user with 0 uid. But for now I have to store some information in session for anonymous users. But Drupal is not allowing me to save the information in session.

Can someone suggest another way around?

I am trying

  session_start();

  $_SESSION['some_param'] = 'value';

for retrieving

  session_start();

  echo $_SESSION['some_param'];

But the values are not available after reload.

PS: It is working fine if I create a user with uid=0. But I need solution without uid=0.

If you "have to store some information in session for anonymous users", then you will have to make uid=0 available to Drupal. Because that's the uid that Drupal always uses for anonymous users.

So you'll have to re-create that user with uid=0 (again) if you want this to work. If you would combine this with not granting any permissions to role anonymous, there is not a lot that anybody can do in your site if they are not logged in (apart from things like performing login). Maybe an acceptable work around?

About your "for some reason we have deleted user with id=0": it might be that the user with id=0 never got created before (so that it was never deleted). E.g. if the database of your site was created via some type of database copy (backup and restore) from a dev site to a prod site (using PhpMyAdmin). Forgot the exact scenario, but I've ran in such sites before, which caused problems for anonymous users (which is how we discovered such cases). The solution we used was to simply use PhpMyAdmin, and insert the user with uid=0 in the Drupal database (using PhpMyAdmin).


Search is broken after updating search_api_solr from 8.x-2.7 to 4.1.4 My Drupal site has a search form, which connects to a Solr index. All of this was working smoothly.
But then I updated drupal/search_api_solr from 8.x-2.7 to 4.1.4 (which also required me to update drupal/search_api from 1.13 to 1.17) – and now the search is broken. Specifically:

The "default" search results – the ones that are displayed when I first land on the search page, before entering any search keywords – are now different.

When I do enter keywords and submit the search form, it always returns no results. This happens with any keywords, even when there are definitely items in the index that should match.

Here's what I've already tried:

Cleared the Drupal cache repeatedly (of course).
From the Drupal configuration dashboard, I have:

Confirmed that the Solr server and index are configured correctly, and that Drupal is able to access them.
Deleted everything in the index, and re-indexed. (This appeared to complete successfully.)
Examined the AJAX response to the search submission, and compared it to the response on a working instance of the site. (The only difference is that HTML returned on the working site includes results, and the HTML returned on the broken site doesn't.)

Looked for upgrade guides for the search_api and search_api_solr modules. (I haven't been able to find any.)

Any suggestions? I'm running out of ideas here.

After the latest search_api_solr module update you need to update config files on your server, as there is a new field added.
If you look into the update log you will find the below message.

A new Solr field type has been installed due to configuration changes. It is advisable to download and deploy an updated config.zip to your Solr server.

You can find the additional information on how to update server configs from the below link.
Upgrade Search API Solr
Even after checking above points if you are still getting issues, check whether it is due to varnish.
And also run cron once and clear drupal cache after cron and check results again.


Is It Possible To Show One More Views In Homepage I have created some Views to show in Home page. I have successfully installed one View in my homepage but i really can't understand is it possible to show one more Views in Homepage. If it possible then please take a time to describe it.. Thanks

In Drupal 7, you should create a "block" display for the views you want to show, by selecting "Add" in the view config page.

When you save the view block, the corresponding blocks will show up in the /admin/structure/block administration page and you can add it to any page you want.


Vendor directory vs. Modules directory. What are the key differences? I've seen articles that instruct developers to add docroot/vendor to the .gitignore but if I require a module with composer and push up that module, will that cause a huge error on the site I'm pushing up to?

Does my composer.json file have to include all of the modules in my modules directory?

If I were to copy and paste the composer.json file into another install and run composer install would that automatically give me all of the dependencies I need?

As you can tell, I'm pretty new to Drupal 8. The team I work with uses Acquia and I'm finding a ton of issues when trying come up with a good workflow using compser, drush, git, and config management.

Thanks

[Assuming you are using composer in this answer]

The vendor directory contains non-Drupal dependencies that core and/or contributes modules require.  This is typically fully managed by composer.

The modules directory contains your Drupal modules.  It can be managed by composer if you are using drupal-composer/drupal-project or something similar where the install paths can be set.

Committing composer managed dependencies or now, like vendor or modules (if you are doing so), is a nuanced subject.  There is no 100% correct answer.

I tend to not commit, even when I am not using a full CI deployment, because the composer dev dependencies should not be deployed on a production server.  So, on the live server I want do do a composer install --no-dev.


Filter a view result by matching a view field to a URL term I have a content type called "Post" which contains two fields:

1) title
2) username

I created a View which creates a block that gathers all Posts. The block will reside on a user's account page, wherein the URL will always be:
www.mysite.com/user/username

How can I filter that block to only show the results where the username field matches the second term in the URL?

Thanks!

Use contextual filter in views and set raw value as second argument from the url (here second argument will be username).


How do I add a confirmation form after the user clicks on "Save" in an edit form? On a site I'm building, a user can edit certain fields on a node that cause a chain reaction to happen (which I've implemented using hook_nodeapi() and its "update" operation).
Since this chain reaction potentially affects a lot of other content, I'd like to inform the user of exactly what other content will be changed, which depends on the changed field values, unknow until the user submits the node.  After the user has read the list of affected content, I'd like to give them the option to click on Yes, which will save the node and start the chain reaction, or click No, which will take them back to the node edit form (with edits intact).
How can I make a confirmation form appear after the user clicks on Save?

In brief, this is what I think you need to do in a custom module:

After validation, override the submit function on the node form to submit to a new interstitial page (you'll need to implement hook_menu to create the new page)
Pass the node object to the new interstitial page and define whatever logic you need in the interstitial page's callback function.
Create a new form on the interstitial page that runs node_save on submit with node object that was passed to it.


CSS grid for custom theming in Omega? I cant find the answer to my question by googeling or in the documentation for the theme but im sure ive heard it exists. Does the Omega theme give you a CSS grid to work with?

So if you wanted to customize a tpl file and have 2 colums, one twice the width of the other, could you just write some CSS a bit like this?

content here

more content here

Im happy to use standard classes but Im trying to avoid adding additional CSS, I would have thought the theme (as a grid based layout) would have classes I could use? Thanks

Absolutely, one might argue that's one of the reasons to use Omega in the first place; as per the first two features listed on the project page:

Fully Responsive Grid layouts based on 960.gs standards.
12, 16, 24 Column Layouts built in.

Have a look in the CSS files with names like alpha-default-normal-12.css under omega/alpha/css/grid/alpha_default/* to discover what classes are available for you to use.

Those files should make it fairly obvious what conventions Alpha/Omega use for naming those classes too, so you should be able to predict what you need to use easily.


Where is the pager data in the Views object I am trying to alter the number of items per page in a View, programmatically. When I display the Views object returned in hook_views_pre_execute, I see fields for in $view->query for items per page, etc., but despite the view initially having a setting of Display a specified number of items: 6, it appears nowhere in the object, that I can find.

In hook_views_pre_execute (hook_views_pre_build is too early), the pager data, in general, can be found at
$view->pager

and the specific piece of data I asked about can be found at
$view->pager->options['items_per_page']


Error sending Drush commands to remote host I have Drush 5.2 installed on my local dev system and my remote host, which has staging and production sites. I have aliases for all three sites, and am able to use rsync and sql-sync on both systems with no problems.

From what I understand, I'm should also be able to issue commands to the remote system such as

drush @stage vset preprocess_css 0

Whenever I try to do something like this, it fails. For instance, if I run drush -d @stage status, I get:

Bootstrap to phase 0. [0 sec, 3.7 MB]                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 3.93 MB] [bootstrap]
Loaded alias @stage from file /path/to/local/drupal/sites/all/drush/aliases.drushrc.php [0.01 sec, 3.94 MB]                          [notice]
Cache HIT cid: 5.2-commandfiles-0-c87dbef8e3e302e07ccdc024aee7fbbd [0.16 sec, 3.95 MB]                                                                      [debug]
Begin redispatch via invoke process [0.19 sec, 8.77 MB]                                                                                [notice]
Backend invoke: ssh -o PasswordAuthentication=no user@my.host.com 'drush  --invoke --debug                                                 [command]
--root=/path/to/remote/drupal/ --uri=http://stage.mysite.com --verbose status 2>&1' 2>&1 [0.23 sec, 8.8 MB]
executing ssh -o PasswordAuthentication=no user@my.host.com 'drush  --invoke --debug --root=/path/to/remote/drupal/      [notice]
--uri=http://stage.mysite.com --verbose status 2>&1' 2>&1 [0.23 sec, 8.8 MB]
Calling proc_open(ssh -o PasswordAuthentication=no user@my.host.com 'drush  --invoke --debug --root=/path/to/remote/drupal/ --uri=http://stage.mysite.com --verbose status 2>&1' 2>&1);
bash: drush: command not found
Invoke process is complete [1.34 sec, 8.79 MB]

In order for remote commands to work, you must make sure that drush is in your PATH.  This is often done by putting something like the following in a line that bash will source when it starts up:

export PATH=$PATH:$HOME/local/drupal/drush

A lot of folks put a line like this in their ~/.bashrc file, but note that on a lot of systems, this file begins with a line similar to the following:

[ -z "$PS1" ] && return

This means that everything below the line above will only execute when bash is running interactively; if you put drush in your PATH after this point, you will be able to run drush when you log in to your remote machine, but not when you attempt to call drush remotely (e.g. via drush, as shown above).

There are many solutions to this problem.

Set your PATH before .bashrc bails out.
Make a symbolic link to your drush executable from a directory that is always in your PATH (e.g. sudo ln -s /path/to/drush /bin)
Set %drush-script as described in examples.aliases.drushrc.php.


How can I have a multilingual URL for a views result page depending on the language? I have a multilingual website that is currently in 5 languages. We are going to be adding more - a lot more.

Views has a Filter, "Language: Current user's language" to display content based on the language the user has selected to view the content in.

Currently we are not using that filter, and the reason is URL path setting for the Views result page. Instead, because we have to have the URL translated into the language being viewed as well, we have a block configured with an English URL page, for example, and the language filter set to English.

Instead, I need to be able to configure just one view to use the Filter "Language: Current user's language" and, when that page is viewed, I need the url to display correctly in that user's language regardless of the one entry I am allowed in the Views page configuration. I also need for this to show properly in the Menu I select there as well when the page is viewed as a translation.

How can I achieve this?

You should enable "Translation sets" and "Path translation" modules, both part of i18n module.

Then in admin/config/regional/i18n_translation/path, you have to add the translated paths and then add a "translation set" which will map all these pages together.

Doing this, you'll be able to switch language on your view page and retrieve the corresponding alias (same view with different current language)

See also this page on drupal.org documentation.


Is there a way to minify HTML? Is there a way to minify HTML in Drupal 8, something like the Minify module which is for Drupal 7?

Use spaceless tag. This will not minify the HTML, instead avoids extra whitespace between HTML tags to avoid browser rendering quirks. When cached, can serve better.

In html.html.twig

{% spaceless %}

<!DOCTYPE html>
<html{{ html_attributes }}>
 #rest of the code
</html>

{% endspaceless %}

For compression there is a twig extension

Edit: Use Minify Source HTML module which comes for both D7 and D8.


Can I configure Send by Email to use CC instead of BCC? So I have a node that is using the Print Module (www.drupal.org/project/print) and it's associated send by email functionality.

The issue is that if I include multiple emails on the send by email page, it sends them so that the email addressees cannot see the other people it was emailed to.

For instance, if my send to looks like: example1@example.com, example2@example.com

Both example1 and example2 will receive the email, but with only their name in the To: line.  Is there a way to get the rest of them to show up there as well, or in the CC: line?

Thanks.

Here's the portion of the code I was able to find where it splits it into multiple emails:

  $addresses = explode(', ', $form_state['values']['txt_to_addrs']);
  foreach ($addresses as $to) {
    if ($use_job_queue) {
      // Use job queue to send mails during cron runs
      $queue->createItem(array('module' => 'print_mail', 'key' => $print_mail_send_option_default, 'to' => $to, 'language' => language_default(), 'params' => $params, 'from' => $from));
    }
    else {
      // Send mail immediately using Drupal's mail handler
      $ret = drupal_mail('print_mail', $print_mail_send_option_default, $to, language_default(), $params, $from);
    }
    if ($use_job_queue || $ret['result']) {
      flood_register_event('print_mail');
      $ok = TRUE;
    }
  }

Anyone know how I can make that so it just sends one email to all of the addresses?

You could try the hook_mail_alter() which lets you intercept emails used by drupal_mail(), but that's problematic since, as you mentioned, each email gets sent out individually.

There's a hook_print_mail_alter() invocation before the email is sent, but this is problematic too since $params doesn't have the email recipients.

The route I would take is to alter the email form submission handler with your own custom submission based off the print module's implementation:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'print_mail_form') {
    $form['#submit'] = array(
      'MYMODULE_print_mail_form_submit'
    );
  }
}

/**
 * Submission Handler.
 */
function MYMODULE_print_mail_form_submit($form, &$form_state) {
  //@TODO: Implement your own email code.

  //print_mail_form_submit($form, $form_state);
}


How to theme "group by" header in a view I'm using views to create a list of nodes grouped by a field.
The problem is that, in the html output, I've something like this:

Group title

content..

content..

Group title

content..

content..

I've put the group title and its contents in a common div, but which template do I have to work on?

Theming views can be done in a number of files.  For best assistance I suggest in views you look at the "Theme Information" option.  It can be found at {drupal site}/admin/structure/views/nojs/display/{view name}/page/analyze-theme (It's under the right hand side "Advanced" column).

On that screen you will find a list of all the files that you Drupal will look for to theme for the view concerned, ranging from the very specific (views-view-fields--{view-name}--{display-name}.tpl.php for row styling) to a slightly more generic views-view.tpl.php (Covers every view)  You can drill further down depending on what your view selects (Fields, Rendered Entity, Display Suite content etc) but the Theme information link shown above should provide you with a list of every file that you can provide to Drupal for theming.

Remember to flush your cache when you add a new theming file so Drupal knows about it.


Add help text to title D7 How can I add Help text to the Title in D7?

Perhaps adding an 'edit' button similar to the other normal fields.

Ideally the solution integrates with Label Help.

This module can be used to add help text to node title
https://www.drupal.org/project/node_title_help_text


views intergration with redirect module I've googled and nothing found about redirect module integration into views to add new filter criteria for a content type or taxonomy.

I need all redirects (FROM and To fields that showing in the image) path against specific nid (contextual filter) or content type (blog, event, article).

For more clarifications, see attached image

For your first question:

Redirect module integrated with views module, just navigate to admin/structure/views and you will see View called Redirects, enable it if it's not enabled, then pick the field you want, source field label is 'Source redirect' and from is redirect URL.

You can also create a new your view just be sure you using the base table or redirect

For the second question:

you need first to understand how redirect module structured.

Each redirect record you see is an entity, and it has the following fields:

rid: Primary Key: Unique redirect ID.
hash: A unique hash based on source, source_options, and language.
type: The redirect type; if the value is 'redirect' it is a normal redirect handled by the module.
uid: The {users}.uid of the user who created the redirect.
source: The source path to redirect from.
source_options: A serialized array of source options.
redirect: The destination path to redirect to.
redirect_options: A serialized array of redirect options.
language: The language this redirect is for; if blank, the alias will be used for unknown languages.
status_code: The HTTP status code to use for the redirect.
count: The number of times the redirect has been used.
access: The timestamp of when the redirect was last accessed.
status: Boolean indicating whether the redirect is enabled (visible to non-administrators).

As you see from the structure, there is no reference to the entity you added the redirect for; you have only a reference for the user who creates the redirect.

You can create a relation between the redirect and the user who creates the redirect, then get the nodes which authored by that user; Then you can adjust the views in the way you want.

Please notice this would work with nodes and with any entity store uid, but for example, in Taxonomy case it won't work because taxonomy entity doesn't store the uid.

another tip might help a bit is to add the redirect URL as a filter then make some string comparison.


How to delete the bulk of custom data when the associated user is deleted I'm one of the maintainer of Statuses(Social Microblog), As of now we are storing the status messages and comments to it in custom tables. We are also having hooks which needs to be invoked for the deletion of every status message,

Since this just  a status update, we will have bunch of messages(even 2k+ also possible) associated with one user.

So when the user is deleted, we need to delete all the status messages and comments associated to that user. The problem I could see that I need to perform these deletions in hook_user_delete, so if I have more number of deletions it may give timeout error and also I need to consider performance here.

If I directly loop through the status messages to delete one by one then it will be a hectic process, because when a status message is deleted it needs to invoke several hooks.

I want a guidance on handling this situation.

One approach would be to add a deleted column to your messages table, and mark the messages for deletion when a user is deleted, e.g.

function statuses_user_delete($account) {
  db_update('statuses_message')
    ->fields(array('deleted' => 1))
    ->condition('uid', $account->uid)
    ->execute();
}

Forgive the obviously incorrect table name, I'm not familiar with the statuses module.

Then in a cron hook, you could grab x number of the messages marked for deletion, and process them:

function statuses_cron() {
  $max = 50;
  $sql = 'SELECT message_id FROM {statuses_message} WHERE deleted = 1';
  $message_ids = db_query_range($sql, 0, $max)->fetchCol();

  statuses_delete_message_multiple($message_ids);
}

I'm making some assumptions about how things are set up in your module, but hopefully the principal is obvious enough. You could one step further and implement hook_cron_queue_info(), which will give you a finer grained control over the amount of time your worker can run for. I think some profiling with both methods would probably be appropriate to determine which which is better.

This is along the same lines as the logic the core field module uses to purge deleted data on the cron run, so I think it's safe to assume the principal at least is well tested...it's just whether this method will work for your use case.

I guess the only sticking point here would be the amount of code you need to change in the rest of the module to respect the new deleted column (i.e. not showing deleted messages to users). Again I can't really comment on that as I'm not familiar with the module, but if you take a methodical approach to implementing changes I can't imagine it being that much of a problem.


Bulk import select element options of a Webform from CSV I am using the Webform 8.x-5.0-beta16 module in Drupal 8.

I added a select field in which I would like to set around 250 options.

Is there a way to easily import these options from a CSV?

It's easier to enter the values editing the webform via Source(YAML).

The CSV values can be easily processed into a format such as " 'label': 'value' ".
Then when editing YAML source it's just a list you can Copy & Paste.

For the record, it would end up looking like this (and so on):

select_field:
 '#type': select
 '#title': 'Title'
 '#options':
   'label1': 'value1'
   'label2': 'value2'


Why does trying to POST a node from Android result in "HTTP/1.1 415 Unsupported Media Type"? I used the following code to post some data to my site. I tested the site with Postman using the same data and it works properly, but when running the following code on Android Studio, response.getStatusLine() returns HTTP/1.1 415 Unsupported Media Type.

       HttpClient httpClient = new DefaultHttpClient();
       HttpPost httpPost = new HttpPost("http://www.example.com/entity/node");
       HttpResponse response = null;
       String responseBody = "";

       try{
           JSONObject json = new JSONObject();
           JSONObject c0 = new JSONObject();
           JSONObject c00 = new JSONObject();
           JSONObject c1 = new JSONObject();
           JSONObject c2 = new JSONObject();

           json.put("_links",c0);
           json.put("title",c1);
           json.put("type",c2);

           c0.put("type",c00);
           c00.put("href","http://www.example.com/rest/type/node/article");
           c1.put("value", "test string");
           c2.put("target_id", "article");

           String base64EncodedCredentials = "Basic " + Base64.encodeToString(
                   ("user"+ ":" + "pass").getBytes(),
                   Base64.NO_WRAP);

           StringEntity se = new StringEntity(json.toString());

           se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

           httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
           httpPost.setHeader("Authorization", base64EncodedCredentials);

           httpPost.setEntity(se);

           // Execute HTTP Post Request
           response = httpClient.execute(httpPost);

           String jsonResponse = EntityUtils.toString(response.getEntity());
           JSONObject jsonObj = new JSONObject(jsonResponse);

           if (response.getStatusLine().getStatusCode() == 200) {
               Log.v("response ok", "ok response :/");
           } else {
               Log.v("response not ok", "Something went wrong :/");
           }
       catch (Exception e){
           Log.v("Error posting:",e.getMessage());
       }

I tested each of these lines separately and together, but none of them work.

    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));

           httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");

Why does it return HTTP/1.1 415 Unsupported Media Type?

I have faced same problem with same situation as you described above.
After spending 2-3 hours I have got data through:

$formdata = file_get_contents('php://input');

It's worked for me.


How do I find out the user name and password for an existing account? MY site was created and maintained from a developer I cannot contact, and I need to know the username/password the developer used to access the site.

How can I achieve this?

If you have access to the database you can change the password with a simple query.  If you want to save one step from having to go to the MD5 website you could also use the MySQL built-in function with something like this:

UPDATE `users` SET `pass` = MD5('mynewpassword') WHERE `uid` =1;

Note:  That only seems to work for Drupal sites <= version 6.x.  If you are using version 7.x the MD5 hash will not work (I'm guessing it uses some sort of salt string on it).  To reset the password on version 7.x you can just change the email address of the admin user to your email address with a query like this:

UPDATE users SET mail = 'myemail@mywebsite.com' WHERE uid = 1;

Once that is done you can go to the normal login page and just request a password reset, and it will be sent to your email address.

Reference:  https://superuser.com/questions/104482/how-do-i-take-control-of-a-drupal-installation-on-my-web-space-without-the-admin


Facebook Connect button in Overlay (Drupal 7) I've been helping a friend with a site, and recently run into a road block.

I've installed FB connect, set up an app, and it's working well from the home page.  However, he has an overlay installed for most of the forms and the Connect button doesn't display on the forms.

I've tried almost every variation that I can think of/find and nothing seems to be working.

Any advice?

I'm not able to post an image, but the sanbox site is at central-mining.com, just click on either of the login/registration links on the top menu.

Make use of Facebook O auth module. It has a huge advantages over the module that you use. It will work fine with any overlay effect.


How to make a Feature available only to certain Spaces? For a Drupal 6 Open Atrium site (i.e., Features, Spaces, Organic Groups) I'm running, I've created some custom Features that only really apply to a handful of the hundreds of groups on the site.

As it stands, the "Customize Features" config screen shows all the Features, including those I'd like to intentionally restrict to just a couple of special groups.

What's the best way to prevent these special Features from being offered to every group, while retaining those Features on the special groups?

The features for each space are configured via the spaces_features_form() function. You could implement hook_form_alter() to selectively and conditionally remove features from specific groups.

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'spaces_features_form') {
    $space = spaces_get_space();
    // Populate the array with hard-coded NIDs, or whatever logic
    // needed to determine if these features should be allowed.
    if ($space->type == 'og' && !in_array($space->group->nid, array(...))) {
      // Hide features foo and bar.
      foreach (array('feature_foo', 'feature_bar') as $feature) {
        $form['spaces_features'][$feature]['#access'] = FALSE;
      }
    }
  }
}


Customized theme not working How do I display a form followed by a table in a module??

I have this:

function main_function(){
  $form = drupal_get_form("report_details_form");
  $tabb = array(
    'header' => $header,
    'rows' => $rows,
    'caption' => $caption,);
  $output = theme("table", $tabb)
  $final_output = theme("report_page", $form, $output);
  return $final_output;
}

function theme_report_page($form, $result = array()) {
  $output = '

    '. $form .'

    '. $result .'

';
  return $output;
}

What am I doing wrong? I am using Drupal 7. I need to display the form and under it the table. There is nothing wrong with $form or $output. If I return them in the main_function they will display correctly.

I don't NEED a theme, I just need to display a form and table on the same page. So if it is to demanding I can skip it, and just have the form and table displayed.

I changed the main_function a bit to this:

function main_function(){
 $form = drupal_get_form("report_details_form");
 $tabb = array(
  'header' => $header,
  'rows' => $rows,
  'caption' => $caption,);
 $output = theme("table", $tabb)

$build['content'] = array(
  'this_does_not_matter_too_much2' => drupal_get_form("report_details_form"),
  'this_does_not_matter_too_much1' => array('#markup' => $output,),);

$build['pager'] = array(
    '#theme' => 'pager',
    '#weight' => 5,
);

return $build;

A dummy table is now displayed, but just in the first call to the page, not when the page is self called after submiting the form for first time. A custom table is then created to list all the results for a SELECT. This custom table is not displayed for some reason.

I think you should this in this way, so you should register you theme hook


How can I redirect a user after adding a node that also added a new taxonomy term? I have a content type with a Taxonomy for locations, these locations can be placed inside parent locations (f.ex United Kingdom -> England -> London), and it is set-up such that the end user can add taxonomy terms that do not currently exist when creating this content.

What I would like to achieve is upon creating a node that ALSO adds a NEW taxonomy term, is to redirect the page to the list of terms page so that the end user can categorise the new location appropriately.

Is this possible?

I'm not positive I understand the why, but the redirect-on-saving-new-node-with-new-terms bit should be reasonably straightforward.

I've suggested two possible methods below because the timing of db inserts/updates etc around node creation is a bit intricate, and you may need to shift the task to an earlier or later stage in the process. For example, the API docs mention that the db write cannot be presumed to be complete during hook_node_insert(), and it definitely won't be on hook_node_submit(). So your mileage may vary :)

You'll need to create a custom module (here's a stackexchange question on creating modules if you don't already know how) that either:

implements hook_node_submit()

This is the very likely to be the simpler/more reliable of the two methods.
implements hook_node_insert()

In this method, it is possible that drupal_goto() will conflict with the redirect specified in the node form's $form_state['redirect'], so it's probably the worse of the two possibilities.

Method 1: implement hook_node_submit()

From inside yourmodule_node_submit(), you'll need to:

Make sure that a node with this nid does not already exist!
find out what terms (if any) are in the new node ($node is passed into the function)
load all the terms for the relevant vocabulary, probably with taxonomy_vocabulary_load()
check to see if any of the node terms are not in the full list
modify $form_state['redirect'] if required

See drupal_redirect_form() for a bit more information on what happens with $form_state['redirect'].

Method 2: implement hook_node_insert()

From inside yourmodule_node_insert(), you'll need to:

find out what terms (if any) are in the new node ($node is passed into the function)
load all the terms for the relevant vocabulary, probably with taxonomy_vocabulary_load()
check to see if any of the node terms are not in the full list
if that's true, use drupal_goto() to redirect accordingly


Spambot creates 4000 orders a day Our webshop (built in Drupal 7 and Drupal Commerce) gets bullied by a SPAMBOT which creates about 4000 orders a day. These orders are getting registered as created by 'Anonymous' (unchecked) and stay stuck in the 'Shopping Cart'
Apparently, the Spambot creates these orders by adding a product to the shopping cart on the product overview page (a custom built view with all products and for every product item  an Add to cart button).
Under each 'Add to cart' button, there's a hyperlink. We've already attributed a 'NOFOLLOW' link to those hyperlinks, but the issue still persists.

Our initial set-up for the 'add to cart' button for each product on the Product Overview Page was that people could instantly add a product to the shopping cart without first having to visit the product page.
On the other hand, we chose to offer customers the opportunity to pay as a guest. This, as well, to rule out as many stumbling blocks as possible during the ordering process, which may discourage customers.

Does anyone have a possible solution, preferably a solution that does not compromise the user experience (or has as little impact as possible on the UX?).

Blocking is hard. Honeypot is a good deterrent, but if you allow anonymous users to click links that add products, then having spam orders might be your new reality. Removing useless, old carts is easy.

We use Commerce Cart Expiration on a number of stores. Also, sometimes its preferable to delete orders outright based on some criteria. For that, you can use Commerce Order Cleanup utility module.


Add site details to be used as tokens throughout site Is there a way to add additional fields to the config/system/site-information area such as "business location", "hours of operation", "phone number", etc. I would then like to be able to use that information throughout nodes and blocks as tokens or something like tokens.

That way if a phone number changes or business hours change you can just change it on the config page and it will change throughout the site.

Is this possible?

I think you could achieve this by altering the site information form in a custom module to add a custom submit function which would use the Token API to add desired values in tokens.

I found a good post explaining the token part for 6/7 here and a good post for altering the form here.

The module developer's guide is handy too.


Creating Sign Up form for 2 types users in Drupal 7 I want to create a single user registration/ sign up form for two types of users e.g buyer and seller. When trying to register, a potential user will have the option of selecting between being a buyer or seller. After completing the form and clicking the sign up button, the user who chooses buyer is immediately logged in while the seller is taken to a page where he needs to provide additional information to complete his/her registration.
I have downloaded and installed profile 2 and auto assign role but am not sure am on the correct path.

Thanks in anticipation.

Sounds like a way to go. Additionally you may use the Rules module to redirect the seller to the profile page and the LoginToboggan module to login users immediately after registration. Also some Spam bot prevention may be useful. Generally I consider registration without user approval (by email) as harmful: A user can easily register himself in the name of another person. Drupals double opt-in usually helps to prevent that. LoginToboggan can delete users which did not approve their registration after x days.

Anyway here is a potentially cooking list:

Add two roles: Buyer and Seller.
Use the Auto Assign Role module to let the user choose between Buyer and Seller at registration time.
Use the LoginToboggan module to login the user immediately after registration.
Create a profile for Sellers using the Profile 2 module. Use Drupal permissions to make it accessible by Sellers only.
Use the Rules module to redirect Sellers to their profile page if they have no profile yet.
Optionally use the CAPTCHA module to prevent spam bot registrations.


Contextual links for node blocks I have the Nodeblock and the Contextual links modules installed. They work fine, but I want to add the "Edit node" link in the contextual links for node blocks. For views, there is a "Edit view" link, but not for nodes. Is there a way to do that, maybe with a preprocess block function?

Ok, it looks like you have to hover the actual body of the block to see those links. It doesn't display them if you hover just the title.


Hook Page Alter using Page ID Is it possible to use a Page ID to target a specific page i.e.

function module_pageid_page_alter(&page){
}

By page ID I guess you mean the page path? There isn't a hook like the one you've suggested but you can do basically the same thing in a standard hook_page_alter() like so:

function MYMODULE_page_alter(&$page) {
  if ($_GET['q'] == 'node/1') {
    // Do something for node 1
  }
  else if ($_GET['q'] == 'admin') {
    // Do something for the root admin page
  }
}


Update multiple rows (with different ids and different values) using one query I want to update multiple rows in a custom table using just one query.

Each row has its own id (obviously) and different fields/values to update.

Given this question and this post, i think i can achieve it with a single db_query, similar to this one:

UPDATE {table} SET

`field1` = CASE `id`
    WHEN 1 THEN 'field1 value 1'
    WHEN 2 THEN 'field1 value 2'
    END

`field2` = CASE `id`
    WHEN 1 THEN 'field2 value 1'
    WHEN 2 THEN 'field2 value 2'
    END

WHERE `id` IN(1, 2);

Or:

INSERT INTO {table} (`id`, `field1`, `field2`)
VALUES
    (1, 'field1 value 1', 'field2 value 1'),
    (2, 'field1 value 2', 'field2 value 2'),
ON DUPLICATE KEY UPDATE
    `id` = VALUES(`id`),
    `field1` = VALUES(`field1`),
    `field2` = VALUES(`field2`);

But i'ld feel more confortable using db_update instead of db_query.

Any suggestions? Thanks

You can use below example to update:

    $items = array(1,2);
    db_update('your_table')->fields(array(
      'update_field_one' => $to_update_one,
      'update_field_two' => $to_update_two,
      'updated' => REQUEST_TIME,
    ))->condition('id', $items, 'IN')->execute();


I just want to move this login button up above the create new account and request new password. How? I want to move login button up above other two options create new and request new password links. what I do I have to do. I am new to drupal

You can use hook_form_FORM_ID_alter in your custom module and change the weight of the links

function MYMODULENAME_form_user_login_block_alter(&$form, &$form_state){
  $form['links']['#weight'] = 100; //define weight as such the links moves below  submit button.
}

Replace "MYMODULENAME" with the name of your custom module.


empty drupal commerce cart with a url? Is it possible to empty the cart with drupal commerce by visiting a url?

/cart/empty

Trying to create a test case for selenium

The code would look something like this:

function MYMODULE_menu() {
  $items['cart/empty'] = array(
    'title' => 'Empty Cart',
    'access arguments' => array('access content'), // or whatever permission you want
    'page callback' => 'MYMODULE_empty_cart',
    'type' => MENU_CALLBACK
  );

  return $items;
}

function MYMODULE_empty_cart() {
  global $user;
  // Load the order and empty the cart
  $order = commerce_cart_order_load($user->uid);
  commerce_cart_order_empty($order);

  // As this page won't display anything you need to redirect somewhere
  drupal_goto('some/page');
}


listing all the pages of a custom content type I would like to know the appropriate way to listing the contents in a single page of type "news". Let me clear it once again, I have a "news" type custom content type.

Now i want to list all the pages of type "news" in a separate(say about us) page and styling them. Prior to this I have created a template file in my custom theme's template directory named as "node-news.tpl.php". Thanks In Advance.

The views module do that. There's many articles about this question. Take a look on existing answers


How can I delete a row from the database? I would like to delete all rows from the database that is older than 1 month. How can I do that in Drupal 8?

  DELETE FROM myTable WHERE MyColumn < DATEADD(MONTH, -1, GETDATE())

You can do it by using this code

$query = \Drupal::database()->delete('table');
$query->condition('some column', 'some condition');
$query->execute();


ShareThis facebook posts previews are perfect, but posts empty images I have been having problems with facebook integration, and I know there are lots of other posts about this as I've been looking through lots of them. I see plenty of information about FB picking the wrong image, but in my case, the image is correct, and the preview of what is going to be posted from ShareThis is perfect. Even the facebook debugger tool has it all correct, but when I actually post it to facebook, the image is just empty.

What confuses me even more is that 2 of my other content types work, and the third doesn't. All 3 are defined in the same fashion, using the metatags open graph module to define the tokens for the meta data. In each page, the source is the same, and the og:image tag is always correct. When copying the image URL out of the source and browsing, the image loads perfectly.

I swear sometimes that facebook just does whatever it feels like sometimes. Anybody have any advice on why 2 of 3 content types work fine, but the 3rd never works?

I have looked at the settings for each imagefield, and they are all nearly identical. None of them are being stored in specific folders, they are all publicly accessible. As an example, the URL http://natureupnorth.org/encounter/mark-martin/smaller-haystack gives me no problems in the facebook debugger, previews fine, but results in just an outline of an image on facebook.

Any help greatly appreciated.

http://natureupnorth.org/sites/default/files/styles/encounter_big_image/public?itok=5aqi4xn6

That og:image gives me a 403 error.  Is this set to require a logged in user?


Uncaught PHP Exception: MissingValueContextException After upgrading to version 8.8.5, I can't access the main web page, but I can log in to the admin panel. When I turn on the verbose logging funcionality I receive the following error message:

Drupal\Component\Plugin\Exception\MissingValueContextException: Required contexts without a value: view_mode in Drupal\Core\Plugin\Context\ContextHandler->applyContextMapping() (line 155 of core/lib/Drupal/Core/Plugin/Context/ContextHandler.php).

Drupal\panels\Plugin\DisplayBuilder\StandardDisplayBuilder->buildRegions() (Line: 183)
Drupal\panels\Plugin\DisplayBuilder\StandardDisplayBuilder->build() (Line: 338)
Drupal\panels\Plugin\DisplayVariant\PanelsDisplayVariant->build() (Line: 29)
Drupal\page_manager\Entity\PageVariantViewBuilder->view() (Line: 105)
Drupal\Core\Entity\Controller\EntityViewController->view() call_user_func_array() (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 573)
Drupal\Core\Render\Renderer->executeInRenderContext() (Line: 124) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext() (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw() (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle() (Line: 57)
Drupal\Core\StackMiddleware\Session->handle() (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle() (Line: 191)
Drupal\page_cache\StackMiddleware\PageCache->fetch() (Line: 128)
Drupal\page_cache\StackMiddleware\PageCache->lookup() (Line: 82)
Drupal\page_cache\StackMiddleware\PageCache->handle() (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle() (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle() (Line: 23)
Stack\StackedHttpKernel->handle() (Line: 708)
Drupal\Core\DrupalKernel->handle() (Line: 19)

I don't know if this is a core or a module error, any help appreciated.

Actual system: Drupal 8.8.5, PHP 7.4.5, 5.5.5-10.1.44-MariaDB-0+deb9u1

Thanks.

It seems to be related to a new constraint added on releases, as seen on https://www.drupal.org/project/drupal/issues/3113474
As "view mode" is asked, with no default context, some modules like Panels IPE, Panels, MiniLayout may generate problems if you ask to display a single entity field as FieldBlock.
Just apply patch on https://www.drupal.org/files/issues/2020-02-13/3001313--63_0.patch ; for the record :

--- a/core/modules/layout_builder/src/Plugin/Derivative/FieldBlockDeriver.php
+++ b/core/modules/layout_builder/src/Plugin/Derivative/FieldBlockDeriver.php
@@ -124,7 +124,14 @@ public function getDerivativeDefinitions($base_plugin_definition) {
           $context_definition->addConstraint('Bundle', [$bundle]);
           $derivative['context_definitions'] = [
             'entity' => $context_definition,
-            'view_mode' => new ContextDefinition('string'),
+            'view_mode' =>  new ContextDefinition(
+              'string',
+              $this->t('View Mode'),
+              FALSE,
+              FALSE,
+              NULL,
+              'default'
+            ),
           ];


Put Site-Wide Contact Form in a Block I want to display the contact form inside a block, so that a user can access it directly from another page. Using Webform Module to create a new form would be overkill.

Is there a simple way to do this, either core, a small module or custom module?

Use the Form Block module. Enables the presentation of user registration, site wide contact, or node creation forms in blocks.


Ajax fired when Filefield "Add Another Item" button is clicked conflicts with my jquery I have a node type with a multivalue filefield. I am using some jquery called by my custom module to modify some of the UI in the form, but when I click the "Add Another Item" button it completely breaks and wipes out my custom external jquery. How can I fix this?

These tips are correct for Drupal 7.
Your custom code should be coordinated with Drupal AJAX Framework.
When you click "Add Another Item" this happens:

AJAX handler sends all the form with all values, and with point to element which has triggered AJAX.
Server returns fully new field. For example, if there were 4 inputs in your field, server will return 5 inputs, not just last fifth.
After that new piece of HTML goes through all the behaviors. As you may know, behavior's attach method has two params: context and settings. context is just new HTML for your field.

So, if you add your JS to this schema correctly it must work.

Drupal.behaviors.YOURMODULE = {
  attach: function (context, settings) {
    $('.some-class', context).once('YOURMODULE', function() {
      // Do some work here
    });
  }
}


Custom registration twig template What would be the best way to make a custom registration twig template ?

I have implemented the hook :

function THEMENAME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'form__' . $variables['element']['#form_id'];
}

Si I get form twig template suggestions such as form--user-register-form.html.twig

Then I can call every value I want using "element" :

{{ element.field_name }}

My only problem is that I'm facing error with fields validation with ajax i.e for the picture field, when uploading a picture I got an error message that the picture size overpass the php limitsize from the server (which is obviously not the case).

So I have to call {{ children }}in my twig template to get it working properly. The only bad point is that calling {{ children }} actually call the whole form ......

Am I doing something wrong ? Is it the best way to accomplish stuff above ? Is it {{ children }} that I have to call to get the form working ?

For simple forms ...

... you can theme a form template by using {{ element }} instead of {{ children }}, see How to Create twig template files in drupal 8 for customizing user login,profile edit and forget password forms?.

But this is not always the best approach, because it's difficult to include all form elements and metadata the form needs to operate.

For complex forms ...

... it might be easier to add an additional template level, which only has to render the inner form elements, not the complete form:

/**
 * Implements hook_form_FORM_ID_alter() for \Drupal\user\RegisterForm.
 */
function mytheme_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  $form['#theme'] = 'user_register_form';
}

The custom template needs to be registered in hook_theme. See How to render specific form elements from the *.theme file for a step-by-step example.


Send argument to custom field constraint I have created custom field type with custom constraint defined and called successfully, the question is how to send the field settings to my constraint in the code block below.

/**
 * Plugin implementation of the 'custom_field_type' field type.
 *
 * @FieldType(
 *   id = "custom_field_type",
 *   label = @Translation("custom field type"),
 *   description = @Translation("custom field type"),
 *   default_widget = "number",
 *   default_formatter = "number_integer"
 * )
 */
class CustomFieldType extends IntegerItem {
  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
    return array(
      'type' => array(
        '#type' => 'radios',
        '#title' => t('type Validator'),
        '#default_value' => 'none',
        '#options' => [],
        '#description' => t('types.'),
      ),
        ) + parent::defaultFieldSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    $type_options = array(
      'type1' => t('type1'),
      'type2' => t('type2'),
      'none' => t('type1 and type2'),
    );
    return array(
      'type' => array(
        '#type' => 'radios',
        '#title' => t('type Validator'),
        '#default_value' => $this->getSetting('type'),
        '#options' => $type_options,
        '#description' => t('types.'),
      ),
    );
  }

    /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['value'] = DataDefinition::create('integer')
      ->setLabel(t('type'))
      ->addConstraint('CustomCheck')
      ->setRequired(TRUE);
    return $properties;
  }
}

How to send the field settings as arguments to the constraint as the validation only takes the field value as parameter.

/**
 * Validates the CustomCheckConstraint.
 */
class CustomCheckConstraintValidator extends ConstraintValidator {

  /**
   * Validator 2.5 and upwards compatible execution context.
   *
   * @var \Symfony\Component\Validator\Context\ExecutionContextInterface
   */
  protected $context;
 public function validate($data, Constraint $constraint) {
//do custom check here
}
}

The method addConstraint allows an optional array of options to be passed to the constraint plugin. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21TypedData%21DataDefinition.php/function/DataDefinition%3A%3AaddConstraint/8.2.x


Code Adding Additional Node Reference to Existing Node I have 2 content types: video and product. Each product contains a node reference to a video, and products can be linked to multiple videos. I'm writing a custom module to add in lists of these products and videos from an outside URL with JSON. Loading the content into Drupal isn't an issue.

What I want to do is check to see if the product exists, and if so then to add an additional node reference to the loaded video. The JSON spits out an array of videos, and there's a product array within each video array (so 1-10 products can be linked to one video). Each product has a specific product ID I'm passing in, and with that I'm able to single out the product node that needs to be updated. I load the product node, and then instead of adding an additional reference, the code I have is replacing the node reference. I've tried a handful of changes which either alter nothing or throw an error.

Here's the code:

 $result = $efq->entityCondition('entity_type', 'node')
  ->fieldCondition('field_product_id', 'value', $prodID, '=')
  ->execute();
 if (!empty($result['node'])) {
   $nids = array_keys($result['node']);
   $node = node_load($nids[0]);
   $node->field_video['und'][0]['target_id'] = $node_id;
   node_save($node);
 }
 else
 {
   Add product node
 }

Found a solution, which was replacing this line:

 $node->field_video['und'][0]['target_id'] = $node_id;

With:

 $new = array('target_id' => $node_id);
 $node->field_video['und'][0] = $new;


Change url alias for user profile pages based on role I have two sets of users, faculty and staff, with corresponding Profile2 profiles.

I can't figure out how to get different paths for users dependent on roles, e.g, staff/userid or faculty/userid.

I've been trying with both Rules and Pathauto.  Seems like it should be simple but can't get work it out.

One way would be to create a hidden field on the user account page, and populate that field with Rules during registration. For example, for someone with the Staff role, give it the staff value; for user with the Faculty role, give it the faculty value.
Then, with the Pathauto module, define a pattern for user paths, for example [user:XXXXX]/[user:uid], where XXXXX is the name of the hidden field you created, prefixed with field.


how do I get the user ID other than the one for the current logged in user? How do I the user ID of the account profile that an administrator user is currently viewing/editin? I can't use \Drupal::currentUser() as it always returns the administrator details.

I tried \Drupal::routeMatch()->getParameter('node') and \Drupal::request()->attributes->get('node'), but it returns this error:

  Call to a member function id() on null...(file path)

Assuming that you're viewing a page at a path like /user/42, then you can use the RouteMatch class. Your example is close, but you need to change the parameter passed to the getParameter() method. The parameter in this case is named 'user' not 'node'. You can determine the parameter name from the route definition. Not all routes have parameters, but when they do, they are specific to the route in question.

In this case the route (entity.user.canonical) is defined by \Drupal\user\Entity\UserRouteProvider::getRoutes. And the 'user' parameter is the UID of the user entity in question. Given that, you can use RouteMatch to get the ID in one of two ways.

Load the $user object specified by the user parameter. Which is probably more common. I'm guessing if you're trying to get the UID it's so you can load the user object. With this method parameters are processed by the parameter conversion system, which does operations such as converting entity ID parameters to fully-loaded entities

$user = \Drupal::routeMatch()->getParameter('user');
$uid = $user->id();

Or access the parameter value directly:

$uid = \Drupal::routeMatch()->getRawParameter('user');

This change record provides a bit more information https://www.drupal.org/node/2295317


What is the equivalent of hook_user_view()? I am basically trying to do what described in How can I let anonymous users view user profiles by role? in Drupal 8. User profiles should only be visible to anonymous users only if those profiles are for users having a certain role; all the other user profiles should not be accessible to anonymous.

The answer there suggests using hook_user_view(), but it appears that hook has been removed in Drupal 8. Is there a different/correct way to do this now?

hook_user_view() is still available in drupal 8, but the hook naming schema has changed, because the hook can now be used for all entity types:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!entity.api.php/function/hook_ENTITY_TYPE_view/8.2.x

A more D8 way to do this could be a custom access check on the route:

https://www.drupal.org/node/2122195


Want two discussion Forum Hello Hiii Again Everyone I Am Creating A drupal website i want to create 2 forum for different topics Mean I want to create a business discussion forum and business ideas forum so in drupal there is only one forum so how can i make 2 different forms in one website

You need to add Forum Containers, and then place the Forums in the appropriate container. Topics are then added into the Forums from the add content or Forums page. So basically you need to plan the hierarchical structure that your forums will take beforehand.

For more forum features look at Adding functionality to your forum with contribs

Tutorial : 203: Creating and Managing Forums in Drupal 7


Link to a referenced entity I have a entity A with an entity reference to entity B, and an image field. I created a view to display an entity A. I want to link the image field to the page displaying the referenced entities B.
Firstly, I've added the entity reference field in my view and checked "Exclude from display", in order to get in the image field the replacement token, but I could not get the link. I just get the the entity B title.
Afterwards, I added a relationship to entity B in my view. No more success.
Could you help me?

ER fields store only the ID of the referenced entity.
Pulling in other information about the referenced entity usually involves adding Relationships, but some details can also be shown through the Formatter Field setting.
Set Formatter to Entity ID and Rewrite
Without adding the Relationship edit the ER field, set the Formatter to Entity ID, then under Rewrite results turn on Override the output of this field with custom text and enter something like this into the Text field:
{{ field_myImagefield }}
Check the correct tokens under Replacement patterns a bit lower under the Text field.
You can also achieve similar result with Output this field as a custom link which has more options for the link if you need them. In this case the Text field will only hold the image token and this option will contrast the anchor HTML.
This approach is helpful when you have a multivalue field it will be possible to show all values in the same row, while using a Relationships usually splits them into separate rows and it requires more steps to aggregate them.
Use the ER Relationship
If you add the ER Relation ship you will be able to add the Link to content field and make it use that Relationship to show the link to the Referenced entity instead of link to the original row entity.
You may want to use the Output the URL as text option to make the token output more predictable.
Now you have the referenced entity link in your Views you can use it to Rewrite other fields.


How to install with composer external library that drupal module depends on Module bootstrap_languages depends on external library of same name how do we ask composer to require the external library that needs to go to libraries/bootstrap_languages folder

The project's composer.json already includes installer-paths but how can I make use of them ?

    "installer-paths": {
        "core": [
            "type:drupal-core"
        ],
        ....
        "libraries/{$name}": [
            "type:drupal-library"
        ]

NOTE: the module itself has not taken care of this dependency

You should be able to include this package via composer by adding some repository info.

Add a package definition to your repositories section in your composer.json. The resulting repositories section may look like this:

"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
        "type": "package",
        "package": {
            "name": "usrz/bootstrap-languages",
            "type": "drupal-library",
            "version": "dev-master",
            "dist": {
                "url": "https://github.com/usrz/bootstrap-languages/archive/master.zip",
                "type": "zip"
            }
        }
    }
]

Then you can just use composer require like:

composer require usrz/bootstrap-languages

This will add a new line to your require section in composer.json like

"usrz/bootstrap-languages": "dev-master"

Normally I would try to use this approach with a release tag of a package, rather than the master branch, but no tag exists for this repository.


Custom date format (instead of %date) for WebForm e-mail title? I have an webform with e-mails adresses that I want to send notifications to.

I want to make the title of the e-mail as e.g. "new message 2017-03-20".

I have tried with pattern suggested under another field (e-mail body):

new message %date

But it output the formatted date:

new message sunday, march 25, 2017 - 17:54

Is there a way to put here date in yyyy-mm-dd format without chaning the global date formatting on the website?

I also tried to add something like the pattern that is not listed under field:

new message [entity-fetched:field_event_date]

but it does not get replaced at all (I get message with that literal title):

new message [entity-fetched:field_event_date]

Place this code in a custom module:

     /* first add a custom date field (mydate), you have to set it's value with rules */
  /* change all capital letters with proper names (in lower case) */
  function YOURMODULE_preprocess_node(&$vars) {
$vars['MYDATE'] =
t('!datetime',
  array('!datetime' => format_date($vars['node']->MYDATE,
    'custom', 'M/d/Y, h:i a')));
}
  /* hide custom field to all users but admin */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $uuid = $user->uid;
  /*  check that user is NOT admin (No1) */
    if ($uuid !='1') {
        /* if is user profile form use: if ($form_id == 'user_profile_form')*/
      if ($form_id == 'YOUR_FORM_ID') {
      //dsm($form);
        hide($form['field_MYDATE']);
       }
 }

for a diferent format look at: http://php.net/manual/es/function.date.php

having date format correct, go agian and do:

new message %mydate


Disable caching (for theme develoment) doesn't work I'm quite desperate. I have disabled it in the admin backend (Administration -> Configuration -> Development -> "Page cache maximum age" = "<no caching>"). In sites/default/services.yml I have:

parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

I even tried to disable the opcache (wich makes not much sense, of course). The templates get translated (or rendered?) only once after I manually clear the cache.

I'm using Drupal 8.3.4, PHP 7.1 with php-fpm, postgresql and lighttpd on CentOS.

To always clear the cache – by clicking in the interface or drush cr –
feels like compiling a c++ application. And doing a delete from cache_render; delete from cache_dynamic_page_cache; delete from cache_entity; in the psql console feels 500 times faster but also isn't really convenient.

You need to follow the procedure in /sites/example.settings.local.php:

/**
 * @file
 * Local development override configuration feature.
 *
 * To activate this feature, copy and rename it such that its path plus
 * filename is 'sites/default/settings.local.php'. Then, go to the bottom of
 * 'sites/default/settings.php' and uncomment the commented lines that mention
 * 'settings.local.php'.
 *
 * If you are using a site name in the path, such as 'sites/example.com', copy
 * this file to 'sites/example.com/settings.local.php', and uncomment the lines
 * at the bottom of 'sites/example.com/settings.php'.
 */

This will enable the service for a null cache backend in development.services.yml, which you then can assign to cache bins of your choice by uncommenting these lines:

# $settings['cache']['bins']['render'] = 'cache.backend.null';
# $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

Then you no longer need to truncate the cache tables.


Drupal 7 open image in colorbox when a “button” on the image is clicked, otherwise go to content I am using Drupal 7 and Colorbox module with Views 3.

In my view I have an image field. Right now based on my settings when I click the image it can either go to the content or open the image itself in Colorbox. What I want to achieve is maybe have a button (or a link?) at the bottom right corner of the image, when this button is clicked, image opens in Colorbox, if image itself is clicked, it brings you to the content (node page).

How can I achieve this?

In Drupal 7 you can achieve it by the following steps

Steps

Create a new VIEW and add the following fields
Background image : Add the image which you want to show as background image using imagestyle. Also add the link to the node using Link image to. And check Exclude from display.

Colorbox image : Add the image which you want to show inside COLORBOX using imagestyle. Dont add the link to this image and check Exclude from display

Image icon : Add the image which is used to render on the top of the background image  using imagestyle. And check Exclude from display.This image we will use in COLORBOX TRIGGER field.
Colorbox Trigger : Add this field and make Image icon field as the TRIGGER FIELD and Colorbox image as its CONTENT by use "Replacement patterns".

Custom text : Add Global: Custom text field and add the below html inside it and make sure you should replace [Background image] and [Colorbox Trigger field] using "Replacement patterns". It act like a container.

[Background image]

[Colorbox Trigger field]

OUTPUT

Note : Arrange the image icon above the background image using CSS


Hide specific sections on admin configuration page I wondering how I may hide some sections on the administration configuration page? I would like to hide some sections entirely for instance the media section and then only remove certain items for others, under the system section I only like to remove the cron item.

I tried to alter the admin/config page using hook_admin_paths_alter() and hook_preprocess_page() but without any luck. Would be nice if some one could point me in the right direction on how to achive this.

function MODULE_admin_paths_alter(&$paths) {
   // hide some paths
   $paths['admin/config/system/cron'] = FALSE;
}

function MODULE_preprocess_page(&$variables) {
  if(path_is_admin(current_path())) {
    // I don't know how to modify the markup of the page
    // tried to add a template called page--admin--config.tpl.php but
    // without any luck
  }
}

In the end I used @Captain Pants solution:

function pe_admin_permission() {
  return array(
    'access extended config' => array(
        'title' => t('Access Extended Configurations'),
        'description' => t('Gives a user access to extended configuration pages.'),
        'restrict access' => TRUE,
    ),
  );
}

function pe_admin_menu_alter(&$items) {
  // add all items you would like to hide here
  // if you hide all items in a specific section the entire block
  // will be removed
  $sections = array(
    'admin/config/system/cron',
    'admin/config/system/actions',
    'admin/config/system/mimemail',
    'admin/config/system/mailsystem',
    'admin/config/date/date_popup',
  );

  // loop through each item you would like to hide
  foreach($sections as $section) {
    $items[$section]['access callback'] = 'user_access';
    $items[$section]['access arguments'] = array('access extended config');
  }
}

You have stated that it would be "nice" to have these paths inaccessible. If a user is not supposed to have access to this paths then you should go above and beyond just "hiding links so nobody can see". Here is the solution to both remove those links from the config page AND having those links inaccessible if one were to type in the url in their address bar.

You will need to make a module with the following code. Note: I'm only doing this for the cron config page.

/**
 * Implements hook_permission().
 */
function my_module_permission() {

  return array(
    'access cron config' => array(
      'title' => t('Access Cron Config'),
      'description' => t('Gives a user access to the cron configuration page.'),
      'restrict access' => TRUE,
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function my_module_menu_alter(&$items) {

  $items['admin/config/system/cron']['access callback'] = 'user_access';
  $items['admin/config/system/cron']['access arguments'] = array('access cron config');
}

This will give you the "Access Cron Config" permission on the permissions page and there you can choose which role has the cron page appear for them.

Please research more on hook_permission and hook_menu_alter for clarification on how to do this for the media pages.


Show taxonomy term's image field on node page Ive added an image field to my taxonomy terms. On a node I need to display the image of the terms it tagged with.

Ive created a view with the NID as an argument and attached it to the node content type with the EVA module.

Ive added a relationship of 'Taxonomy terms on node'. This allows me to add 'Content: All taxonomy terms' as a field which shows the term name, but I cant figure out how to load the term's image instead.

You can achieve this in a different way, using Display Suite module you can simply render taxonomy terms in a desired view mode.


Why drush sql-sync fails with mysqldump unknown variable error? I am having issues trying to sync my staging server with my local server using drush sql-sync command.

I've set my aliases right and the same configuration is working with my development server and local machine.

Here are the issues I get once I type in:

drush sql-sync @stag @local

I get the standard warning about backing up my target database.

Then I'm having this error:

stdin: is not a tty
mysqldump: unknown variable 'table_cache=67108864'
Database dump failed

So I am pretty sure this has something to do with MySQL configuration on the staging server.

From what I've googled/read, a large value for the table_cache is not necessarily a good one for the server and can slow it down. But I am not sure what a "good" value is.

This does look like an issue with mysql, not Drush.  Run your Drush command again with the -s flag (simulate);

drush sql-sync @stag @local -s

Drush will then print out the shell commands that it would execute, without doing anything.  You can copy the mysqldump command into your shell, and experiment with the options until the dump works.


User register endpoint showing notifications I'm trying to setup an endpoint for a 3rd party app to allow users to be created on my site through a REST endpoint, which is mostly working so far, although, I've just navigated to my site through the front end, and I've realised it's showing me all the notifications for all the test users I'm creating.

I'm not logged in as an administrator, just a normal user account, and the setting for Show errors and notifications is off, so why is it showing me all these notifications, there's no way I can leave that in

Base on you're working with RESTful API and does not need these messages anymore you can disable them ( all of them or parts of them based on what you don't want)
by  Disable message module :

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

Features

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

or another solution is  on the theme prevent it got rendered by  this solution : https://www.drupal.org/forum/support/installing-drupal/2011-01-23/how-to-turn-off-error-messages


Reordering values in a multi value field Is there a module that allows you to reorder the values of a multi value field?  By drag and drop or by weight.

Example:

Field XYZ:
+ Value 1
+ Value 2
+ Value 3
+ Value 4

Reorder to:

Field XYZ:
+ Value 4
+ Value 2
+ Value 3
+ Value 1

If you need to do this in the context of adding/editing nodes, Drupal 7 core provides this functionality on node add/edit pages.


search_api_solr with accurate radioactivity sorting in views We're using Views to display our search_api_solr results. We'd like to be able to show these results by radioactivity (popularity) sort order.

The radioactivity field is one of several fields indexed by Solr so that it can be used by the Solr views for sorting.

The problem is, the radioactivity value that gets indexed by solr only gets updated when the entity gets indexed. The entity only gets indexed when it gets changed (node_update), or when the Solr index is cleared and everything is reindexed again. Having an entities radioactivity energy adjusted by visiting the entity, does not trigger solr to reindex the entity - and probably rightly so.

I've tried adding a relationship in the Search View to node, but that isn't available as a "search index" view type.

Does anyone have any other suggestions for solving this? There doesn't seem to be a radioactivity hook that lets you execute your own code, i.e. update search_api_item table to say its changed.

As you say there's no API, so you're probably going to have to resort to patching the module.

There are at least two places you'll need to make additions as far as I can tell:

_radioactivity_update_energy()
radioactivity_cron()

I would suggest adding your own hook which gets fired whenever an entity is updated in either of those functions, and perform the search indexing there.

You should have a good think about the values you use for half lives/Solr processing delays if you choose to implement it like this. If your values for those settings aren't sensible you could end making the changes without actually seeing any effect. Also, depending on the amount of traffic the site receives, you could slow your server down quite a bit doing this.


Where should I define the "drupal_stale_file_threshold" Drupal variable? I want to delete my CSS and JavaScript files every day. Where do I define the "drupal_stale_file_threshold" variable?

In the template.php file with variable_set('drupal_stale_file_threshold', 86400);
In the settings.php file with $conf['drupal_stale_file_threshold'] = 86400;

Settings.php makes sense if the setting isn't supposed to change.

A module may be useful if the value of the setting is just temporary.

A themes template.php file is absolute not the place to put it.


Find the page from link This is a scenario. I wanted to find the content of the page from a link.

For eg while navigating the website, i clicked a link and the page loads. The page link is like www.example.com/gallery/videos

While checking I found there is a view named Gallery Videos and contains a 4 blocks attached. In the configuration of one block's path setting has been given "gallery/videos". But I did not find the page created for it. How can I easily detect where the content is loading and which view is it?

This seems to be a very basic question , but it seems hard to find when there are lot of contents, views and blocks used in the site.

Programatically speaking, if a View is involved in a template, the module injects the $view object into the available variables. So you can get to it pretty easily:

function MYMODULE_preprocess_node(&$vars) {
  if (isset($vars['view']) && $vars['view'] instanceof view) {
    if ($view->name == 'foo') {
      // ...
    }
  }
}

From a UI perspective, enabling the Contextual Links module might be a good solution to your problem. That will add direct edit/delete/etc links to nodes/blocks/views, and others depending on the contrib modules you have installed).

You can browse the site and simply click the edit link on a view to be taken to the edit page, where you can find out everything you need to know. Same for content, assuming it's been rendered in an entity view mode and not as fields.


How to restrict content for Anonymous users after they viewed more than two articles? After an anonymous user viewed more than two or three articles, I want to redirect such user to the login/register page.

Any suggestions about how to make this work somehow?

Not sure if it is the only way to get this to work, and not sure if it is the most elegant way, but it should be doable as detailed below. It does not require any "custom" code, only some (often used) contributed modules.

Rule 1 - Count the visits

The Flag module can by used to flag (eg) articles, which itself can be done automatically (behind the scenes) via the Rules module (= 1st rule). To make the Flag module work for anonymous users also, you'll need to get the Session API involved. For more details on that, refer to:

My answer to "How to display a flag to anonymous users?".
The great article about Enhancing the Anonymous User Experience: Adventures with Flags.

Rule 2 - Trigger the redirect

With that, you have "a" counter (= number of articles flagged by a user) that you can use as a Rules Condition in a 2nd rule, whereas this 2nd rule can be triggered by a Rules Event like "after an article gets flagged". In that Rules Condition you just check if the counter exceeds your limit (= 2 in your case), then you perform the Rules Action (in the 2nd rule) which is to redirect to your login/register page.