How to create a rule that grants user points after a user passed a quiz? I'm using Drupal 7 and the Quiz module (version 7.x.5.x).

I'd like to grant User Points to a user whenever a user answers correctly. I have to use the Rules module and I wonder how I can create a Rule for it, like what's the Rules Event, the Rules Condition(s), etc...).

Note that I have set the percentage of passing at 75%.

I prefer not to code anything or use the Quiz userpoints module because I had some troubles in the past with this Quiz userpoints module.

Update: I tried the 2nd rule included in revision 2 of the answer below. But it only grants the points whenever users take a test, no matter whether they passed it or failed it.

If using Quiz 7.x-5.x

Assuming you're using the 7.x-5.x version of the Quiz module, you can take advantage of integration with the Rules module that this new release comes with.

To do so, you can start from the delivered rule, which looks like so:

{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      }
    ]
  }
}

After you enable Rules (and Rules UI, a submodule of it), just clone the above rule (using the Rules UI) and apply these changes:

Add these extra Rules Conditions:

entity is of type (to make the data about the Quiz node available, such as pass rate).
verify if the user taking the Quiz actually passed.

Add another Rules Action to grant an amount of User Points that you may want to be related to [quiz-result:score] (note that this token is also shown in the Rules example above, within the Rules Action), e.g. an amount that equals the score of the Quiz. If you're not familiar with how to use Rules to grant user points, then have a look at the answer to "How to grant userpoints only for modifying nodes last changed at least 20 days ago?" (which also includes a Rules example to make that happen).

After you added this extra Rules Condition and Rules Action, your rule should look similar to this rule:

{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "userpoints_rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } },
      { "NOT data_is" : {
          "data" : [ "quiz-result:score" ],
          "op" : "\u003C",
          "value" : [ "quiz-result:nid:quiz:pass-rate" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      },
      { "drupal_message" : { "message" : "Congratulations, you passed this quiz with a score of [quiz-result:score] % ..." } },
      { "userpoints_action_grant_points" : {
          "user" : [ "quiz-result:uid" ],
          "points" : [ "quiz-result:score" ],
          "tid" : "0",
          "entity" : [ "quiz-result" ],
          "description" : "Points earned because of your results in the quiz.",
          "operation" : "Insert",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Just use the Rules UI to import the above rule and you should (more or less) be ready to go. Possibly the only remaining tuning you want to do in this rule is like so:

Review the various settings of the Rules Action to grant User Points (eg the amount (= quiz-result:score in the rule above), the description and the category for the points.
Optionally also review the messages being shown when a user passes a quiz. Using the above rule, you'll get a messages similar to this example:

  Congratulations, you passed this quiz with a score of 80 % ...

That message is also followed by a related message produced by the User Points module, which looks like in this example:

  You just earned 80 points and now have 29.512 points in the General category.

Attention: be aware that the above rule will grant user points over and over again, since there is no validation (Rules Condition) if the user taking the quiz already passed the quiz before. If you also want to get that resolve (= only grant such points once), then refer to my answer to "How to check if user has passed the quiz already before granting user points?".

If using Quiz 7.x-4.x

For the 7.x-4.x version of the Quiz module, you may want to try the patch from fago (aka the Rules maestro ...), attached to issue # 1300420, which has a description like so (note the last phrase in it ...):

  ... adds basic rules integration to quiz. It includes an event when users have finished taking a quiz, a condition to check whether a user has passed a certain quiz and an action to clear quiz results for a user.

  Patch works for me.


Disable breadcrumb on View in Drupal Commerce Kickstart I am using Drupal Commerce Kickstart. I have been able to disable the hard coded menus by this advice - specifically my own post at the bottom. Unfortunately this has not disabled the breadcrumbs on certain Views I have created. The Views in question show a single product. One of the views shows content: Full content and the other just draws in node fields from the products. I have a view that doesn't call in any products and this does not show the breadcrumb trail.

The breadcrumb must be hardcoded somewhere as it doesn't appear in the blocks area. It seems to be set to show the breadcrumb in the preface first area.

I would appreciate some advice on where to disable this breadcrumb. Failing that are there any tools in drupal that you can use to trace back to find where things (like the breadcrumb) are getting generated from?

Do you want to disable the breadcrumbs entirely? If so, with kickstart, you can do so at:

Appearance > Settings > Commerce Kickstart Theme > Toggle advanced elements

It looks like commerce kickstart 2 uses the crumbs module (https://drupal.org/project/crumbs) to handle breadcrumbs (that's what I see in a local install from late July).

I haven't worked with Crumbs, but the documentation is here: https://drupal.org/node/1004394


Views - Protect user-assigned content from direct url access I'd like to create a restricted area from scratch using views.

What I'd like to achieve:

The admin creates a photo album and assigns it to a photographer
A photographer is able to log into the site, and see a list of albums that are assigned to them
The photographer can upload photos to the album
If a non logged user tries to access the album by typing its url, they get rejected
Ideally, photos (the files themselves) that are in an album are also protected, I know that file access restriction is a complex subject, but I'm okay with a sort of proxy-page that would then redirect to the file with an unguessable url, or a solution of this type.

Where I am so far:

Create a user role Photographer
Create a content type album with fields:

Photographer (user reference, role=photographer)
Photos (file, number of values unlimited)

Create a view to list content type=album, with a contextual filter on the Photographer field that defaults to current user id when not provided in the url. So that a logged photographer only sees their own albums. That works fine.

My problem:

Anyone can enter an album's url and access it directly [solved]
Anyone can enter a photo's url and download it [solved]

I've built this on drupal 8 but can also use drupal 7 and other modules. Any help would be very much appreciated!

Update:

I think I found part of the answer. Using private directory with the files module: https://www.drupal.org/documentation/modules/file. According to the docs:

  For example: you have created a new content type with a file field
  which stores files in your site's private file directory. Next you
  create a node from this new content type and attach two new files.
  When the node is published links to both attached files are visible
  and anyone who can view the node may download the files. Now, if you
  unpublish the node, all attached files become inaccessible for
  download even if you use the direct link to the files that worked when
  the node was published.

Have a look at the Group module which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also.

The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

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

Resources

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


#states doesn't work with exposed filters I have two exposed filters Contry (name=field_country_tag_tid) and City (name=field_country_tag_tid_option_limit). Reference limit option Module limet avaliale options in city but not when page with filters loaded at first time. That why I wanted to desable City Filter by using #states

function mymodue_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'map') {
   $form['field_country_tag_tid_option_limit']['#states'] = array(
  'visible' => array('select[name="field_country_tag_tid"]' => array('value' => '1')),
       );

    }
}

I used the following example http://api.drupal.org/api/examples/form_example!form_example_states.inc/function/form_example_states_form/7

But there are no any changes in my exposed filter, where is my mistake? Thanks

I tried to use id instead of name and now it works!


What is the equivalent of #page & #page-wrapper in Bootstrap theme? In most of the Drupal themes I find the IDs #page and #page-wrapper, but it is not available in the Bootstrap theme.

I tried to find in theme, but maximum I could find is class .container but is covers only that particulate section i.e. header, main-content, footer.

Is there any ID or class in Bootstrap theme which covers entire webpage like #page does in almost all other themes OR if there is not how can I add that?

To experiment, I did try to add following to page.tpl.php like other themes,

And added following CSS to check,

#page {
    border: 5px solid red;
}
#page-wrapper {
    border: 5px solid blue;
}

But it applies to border of the browser not to actual width of the page  as shown in the following image.

Hence looks like this way we can not add this to Bootstrap theme.

Any idea or suggestion how to apply #page and #page-wrapper to Bootstrap theme? Thanks.

After several try and error method, I did find the solution for this.

For a note, I am using LESS.

Step-1: Add a
 to page.tpl.php

Add following code in the page.tpl.php file of your sub-theme.

Step-2: Add the following CSS in the style.less of your sub-theme.

@media(min-width:@screen-sm-min) {
      #page-wrapper {
      width: @container-tablet;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red; }
    }
@media(min-width:@screen-md-min) {
      #page-wrapper {
      width: @container-desktop;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red;}
    }
@media(min-width:@screen-lg-min) {
      #page-wrapper {
      width: @container-large-desktop;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red;}
    }

So, this way, the added
 will be in harmony of Responsive theme of bootstrap and it will not displace any other container in the site and will not interfere with the native responsive design of Bootstrap.

Further Any suggestion or comment are welcome.


How to generate 'tag' field in form config module? I'm need to create a tag field (the field that you see in this stackexchange.com website for tagging)

I'm wondering is there any api for this or this has to be created from scratch?

If this has to be created from scratch, how to make a 'custom' field in drupal - a very simple sample will be much appreciated.

The standard site install includes a "Tags" taxonomy vocabulary, and includes a "Tags" field on the "Article" content type.  You can either reuse these components on your own site, or duplicate them for your particular use case.


Can I use the $language variable in a Drupal 6 template file? Is it correct to use the $language variable to make conditions in the page-front.tpl.php?
Is if ($language == 'es') correct?

The variables that are usable in a page template are visible in the source code of template_preprocess_page(). The template file you are referring to has the variable $language, which is a copy of the global $language, where $language->direction has instead the values "rtl" and "ltr."
The content of $language is an object with the following properties:

'language'
'name'
'native'
'direction'
'enabled'
'plurals'
'formula'
'domain'
'prefix'
'weight'
'javascript'

The line of code you wrote needs to be written as if ($language->language == 'es').


Running Drush Launcher on Windows When I run Drush in the command line on my Windows 10 computer or Windows Server 2016 servers, I get the following error:

drush : The term 'drush' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ drush
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (drush:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I've downloaded drush launcher and made sure that it was located in my PATH. Why is this error message showing and how do I get passed it?

The error message occurs because the command must be drush.phar and prefaced by the php command. In the same folder as Drush Launcher, you'd have to run php drush.phar to get it to work. Elsewhere, you'd have to run php /path/to/drush.phar (which can be just as, if not more, annoying that vendor/bin/drush).

To get it to work, create a folder called drush.bat in the same folder as drush.phar and include the following two lines of code:

@echo off
php %~dp0\drush.phar %*

This file is executed by the command drush since it is in your PATH and will then execute the proper php command passing the correct parameters. You'll then be able to run drush from anywhere on your computer.


How can I change the precision of a field used in a field collection or content type? I have a decimal field (ie field_testing) with precision = 10 and scale = 8.  I need to change the precision to 11.  I was planning on writing a migration script that does the following:

Update field_config row with field_name = 'field_testing' -- set the 'precision' field to 11.
Alter the field_testing table structure to adjust the precision of the 'field_testing_value' field to 11.

Few questions related to this:

Given that I run this while in maintenance mode, is this safe to do?
Is there anything else I need to do?  The default values is and will still be blank, so changes need to go into field_config_instance, I think.

Thanks,
Larry

Larry,
On the Drupal side, those are the only changes you need to make, the field_config_instance table doesn't track the data specifications. Just don't forget to clear the cache_field table, and the MySQL tables themselves too.


How do I programmatically assign the access to a block? I have created a block programmatically but I don't know how I can programmatically assign the access to it. How can I achieve it?

Setting the "roles" array in the array returned from hook_block_info() doesn't work because:

The roles that are allowed to see a block, and which are set in the user interface, are saved from block_admin_configure_submit() in the "block_role" table

$query = db_insert('block_role')->fields(array('rid', 'module', 'delta'));
foreach (array_filter($form_state['values']['roles']) as $rid) {
  $query->values(array(
    'rid' => $rid,
    'module' => $form_state['values']['module'],
    'delta' => $form_state['values']['delta'],
  ));
}
$query->execute();

The code that decides which blocks should be shown to the currently logged-in user is contained in block_block_list_alter(), which is an implementation of hook_block_list_alter(), and uses only the content of that table

$result = db_query('SELECT module, delta, rid FROM {block_role}');
foreach ($result as $record) {
  $block_roles[$record->module][$record->delta][] = $record->rid;
}

foreach ($blocks as $key => $block) {
  if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
    // This block was added by a contrib module, leave it in the list.
    continue;
  }

  // If a block has no roles associated, it is displayed for every role.
  // For blocks with roles associated, if none of the user's roles matches
  // the settings from this block, remove it from the block list.
  if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
    // No match.
    unset($blocks[$key]);
    continue;
  }

  // …

}

There isn't another Drupal function that checks the roles property in the data returned from hook_block_info(), nor is the content of the "block_role" table merged with what returned from the hook_block_info() implementations.

You could verify the user has the required role to see the block in hook_block_view(), but at that point Drupal is already rendering the block; that means the user would still see the block title, if one has been already set.

What you can do is implementing hook_block_list_alter() to remove the information about that block when the user doesn't have the required role.
To avoid confusion to the users who administer the blocks, I would also alter the form used to edit a block, and disable the form field used to set which roles can see that block, since the module implementing it is going to use its own list of roles; the minimal code should at least show a message about the role settings not having any effect, but I would also disable the form elements for the role settings.

Since the Block module already shows form fields to select which roles see a block, you could also simply set a default for your block, and let the administrator users change it if necessary.

As per checking the roles a user has versus checking the permissions a user has, the last is preferred, especially when the alternative would be hard-coding a list of roles in a module.
As shown from the Block module, using permission is not the only alternative: A module could have setting for deciding which roles are allowed to see something.
Clearly, it is not always worth having a setting for which roles are allowed to do something. I imagine also what for the administrator users would mean if 10 modules would have their own settings for which roles are allowed to do something, instead of using permissions, and allowing the administrator users to use a single page to set them.


Multiple Relations and Contextual Filters in a Translated View I have a View designed to filter down translated content (of type "Asks, Actions, and Updates") using three arguments:
1) country
2) year
3) month.

I have translated the content type and content, all three vocabularies and terms, and the View.

I want the URL to be readable, so the View has a relationship to the three vocabularies. I also have four "Translation language" filters, one for the content, which is being shown, and one each for the three vocabularies.

I also have three contextual filters that use the taxonomy "Name" and filter correctly in English with the following
contextual filters entered into the preview:

burkina-faso/2018/july

However, for some reason, the contextual filters do not work for French with these parameters:

burkina-faso/2018/juillet

Interestingly, the following does work

burkina-faso/2018/all

but when the last argument is 'juillet' (which is the French translation), it acts as through the name does not validate (no query shows in the preview section).

Why is this happening, and what can I do to have these filters work in both languages?

Here are images of the set-up of the third contextual filter:

Not sure if there's anything else that could be configured.

Something you could consider is using something like hook_views_pre_view(). Internally then you can check the language of the site for that request, read the values of the month, and using a table, translate internally juillet to july.

hook_views_pre_view() - https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/function/hook_views_pre_view/8.6.x


Payment Gateway integration on selecting user profiles I am working on a project where human resource agents can view a list of job applicants. On each job applicant profiles theres a Confirm job applicant link visible only to human resource agents.
Once the HR agent clicks on Confirm job applicant link, the control should go to a payment gateway and after the HR successfully does the payment, the job applicant should get confirmed by that HR agent.

I was thinking to use ubercart module to handle all the payment transaction, but is ubercart the best choice for this type of workflow as theres no product shopping cart model here.

Is there any other module which can be used for the above workflow?

Drupal Commerce would probably be a better choice. I've used it on two non-standard ecommerce systems and it works well. It's very flexible and the rules integration would allow you to do things like comfirm and email applicant on order completion.


How to add the configuration changes from a website to another website? This is what I'm trying to do:

I have a website A where I make configuration changes and add other stuff. Now I create a website B. I would like to add the configuration changes from website A to this website.

I know the UUID of both websites have to be the same (like staging & production environment). In "How can I import the configuration on a different site?" they explain how to do this with drush cget system.site.

The problem is when I run drush cget system.site in my website A I get the following drush error:

  Command config-get needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.                                                               [error]
  The drush command 'cget system.site' could not be executed.                                                                                [error]
  Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
  Hint: This may occur when Drush is trying to:
   * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter
  on the command line. See drush topic docs-aliases for details.
   * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  8.0.0-rc1
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  root
 Database name          :  s_1
 PHP executable         :  /Applications/MAMP/bin/php/php5.5.10/bin//php
 PHP configuration      :  /Applications/MAMP/bin/php/php5.5.10/conf/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /Users/myname/.composer/vendor/drush/drush/drush.php
 Drush version          :  8.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/MAMP/htdocs/s1
 Site path              :  sites/default
 Sync config path       :  sites/default/files/config_bZM1aJhLcWGpFZJEzfEw_pKF4g71jOdkSRti30k540BAwE9GQ4U6p469a9VxyJS4j4JVfC58qg/sync

I've installed the latest version of drush .. . I'm working with the release candidate of Drupal 8. Is there another way to get my UUID? Or do you have a tutorial or a video/blogpost of somebody who already did this?

UPDATE:

Ok, I was able to retrieve the UUID from website A and changed the UUID in website B so they have the equal UUID.

After that I changed the system site slogan of website A.

Then I did an export of the configuration in website A. But when I tried to import it in website B I got 137 new files to sync .. . The UUID is different in all files like this:

When I tried to synchronize I got the following error:

There was a discussion in the Drush issue queue on allowing config-import to force the adoption of the UUIDs in the imported configuration to be inserted into the database.  The problem with allowing this is that this operation is equivalent to deleting all of your configuration (e.g. all of your content types) and then re-creating them, which has the side-effect of deleting all of the data associated with that configuration (e.g. all of the pages in your site).  It was thought that erasing a site entirely was too surprising of a side-effect for a config-import operation, even with a --force flag, so this use case will not be supported.

The current thinking is that the right time to force the UUIDs of a site to change would be at site-install time.  At the moment, the Drush site-install command does not support this directly; however, there is a configuration import installation profile that Alex Pott wrote that will perform this function.  It should be possible to use this from Drush site-install.

In general, though, if your use-case is moving configuration from one site to a different site, you should use features, not the configuration system.


Load id of paragraph in hook_preprocess_layout using load($id) method I want to load the paragraph id in theme preprocess.

function theme_preprocess_layout(&$variables) {
  $ID = $variables['content']['#paragraph'] ???; "contents - protected 'id' => array(1) = 68"
  $variables['attributes'] = new Drupal\Core\Template\Attribute($variables['attributes']);
  $variables['attributes']->addClass($ID);}

It gives me the available method "load($id)" but I don't know how to implement this method.

Thanks to Beau for the help.
The method is simply

$ID = $variables['content']['#paragraph']->id();


Tried to create a custom page template for my home page and now get a 404 error I'm new to Drupal so I may have done something horribly wrong.

Using Drupal 7.

I tried to create a custom home page by using the Page builder. I created a page template and assigned it to be used as the home page. Then decided against and deleted the template.

Now I get a 404 response when I go to my home page. The rest of the site works and shows all the pages. I tried clearing the cache but no luck.

Andy help or ideas would be greatly appreciated. Thank you

I figured out the answer. I needed to install the Panels module so that I could use it as a variant. And that allowed me to set my home page template the way I needed it to be. Sorry for any confusion I may have caused with my question. And thanks for the help!


How woud you plan a sector directory with Drupal? I have to realize a sector directory, a directory of restaurants, bars, wineyardsm, carpenter...

So each sector has it's own properties like the menu card or something else. But there are properties like the name, address, telephone number etc. which are the same in for each sector.

I thougt to realize it so: 1 node type: Business (Fields: title, address, city, telephone number...); for each sector one content type with the special fields like the menu card or the wine list; to connect these two nodes i thougt to use the Relation module

What do you think of my plan? Is it used to do it like this or are there other solutions? One problem of my plan would be the backend. I have to edit/create two nodes for one business. For the normal user it would be too complicate. Is there a way to edit the connected node on the same page?

Thanks

Reference entity http://drupal.org/project/entityreference will let you make all the relations you need.

Also, instead of use node I will create my own entities (http://www.istos.it/blog/drupal/drupal-entities-part-1-moving-beyond-nodes) and all the connections with views.

And remember that taxonomies also are Entities, so you can create a Vocabulary that it's "Sector", and every Sector add all the fields you need.

It'll harder but it'll improve the performance.

Oskar


How to update taxonomy term of a node using services I have created a new node using Services 3 module successfully, the code is below

{

 "type":"page",
"title":"New test page",
"taxonomy": {
       "tid" :"367928"
      }

}

Configuration:

Drupal version = 6.26,

url = serviceurl/node,

App = Postman application in chrome,

Method = POST,

data = json.

But when i tried to edit the taxonomy term of the node using same format as below , its not working

url = serviceurl/node/node-id,

Method = PUT,

data = json.

{

"type":"page",
"title":"New updated title of the Page",
"taxonomy": {
       "tid" :"367930"
      }
}

When I checked the node, the title is getting updated where as the taxonomy term remains the same.
I searched a lot on the net, but could not find any solution. Can anyone please help to fix this issue.

I think your JSON format to create node is wrong. Please check the created node. I guess it creates node but with empty taxonomy field.

The correct format to create a node having taxonomy term is like follows.

Assuming that your 'widget type' for 'term reference field' is 'Select list' or 'Check boxes/radio buttons'

{
    "title": "my title",
    "type": "page",
    "field_mynodeterm": {
        "und": "3"
    }
}

here field_mynodeterm is machine name of your 'Term reference field' (which is used in content type).

Similarly you can use the same format to update the node

{
    "title": "my updated title",
    "type": "page",
    "field_mynodeterm": {
        "und": "5"
    }
}

If you use 'Autocomplete term widget (tagging)' as widget type for term reference field, the JSON format would be the following

{
    "title": "my updated title",
    "type": "page",
    "field_mynodeterm": {
        "und": "termname"
    }
}

I tested the above scenarios and working fine. Hope this helps.


Unable to filter Views by a date field in the user profile I have used the Profile module to create a date field on users profiles.

Now I want a view to list users filtering by that date field, but when I choose "Add filter criteria" in the Views UI, it does not list the date field. Fields of other types show up normally.

Is this a Views bug? How can I filter a view based on a date field from user profiles?

To create a view about Users, you start from admin/structure/views/add (of course).

However, below "Description" you need to select what type of data you want to "Show", and then optionally also select a "Type", etc).

By default (when you start creating a new view) it will suggest "Content" as value for "Show". But in your case you should have selected "Users" instead. If you do select "Users", you won't be able to select a "type" anymore. Because of the "... Fields of other types show up normally ..."
in your question I assume you used the default (Content) instead of "Users".

That's possibly the reason why you can't select the user related fields either ... To resolve this, just create a new view about "Users".


Project directory in Ubuntu I am trying to get Drupal 8 installed on Ubuntu 18.04. I have installed LAMP and composer. I will install Drupal 8 with this (I think this is the latest recommended way) ...

composer create-project drupal/recommended-project my_site_name_dir

Where should my_site_name_dir be?

Some guides suggest it should be at apache2's web directory: /var/www/html/my_site_name_dir. And then change the directory owner to www-data (for apaches benefit?). But how then does Composer or myself write files to this directory if the owner is changed?

This guide Using Composer to Install Drupal says:

  Your 'my_site_name_dir' will contain files that should be outside of
  your web root and not  accessible by the web server. The web root will
  be 'my_site_name_dir/web'

So am I right in thinking that my_site_name_dir should not be visible by apache, but my_site_name_dir/web should be? If so how to I tell apache to find it?

I was imaging that my_site_name_dir would be somewhere in my home directory (easier for dealing with file permissions?) and I would view it in a browser with something like: http://localhost/my_site_name_dir

(I'm struggling a bit trying to grasp file ownership and how composer works.)

It all depends on whether your Ubuntu 18.04 machine is intended for use as a local workstation or a web server exposed to the Internet.

If it's your local workstation, you should absolutely just make a subdirectory in your home directory.

I like to keep my projects in ~/repos/clientname/projectname/ directories. I call the directory repos because I recommend always keeping your project in a local git repository and pushing all your changes to a private repository on github/gitlab/bitbucket or wherever. That way you can always pick up work on a new computer if yours crashes.

Your local workstation is probably not (indeed, hopefully not!) the server where you will expose your Drupal site to the Internet. You want a local copy that you can break and fix a dozen times a day without taking the real site offline.

Then, you want a way to serve that to yourself on localhost. Check out my other answer here to see one way of serving the files locally. I recommend Lando for newbies because it manages a lot of the complexity for you, providing Docker containers for web server, database server and other services as needed. And you can easily free up system resources with lando stop and switch to another project with lando start. See my linked answer for more details.

Then you can worry about deploying the site to a production server ... ideally, multiple environments for Dev, Stage (Test), and Prod (Live) environments.

There are many ways to approach this depending on your hosting. Just take things one step at a time, start with local development and work your way up to DevOps concepts like automated testing and deployment.

If your Ubuntu 18.04 installation is intended to be a web server, then you'll want to install a complete LAMP stack and set up the directories as @pinueve suggests in his answer.

There is also a middle ground. You can test deploying your site from the local dev instance in your home directory to the local Apache server, but just be aware that you can run into port conflicts between your Ubuntu host's Apache server and the Docker guest's Apache server if you try to start both at once. This can be mitigated by changing your default Apache ports.

Edit the VirtualHost entries in /etc/apache2/sites-available/000-default.conf and change port 80 to something like port 8080:

<VirtualHost *:8080>

If you do this, you can browse the host machine's Apache on http://localhost:8080 and you will still be able to start and stop your Docker containers with Lando.


What is the best way to show category by image? I have a online store with commerce module .
I have a category/taxonomylike this :

Writing Product

pen
pencil

Art Product

paper
something

All i want is to show writing product sub category in a page with image.
i've added image field to taxonomy and create a views from taxonomy .

How can i get sub category (image field) from views ?
Thx

In you view change the Format section to show fields and after that add the image field from your taxonomy, then add the filter Taxonomy term: Parent term


Node access doesn't consider translation I'm trying to check user access to node via this code:

 $node = Node::load($node_id);
 User::load(\Drupal::currentUser()->id());
 $node->access('view', $account)

It seems it doesn't check if user has access to node translation or not and it check only for first language of node -when we create node for first time.

For example if node is created in English as published and later in french as unpublished node access returns which user has access.
If I update English language to unpublished and french to published, node->access returns false;

So node_access doesn't consider translation? How we can check for translations too?

You can just call getTranslation like this:

$node_translation = $node->getTranslation('LANGCODE');


How is Drupal Planet realised? How is the Drupal Planet realised?
I found the Planet installation profile, but it seems to be dead (the Git instructions tab is empty).

Drupal planet is built upon the core aggregator module, blogs are required to set up a special feed (generally tagging it drupal-planet) to be imported in the list.

That should be pretty simple to reproduce: What is Planet Drupal and how do I get added?


How to fix Drupal commons 7.x-3 OgException Problem is fixed in new version commons 7.x-3.3-rc4
https://drupal.org/node/2067473

Modules:

Organic groups 7.x.2.3
Organic groups access control  7.x.2.3

The content access permissions have been rebuilt.

In OG field settings (as default)
User-User entity
Group visibility Determine access to the group
Group            Determine if this should be a group

I created a Private group with "Joining requires an invitation"
trying to add a post to the group I get following exception:

  OgException: Cannot set visibility of node ID 13 as the group node of
  type "user"  does not have the "Group visibility" field attached to
  it.  in _og_access_verify_access_field_existence()  (line 250 of
  srv/www/htdocs/commons7x33rc2/profiles/commons/modules/contrib/og/og_access/og_access.module).

The same happens with a Public group with "Any site member can contribute"

What is wrong and how do I fix this?

A bit too late maybe but...

...check answer #8 at Organic Groups issues place: https://drupal.org/node/2063479#comment-7882345

I've followed it and solved (at least apparently) the issue.

Hope it helps. Have a nice day!
hip


How to use downloaded images, for specific field? I have dropdown list with 2 options.
First one is to upload image, where I use image upload field and imagecashe for re-sizing uploaded image.
And Second option is to get picture from other site.

If user choose to get picture from other site, i don't know how to use downloaded image.

I downloaded image using following code

$managed = TRUE;
$path = system_retrieve_file($image, 'public://down_images/', $managed);

When this image is downloaded I want to use it as logo. Logo is image field which is added to user account.

How can I do that?

You need to get the file fid; you can use EntityFieldQuery.
Then insert/update the "file_managed" table, using code similar to the following one:

db_update('file_usage')
  ->fields(array('id' => $user->uid,))
  ->condition('fid', $file->fid)
  ->execute();


post-save case in node api? Is there such thing as a post-save type of case in the node_api function or any other type of function? This question is in reference to a question I posted What operation should I use to write node's information in an email when the node is saved?

I want to be able to have something happen after pressing the save button, but AFTER the saving into the database has been completed. I have tried 'update' and 'insert' and they don't seem to work.

EDIT: heres my code

case 'presave':
    {
        if(($node->type == 'team_practice_info') | ($node->type == 'schedule'))
        {

            if(!empty($node->field_alert[0]['value']))
            {
                if($node->field_alert[0]['value'] == 'on')
                {
                    //email out to everyone an email about the content change/update
                    $query = db_query("SELECT *
                                       FROM {content_type_athletics_alert}
                                       JOIN {content_field_team}
                                       ON content_type_athletics_alert.nid = content_field_team.nid
                                       WHERE content_field_team.field_team_nid =
                                            (SELECT field_team_nid
                                             FROM {node}
                                             JOIN {content_field_team}
                                             ON node.nid = content_field_team.nid
                                             WHERE node.nid = %d)", $node->nid);
                    $rows = array();
                    //db_fetch returns an array of the next row in the query
                    while ($row = db_fetch_array($query))
                    {
                        //pull out the email from the array, then send an email to each subscriber
                        $email = $row['field_email_address_value'];
                        $first_name = $row['field_first_name_value'];
                        $last_name = $row['field_last_name_value'];
                        $t_id = $row['field_team_nid'];
                        $t=node_load($t_id);
                        $sport = (current($t->taxonomy));
                        $team = $t->title.' '.$sport->name;

                        alert_message_mail_send($email, $first_name, $last_name, $team, $node);
                    }
                    //reset the alert checkbox to off
                    $node->field_alert[0]['value'] = 'off';
                }
            }
        }
    }

   break;

If you are having trouble with hook_nodeapi (though I have never had problems with it), you could try using Rules.

There is a stock event After saving new content that you can try.  There is also a stock DO action, Send a mail to a user.  You then get the normalish token-based email form that you can configure.

We have used this on few projects with good luck.


Why I cannot get translated entities I wrote service to get all necessary data for my page. Now I wanted to load them with translations. But whey I try, I got error:

  InvalidArgumentException: Invalid translation language (id of language here) specified.

When I open page in default language it works fine. Does it mean that I need to translate all of the things in order to make it work?

My service:

namespace service;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use entity\Entity;

class PostTypeService
{
    public static function getEntititiesByPostType($postType, $entities = array(), $nid = NULL)
    {

        if ($nid != NULL) {
            $nids = \Drupal::entityQuery('node')
                ->condition('type', $postType)
                ->condition('status', 1)
                ->condition('nid', $nid)
                ->execute();
        } else {
            $nids = \Drupal::entityQuery('node')
                ->condition('type', $postType)
                ->condition('status', 1)
                ->execute();

        }

        $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
        $returnValues = array();
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        foreach ($nodes as $index => $node) {
            foreach ($entities as $entity) {
                $type = $entity->type;
                $entity_name = $entity->entity;
                if ($type == 'image') {
                    $returnValues[$postType][$index][$entity->entity] = file_create_url($node->$entity_name->entity->getFileUri());
                } else if ($type == 'url') {
                    $returnValues[$postType][$index][$entity->entity . '_uri'] = $node->$entity_name->uri;
                    $returnValues[$postType][$index][$entity->entity . '_title'] = $node->$entity_name->title;
                } else if ($type == 'list') {
                    foreach ($node->$entity_name as $list_item) {
                        $returnValues[$postType][$index][$entity->entity][] = $list_item->value;
                    }
                } else {
                    $translation = $node->getTranslation($language);
                    $returnValues[$postType][$index][$entity->entity] = $translation->$entity_name->$type;
                }
            }
            $returnValues[$postType][$index]['node_id'] = $index;
            $options = array('absolute' => TRUE);
            $url = Url::fromRoute('entity.node.canonical', ['node' => $index], $options)->toString();
            $returnValues[$postType][$index]['node_url'] = $url;
            $returnValues[$postType][$index]['lang'] = $language;
        }
        return $returnValues;
    }

This solves the problem:

namespace service;

use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use entity\Entity;

class PostTypeService
{
    public static function getEntititiesByPostType($postType, $entities = array(), $nid = NULL)
    {

        if ($nid != NULL) {
            $nids = \Drupal::entityQuery('node')
                ->condition('type', $postType)
                ->condition('status', 1)
                ->condition('nid', $nid)
                ->execute();
        } else {
            $nids = \Drupal::entityQuery('node')
                ->condition('type', $postType)
                ->condition('status', 1)
                ->execute();

        }

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

        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $defaultLang = \Drupal::languageManager()->getDefaultLanguage()->getId();

        $returnValues = array();
        foreach ($nodes as $index => $node) {

            if (!array_key_exists($language, $node->getTranslationLanguages())) {
                $translation = $node->getTranslation($defaultLang);
            } else {
                $translation = $node->getTranslation($language);
            }

            foreach ($entities as $entity) {
                $type = $entity->type;
                $entity_name = $entity->entity;
                if ($type == 'image') {
                    $returnValues[$postType][$index][$entity->entity] = file_create_url($translation->$entity_name->entity->getFileUri());
                } else if ($type == 'url') {
                    $returnValues[$postType][$index][$entity->entity . '_uri'] = $translation->$entity_name->uri;
                    $returnValues[$postType][$index][$entity->entity . '_title'] = $translation->$entity_name->title;
                } else if ($type == 'list') {
                    foreach ($translation->$entity_name as $list_item) {
                        $returnValues[$postType][$index][$entity->entity][] = $list_item->value;
                    }
                } else {
                    $returnValues[$postType][$index][$entity->entity] = $translation->$entity_name->$type;
                }
            }
            $returnValues[$postType][$index]['node_id'] = $index;
            $options = array('absolute' => TRUE);
            $url = Url::fromRoute('entity.node.canonical', ['node' => $index], $options)->toString();
            $returnValues[$postType][$index]['node_url'] = $url;
            $returnValues[$postType][$index]['lang'] = $language;
        }
        return $returnValues;
    }
}


How do I create an ajax link? I want to create an ajax linking a view (front page, for example).
I create an ajax edit link to edit content directely in the node. I success to add a link but when i click to it, a popin was opened(to edit content).
I know how to make it in Drupal 7, but I don't find the solution for Drupal 8.

This is the code I am using.

    $build['ajax_edit_link'] = array(
    '#theme' => 'links',
    '#weight' => -2,
    '#links' => array(
      'ajax_edit_link' => array(
        'title' => t('Edit'),
        'url' => $entity->urlInfo('edit-form'),
        'attributes' => array(
          'class' => array('use-ajax'),
          'data-dialog-type' => 'dialog',
          'data-dialog-options' => Json::encode(array(
            'width' => 1200,
            'height' => 500,
          ))
        ),
      ),
    ),
  );

Here is all captures of the result of this edit ajax link in Drupal 8 (popin).

And here are the capture I want to make in Drupal 8 (Capture in Drupal 7 site).

Your code is missing one part that I can see, the #attached key:

  $build['ajax_edit_link'] = array(
    '#theme' => 'links',
    '#weight' => -2,
    '#links' => array(
      'ajax_edit_link' => array(
        'title' => t('Edit'),
        'url' => $entity->urlInfo('edit-form'),
        'attributes' => array(
          'class' => array('use-ajax'),
          'data-dialog-type' => 'dialog'
          'data-dialog-options' => Json::encode(array(
            'width' => 1200,
            'height' => 500,
          ))
        ),
      ),
    ),
    '#attached' => array('library' => array('core/drupal.ajax')),
  );


Add cck field as scoring factor to drupal standard search So, by default there are four scoring factors in drupal:

relevance of keyword
recency
number of comments
number of page views

I'd like to be able, to control relevance of specific cck-fields.
In my case, i've got a cck field (computed field), where all relevant search-data is getting summed up.

I'd like to be able to give this special field a higher relevancy to the search results than anything else.

Is there a possibility to do this?

Implement hook_update_index in a way that calls search_index. The source code of search_index tells you how the $text argument is analyzed. From a quick look at the source, I would wrap the field content in <h1> tags. Not that the string only applies to searching, not to rendering. So it does not need to represent the actual structure of the node.


How can I configure the Mail System module to use Swift Mailer for registration emails? This seems like it should be straightforward, but I haven't had success theming the default registration emails on my site. I am able to see the themed email (just using swiftmailer.html.twig in my theme) when I send a test email via the Swift Mailer UI, but using Swift Mailer for my formatter and sender in the default mail system config in the Mail System UI and using my theme to render the emails, I'm still not getting the themed registration emails as I would expect. I must be missing something simple, but I've tried all sorts of combinations without luck.

The trick was to make sure the 'Respect provided e-mail format' option is unchecked in the message settings. Then I added a plugin to force HTML output for these email, as per this suggestion and used that for my Formatter and Sender in the mail system settings.


how to add a class to the widget pager of views slideshow I want to add a class to the widget pager of views slideshow. I found the function in the file /theme/views_slideshow.theme.inc wich theme the wrapper of the widget

function theme_views_slideshow_pager_widget_render($vars) {
  // Add javascript settings for the pager type.
  $js_vars = array(
    'viewsSlideshowPager' => array(
      $vars['vss_id'] => array(
        $vars['location'] => array(
          'type' => preg_replace('/_(.?)/e', "strtoupper('$1')", $vars['settings']['type']),
        ),
      ),
    ),
  );

  drupal_add_js($js_vars, 'setting');

  // Create some attributes
  $attributes['class'] = 'widget_pager widget_pager_' . $vars['location'];
  $attributes['id'] = 'widget_pager_' . $vars['location'] . '_' . $vars['vss_id'];
  return theme($vars['settings']['type'], array('vss_id' => $vars['vss_id'], 'view' => $vars['view'], 'settings' => $vars['settings'], 'location' => $vars['location'], 'attributes' => $attributes));
}

I just want to modify the line to add my own class (as grid-6 for example)

$attributes['class'] = 'widget_pager widget_pager_' . $vars['location'];

I try to use this function in my file template.php without success.

the classes of the wigdet pager in my html code are :

views-slideshow-pager-fields widget_pager widget_pager_bottom views_slideshow_pager_field views-slideshow-pager-field-processed

So i imagine that an other function add the classes. But wich ?

How can i do this ? May i write a module or simply use a preprocess function in my template.php

Thanks

In fact, after looking at the HTML code generated by views slideshow, pager widget is contained in a div on the same level that the content of the slideshow. So even if I could add a class, it would not be useful because I already positioned text to the right of my image. So the div content of the slideshow is already 100% of the width (and the sub-content have already custom classes to position them in line) .

So I have to use position: absolute to position the pager widget, so I can just add my classes on the container of all global gadgets (positioned at the bottom) by overriding the template views-slideshow.tpl.php as below, and then use the default classes of the widget in my css.

views-slideshow--MY-BANNER.tpl.php

<div class="skin-<?php print $skin; ?>">
  <?php if (!empty($top_widget_rendered)): ?>

      <?php print $top_widget_rendered; ?>

  <?php endif; ?>

  <?php print $slideshow; ?>

  <?php if (!empty($bottom_widget_rendered)): ?>

      <?php print $bottom_widget_rendered; ?>

  <?php endif; ?>

But I'd like to know if this is possible and with wich function.


Getting information from database and giving it to javascript The main thing I want to achieve is that my module makes a google map with markers.

For now im doing this:

drupal_add_js('https://maps.googleapis.com/maps/api/js?key=AIzaSyDcl28Qcn9GTi02rRtQaLgVS4GWZbGcQ8E', 'external');

$locations = db_query('SELECT * FROM {locations}')->execute();

$script = '
';

$html = '

';

return array('#markup' => $script.$html);

As you can see in the third line of code im trying to get information from the database that I have saved. The problem is I dont know how would i get it properly. And then I want to pass it down in the var locations part in the script..

I have tried finding some tutorials where they explain how would this work but most of them is just how to show some posts or somthing like that and that doesnt help me.

Thanks for help already! :)

// EDIT

This is the script that i have now in js file

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

          function initialize() {

          var mapOptions = {
             center: { lat: 56.9714744, lng: 24.1291624},
             zoom: 9
          };
          var map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);

    var locations = [
                    ['Mājas',56.956344, 24.197409],
                    ['Domina',56.966058, 24.162004]
                    ];

    for (var i = 0; i < locations.length; i++) {

      var loc = new google.maps.LatLng(locations[i][1], locations[i][2]);

      var marker = new google.maps.Marker({
        position: loc,
        map: map,
        title: locations[i][0]
      });
    };

  }

  //google.maps.event.addDomListener(window, 'load', initialize);

}

}
 )(jQuery);

I have the "google.maps.event.addDomListener(window, 'load', initialize);" commented becouse I think i dont need it..? And becouse there is no function initialize anymore? Or should i add that back?

The problem now is that my script seems to be added.. But it doesnt seem to be run becouse the google map dosnt show up..

You should never need to build javascript with PHP, there's just no need (especially in Drupal, which already has a mechanism).

What you should do instead is put your JS in an external file, then use Drupal's JS settings to pass the data. So the JS file might look like:

(function($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      var locations = Drupal.settings.myModule.locations;
      // Do something with the locations var.
    }
  }
)(jQuery);

And in your page callback or whatever:

$settings['myModule']['location'] = db_query('SELECT * FROM {locations}')->fetchAll();
drupal_add_js($settings, 'setting');


Unpublished taxonomy term keep showing in main menu and contextual filter I'am creating a Drupal 8 multilingual side, i have a main menu and a contextual filter that uses taxonomy term. in english version i wont translate all those taxonomy, so i dont want theim to be displayed on the menu neither on the contextual filter.

i've tried to uncheck the button "this translation is published" for the translation but the taxo keep showning on the site :/

Any help please?

It is my understanding the Drupal’s multilingual will fall back to the default language, meaning that if a translation is not available, the asset will be shown or rendered in the default language. I don’t think there is a workaround for that.


Drupal 7 .htaccess redirects I'm trying to redirect some old urls to the new Drupal ones with .htaccess rules.

This works

Redirect 301 /oldurl http://mysite.com/new-url

But this gives me a Drupal error

Redirect /people/details.aspx?id=1234 http://mysite.com/name-surname

Is it possible to perform a redirect like this?

The errors I get are

Warning: array_flip() expects parameter 1 to be array, string given in DrupalDefaultEntityController->load() (line 178 of /var/www/includes/entity.inc).

Warning: Invalid argument supplied for foreach() in DatabaseCondition->compile() (line 1854 of /var/www/includes/database/query.inc).

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 2: SELECT revision.vid AS vid, base.uid AS uid, revision.title AS title, revision.log AS log, revision.status AS status, revision.comment AS comment, revision.promote AS promote, revision.sticky AS sticky, base.nid AS nid, base.type AS type, base.language AS language, base.created AS created, base.changed AS changed, base.tnid AS tnid, base.translate AS translate, revision.timestamp AS revision_timestamp, revision.uid AS revision_uid FROM {node} base INNER JOIN {node_revision} revision ON revision.vid = base.vid WHERE (base.nid IN ()) ; Array ( ) in DrupalDefaultEntityController->load() (line 196 of /var/www/includes/entity.inc).

My new rules begin before the Drupal rules of

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

As suggested I have tried redirecting to non clean URLS. This works

Redirect 301 /oldurl http://mysite.com/?q=new-url

But the URL stays as that which isn't any good as there will then be duplicate URLs of http://mysite.com/?q=new-url http://mysite.com/new-url

I tried

Redirect 301 /people/details.aspx?id=1234 http://mysite.com/?q=name-surname

But I still get the same errors as before

I've experienced that in Drupal 7 you must not rewrite to a clean URL destination, even if you have clean URLs enabled.

(This is possibly a duplicate of: Rewrite URL not working.)


How do I alter a way node is rendered so I can add custom links/buttons? Sometimes I want to add custom links/buttons specific to a content type to a node when the page for that node is rendered, how would you achieve this when you write a module? An example code to achieve this by adding hello world link somewhere in the page when a node is rendered would be appreciated as the lack of documentation I can find for this is discouraging.

The easiest way to do this would be to use Content Templates!

Using this module you can have some fine-grained control over how templates and individual fields are displayed without actually creating a new .tpl.php file for that node (which is another pretty good much more laborious solution)


CCK Nodereference individual imagefields Is there a way to use a nodereference field on each individual image in a node? The images are CCK imagefields.

I don't think so, no. A node reference as its name suggests references an entire node. I've not heard of a CCK type that references another CCK field, though I could find a reference to a module that did that for D5. If that's your requirement, my recommendation would be to use an image-as-node method.


Migrating a forum created with Advanced Forum 1.x branch from Drupal 6 to a Drupal 7 site running Advanced Forum 2.x branch? What's the best way to do it? What module(s) should I use to export the data from the Drupal 6 site and import the data into Drupal 7 and what do I need to think about regarding the different branches? Please also describe the process if you have experience with it.

First, upgrade the site to Advanced Forum 6.2.x, then, after everything is correct, migrate to D7.

The upgrade to 6.2.x should be relatively smooth (there were no problems in my experience).

You might have to have several tries for the D6->D7 migation, depending on your site configuration. Always do it in a separate installation, and back up everything, step by step. If something does not go right, this will allow you to reset the site to a point where you can restart a step, rather than going back to a fresh install and starting from scratch.

Follow the Upgrading from previous versions on D.O. to the letter.


How do I get a textarea form field to use a full HTML WYSIWYG editor? I have configuration form for a custom module.

namespace Drupal\amu_http_status_code_display\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class AmuHttpStatusCodeDisplayConfigForm extends ConfigFormBase {

  public function getFormId() {
    return 'AmuHttpStatusCodeDisplayConfigForm';
  }

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

    $config = $this->config('amustatuscode.settings');
    $form = parent::buildForm($form, $form_state);

    $form['404_message'] = array(
      '#type' => 'textarea',
      '#title' => t('404 error message'),
      '#description' => t('error 404 message.'),
      '#default_value' => '404 error',
    );

    $form['403_message'] = array(
      '#type' => 'textarea',
      '#title' => t('403 error message'),
      '#description' => t('error 403 message.'),
      '#default_value' => '403 error',
    );

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('amustatuscode.settings');
    $config->set('404_message', $form_state->getValue('404_message'));
    $config->set('403_message', $form_state->getValue('403_message'));
    $config->save();

    return parent::submitForm($form, $form_state);
  }

  public function getEditableConfigNames() {
    return ['amustatuscode.settings'];
  }

}

How can I make the form field I add use a WYSIWYG editor?

You want to use the TextFormat form element: https://api.drupal.org/api/drupal/core%21modules%21filter%21src%21Element%21TextFormat.php/class/TextFormat/8.4.x

Note that this will give you a value and a format in a nested form structure, you need to store both (or lock to a specific format) and then render the content with that format to avoid security issues.


Contextual view that limits results? This is a hard one to explain, so thanks for taking a look.  I've created a menu in views of all the nodes associated with a particular taxonomy term.  The problem is that some of these nodes have children associated with them that I do not want to show in the views menu.  BUT, they should still display the menu.

  Node 1
  Node 2
  - (child) Node 2a
  - (child) Node 2b
  Node 3

In that example, the menu would show up on all 5 pages, but would only have 3 items in the menu.

I am able to make a menu of all the items associated with a term, but can't figure out how to add depth.  Any ideas?
-JB

A better understanding of contextual filters led me to a solution.  I used a contextual filter to limit which pages showed the menu, then used a filter to control the items.


Alter field (multiple values) to add more items/values of another field In my case, I use Drupal Commerce (Kickstart 2x distribution) with a images field (multiples/unlimited values).

I need to display all images of parent product AND images of their childrens (variations).

Another case are to display images of a field but if empty, I want to display images of another images field.

What's the good way for this?

Relation module
hook_field_load()
hook_query_alter()
hook_node_load()
hook_load()

Related questions:

How to create a single slideshow combining several image fields?

Here my current solution but I think it is better to use hook_preprocess_field()?

/**
 * Implements hook_node_load().
 */
function MY_MODULE_entity_load($entities, $type){
    if('commerce_product' === $type && !path_is_admin(current_path())){
        foreach($entities as $entity){
            if(in_array($entity->type, array('MY_PRODUCT_TYPE')) && property_exists($entity, 'sku') && !empty($entity->sku)){
                $query = new EntityFieldQuery;
                $query->entityCondition('entity_type', 'node', '=')
                  ->propertyCondition('type', $entity->type)
                  ->fieldCondition('field_product', 'product_id', $entity->product_id, '=')
                  ->range(0, 1);

                if ($result = $query->execute()) {
                    reset($result['node']);
                    $nid = key($result['node']);
                    $parent_product = node_load($result['node'][$nid]->nid);
                    $parent_product_images = field_get_items('node', $parent_product, 'MY_IMAGES_FIELD');
                    if (is_array($parent_product_images)) {
                        $pos = count($entity->field_images['und']);
                        foreach($parent_product_images as $ppi_field){
                            $entity->field_images['und'][$pos++] = $ppi_field;
                        }
                    }
                }
            }
        }
    }
}


Help with #text_format and field widgets I'm struggling with #type 'text_format' for a widget form field as this field gets expanded two separate elements, one holding the orignal element and the other the format selector. The orignal element is moved into a child element.

All of this is fine, but as the orignal field is now moved into a child when the widget form is saved is tries to save the child element (array). As the widgets fields have to be at the root of the form with names that match 1:1 with db columns.

From form.inc:

  If the property #text_format is set, the form element will be expanded into
  two separate form elements, one holding the content of the element, and the
  other holding the text format selector. The original element is shifted into
  a child element, but is otherwise unaltered, so that the format selector is
  at the same level as the text field which it affects.

I've looked at the text.module but I can't work out how it is getting around the issue of the field being expanded?

Good luck with that. What a head-scratching nightmare. See Missing hook_field_widget_form_submit()? for an idea of how to make this easier.

I got this to work once in a module, but then had to remove it for other reasons. The code is still there, look at this older version of flashcard.install and flashcard.module, especially flashcard_field_widget_form() and flashcard_field_formatter_view().


Delete permissions not working with Domain Access instaled I have a site with Domain Access module installed. I have created an Admin View, which lists types of content (exposed filter). My surprise is that a role, which is Editor (a kind of Authenticated user), and which in permissions has only Edit permissions for that kind of content, is able to Delete the node, when he/she would not be allowed according to the permissions. I have rebuilt permissions, and there appears the Delete link, and it also performs the deletion. How can I check it, maybe at low level database?

For some unknown reasons, I had this option checked under Permissions: Delete any content on assigned domains. Obviously, it overrided every other permission filtered by content type. Unchecking it, the "Delete" link only appeared on the Admin role, which is what I wanted.


How to set a field value from parent template in Twig? I have node--article--teaser.html.twig which calls image-formatter.html.twig to printout the field_image. Everything works fine except that I don't want the field_image itself to be a linked. i.e image-formatter.html.twig should not find a url to only print an img tag.

I have tried the following in node--article--teaser.html.twig:

{#{ content }#}
  {% set content.field_image[0]['#url'] = null %}{% endset %}
  {{ content.field_image }}
    {{ label }}

The second line causing the following error:

  Twig_Error_Syntax: Unexpected token "punctuation" of value "." ("end
  of statement block" expected) in
  "themes/saidbakr/templates/node--article--teaser.html.twig" at line
  78. in Twig_TokenStream->expect() (line 87 of vendor\twig\twig\lib\Twig\TokenStream.php).

While {{ content.field_image[0]['#url'] }} prints the url without any problems!

The image-formatter.html.twig code is as the following:

{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

There is no any suggestion from twig debug about any alternative template for image-formatter.html.twig

Also using Theme Hook image_formatter as saidbakr_preprocess_image_formatter will not be an option because it is not possible to know the view context, i.e teaser or full, or content types to restrict this interaction for articles type. I think that the most simple way is from Twig, but how?!

There should be no reason to change any code for this, as you are using the default image formatter. You should be able to remove the link by going to /admin/structure/types/manage/article/display/teaser and change your field's formatter settings using the cogwheel-button and then select "None" for "Link image to".

Should the teaser view mode configuration page not be available, got to /admin/structure/types/manage/article/display and activate its checkbox on the far bottom of the page, then save and try again.


Using clientside_validation project, default validation plugin message not being overridden for states dependent field I am currently using clientside_validation with clientside_validation_states to validate conditionally required fields.

The issue I am experiencing is when the conditionally required element is invalid (empty), it is showing the generic "This field is required" (from jQuery.validation defaults) instead of using a message that is typically seen (and shows on all other, non-conditionally required fields) - for example, "First Name field is required".

I am using a custom errorPlacement method, but I'm not sure that it matters:

    // custom error placement
    Drupal.clientsideValidation.prototype.replaceLabel = function (error, element)  {
      var label, origLabel;
      var wrapperClass = 'formReplacedLabel';
      var WrapperEl = 'span';
      label = element.siblings('label');
      if (label.find('.form-replaced-label').length === 0) {
        label.wrapInner("");
      }
      label.addClass('labelError');
      label.prepend(error);
    };

So, the error being passed (for the states dependent control) to the custom errorPlacement method is just the default $.validator.messages.required instead of what is passed for the other controls.  I can't just change .messages.required to something that is for this field specifically either, as I have several forms with state dependent fields.

I have attached an animated gif that I think can explain the issue better than I do.

Turns out this is a bug. The hot fix is to add the $message argument to the _clientside_validation_set_equal() call on clientside_validation_fapi.module. So that it looks like:
_clientside_validation_set_equal($name, $title, $params[0], $js_rules, $message);.

I've started an issue and submitted a patch https://drupal.org/node/2140163


View only displays nodes that has comments when adding comment count field On drupal 8 I am facing an issue with views.
I created a view listing all nodes of a certain content type.
I added basic fields, Title, Date content was created, and a read more link.
The view works fine with these fields, but when i add Comment Statistics: Comment count, all nodes that don't have any comment don't show up in the view.
It only lists nodes that received comments.

Any idea on how to fix this ? Am I doing something wrong ?

Thanks

I think it is you. Unable to re-produce. Here is a example view listing content nodes, two fields and the comments count.

I also exported the example view example view that you can import and test out for yourself.


How to display a view of products that are selectable I am working on a site that will capture site details by the sales reps. They will also use the site to order products for the customer and at the same time enter the installation criteria of the product by uploading photos and filling out text boxes.

The site will need to display all the products (50) in a table like views would on the page at once. The products will need to have a check box to select each product and a quantity to be entered. The products entered will need to be saved to the specific site that the sales rep has sold to.

In the screen shot I am using panels to layout the form. I have highlighted in red the image I am currently displaying with html in panels.

I have tried a few modules like Entity Reference / Views and Commerce but cannot find the best way to tackle this. Can anyone point me in the right direction.

Thanks.
Drupal 7.31

Screen Shot http://sitetrack.com.au/images/Screen_capture_1.PNG

Save a lot of head-scratching (not all though;) and use Drupal Commerce Custom Product:

https://www.drupal.org/project/commerce_custom_product

It's not that you can't do this with 'normal' Drupal, it's just that Commerce Custom Product is set up to do precisely what you want... so might as well use it!

HTH

Steve


How to get all group content from group? I am using OG, Flag and Rules module. I would like to do like this.

When a user click Flag links in Group (name is follow_group) then all group content of that group will be flagged as following.

For now, i'm stuck at getting all group content of specific group. Is there a way to get group content of current group?

All the contents are associated in og_membership table. If you can get the gid (group node id), then it will be easier to get the content associated with that group.

$og_contents = db_select('og_membership', 'ogm')
->fields('ogm', array('etid'))
->condition('ogm.gid', $gid, '=')
->condition('ogm.entity_type', 'node', '=')
->execute()
->fetchAll();


What security issues are involved with cross-domain logons using OpenID? I want to implement cross-domain logons for 3 sites. Is OpenID the best tool for protecting my site and users?

As far as I'm aware OpenID is reasonably secure. The downside to OpenID is that it's fairly complicated for non-technical users to understand. Something like this might make that a little easier on your users. There are options to make your site the OpenID provider, but they don't seem ready for production sites yet from a brief skim through the issues.

Another option might be OAuth. This would let your users log in with their accounts from sites like Facebook, Twitter and LinkedIn.

If all 3 sites are Drupal sites, one final solution might be to share the users between the sites, by sharing certain database tables. This would allow you to share other information about your users between the site profiles as well.

This page on Drupal.org describes the details, as well the downsides. Main one being that upgrades to major Drupal updates aren't supported. I honestly wouldn't recommend this unless you know a great deal about how the database side of Drupal works.


How to hide a specific user profile? I would like to be able to hide a specific user profile.

I want to completely hide it from Drupal and search engines. How can I achieve this?

To avoid users can access a user profile, I would implement hook_ENTITY_TYPE_access().
For the search engines, it would be sufficient to check the logged-in user isn't anonymous. For any Drupal user and the search engines, it's sufficient to check the permission the logged-in user has. (I would not hide the user profile to users who have the permission to administer users.)

In the first case, I would use code similar to the following one.

function mymodule_user_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'view' && $entity->id() == USER_ID && $account->isAnonymous()) {
    return AccessResult::forbidden()->cachePerUser();
  }
}

In the second case, I would use code similar to the following one.

function mymodule_user_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'view' && $entity->id() == USER_ID && !$account->hasPermission('administer users')) {
    return AccessResult::forbidden()->cachePerPermissions();
  }
}

(In both the cases, replace USER_ID with the actual user ID of the user profile you need to hide.)

The code checks the value of the operation, and forbids it only when it's view. In this way, the code is simpler, as it doesn't need to check users are trying to edit their own accounts, for example (which I assume it's not an operation you want to forbid).

hook_ENTITY_TYPE_access() is not invoked for pages listing more than one entity, for example a view page. In the case of user accounts, hook_ENTITY_TYPE_access() should be sufficient, but if you want to avoid that user account is listed also in a view output, the alternative is hook_query_TAG_alter() which is more complicated to implement, but it works in every case.


Custom theme function not being called? I'm building a Drupal 7 module to create a bespoke field type. I've implemented all the required hooks. My hook_field_formatter_view() function looks like this:

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'default':
      foreach ($items as $delta => $item) {
                $element[$delta] = array(
                  '#theme' => 'test',
                  '#item' => $item,
                );
      }
      break;
  }

  return $element;
}

I've then defined the theme() function below:

function theme_test($variables) {
    return '
Hello World
';
}

But when I view the page nothing is output. If I look at the recent log entries I see this message:

Theme key 'test' not found.

If I change my MYMODULE_field_formatter_view render array '#theme' value to a built in theme function like 'item_list' it works. But for some reason my custom theme function is not being picked up.

I've rebuilt the theme registry hundreds of times as well as cleared the caches.

You probably have not defined your theme hook in hook_theme().

The Using the theme layer section of the Development handbook has an in-depth discussion about this.


Synchronize with the correct time This may not be Drupal specific, but does Drupal have a module that can fetch the correct world time from any remote time server, which can help me in keeping the time shown in my Drupal site correct?

I don't want to use my system time which may be inaccurate.

If you are on shared hosting your hosting company should be responsible for keeping the time correct. If that's not happening contact them and ask why. If you are on VPS or your own private server you can set up a NTP client as tostinni recommended.


Can't render node view mode pro-grammatically I try to render an HTML data from my node view mode but unfortunately, I have some small progress.
I did some searching and modification on the others code Here.
I have this now.

$nid = 145;
$entity_type = 'node';
$view_mode = 'pdf';

$view_builder = \Drupal::service('entity.manager')->getViewBuilder($entity_type);
$storage = \Drupal::service('entity.manager')->getStorage($entity_type);
$node = $storage->load($nid);
$build = $view_builder->view($node, $view_mode);
var_dump($build);
die();

But when I run it I got this error

  TypeError: Argument 1 passed to Drupal\Core\Routing\CurrentRouteMatch::getRouteMatch() must be an instance of Symfony\Component\HttpFoundation\Request, null given, called in C:\wamp64\www\executive-coatings\docroot\core\lib\Drupal\Core\Routing\CurrentRouteMatch.php on line 127 in Drupal\Core\Routing\CurrentRouteMatch->getRouteMatch() (line 99 of core\lib\Drupal\Core\Routing\CurrentRouteMatch.php).

As I did step by step checking I got that just issue is with $build = $view_builder->view($node, $view_mode);

What is wrong with this code? Am I in the right way to render HTML data from a view mode?

MORE INFO

The Idea behind this is to get node data according to a specific view mode, then render the data to HTML format and use that HTML data in a PDF function to generate the related PDF file.

I simply use this code in one of my custom modules, that is ecc_pdf module.
as you can see I simply set a valid ID to load valid data for the test process.
My node type name is safety_report
this is my full view mode list

I use Drupal 8

PHP 7.2

For checking that I have any issue with other codes or not, I create a new basic site and apply this part of code inside a custom module but I get the same error again.

This is my new custom test module code, This is my full module code for test.mudole file.

use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
use Drupal\Core\Render;
$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';
$builder = \Drupal::service('entity_type.manager')->getViewBuilder($entity_type);
$storage = \Drupal::service('entity.manager')->getStorage($entity_type);
$node = $storage->load($nid);
$build = $builder->view($node, $view_mode);
$output = \Drupal::service('renderer')->render($node);
var_dump($node);

This my info file

name: ECC TEST
description: For creating the custom TEST
package: Custom
type: module
version: 1.0
core: 8.x

As I said I create just a new site, and I don't have any other file in my module, I just have .mudole and .info.yml file that I mention above.
And the Article node that I test just is Drupal default.

This is the full error that logged for me

Your problem is here:

use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
use Drupal\Core\Render;
$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';
$builder = \Drupal::service('entity_type.manager')->getViewBuilder($entity_type);
$storage = \Drupal::service('entity.manager')->getStorage($entity_type);
$node = $storage->load($nid);
$build = $builder->view($node, $view_mode);
$output = \Drupal::service('renderer')->render($node);
var_dump($node);

You have dumped your code raw into a file. You cannot do that - your code is being called before Drupal has bootstrapped. You need to put your code into a function some hook that is called after Drupal has bootstrapped. I don't know what you're trying to accomplish, so I can't give any more info than that.


Change image style in view depending on node type I have a view which shows a list of nodes of two different node types. Both have an image field.

Now I would like to have the image style to be different for the two node types.

I can't use hook_views_pre_render(), because then I would change the image style for all the nodes displayed. I also think I can't use a tpl.php file, because then I already have a URL, and can't retrieve another image style URL based on that that URL. Another option would be to define the image field twice in the view, and hide one depending on the node type, but I wouldn't know how to do that.

I'm using Drupal 7.

Any idea I overlooked?

Here is a better way to format your image or check out this post http://drupal.org/node/958726

$hero_image = array(
  'style_name' => 'case_study_teaser',
  'path' => $image['uri'],
  'width' => '',
  'height' => '',
  'alt' => $image['alt'],
  'title' => $image['title'],
  );
print theme('image_style',$hero_image);


Drupal prevents file save on chunked upload because of php.ini max upload size I'm encountering a tricky problem with my custom file widget (which extends the core file widget).  It chunks files so that I don't have to raise upload_max_filesize and post_max_size in php.ini, and puts them together.  The problem is, even though the files now exist remotely (and have also been saved as file entities in Drupal) it refuses to save them into the field, because even though the file field's settings are set to 500 MB, php.ini's uploads are maxed at 20 MB.

The problem is in FileItem.php:

public function getUploadValidators() {
  $validators = array();
  $settings = $this->getSettings();

  // Cap the upload size according to the PHP limit.
  $max_filesize = Bytes::toInt(file_upload_max_size());
  if (!empty($settings['max_filesize'])) {
    $max_filesize = min($max_filesize, Bytes::toInt($settings['max_filesize']));
  }

  // There is always a file size limit due to the PHP server limit.
  $validators['file_validate_size'] = array($max_filesize);

  // Add the extension check if necessary.
  if (!empty($settings['file_extensions'])) {
    $validators['file_validate_extensions'] = array($settings['file_extensions']);
  }

  return $validators;
}

Which calls file_validate_size in file.module.  I've already tried using ini_set() to change the file size ini values, but that doesn't seem to work.

So, to recap:

Drupal has the file

My widget tells it to save the file by its fileID for the file field

Drupal tells me it won't save the file that it already has because of php file upload limits

Can anyone think of something I can do to get around this without modifying core?

Just a guess, but this may have something to do with max_file_uploads in php.ini. Perhaps chunking it counts as multiple files?


how to update price from front end in ubercart product in drupal 7? I have a site in drupal 7, and I am the admin of site. I am using ubercart in my site for products. I have lot of products in my site with attributes and options. My products options are price based..

For example: I have one jewellery $100 with siver $23 and gold $43. Silver and gold are comming from option.

I want to update  options price from front end where product are displaying without going from edit product from backend.

This functionality isn't built into Ubercart. In order to do something like this, you're going to have to implement your own custom form to manipulate the options data, or, better yet, invoke uc_object_options_form (the options form display on node/$nid/edit/options) with drupal_get_form().


Get field content of all instances of a field I'm trying to get the content of all instances of certain fields based on their names. I've got a list of fields (which are in nodes/paragraphs and blocks) of which I want to extract the values from.

For example field_call_to_action_link. I need values of all the instances of this field.

Each field has it's own database table, like: node__field_name, paragraph__fieldname, block_content__fieldname.

I get the field names like this ($configFieldTypes is an array of types I want):

foreach ($configFieldTypes as $fieldType) {
  $fieldNamesFiltered[] = $this->entityFieldManager->getFieldMapByFieldType($fieldType);
}

Then I filter based on the name starting with 'field_' and make an array with the fieldname as key and the bundles associated with each field:

  private function recursiveKeys($fields, &$fieldNames) {
    foreach ($fields as $key => $field) {
      if ($key === 'parent_field_name'){
        continue;
      }
      if (FALSE !== strpos($key, 'field_')) {
        $fieldNames[$key] = [$field][0]['bundles'];
      }
      if (is_array($field)) {
        $this->recursiveKeys($field, $fieldNames);
      }
    }
  }

The endresult is an array like this:

  ["field_call_to_action_link"]=>
  array(1) {
    ["call_to_action_button"]=>
    string(21) "call_to_action_button"
  }
  ["field_image_gallery_link"]=>
  array(1) {
    ["image_gallery"]=>
    string(13) "image_gallery"
  }

Now I need to know if field_call_to_action_link is a node, block, or paragraph.

How can I determine which database table to query?

Drupal 8.8.x

If i understand correctly you have field_call_to_action_link in node, paragraph, block entities. And you would like to get values from this field from all entities which contain this field.

I would use EntityQuery and condition to check if field exists in given Entity.

$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('field_call_to_action_link', 'NULL', 'IS NOT NULL')
->execute();

this should give you all published nodes which contain field_call_to_action_link. You can obtain 'block' Entity the same way only change 'node' to 'block'.

Useful links:

Condition exists DOC link
EntityQuery DOC link


How to make User Picture a required field? I do not see any option to make User Picture required in Account - Manage Field settings as it is not a real field in D7. Any tips?

You can do it by using these modules :

Register with Picture

  Install and enable the module
  Navigate to: Configuration -> Account Settings. (admin/config/people/accounts)
  Check Enable user pictures if it isn't checked already.
  Confirm Enable pictures on registration is checked.
  Use the Registration Picture Field Weight field to adjust the display order of the picture field on the registration form. It can be
  a negative or positive number.

user picture field

  1, Add a image field to user, for example "field_user_avatar"

  2,config this field,and make it show on user register form.

  3,install this module, navigate to
  "admin/config/people/user_picture_field", here you can config the
  "Machine name of source field that used as user picture"

  When user register an account, he/she upload an image through image
  field "field_user_avatar", this image will be used as user's
  picture(avatar).


How to keep track of unique node views? I'd like to display the number of unique node views (= how many times the full node page is visited by a unique user) in my nodes' teasers. I've tried to use the Statistics module, but in that case, all reads are stored.

Is there a way to only count the unique views? Which code should I use in my node.tpl.php file to display this information?

You can try Node View Count module.

  Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

To print the count in teasers.

Implement hook_node_view()
Check the $node->type and $view_mode
Call nodeviewcount_db_count_node_views($node, $user = NULL, $distinct_users = FALSE) to get the count
Add the count to $node->content
In your template file print the count that you added.

Update:

You cannot rely on IP for uniqueness,  but if you want to count unique views based on IP then follow one of the below steps.

The accesslog table will contain all the access logs with IP details, you can query this table for path like node/nid and group by IP to get the count, One thing to note is that accesslog will be cleared periodically, if you are going to use this table then you have to make sure that it won't be cleared by selecting never in Discard access logs older than. I will not suggest doing this way because this table will contain access log for all pages, though there is a moule Better Statistics using which you can restrict statistics to log access details only for node pages.
Or, you can create a custom module and create a custom table somewhat similar to accesslog and then implement hook_node_view() to populate the table, later you can query the table to get the count.


How to install and enable a default and admin theme in a Drupal 8 install profile with just YML (without using hook_install() or a .profile file)? I want to avoid using hook_install() so I can install from configuration.

I'd like my install profile to use seven for the admin theme, and my custom theme rutherford for the default/main frontend theme.

The annotated *.info.yml example on Drupal.org suggests that putting the following will install my themes:

# List any themes that should be installed as part of the profile installation.
# Note that this will not set any theme as the default theme.
themes:
  - rutherford
  - seven

My understanding of CMI is that I can then create a file called www/profiles/rocket/config/optional/system.theme.yml and put this in it to enable my themes:

admin: seven
default: rutherford

However none of this seems to work? My themes are found, but not installed or enabled:

Edit:

I've just noticed that the themes are set as default and admin, they're just not installed:

Ah ♂. Trying to install my rutherford theme via the web UI gave a The rutherford theme was not found. error message, so it seemed the theme was at fault, not the profile.

I inspected my theme's info file and realised it had a dependency which was not being met. Commenting out the dependency got everything working again!

It's a shame that the php www/core/scripts/drupal quick-start rocket did not give me any errors about this unmet theme dependency, otherwise I would have saved about six hours of trying various different configuration approaches! Ah well, ce la Drupal!


User Name and User Email Conflict? I imported 500+ users into Drupal 7 by Feeds module. However, 1 of the user has 2 accounts. I got a error message "This name has already been taken by another user." when chaning their roles. Their username is different, but account A user name is same as account B email address. I think they have user name and user email conflict. Is it possible to fix this without changing username and user email?

User account A:
Username - usernameX
user email - usernameX@gmail.com

User account B:
username - usernameX@gmail.com
user email - usernameB@gmail.com

I am puzzled by your description of the problem.  Drupal 7 should not complain if  A user name is the same as account B email address.

However, without making a too big deal of that, there is a way you can change an email address to avoid any conflict within Drupal, and still get mail delivered to that user without interruption.

Simply insert the character + and some string after the name part of the address, like this:

User account A:
Username   - usernameX
user email - usernameX+a@gmail.com

User account B:
username   - usernameX@gmail.com
user email - usernameB@gmail.com

Drupal allows email-adresses with a + in them.

And for string comparison purposes:

usernameX+a@gmail.com ≠ usernameX@gmail.com

While for mail delivery purposes:

usernameX+a@gmail.com = usernameX@gmail.com

This technique, known “plus-addressing” allows users to sign up for different services with different aliases and then easily filter all e-mails from those services (provided their mail server doesn't strip it). Mail servers deals differently with “plus-addresses”. MS Exchange strips it, while Cyrus and GMail retains it - but AFAIK all mail servers deliver mail with “plus-addresses” to the intended recipient.


Use One Content type's field as a reference in another content type's view? I have following requirements :

Add and List of Book
Add and List of Quiz related to book.

I have created content type for Book with field name : book_id,book_name,price etc..,here book_id will be unique in every time.

Also created content type for quiz with field name : quiz_name,my_book_id etc..

Now in view of quiz i have to show field quiz_name with book_name. How can it will be possible to map this field?

I refered too much like entity reference, node reference module etc but didnt get any solution.

My solutions is

1. In your Quiz content type remove book_id field , add another field with (each name you want here I named it my_book_id ) select type node reference  for it.

then in views, create a views of content type quiz, create a relation on my_book_id then you can add book title .

2. Another way is using php views field
create a views with content type quiz, select quiz desire field, then add my_book_id field ,exlude it from dispaly then create php field , in value use something like this

<?
 $node=node_load($data->mybookid); // this is not precise way, you should put nid in node_load(nid);
 print $node->title;
?>