How do I get a dashboard like the one drupal.org is using? In search of making the dashboard for the user like drupal.org site I came to know there is a dashboard module in the drupal core. It is already enabled but I am not getting user interface like drupal.org site, not for admin and not for otehr users, How can I activate that so the user profile looks like what is on drupal.org site. I enabled the permission for user also. And where is the tab for the dashboard or how to enable it? Or am I missing something?

The dashboard on drupal.org is made using Homebox module.

  Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.


A table was not created by _schema() function I added this function to cleanetica_advanced module and after this ran /update.php

function cleanetica_advanced_schema() {
  $schema['videos'] = array (
    'description' => 'Videos with HTML titles',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for our table of videos',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'urlinfo' => array(
        'description' => 'The string referring to the video',
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE
      ),
      'title' => array(
        'description' => 'The title for a video, used in admin part only',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
      'richtitle' => array(
        'description' => 'The HTML-formatted title for a video',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
    ),
    'primary key' => array('id'),
  );

  return $schema;
}

But the table videos was not created.

What have I missed in order for the table to be created?

The module cleanetica_advanced is enabled and I checked that it really loads by inserting a nonsense (non-PHP) there and seeing that the site crashes with an error. (After this I removed the nonsense.)

The hook_schema is only run for table creation during module install.

To run it later, you'd need to install the schema from .install file with something like

/**
 * Implements hook_update_N
 */
function cleanetica_advanced_update_7001(){
  drupal_install_schema('cleanetica_advanced');
}

Add, and then run update.php


Add content to the front page in module I made a module, that outputs the data when the user opens a page /courses

function courses_menu()
{
  $items['courses'] = array(
    'title'            => t('Courses'),
    'page callback'    => 'courses_output',
    'access arguments' => array('access content'),
  );
}

function courses_output()
{
  return "some HTML";
}

How can I add this data to the main page below the node contents?

I would either implement a block or if you are using panels create a content pane.


7 - Views 3 - Displaying taxonomy description in a block I am trying to create a view displaying a description of the current taxonomy term. This view will be a block in the taxonomy/term/% page, so the idea is that it uses the argument passed to pick the description in the database.

My view works fine in the Views' preview but does not display any result on the pages which  probably means that the argument is not passed to the block. Can someone help me fix my view?

EDIT

Contextual filter

The URL is /taxonomy/term/% and I am using pathauto aliases.

The URL is /taxonomy/term/% and I am using pathauto aliases.

If you're using aliases I assume that your URL is something like some/path/your-term-name.

In that case I had exactly the same issue a while ago. You should try setting Filter Value Type to "Term name converted to term ID and check "Transform dashes in URL to spaces in term name filter values".

Also make sure that proper value is provided to the filter.

In the WHEN THE FILTER VALUE IS NOT AVAILABLE section select Provide default value
and then select Raw value from URL and specify url component to provide as a default value. Unfortunatel "Term ID from URL" option doesn't work as you might expect in case of aliases so you need either provide default value from URL using Raw value option or even using PHP Code option. If you choose this option, you might find the following piece of code useful:

$get = explode('/', $_GET['q']);
return $get[2]; //the "2" constant assumes that your term name is a third path component


Is there a module that provides perpetual results on scroll? Let's say you have a page that is a view, and the view is set to page at 50 items. You have 150 items, so you have three pages. Is there a module that will load additional results, like 30 more, when the user scrolls towards the bottom?

The effect is that you don't need to use the pager, as new results appear automatically.
The effect I want to get is the one used in this site.

Is there a module that will do this for a view?

Found it. There are two (quotes included are from their project pages):

Views Infinite Scroll (Requires Views 3):

  ... provides pluggable pagers that enables Views infinite scrolling (autopaging, depaging, endless pages ... you name it) by using jquery.autopager plugin. Using this module with views page display will load another page whenever the user reaches bottom of the page.

Views Infinite Pager:

  ... implements "infinite pager" (earlier called "sliding pager") functionality for Views. Infinite pagers open the next page via Ajax below the current page, each sub-page expanding the page vertically downwards. For a well-known infinite pager example, visit a stream on Twitter.com.


Get the form to add a term to a vocabulary programmatically I am working on Drupal 8.9.6.
I am trying to retrieve the form to add a term to a vocabulary programmatically. I know how to do it for a content type:
    $values = array('type' => $content_type);

    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->create($values);

    $form = \Drupal::entityTypeManager()
      ->getFormObject('node', 'default')
      ->setEntity($node);
    $modal_form =  \Drupal::formBuilder()->getForm($form);

Nevertheless, I am not able to do the same for the form of adding a term to a vocabulary. Any hint would be more than welcome.
Thanks!

$vocab_machine_name = 'tags';
$values = array('vid' => $vocab_machine_name);

$term = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->create($values);

$form = \Drupal::entityTypeManager()
  ->getFormObject('taxonomy_term', 'default')
  ->setEntity($term);

$term_form =  \Drupal::formBuilder()->getForm($form);

Shorter way
$vocab_machine_name = 'tags';

$term = \Drupal\taxonomy\Entity\Term::create([
  'vid' => $vocab_machine_name,
]);

$term_form = \Drupal::service('entity.form_builder')->getForm($term, 'default');


Get name of table for a field I've been using EntityFieldQuery to query my fields but I need the SQL 'like' operator.  For this I'm querying the database manually.  Question:  How do I get the name of a field's table?

What you need to use is the fieldCondition
, which works pretty much like entityCondition and propertyCondition, only you are adding a condition for the field and not the entity or one of it's properties.

This is how you should query fields and entities.

If you wanted to get info about the how the data of a field was stored, that information is available on the field itself. So you could do

$field = field_info_field('field_name');
$storage_details = $field['storage']['details'];

What info you get depends on how the field is stored, as Drupal support multiple storage backends for fields.


I cannot access the login page I have to change a website, but I cannot log in. The problem is, that the login page does not appears in any way. I get a 403 error when accessing /user. That should come from a change that I did in the past to deactivate the login page at all. Even I cannot remember what I did or (last conclusion), the database has an error and the login page does not appear.

I setup a new Drupal installation with the same version, but I cannot see any significant difference of the folders.

Is there a hack to activate for a moment to allow anonymous user act as an administrator?

I am using Drupal 6.19.

Querying the database, I get the following.

    drupal=> SELECT path FROM menu_router WHERE path LIKE '%user%';
     user/login
     user/password
     user/register
     user/autocomplete
     admin/user
     user/%
     user/%/view
     user/login/lightbox2
     user/login/thickbox
     admin/user/rules
     admin/help/user
     user/%/contact
     user/%/delete
     admin/user/permissions
     admin/user/roles
     admin/user/settings
     admin/user/user
     user/%/edit
     admin/user/rules/list
     admin/user/user/list
     user/%/edit/account
     admin/user/rules/add
     admin/user/user/create
     admin/user/rules/check
     admin/user/roles/edit
     admin/user/rules/edit
     admin/user/rules/delete
     admin/views/ajax/autocomplete/user
     user/reset/%/%/%
    (30 rows)

Try accessing user/logout, and then log in the usual way.


Can I use the Rules module to send mass emails to authors of selected nodes? How can I leverage the Rules module to look for nodes where a CCK field has a specific value, and when found, email those node authors?

For example, if I wanted people to login and update their profile when I add a new CCK field, how would I do that?

If you want to use rules for that, you would have to create your own event: when you add a CCK field. You would then have to write some code to trigger then event when a new CCK field is added, and supply rules with the nodes of that type or whatever data you would need in your rule.

My guess is that the amount of custom coding needed for this to work, would be more than what is needed to just do this yourself in a custom module, with hook_mail. Also you might have problems configuring the rule to do what you need. I haven't tried using an array of data types in rules, so that might make things more complicated for you as well.


Is there a way to add a Captcha to Ubercart? After some fraud attempts, I've been requested to add a Captcha to an Ubercart store in Drupal 7 and am surprised that in my searching I can't find any information on how to do this. Has anyone achieved this?

I am assuming you are talking about the add to cart form. Please share on what page or place you need captcha?

If you cannot find a module, then you need to do exactly what the captcha module does,

Write hook_fomr_FORM_ID_alter for the form for which you need to add the captcha.
Look for articles online explaining how to add captcha programmatically on a form in Drupal, ex: How do I add reCaptcha to a custom form?, https://www.drupal.org/node/743056.
Enable your custom module containing this code, and the captcha module.

You should have your captcha on ubercart's add to cart or any other form with a submit button.


How do modules come up with their green, yellow, and red releases? As we all know, not every module marked "Recommended Release" on drupal.org is truly stable. In fact some modules are perpetually marked beta, in some sort of permanent limbo state. Even when hundreds of sites use them every day.

I was wondering what kind of standards or best practices do you use, as a maintainer or contributor, in your modules to mark releases 'Recommended' (Green), 'Other' (Yellow), or 'Dev'(Red)? What do you use when marking it beta, alpha, or stable as well?

Thank you in advance for any advice, help, or documentation you can provide.

NOTE: Many of these standards may be general standards for coding or project development. I simply wanted to know what methods or standards are used in Drupal modules specifically, even if they are / can be generalized.

Many of these standards may be general standards for coding or project development.

In Drupal there is no standard for this. It is left to the best intentions of the module owners.

My personal philosophy is:

Release beta and/or releasecandidate if tested in a testing environment, or if all testcases pass.
Release stable only if I, myself, have successfully implemented the (version of the) module in at least three different real-world projects; or if someone whom I know has my standards, did that and reports back.
A module can be finished. It needs no additional work ever anymore. Something that is limited and scoped in featureset, is stable and predictable. Such modules need no bugfixes, feature-requests or tasks.

In practice, this means very few releases, yet the releases done will affect hardly anyone. That results in hardly ever releasing anything in practice.

My reasoning behind this is:

People in issue-queues hardly test appropriately: they apply a feature, fix or patch, hit f5, see it working and say "yes, works for me +1". "It seems to work" is not equal to "it is fixed". You need trustworthy testing, or else the rest, those who did not even test the change, will flock in with issues reporting something COMPELETELY BORKEND, need fix NOW!!.
Only when a module is implemented in different situations and environments will it have some real-world experience. Most often, during the second implementation you find that you need to rewrite some central api's, forgot some usefull parameter, or simply had a wrong idea about the need for some feature. Only after real-world deployment can something be considered stable. Else it is only stable in theory.
Developers and maintainers of sites, the users of your modules, need to put a huge effort (far more then in any other piece of software I know) in keeping up with new releases, security releases and new versions. any relief for that effort (and budget and time) should be more then welcome.


Unique profiles for each user role I have 3 different roles: Patient, Operator, Nurse. I have one registration form for all my users with basic information (applied via 'Account Settings'). I've been messing around with Profile2 to give each of roles a unique profile.

My problem is that I can't seem to stop Patients from having an Operator Profile and Nurses from having a Patient Profile. Is there a way for me to make the profiles unique to the roles?

I've also considered doing it exclusively in 'Account Settings' and restricting fields using Field Permissions?

I would like to do this so that alternations to the profiles is quick and easy to do.

Restricting fields using field permissions would probably be the easiest way to do it; I've had to do something similar with Profile2 in the past and it involves overriding the access callback for profile pages, and checking that the user has a certain role.

Here's some sample code if you want to try it that way:

function MYMODULE_menu_alter(&$items) {
  // Ensure that category profiles are only visible if the user has the correct role
  $items['user/%user_category/edit/parent']['access callback'] = 'zylo_user_category_access';
  $items['user/%user_category/edit/tutor']['access callback'] = 'zylo_user_category_access';
  $items['user/%user_category/edit/school_staff']['access callback'] = 'zylo_user_category_access';
}

function MYMODULE_category_access($account, $type_name) {
  // First make sure the user has normal access to the page
  if (profile2_category_access($account, $type_name)) {
    // Check that the user has the correct role
    return in_array(str_replace('_', ' ', $type_name), $account->roles);
  }

  return FALSE;
}

It isn't the prettiest but it does get the job done


Drupal user registration form I just want to do somthing without using module like profile2, so here is my requirement.

=> theme user registration form for e.g. I already have a beautiful user registration form as static html template which use bootstrap classes for css so how can I implement this html template in my drupal registration form..

=> In login form I want to remove tabs LIKE create new account and request new password and enstand of these tab I want to give like just before login button.

let me know if anything not clear.

1. theme user registration form

implement hook_theme:

function MYMODULE_theme()
{
  $return = array(
    'my_custom_registration_form' => array(
      'render element' => 'form',
      'template' => 'my_custom_registration_form'
    ),
  );

  return $return;
}

implement hook_form_alter:

function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{
  //dpm($form_id);
  if ('user_register_form' == $form_id) {
    $form['#theme'] = 'my_custom_registration_form';
  }
}

create my_custom_registration_form.tpl.php file in MYMODULE directory, clear the cache, check if it works;

<?php dpm($form) ?>

copy html from your static file (just form part), put it into my_custom_registration_form.tpl.php, example (this will be different in your case):

<?php print render($form['DESIRED_FIELD']) ?>

...

//render other fields (hidden fields), without them submit won't work
<?php print drupal_render_children($form) ?>

// or you can render them manually

// <?php print render($form['form_build_id']) ?>
// <?php print render($form['form_token']) ?>
// <?php print render($form['form_id']) ?>

2. In login form i want to remove tabs LIKE create new account and request new password - you can do it with CSS, or by removing $tabs variable from page template (you can create specific page template just for login page),

3. enstand of these tab i want to give like just before login button -
with hook_form_alter fnction you can add other fields (manage theme) to the form

P>S: dpm() - is from Devel module


Multiple terms in one filter I am passing multiple tags into an exposed field separated by a comma. If a single tag doesn't have a result, it ruins the entire view.

Is there a way to treat the extra tags as optional?

Use '+' to separate the tags instead of ','. The '+' is used for "OR" while the ',' is used for "AND".

Here is a screenshot from the Views administrative interface:


Rules: Send mail to author when value in date field has passed So, I have a content type "contest" which has an "end date" field. I want to setup rules so the author of a "contest" gets an e-mail as a reminder that the contest ended.

As event I used "Cron maintenance tasks are performed" and as condition I try to use "Data Comparison" to check the value of the end date to be smaller than current site time. The problem is I can't use the token of the "end date" field as my event is not node-related. I tried to add a "Content is of type" condition, but also here, I can't select anything node-related.

I feel like overlooking something small but I've been searching now several hours and could use some help..

Assuming you are using Drupal 7.

You need to enable the Rules Scheduler module, it comes with Rules.

Then for Rule event use After saving new content.

Add condition, content is of type: Contest

Exit out of your Rule, and now create a Rule Component of Data Type: Node

Add condition, content is of type: Contest

Action Send E-mail.

Now exit the component and go back to your rule, for action, schedule rule component, and use your end-date field for schedule evaluation date.

I highly suggest you watch Introducing Rules Scheduler and I am sure my answer will make more sense to you.


How do I give the permission to add points, but not to moderate them? When I give users the permission to administer user points, they can both add and moderate points. How do I give them only the permissions to add points, but give other users the permission to moderate points?

Can someone tell me how to use the hook_menu stuff, to set permissions? My email is lucas.famelli@gmail.com

In Drupal 6, there is no easy way to do that. It might work if you implement hook_menu_alter() in a custom module and add a different permission in access arguments that the default.

It might not help you at this point, but I have taken over that module for Drupal 7 and we have improved it a lot. Among many other things, it now has separate add/edit and moderate permissions which allow for fine-grained access control. So if you are just starting your site, you might want to consider using Drupal 7 instead.


Trying to leverage drupal_add_html_head to add an ie10 class Since IE10 does not understand conditional comments, I can't use the typical methods to single out that browser. However, I found a nice function that works well and if I add this to html.tpl.php in my theme:

<script>if (Function('/*@cc_on return document.documentMode===10@*/')()){
    document.documentElement.className+=' ie10';
  }
 </script>

... it works for IE10 and adds an HTML class of ie10.

But for best practices, I really want to use a preprocess function. So I looked at drupal_add_html_head and that seems to be the ticket. But when I formulate my code as such:

function MYTHEME_add_html_head($element, $inline_script) {

  $inline_script = <<<EOL
  <script>if (Function('/*@cc_on return document.documentMode===10@*/')()){
    document.documentElement.className+=' ie10';
  }
  </script>
EOL;
$element = array(
'#type' => 'markup',
'#markup' => $inline_script,
);
drupal_add_html_head($element, 'system_ie_browser');
}

... it does not work. There does not seem to be a lot of documentation around this and I could not really find anyone else doing exactly what I need so I'm a bit lost here. I replaced MYTHEME with the actual theme machine name and cleared cache too.

What I'm not sure about is if this part...

drupal_add_html_head($element, 'system_ie_browser');

... is significant in terms of Drupal understanding it and where to put it. I don't know if there are specific variables that go there. I just sort of made system_ie_browser up.

Hope this will help you,

Use Browser class module.

  This small module helps theme-developers to deal with cross-browser compatibility. It makes easier to handle different types of non-widespread browsers just as much as it helps with using different versions of Internet Explorer.
  The module extends the $body_classes variable in page.tpl.php based on the enduser's browser, and platform.

  The module also makes a $browser_classes variable available in page.tpl.php, which stores the data in an array, this way the developer can make use of it as needed, if he does not wish to use the $body_classes variable.


Anyone any good reference about the variables available in the view template? Tried to print variables in view template, but the print-out is huge,deep-nested and recursive... crazy thing... Just can't drill down to the rendered_fields array, which seems to be just what I need. Is there any comprehendable reference anywhere?

What I usually do when I need to inspect a views variable, that often can be as complex as you describe is to use dpm. Dpm can't always show all of the items since the information is repeated. But then you can dpm the specific parts you need.

So you often start doing dpm($view); but end up using dpm($view->displays...); to get what you need. Using a reference might be a bit overkill since the view varisble is dymanic, but after doing it a while you start figuring out where you can find stuff. The names is pretty selfexplanatory.


Ubercart alter product price when product added to cart I need to alter Ubercart product price on Ubercart 3, Drupal 7, when product is added to cart.
I need to check some conditions, and if met, change the price. I thought i can go with

function MYMODULE_uc_cart_item($op, &$item) {
  switch ($op) {
    case 'load':
      drupal_set_message(t('It works!'), 'status');
      break;
  }
}

but not sure am i targeting right hook.

It seems that it does not work (it is not invoked).

Thanks for clues

Here is another hook you can play with hook_uc_add_to_cart

Parameters:
$nid - the node ID of the product
$qty - the quantity being added
$data - the data array, including attributes and model number adjustments

Here is how to work with hooks

  Drupal's module system is based on the concept of "hooks". A hook is a
  PHP function that is named foo_bar(), where "foo" is the name of the
  module (whose filename is thus foo.module) and "bar" is the name of
  the hook. Each hook has a defined set of parameters and a specified
  result type.

function hook_uc_cart_item($op, &$item) { the work hook should be replaced with your modules name like

function YOURMODULENAME_uc_cart_item($op, &$item)

See Hooks


How to create an editable table (by users) from Webform submission data? I'm using D7 and creating a system to manage information about a specific game's characters. I have been advised to use webforms to collect the data from the character's, and I want the user that fills out those webforms be able to edit the data, just like they would on an Excel table.

I've been looking and looking and haven't been able to find an answer to how to get it done.

Any help?

You could use Editable Views

Drupal Editable Views demo


Send HTML email to all users of a role in action not display .....help me please Send HTML email to all users of a role in action not display ;
only send HTML-email display
help me please.

That action comes from the Mime Mail module, it's not one of Rules's defaults.

Once you've downloaded and installed the new module, just re-visit the Rules setup page and you'll find it in the list.


How to add fields (variables) to users to be used in combination with data about events? About my site:

I have a site about events where users can:

post and rate events.
confirm that they will attend (everyone can see who will attent).
etc.

Requirement 1: I want to make it so that you can add fields (variables with some value) to users, which resembles what they did. For instance: "User Anon had a red jacket and was drunk".

Requirement 2: Then I would like to have a drop down list:

that is unique PER event
with these fields (variables) which the users can use to add the appropriate values to their own profiles.

That way everyone can see what they did/had at that specific event.

Summary:

The following should be the desired result:

Add fields (variables) to users  .
Must be unique PER event.
Multiple choices possible.
Visible by other users.
Visible on own profile.

What I tried so far:

I tried to use the Views module with references and such. But it didn't work.
Then I tried to achieve it with a poll, which would work but is not unique per event.

My question:
Any ideas how I can get this done?

How about using the Flag module for this? Excerpt from its project page:

Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

Possibly in combination with some of the Flag related modules also, such as (partial list):

Views, to create lists of flagged content, users, etc, such as in the video about Creating global flags and listing flagged content in Views.
Rules, to trigger rules for anything that is flagged, such as in the video about Triggering rules with Flag, or to set flags with the Rules module, such as in the video about Setting flags with Rules.
Flag Lists, to allow users to create custom lists.
Flag Weights, to add weights to Flags (to be used for sorting).
DraggableViews, to make Views draggable (so that they can be rearranged by Drag'n'Drop.).
Flag Friend, a pre-built flag for marking other users as friends (using the Flag module).
Flag Abuse, a pre-built flag for marking offensive content, with some extra administrative features.
Flag, Hide & Mute, for users to hide individual nodes, such as site-wide announcements or advertisements, and/or to suppress all posts by users they do not want to see.
Flag Files, to flag media files.
Flag Service, to allow Flag to be accessed via a web services interface through the Services module.
DLike, provides a Facebook like "Like" functionality using the Flag and Lightbox2 module.
Conditional Flags, provides an extra API to Flag module, for custom conditions between flags.
Organic Groups Flag Integration, extends the flag module with organic groups support allowing the administrators of each group to override the global flag settings for their group.
Context Flag, allows the use of Flags as conditional triggers for use with the Context module.

Refer to its community documentation for way more details (if you like to read), and/or various screencasts about the Flag module (if you like to watch).


How to sort users in a view by the number of nodes authored of a specific node type? I was happy to find that in Views 3 I can sort users in a view by the number of nodes they have authored (Using a relationship "User: Content authored" and the Aggregation / 'Group by' - Count function, see here).

How can I do the same, but counting only nodes of a certain node type? (I'm actually using this in a view of profiles (Profile2), but using the relation "Profile: User UID" the solution would probably be the same).

Not sure if I understand you correct, but have you tried setting up a normal filter:

Content: Type (= nodetype)


How can I render a responsive image style from an image in the theme directory? I am working on template views-view-fields--myview.html.twig. But I do
not think it matters what template you are working with for this to
work.

I found this Twig that can add Drupal responsive images to an
image that is not in a field. In this case this image is in the files
directory. My question is that I want to place this image in my themes
directory in: /themes/custom/mytheme/img/mygraphic.png. What URI can I
use to make that work in this example?

Second question is: The
image alt tag is empty even though I provided one. How can I display an
alt tag?

{% set responsiveimagestyle = {
    '#theme': 'responsive_image',
    '#responsive_image_style_id': 'my_custom_responsive_style',
    '#uri': 'public://mygraphic.png',
    '#alt': 'my alt text',
    '#attributes': { class: 'img-responsive' },
} %}

In the views-view-fields--myview.html.twig template I now can use the following
variable.

{{ responsiveimagestyle }}

The image is wrapped in the picture tag and is using the Drupal Responsive Images style.

This is the same when using the image filters from the Twig Tweak
  module: You can't render responsive images from a random URI, it has
  to be an URI that is stored in the file_managed DB table. But with
  Twig tweak you can render normal image styles from random URIs, and
  manually create a responsive image tag by rendering multiple normal
  image styles. – Hudri

Great, so there is a workaround one can do, manually create one:

{% set imagePath = '/themes/custom/mytheme/img/mygraphic.png' %}
<img srcset="{{ imagePath|image_style('thumbnail') }} 300w, {{ imagePath|image_style('medium') }} 800w" src="{{ file_url(imagePath) }}" alt="some graphic image" typeof="foaf:Image"/>


How to set access permission to roles due to the content's vocabulary There is only one Content Type in my site and two vocabularies  ,say, vocabulary1 and vocabulary2. Now I don't want some roles to access some content due to their vocabulary.

Can I set  access permission to roles due to the content's vocabulary???

thanks!

Have you tried these Drupal modules (quotes included are from their project pages):

Taxonomy Access Control:

Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.

ACL:

The ACL module, short for Access Control Lists, is an API for other modules to create lists of users and give them access to nodes. It has no UI of its own and will not do anything by itself; install this module only if some other module tells you to.


How to regenerate xmlsitemap to https? I'm new to Drupal community and I wonder if there is a solution to regenerate all urls from http to https?

I have already tried to just regenerate and try to update $base_url in setting, nothing helped.

There is a setting in the XMLSitemap admin configuration that lets you set the base domain. Update that value, clear cache, and regenerate the sitemap.


How to fix my Rules Actions to copy data from geofield to geofield? I want to copy a geofield to another geofield in the same content type.

I created a Rule where I "Set Data Value" and with that I copy the data of one geofield into the other. Actually I created two actions one for longitude and latitude.
This action is triggered when "After updating existing content".
I used VBO to parse through my nodes therefore the trigger to be fired and geofield data to be copied.

Nothing happens. I get two errors in error log saying:

Unable to evaluate action data_set.
Unable to modify data "node:field-business-location...

I tried to expose the fields to rules by "Entity has field" condition but doesn't work either.
What am I doing wrong.
PS: There is also an option of "Create Geofield values from Lat/Lon but I don't see how I can copy data from one Geofield to another Geofield like this.
My Rule Export

{ "rules_copy_geolocation_data" : {
"LABEL" : "Copy geolocation data - Destinations",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--destination" : { "bundle" : "destination" } },
"IF" : [
  { "entity_is_of_bundle" : {
      "entity" : [ "node" ],
      "type" : "node",
      "bundle" : { "value" : { "destination" : "destination" } }
    }
  },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_destination_location" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_business_location" } }
],
"DO" : [
  { "data_set" : {
      "data" : [ "node:field-business-location:lat" ],
      "value" : [ "node:field-destination-location:lat" ]
    }
  },
  { "data_set" : {
      "data" : [ "node:field-business-location:lon" ],
      "value" : [ "node:field-destination-location:lon" ]
    }
  }
]   } }

Debugging is the art of taking away all possible reasons that may cause your issue ... Read on for more details to find out which one it might be, and how to possibly solve it.

Option 1: After updating actually happens before updating

Have a look at the issue about "After updating existing content" runs before content is saved, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". Therefor I'm about sure this is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to transform what you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules Component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so that can't be the reason anymore then why things don't work as expected).

Option 2: Add an extra Rules Action 'Save Entity'

Another cause of possible confusion is within the Rules module, where sometimes it gets tricky to "save entities". So possibly adding an appropriate "save entity" action (after the 2 Rules Actions you already have) may also help (if nothing else helps).

Option 3: Rules debugging

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging (further detailed below), but a Keep-It-Super-Simple technique I often use, is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think). If tis doesn't help, then there are typically 2 ways of more advanced debugging:

Rules Evaluation Log

Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).
Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Obviously, make sure that there are no Rules Conditions that would prevent the Rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

For way more details about these 2 variations, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


Views - alter date field granularity on exposed filter mid-request? I have an exposed filter on a date value that has it's granularity set to month, so it shows possible year and month values in the form.  If I select just a year, no results are returned, even though I know there are posts that should be retrieved based on the year.  If I then specify a month, all posts from that month and year are returned.

I need to be able to return results from the entire year when just year is selected.  I'm thinking there might be a way to alter the granularity somehow during the request based on whether or not the month was specified?  Any thoughts?

Working solution thus far:

/**
 * Impliments hook_form_views_exposed_form_alter
 *
 * Used to change exposed date filter to year only, as this is not available in the views UI
 */
function bain_views_form_views_exposed_form_alter(&$form, $form_state)
{
    if( $form['#id'] == 'views-exposed-form-news-items-page')
    {
        // dpm($form_state['input']['date']['value']);
        if (isset($form_state['input']['date']['value'])
            && empty($form_state['input']['date']['value']['month']))
        {
            // Switch date formatter to year only
            $form['date']['value']['#date_format'] = 'Y';
            // Add extra validator to handle filter submit
            $form['#validate'][] = 'bain_views_views_exposed_form_validate';
        }
    }
}

/**
 * Custom validator for exposed date filter
 */
function bain_views_views_exposed_form_validate(&$form, &$form_state)
{
    if ($form['#id'] == 'views-exposed-form-news-items-page')
    {
        $handlers = &$form_state['view']->filter;
        $date_handler = $handlers['field_news_date_value'];
        // dpm($date_handler);
        if (!empty($date_handler->options['exposed'])
            && isset($form['date']['value']['#type'])
            && $form['date']['value']['#type'] == 'date_select'
            && $form['date']['value']['#date_format'] == 'Y')
        {
            $date_handler->options['granularity'] = 'year';
            $date_handler->format = 'Y';
        }
    }
}


Simpletest fails with "invalid database prefix" - no other information given I am trying to setup a simple test that tests some breadcrumb altering code I have introduced only for a specific content type.

Here is the test, still just barebones:

namespace Drupal\mymodule_breadcrumbs\Tests;

use Drupal\simpletest\WebTestBase;

/**
 * Class ArticleBreadcrumbTest
 * @group mymodule_breadcrumbs
 */
class ArticleBreadcrumbTest extends WebTestBase {
  protected $node;
  private $account;

  /**
   * Modules to install.
   * @var array
   */
  public static $modules = ['node', 'mymodule_breadcrumbs', 'menu_breadcrumb'];

  /**
   * Set up our test.
   */
  public function setUp() {
    parent::setUp();

    // create admin user
    $this->account = $this->drupalCreateUser(['administer site configuration', 'administer content']);

    // create article node
    $this->node = $this->drupalCreateNode(array(
      'title' => t('Test Article'),
      'type' => 'article',
      'status' => 1,
    ));
  }

  public function testNodeTitleIsInBreadcrumb() {
    $this->drupalGet('node/' . $this->node->id());
    $this->assertResponse(200);
    #$this->assertText('Home > ' . $this->node->getTitle(), 'Breadcrumb contains the node title.');
    // get page
    // test that breadcrumb is correct per node title
    // change node title
    // save node
    // visit node, check that breadcrumb is updated
  }
}

However, I am getting this error and not sure what to make of it:

The website encountered an unexpected error. Please try again later.

InvalidArgumentException: Invalid database prefix: in Drupal\Core\Test\TestDatabase->__construct() (line 81 of core/lib/Drupal/Core/Test/TestDatabase.php).
simpletest_log_read(NULL, , ) (Line: 476)
_simpletest_batch_finished(, Array, Array, '1 sec')
call_user_func_array('_simpletest_batch_finished', Array) (Line: 414)
_batch_finished() (Line: 81)
_batch_page(Object) (Line: 55)
Drupal\system\Controller\BatchController->batchPage(Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 652)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

It's a very basic test, why would it cause an error like that?

Also I am running this from the UI runner, if that makes a difference.

For functional (browser) tests you need to provide some environment variables, in this case the SIMPLETEST_DB environment variable.

It can either be supplied in the phpunit.xml.dist file, or in phpunit command, or actually added to the environment before executing the phpunit command.

The format of the variable is seen in the phpunit.xml.dist file provided by Drupal core.

<!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
<env name="SIMPLETEST_DB" value=""/>

From the error it seems that the provided SIMPLETEST_DB is not valid.

Note: the author mentioned that he was using the Admin UI and this answer does not address this problem.


User page tab with node edit, file upload image widget not working On every user profile page i have a tab My company its a node edit form of content type Company. Here the code:

/**
 * Implementation of hook_menu().
 */
function feature_directory_section_menu(){
  $items = array();

  $items['user/%user/company'] = array(
    'title' => 'My company',
    'page callback' => 'feature_directory_section_user_company',
    'page arguments' => array(1),
    'access callback' => 'feature_directory_section_access_user_company',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );

  return $items;
}
//callback function
function feature_directory_section_user_company($account) {
  $uid = is_object($account) ? $account->uid : (int) $account;
  module_load_include('inc', 'node', 'node.pages');
  $output = '';
  $nid = db_query("SELECT n.nid FROM {node} n WHERE n.uid = :uid", array(':uid'=> $uid))->fetchField();

  if (is_numeric($nid)) {
    $output = node_page_edit(node_load($nid));
  } else {
    $output = t('You have no company. Please contact the site administrator.');
  }

  return $output;
}

Content type company has alot of fields, when i trying to edit node on user/%user/company page everything works fine, but one thing not working its ajax image upload or i can't delete image of my field(field_company_gallery) - its just a image field and u can upload unlimited count of images.

I get a lot of errors. If i go to node/%nid/edit i can manage images. but on user profile tab i can't.

Some errors are next:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 798 of /home/www/buildit/htdocs/includes/form.inc).
Notice: Undefined index: #node in comment_form_node_form_alter() (line 1194 of /home/www/buildit/htdocs/modules/comment/comment.module).

Notice: Undefined index: field_company_gallery in file_ajax_upload() (line 271 of /home/www/buildit/htdocs/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /home/www/buildit/htdocs/modules/file/file.module).

I guess i need to load all the modules with this function module_load_include or maybe not, i am stuck here.

Ok i found solution:

If your node form has a file upload widget, you should add this code to hook_menu.

'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',


How do we pass php code as a twig variable in global custom text field of views How can we pass this php code as a twig variable in global custom text in views without using views php module?

I have created a view of news content with masonary layout .

<?php
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node /'.$row->nid);
echo $language.$alias;
?>

I just want to render it as a twig variable in custom text field of views without creating template because i have already created a page long ago i dont want to rework by creating template.

To place PHP code in a field extend a field plugin and override render(). But in your case you should get the result of this code from the existing EntityLink plugin (in UI "Link to Content") and the option output_url_as_text. If you want to use it as Twig variable in another field, hide the entity link field from display and place it in front of the other field.


Wysiwyg, ckeditor disappers when click "Add another item" button I use Field collection modules to group image + textarea for multiple field group inputs.
When I click "Add another item" button, ckeditor bar disappeared from the textarea.

I think there would be some errors occured on Ajax request for an iframe tag appeared at the bottom of the script.

This thing only happened when field collection group contains both image and textarea.
Field collection with only textarea are fine.

The modules I use:
wysiwyg 7.x-2.1
ckEditor 3.6.4.7575
IMCE 7.x-1.5
File Field Sources 7.x-1.4
field collection 7.x-1.0-beta4

I had this problem as well. This was fixed in http://drupal.org/node/1155678#comment-5358290 by adding a detach function to the WYSIWYG behaviors. You can apply the patch at the above link (that's what I did) or you should be able to download the 7.x-2.x-dev version (I haven't tested that) since it's been committed already.


How to get defined display names (id) from selected view? Getting selected view is simple:

  views_get_view('name');

I didn't find and have no idea what do next...

I need to get every defined view page path and add menu item to it.

This will loop through every page display and set a menu item.

  $view = views_get_view('VIEW_NAME');
  foreach ($view->display as &$display) {
    if ($display->display_plugin == 'page') {
      // Add an if or switch statement here to check $display->id
      // so you can set different menu items for each display.
      $display->display_options['menu'] = array(
        'type' => 'normal', // Menu item type.
        'title' => t('Menu item title'), // Menu item title
        'description' => '', // Menu item description
        'name' => 'main-menu', // Menu name
        'weight' => 0, // Menu item weight
        'context' => 0, // Not sure off the top of my head what this is for.
      );
    }
  }

However this will set the same menu item for each display.
You will need to check the $display->id for each one so that you can set a different menu item for each display.

Also, that example sets a normal menu item.
If you want a local task or default local task it will be slightly different.

...also, why do you need to do this? why not add the menu item via the views UI?


8 - Caching for custom blocks doesn't work on I'm working on a project based on Drupal 8.3.x . It comes with cache already enabled which is great if we know how to customize it. I've been going through the different tutorials and I was able to implement the following cache for my custom block:

$build = [
      '#cache' => [
        'tags'=>['node'], // Invalidate cache whenever a new node is created/modified/deleted
        'contexts'=>['url'] // Invalidate cache per url
      ]
    ];

The problem I'm having is my website depends on cities and display different content for different cities.
I have the following scenarios:

When I visit www.example.com/city1 the block should display nodes from city 1
When I visit www.example.com/city2 the block should display nodes from city 2
When I visit www.example.com the block should display the nodes from the latest visited city

With the snippet above I'm able to make the point 1 and 2 work. however when visiting front only the content of the first visited city appears, which make sense because the Invalidation of the cache depends on the url and  is only 1 url.

I tried this but didn't work:

global $selected_city;
'#cache' => [
    'keys'=>['home_slider_'.$selected_city],
    'tags'=>['node'],
    'contexts'=>['url']
  ]

Where $selected_city is coming from the cookie or the request depending on separate logic.

Is there a way to Invalidate the cache per url + global variable ?

EDIT: The answer below fixes the issue for authenticated users but doesn't fix it for anonymous users. Any help with that would be appreciated.

The issue I had is the front page always returns the first visited city. Which is normal because the cache was invalidated by url OR node and the homepage has 1 URL. So unless I create/update/delete a node the cache would not be invalidated.

The solution was to create my own cache context, i.e city and merge it with the url context. This would invalidate the cache per url per city and create a combination of the different possibilities.

Here is the code :

city/city.services.yml

cache_context.cw_city:
    class: Drupal\city\CacheContext\CityCacheContext
    arguments: []
    tags:
      - { name: cache.context }

city/src/CacheContext/CityCacheContext.php

<?php
namespace Drupal\city\CacheContext;

use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Cache\CacheableMetadata;

class CityCacheContext implements CacheContextInterface {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {

    return t('some label');
  }
  /**
   * {@inheritdoc}
   */
  public function getContext() {
    // The logic goes here
  }
  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }
}

And on the block I merged the new context with the parent contexts like this :

/**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(
      parent::getCacheContexts(),
      ['city']
    );
  }

For more information please check this post


Entity form reusable form part I am creating more than 50 entity forms and major parts (contains 20 fields) of these forms are exactly same. Forms are different from each others only one or two field. If I need to edit major and exactly same part of these forms I must repeat editing process for all forms. Are there any aproach to solve this problem? I need edit major part of forms only one time.

Entity forms, also know as Reusable forms, because they are not created directly in the process but in the entity that contains their information, that is, in the Context entity.

Now you please take a look at "Reuse of field collection entity type on more than one collection field?", a drupal community question explains something about it(google for it).
I hope this would help though.

Thank you.


blocks are null on admin theme I made a sub-theme of the admin theme "Seven" and called it Seven2
Because I wanted to customize the node-edit-form.twig.html file.
That works.

My next step, I want to add a block I made in a custom module, to that node-edit-form.twig.html.
There are several ways of doing that, and one I chose is preprocess page (or node for that matter), where I want to load my block.

The preprocess functions can either be in Seven2 .theme file or the custommodule.module file.

When I execute:

$block = \Drupal\block\Entity\Block::load('checkmark_block');

The $block is NULL when I do kint($block). Its like it can't find the damned block!! I have spent like 4 hours trying to make this thing work, in different ways, but no matter what, I can't load that block in my preprocess function. I don't know why but I think it's because it's an admin theme? Or... please help.

One of the blocks located in custommodule/src/Plugin/Block:

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

/**
 * Provides a 'CheckMark' Block.
 *
 * @Block(
 *   id = "checkmark_block",
 *   admin_label = @Translation("CheckMark block"),
 *   category = @Translation("CheckMarks"),
 * )
 */
class CheckMark extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $markup = 'Test test';

    $build = array(
      '#type' => 'markup',
      '#markup' => $markup,
      '#cache' => array('max-age' => 0),
    );

    return $build;
  }

}

Ok, I made it work by the answer from this post:
How can I programmatically display a block?

And rendered it by adding this in hook_form_alter:

if ($form_id == 'node_article_edit_form') {
  ... code from the other post here ...
  $block = $plugin_block->build();
  $form['checkmark_block'] = $block;
}

And then in the twig file:

{{ form.checkmark_block }}

I find it way to difficult for a small task like this, and annoying to spend so much time on it, but one hopefully learns by it.


How to add classes to image fields set to Unlimited and a "rel" attribute to the  tag that wraps them I have an image field set to Unlimited and I have some questions on how to display them:

How do I display only the first image while all the rest are hidden (has class="hide")?
Add a rel="something" attribute to each  which wraps

Answer to #1 found! After several tests, simply capture the field by adding this to your field.tpl.php file. This will insert the hide class to all succeeding images after the first one.

<?php if( $element['#field_name'] == 'field_gallery') : ?>
  <div class="<?php print $classes; ?>" <?php print $attributes; ?>>
    <div <?php print $content_attributes; ?>>

      <?php $i = 0; foreach ($items as $delta => $item) : ?>

        <div class="field-item <?php if($i > 0) print 'hide '; print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
          <?php print render($item); $i++; ?>

      <?php endforeach; ?>

<?php endif; ?>

Don't you want to use a module like Views Slideshow: Dynamic Display Block to produce what you're looking for ?

If not you should create a specific template for your field using a name like field--field-name.tpl.php (Drupal 7 Template Suggestions), put it in you theme folder and customize it.

You can use theme_imagecache() if you're on Drupal 6 or theme_image_style() on Drupal 7.

$img = theme('image_style',
             array('style_name' => 'thumbnail',
                   'path' => $content['field_image'][0]['#item']['uri']
                  ));

Then you wrap your images in a using l():

$attributes = Array('rel' => 'rel_text');

echo l('yourpath', $img, array('html' => TRUE, $attributes));


How to debug what module/process is requesting a file? I moved my drupal 6 site to server with php 5.5 and the site started to throw not found error -  sites/all/libraries/jquery.ui/themes/base/jquery-ui.css on every page. I have not installed any new module and the file was never on that location. How would be possible to debug this? Thank you.

It is possible that the previous server was suppressing errors entirely and this error would have shown up had error reporting been turned on. In general, you can debug such errors by using the dsm() function from devel module. If you need to know where a functional call is coming from, you can use debug_backtrace().


Knocked out my own admin recongizion on my own site I have Drupal 6  site. In deleting spammers I accidently knocked myself out. Can I reclaim admin on my own site? Help.

If u are able to create account,create it and in the database for the 'users' table update '1' to the 'uid' field for the account you created and if you are unable to create a account then create a account manually in the database

INSERT INTO users (uid, name, pass) VALUES ('1', 'yourname',> md5('yourpassword'));


Commerce Attribute price is not updating in cart I am using commerce price attributes module then I am facing problem , price is updated on the product display node but not in my cart...also, there is no line item for the added price attribute.

Example :

In above images ,regular licence   is showing price $2.00 and School licence is showing price  $10.00.
i select school licence then click on add to cart button but price is show $2.00 in cart.

Unfortunately, the https://www.drupal.org/project/commerce_pricing_attributes module and it's brethren (product options and product attributes) are a part of what I like to call the "hunziker approach." This removes the idea of separate SKUs per attribute. Which has the unfortunate effect of giving the masses what they expect and distorting/side-stepping a very deliberate separation of logic in Drupal Commerce. It would be like forcing Views to store taxonomy terms. It might make your task easier, but it is not the right approach.

The "hunziker" approach to Drupal Commerce is not supported nor recommended by the creators of Drupal Commerce. Thus, any problems you might have with the modules is "by design" unfortunately.

If you want attributes to update the pricing correctly, try creating separate product entities with unique and single attributes and attaching them to one single product display node.


"The website encountered an unexpected error. Please try again later." error show on cache clear My Drupal 8 site is working fine but when I am clearing the cache then my site display below errors.

    The website encountered an unexpected error. Please try again later.

Please suggest me what is the problem ?  I have checked status report and it shows the error below

I was also getting the same error. The reason is given in the error message,i.e. Drupal is not able to find the specified controller. In my case, in the routing yml, the controller's path is "hello_world\Controller\HelloController", whereas my HelloController.php file was contained in the hello_world\src folder instead of the required path (**hello_world\src\Controller** folder).

My hello_world.routing.yml contents

hello_world.content:
 path: '/hello'
defaults:
 _controller: '\Drupal\hello_world\Controller\HelloController::content'
_title: 'Hello World'
requirements:
_permission: 'access content'


Theme for mobile devices I want parts of my site to be accessible to Android, iPhone and other mobile platforms. Is there a particular theme I should start with, or anything I should look for in a theme besides it being clean and simple?
Would I be better off creating a theme from scratch?

The Omega theme is a grid based theme that will allow the developer to use a shared CSS file and three different CSS files for different screen resolutions. This way the same site can be served to different devices without having to do a ton of work to make it look nice on all of them.


Restrict views to specific languages Using the locale modul (core) and i18n it is possible to show a language switcher, which will guide the user to corresponding nodes in another language. In case of views, this language switcher points to a view in every language. The views path i.e.

www.website.com/path/to/view

gets "translated" to every language

www.website.com/language-path/path/to/view.

Is it possible to change this behaviour or to restrict the view to specific languages?

If you want to map different URLs corresponding to the same view in different languages, this answer will help you. Basically you have to enable "Translation sets" and "Path translation" modules, both part of i18n module. Then in admin/config/regional/i18n_translation/path, add the translated paths and then add a "translation set" which will map all these pages together.

If you want to restrict the view to specific languages because it yields no results for the other languages, you can filter your view results by the user's current language and set a "No results behaviour" to display the view results for a different (default) language, using a Global: View area. See this question for more details. Of course you can also display a specific node (404 page or other) as a "No results behaviour".

@jumper: I've put this answer in case you want to give the bounty :)


Ajax callback on select box change event not working on second time I am building a form with form API in a custom module. Certain fields should be populated based on the selected value of a dropdown.

User will select the pre-entered profiles, based on which other fields should be populated.

I have used ajax callback on select box, it works fine for the first time. But not working on next time.

function multi_step_user_info_form($form, &$form_state) {
$form['user_data_form']['reference_number_ajax'] = array(
'#type' => 'select',
'#title' => 'Select a Patient',
'#ajax' => array(
        'callback' => 'ref_number_dropdown_callback',
        'wrapper' => 'ref_number_list',
        'event' => 'change',
        'method' => 'replace',
        'effect' => 'fade',
        ),
'#attributes' => array('class'=>array('dynamic-select')),
'#default_value' => isset($values['reference_number_ajax']) ? $values['reference_number_ajax'] : NULL,
'#prefix'=>'
',
'#field_suffix'=>'
');

$form['user_data_form']['patient_name'] = array('#type' => 'textfield',
'#title' => 'Patient Name','#value' => $patient_name, '#default_value' => isset($values['patient_name']) ? $values['patient_name'] : NULL,
'#prefix'=>'

',
'#field_suffix'=>''
 ); return $form; }

function ref_number_dropdown_callback($form, $form_state) {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'query')
      ->propertyCondition('status', NODE_PUBLISHED)
      ->fieldCondition('field_reference_number', 'value', $form_state['values']['reference_number_ajax'], '=')
      ->range(0, 1);
    $result = $query->execute();
    $nid ='';
    if (isset($result['node'])) {
       $nid = $nid = current($result['node'])->nid;
       $node = node_load($nid);
    }
  //  $form_state['rebuild'] = TRUE;
  // THESE TWO VALUES SHOULD BE POPULATED ON AJAX CALLBACK //
    $form['user_data_form']['patient_name']['#value'] = $node->field_patientname[$node->language][0]['value'];
    $form['user_data_form']['age']['#value']          = $node->field_age[$node->language][0]['value'];
    $elements = array($form['user_data_form']['patient_name'],$form['user_data_form']['age']);
    return $elements;
  }

You are using wrong notation for form elements, instead of field_suffix you should use "suffix" tag, as drupal is not able to track your closing tag, for a form element.

function demo_pane_form($form, &$form_state) {

 $options= array(1=>1, 2=>2, 3=>3, 4=>4, 5=>5);

 $form['user_data_form']['reference_number_ajax'] = array(
  '#type' =>'select',
  '#title' => 'Select a Patient',
  '#ajax' => array(
     'callback' => 'demo_pane_dropdown_callback',
     'wrapper' => 'ref_number_list',
     'event' => 'change',
     'method' => 'replace',
     'effect' => 'fade',
   ),
   '#attributes' => array(
     'class'=>array('dynamic-select')
   ),
   '#default_value' => 1,
   '#options' => $options,
   '#prefix'=>'
',
   '#suffix'=>'
'
 );

 $form['user_data_form']['patient_name'] = array(
  '#type' => 'textfield',
  '#title' => 'Patient Name',
  '#value' => 1,
  '#prefix'=>'

',
  '#suffix'=>'

',
 );

 return $form;

 }

 function demo_pane_dropdown_callback($form, $form_state) {

   $form['user_data_form']['patient_name']['#value'] =
   $form_state['values']['reference_number_ajax'];
   $form['user_data_form']['age']['#value']          =
   $form_state['values']['reference_number_ajax'];
   $elements =  array(
     $form['user_data_form']['patient_name'],
     $form['user_data_form']['age'],
   );

  return $elements;
 }


How to speed up node add form with around 50 fields? I had a node add form with around 50 fields, mostly text with 1 field collection (with another 5 fields) and a few entity and term references.

The page is taking around 30 seconds to load making it unusable.

There are several slow queries (99.28 - DrupalDatabaseCache::getMultiple, 34.21 - views_plugin_query_default::execute, 20.51 - DrupalDefaultEntityController::load, 18.46 - DrupalDatabaseCache::getMultiple, 17.46 - DrupalDatabaseCache::getMultiple.. they go on)

The Cache::getMultiple query has 1087 placeholders, and the EntityController::load has 1084 placeholders.

If a click on the "Add Another Item" on the field collection that takes a further 30 seconds to complete.

What can I do to speed up the load times of the page?

EDIT: I just installed APC which removed all of the caching queries but did not solve the problem - still around 30 second load time. I don't think the slow load times are related to caching. Is taking around 280MB of memory load build the page.

EDIT: Removing the field collection, installing memcache and entitycache has shaved 20 seconds off the load time. However 10 seconds to initially load the page and another 10 seconds per ajax request is still unacceptable. How do webforms perform with a large number of fields? Maybe that would be a better option?

Have you considered using multistep forms for your node creation?

Given that you have a lot of fields, you can do it at multiple page loads via various logical steps. There are lots of tutorials for multistep form implementation in Drupal and the example module ships with one.


What is the difference between renderPlain and renderRoot? I added a login form to a node with following code :

function my_theme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['login_form'] = FALSE;
  $variables['username'] = FALSE;
  if(Drupal::currentUser()->isAnonymous()) {
    $form = Drupal::formBuilder()->getForm(\Drupal\user\Form\UserLoginForm::class);
    $variables['login_form'] = Drupal::service('renderer')->renderPlain($form); // renderRoot
  } else {
    $variables['username'] = Drupal::currentUser()->getDisplayName();
  }
}

If I change the line

$variables['login_form'] = Drupal::service('renderer')->renderPlain($form);

to

$variables['login_form'] = Drupal::service('renderer')->renderRoot($form);

I can't see any difference. Both seem to work either.

I read the docs, the latter mostly checks

  Whether we're currently in a ::renderRoot() call.

but it is not very explicit about why /when this check is useful and so when to use the former or latter function ?

renderRoot() is for rendering the final result returned by a controller. renderPlain() is for rendering HTML which is not part of a page and is used for other purposes like emails. In your case the correct method would be render(), because this is the only render method which can bubble up metadata to the page. But you don't need to render at all, because you can put the unrendered form build array in a template variable and it will be rendered automatically when printed in TWIG.


How to add extra classes to  in Views? Is there a way to add an extra class to the View content wrapper, which outputs as <div class="view-content">?

To make it clear: I use Semantic views to generate a nice UL for a slider, but I am not able to add a wrapper with the proper class name to trigger the Jquery.

For Drupal 7

The div with view-content class comes from views-view.tpl.php template file.

You can always override your view theme and adjust the class names, HTML etc..

Under Advanced section of view click on information at the bottom of the section next theme, you will see a list of template files including the top level template which is views-view.tpl.php.

You can find a lot of tutorials how to override views templates file but in general, it's all about copying the right file to your theme and rename it with the right template file.

You can take look at this tutorial how to do that

For Drupal 8

Views UI no longer provide suggestions, In order to get the same information you need to enable Twig debugging.

You can enable Twig Debugging in sites/default/services.yml.

Set the debug variable to true. And clear cache.

parameters:
  twig.config:
    debug: true

(If services.yml does not yet exist; copy default.services.yml and copy it to services.yml.)

Using your browser debugger, you will see the templates suggestion as HTML comments, just be sure your browser debugger is set to show HTML comments.


how to add fields for drupal registration form internally souce code of drupal7.17 application generally all you are editing template in this location  files C:\wamp\www\drupal\themes\bartik\template.php
i think so ...
so please guide me how to create customise registration form step by step in this folder
like adding fields like

first name:-
last name:-
date of birth:-
email:-
user name:-
password:-
confirm password:-
location:-
referer:-

{not graphically using  wampserver opening site and login go to configuration/managefields}.
show me code method where we insert source code

example:-like using other applications
home.html,about us.html,form.html,contact.html

we are interlinking these pages..
generally we insert username password field in first page
if the user is not register we will add one more option signup
,when user click signup it will display registartion form
like this i want to create ....how it is possible
and also show database connectivity in dos command base
by using my sql software application

not in wamp server application ....create database

please any one suggest me  step by step using bartik theme.... or others.

thank you in advance
& sorry for bad english

To add the fields to user profile you should use Profile2 module.

With profile2 user account settings and user profiles are
conceptually different things, e.g. with the "Profile pages" module
enabled users get two separate menu links "My account" and "My
profile".
Profile2 allows for creating multiple profile types, which may be
assigned to roles via permissions (e.g. a general profile + a
customer profile)
Profile2 supports private profile fields, which are only shown to the
user owning the profile and to administrators.


Drush and MAMP3: cannot connect to database I've just updated to MAMP 3.1, and am running Yosemite 10.10.3 (public beta).  Since updating, I cannot perform any commands using Drush.

I have:

sim-linked from /var/mysql and also /var/lib/misql into /Applications/MAMP/tmp/mysql/mysql.sock
Tested the connection to the database using Sequel pro;
Tested the connection using a standard PHP script.

In both 2 and 3 above, I used the direct path to the MAMP socket, and also the one in /var/mysql/mysql.sock

So can anyone think of a reason why this won't work?

Thanks for those suggestions.  I inadvertently stumbled on  a solution.  I'm no expert here, so there could (and probably are) reasons why this isn't a good idea but I'll share it anyway.

I simply created a sim-link by doing the following:
cd /tmp
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock mysql.sock

Worked like a charm.


Showing each node's creation date but in the content-list (instead on in each node)? In Drupal 7, we can show nodes' creation date very easily by going to the edit back-end forum, scroll to the lower part of the form, and there add "show node creator and creation time date" (or a similar phrasing).

But, AFAICR this does not show creation date for all such nodes in the content list.

Is there a way to add a creation date column to the node list in the "content" page of the site?

I found a patch that supposed to do so but it seems to have failed testing.

I don't mind if the way to solve it is via a module or a codepiece I could implement somewhere with or without further customization.

Maybe someone here has a ready solution for this?

*As can be seen in the above image - there isn't any "sort by creation date column" here...

I believe the purpose of this module Administration Views is exactly what you are asking for.
Once you install it, it will allow you to override your "content" page.
This way you can add extra columns, sorting and filters to that page, using the Views UI.

The View you are looking for is called Administration: Nodes (at least in D7) and if you edit that and add fields, they will show up on the content overview page. (comment by @Neograph734)

You would need to edit this view, by navigating to the admin/structure/views/view/admin_views_node URL.
Add the "Content: Post date" to the field of that view
Configure the new field; set the Date format to "Short" and possible renaming its label to sth like "Created".
You can optionally rearrange your columns and also make the new "Created" column Sortable in the Table format setting
Save your view and visit the admin/content URL, it should now look similar to this:

Hope this helps!


How can menu title be included in breadcrumbs? I have menu block  with title 'Content'. It has several links. Breadcrumbs are made throw template.php by splitting url. Is it possible to include menu name before last link (which is content title) in breadcrumbs? I need to make it for all custom menu block links.

You can make use of drupal_get_title

  The title is displayed on the page and in the title bar.

Alter breadcrumb code accordingly.


How can I set a View contextual filter fallback? Ok I have 2 content-types:

Page
Video

I have a block in the sidebar that shows videos embed by youtube.

In the Video content-type, I have a Node References field that can reference any Page-type node.

I would like to set up the sidebar block View so that it can output a random video-type tagged with the current page-type node, however if there are no video-type nodes referencing the current page, or if the current page is not a page-type node, then it would select ONLY  video-type nodes that are either (depending on what is simpler to implement):

Have another field on the video-type which can tag the node as "global" (this would be preferable)
OR Not referencing any page-type nodes

I was hoping to try and make use of the Context module, but I'm wondering whether the module is quite so granular or conditional?

Thanks!

Ok, decided to write my own context condition plugin for this, all in a single file for a custom module that would be called custom_context:

function custom_context_context_registry() {
  $registry = array(
    'conditions' => array(
      'views_result' => array(
        'title' => t('Views Results'),
        'description' => t('Set this context when one of these views returns a result.'),
        'plugin' => 'custom_context_condition_views_result',
      )
    )
  );
  return $registry;
}

function custom_context_context_plugins() {
  $plugins = array();
  $plugins['custom_context_condition_views_result'] = array(
    'handler' => array(
      'class' => 'custom_context_condition_views_result',
      'parent' => 'context_condition',
    ),
  );
  return $plugins;
}

function custom_context_init(){
  if ($plugin = context_get_plugin('condition', 'views_result')) {
    $plugin->execute();
  }
}

class custom_context_condition_views_result extends context_condition {

  /**
   * Generate a list of database and module provided views.
   */
  function condition_values() {
    $enabled_views = array();

    $views = views_get_all_views();
    ksort($views);

    foreach ($views as $view) {
      if (!isset($views[$view->name]->disabled) || !$views[$view->name]->disabled) {
        $displays = array();
        foreach ($view->display as $id => $display) {
          $displays[$view->name . ":" . $id] = check_plain("{$view->name} : {$display->display_title}");
        }
        $enabled_views += $displays;
      }
    }
    return $enabled_views;
  }

  function execute() {

    $view_name_displays = array();

    // Gather all required views for checking, to prevent duplicate checking
    foreach ($this->get_contexts() as $context) {
      foreach ($context->conditions['views_result']['values'] as $view_name_display){
        $view_name_displays[$view_name_display] = $view_name_display;
      }
    }

    foreach($view_name_displays as $view_name_display){
      list($view_name, $view_display) = explode(':',$view_name_display);
      $view = views_get_view($view_name);
      $view->set_display($view_display);
      $view->build();
      $view->execute($view->current_display);
      if(count($view->result)){
        foreach ($this->get_contexts($view_name_display) as $context) {
          $this->condition_met($context, $view_name_display);
        }
      }
    }
  }
}

Just to explain how this works, it loads all the views which context module should check on hook_init and checks whether each view has rows or not. I've combined this with certain views which obtain their contextual filters from the current node ID.


dpm function doesn't display results for arrays I need to work over the hook_menu_alter function and I found that the dpm() function is not working for arrays. I have devel and admin_devel enabled. I flushed all cache to make sure the hook is fired.

function MY_MODULE_menu_alter(&$items) {
  dpm('hello'); // This is printed
  dpm($items); //This one is not printed at all
}

hook_menu_alter() is fired directly in the same call that flushes the caches - and only once. If you do that via drush cc all the result is never displayed.


How to handle a post request from an external application in Drupal? I am integrating with the Stripe payment gateway and I need to be able to handle a post from their server to authenticate a standalone account. I am trying to follow the instructions at https://stripe.com/docs/connect/standalone-accounts

Namely, I need to provide a callback URL which will receive the data I need through request parameters.

https://mydrupalsite.com/callback?scope=read_write&code=AUTHORIZATION_CODE

I need to be able to get the scope and the code value.

Once I have that, I will need to then redirect based on their values to certain pages.

I tried creating a MENU_CALLBACK type menu item with a page callback to handle the parameters, but what I tried didn't work.
Below is the code I tried.

function bh_commerce_stripe_oauth_menu() {
  $items = array();
  $items['bh_commerce_stripe_oauth/callback/%'] = array(
        'title' => 'bh_commerce_stripe_oauth_callback',
        'page callback' => '_bh_commerce_stripe_oauth_handle_callback',
        'page arguments' => array(2),
        'type' => MENU_CALLBACK
  );
  return $items;
}

function _bh_commerce_stripe_oauth_handle_callback($post_parm_args) {
  drupal_set_message(t('_commerce_stripe_oauth_handle_callback: called'));
  drupal_goto('<front>');
}

Your path is wrong I think. You should be able to access that callback here.

https://mydrupalsite.com/bh_commerce_stripe_oauth/callback/randomstring

So actually your hook_menu should look like this.

/* Implements hook_menu */
function bh_commerce_stripe_oauth_menu() {
  $items = array();
  $items['callback'] = array(
    'title' => 'bh_commerce_stripe_oauth_callback',
    'page callback' => '_bh_commerce_stripe_oauth_handle_callback',
    'type' => MENU_CALLBACK
  );
  return $items;
}

Note: You don't have any path wildcards (represented by % in your array key) in the callback you are getting that are useful. Therefore you don't need any page arguments. The interesting things are in the $_GET (or $_REQUEST).

And then to access the results something like:

function _bh_commerce_stripe_oauth_handle_callback() {
  $scope = $_GET['scope'];
  $code = $_GET['code'];
  drupal_set_message(t('_commerce_stripe_oauth_handle_callback: called'));
  drupal_goto('<front>');
}


Is performance affected on local server? I have my drupal on a server that doesnt have access to internet.

Does this hurt the preformance?

I am getting this error on the status report :

  "HTTP request status  Fails"

If it does, how can I overcome this?

Thanks

You should be able to set up Drupal on your local machine without an Internet connection, where you can do most of your development work. See this post on Drupal.org for info about setting this up properly. You shouldn't be getting any HTTP errors, I'd check to make sure you don't have any some external images, files or other resources (like feeds) embedded which would require the browser to fetch from www.


How to share fields between commerce variation types? Assume I have more than 100  different variation products and all of them share same fields ( such as commission rate, Brand, Weight and etc). As I understood so far, I need to create 100 product variation first.

Now, my question is:

Do I need to add each of these fields for each variation separately? or is there any way to add them only one? e.g how can I add these fields to the product entity so that every time I create a variation, it automatically adds all these fields, similar to sku and price?

p.s: I use commerce_kickstart-7.x-2.40

Any help will be highly appreciated!

Thanks

It sounds like what you're wanting to do is create a group of product variations where you only have to specifically set the unique field value per variation. If that's the case, it isn't possible. We tried to implement some sort of field inheritance model where you could set default field values for each variation at the product display level, but it never developed.

The closest thing is the Bulk Product Creation module, which does let you create a whole set of related product variations at once. I don't believe it's been integrated into Inline Entity Form / Kickstart 2.x, though, so you may want to play with it first in a development environment before trying it in your live database.


About shaping the Drupal "add content" pages My question is that do you change the Drupal "add content" pages appearance and fields for your final version of project?

Actually, I really do not know how it is conventionally provided for Drupal customers. If you customize those pages, how do you do it?

Thanks

I like to work with Panels to customize the Add content pages. I'll write down a small step by step tutorial to give you a starting point and maybe a better understanding how to module works if you are not familiar with it.

Once you have Panels installed you navigate to » Administration » Structure » Pages in the menu. Then enable the Node add/edit form variant.

When the variant is enabled click Edit and then Add a new variant. Click Create variant, choose layout and click continue on the next step click continue.

Now add the form elements you want in the respective regions by clicking the cog wheel in the top left corner of the region.

Under the category Form you will find all form elements.

In the example below I've added the title and body field to the left and the menu settings and the submit button to the right.

Under selection rules in your panel you can say that this variant is valid for the content type "Page" for example and have another layout/setup for other content types. If you don't add a selection rule the variant will take over the content creation page for all content types.

You can add new Panel layouts to a module/theme if the standard provided doesn't work out for you.

A gotcha
One small gotcha I've experienced is that if a field is not placed in the panel, let's say an image field. And you re-save existing content it will remove the image from the node. When the node is saved the submit function interprets the value as empty. To avoid this add the pane General form to one of your regions and click the cog wheel for the pane and css properties. Under css class enter element-invisible. This way all form elements are present but hidden by css to avoid the missing image situation :)


HTML after label radio button (depending on radio button) I need to add some html to specific radio buttons. This is a picture to clarify what I'm looking for:

As you can see I want to add some text to the options. These are radio buttons where you can select one option. This is what I have now:

I've tried adding html with the theme_radio function with suffix like this:

function ppprogram_radio($variables) {
    $element = $variables['element'];
    $element['#attributes']['type'] = 'radio';
    $element['#suffx'] = "
just testing
";

    element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

    if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
        $element['#attributes']['checked'] = 'checked';
    }
    _form_set_class($element, array('form-radio'));

    return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

But that didn't do anything ... . I've also tried adding html to the return but then it's added before my label and I want it after my label.

Hope this will help. please follow the comments.

 function CUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id){
        if($form_id=='YOUR FORM ID'){
           /* uncomment the following code after updating the key variables<field machine name> and check out the option keys.
           */
           // echo '
';
           // print_r($form['<field machine name>']['und']['#options']);
           //exit;
            $form['<field machine name>']['und']['#options']['<key>'] .= '
Hello World
';
            // the above code will add
Hello World
 alone with the existing radio button label
//Remove the comments if it helps.
        }

    }

Let me know if you need any additional clarity.

Thanks


Creat a test user with no access permisions On a site where only authenticated users have the permision to access content, I want to set up one test user that can log in but not access any content.

How would I achieve this?

This user will only be used to test different authentication methods. After logging in the user shoud get a "acces denied" result for all content.

I would say to create a role that has access to content, grant that to the existing users, then uncheck "access content" from the 'Authenticated' role. This will also allow the system to know that even if a user is logged in, this does not grant them special privilege until they have an elevated role assigned to them.

The authenticated role should be just a starting point for a user that logs in. I never leverage it for granting permissions in a way that would make it a 'unique' role - just make that role. Otherwise you are going to have to jump through hoops with code which can be easily avoided by creating a few roles.

You can assign a user multiple roles. During authentication, I take it you can figure out how or what role to assign to them. Every authenticated user will get the 'authenticated' role by default.


Is there a hook or sth after file is uploaded via file field? I have drupal 7 installation with file field + video field(and media module). I can change where to upload files in video field setting(default: videos/original).
I'm trying to do stuff to videos after file is uploaded and node is saved.
Is there a hook I can use to achieve this?

What I want Exactly: Make a copy of the videos to 2 different servers via ftp and some transcode codes. First file needs to be uploaded to drupal folder and after that I need my code to run. sometimes videos need to be converted using ffmpeg(move to videos/converted) and then I run my code.

I've found these hooks but none of theme get called after uploading files or even after saving the node:

hook_file_copy($file, $source)

hook_file_move($file, $source)

how about this one?

hook_field_insert or hook_node_insert

hook_node_insert() and/or hook_node_update() would probably be the right place to do this. Your code might look something like this:

function MYMODULE_node_insert($node) {
  // See if a file has been added
  if ($file_items = field_get_items('node', $node, 'field_file')) {
    // Get the first file item
    $file_item = array_shift($file_items);

    // Load the file object from the cache/database
    $file = file_load($file_item['fid']);

    // The path to the file is in $file->uri
    do_something_with($file->uri);
  }
}


How to send an email to a node author after selecting a specific value in a selected list field? Actually this is my content and I have one select list field in it. If I select a "New litter" and click on save, I have to generate an email to the author. If however I select any other value for that field (and click on save), then there is no need to generate an email.

How can I do this?

You can use hook_node_presave() and in this function check if the select value is "new litter" and generate email.

function YOUR_MODULE_NAME_node_presave($node){
    if($node->type == 'YOUR_CONTENT_TYPE'){
        //get your field value
        $field = field_get_items('node', $node, 'YOUR_FIELD_MACHINE_NAME')[0]['value'];
        //check if value equals "new litter" key
        if($field == 'NEW_LITTER_KEY'){
            generate_email();
        }
    }
}

change uppercase strings with your module and machine names


Execute product pricing rule for the order owner I have a custom product pricing rule set up in Drupal Commerce which gives users of role Trade a different price by using a different commerce_price field on the product which works fine.

But I need to export the values later on in to a XML file. The original product price is being returned as the rule is set up to use the Current user role, not that of the original user who made the transaction.

Is there anyway to have the rule act on the line item owner or for me to overwrite this in my XML output when calling rules_invoke_event('commerce_product_calculate_sell_price', $line_item);

In any product pricing situation, you should always make your user related conditions check against the commerce-order:owner token, not the site:current-user. That sounds like exactly what you need.


How to iterate thru a webform checkbox results How do you iterate thru a webform checkbox array like so :

Checkboxes_name :
☒ option 1
☒ option 2

[webform_submission:values:checkboxes_name_:value] print :

option 1, option 2

I would like to have

- option 1
- option 2

I tried something like this and other variants, but no luck :

<ul{{ webform_token('[webform_submission:values:checkboxes_name_', webform_submission)}}>
  {% for item in webform_submission.values.checkboxes_name_ %}
    <li>{{ item.value }}</li>
  {% endfor %}
</ul>

Thanks for your help

I'm not sure this require a technical answer. We would need more informations about the template you're in.

Usually, when you experience this kind of difficulty to access or decorate data, it means you're at the wrong template level. Manually iterating on elements in a template is not the "Drupal Way".

The rendering engine will do it for you and provide a template name (suggestion, that you could see in the source code with the debug activated)

Check carefully the provided theme suggestions to choose the template in which the actual checkbox is rendered.

Override the template by using a more specific suggestion. Copy the code from the previously used template, you will have to the name and attributes of the checkbox element and it will be much easier to manage the display you want.


All available variables returning node ID in views php in drupal 7 I am trying to define a custom field in D7 view, and I used views_php.
Here few variables are available as field tokens, but while using it inside the code, it doesn't return its original value, but does the node id.

Available variables:

$view: The view object.
$handler: The handler object.
$static: A variable that can be used to store reusable data per row.
$row: Contains the retrieved record from the database (e.g. $data->nid).
$row->nid: Content: Nid
$row->field_twitter_page: Content: Twitter Page
$row->field_facebook_page: Content: Facebook Page
$row->php: Global: PHP
$data: Contains the retrieved record from the database (e.g. $data->nid).
$value: Value of this field.

I need to fetch the value of "$row->field_facebook_page";
so I wrote:

<a href="<?php print $row->field_facebook_page; ?>"Like

When I click on the "Like" link, the given URL is empty. When I print the variable, I get the node ID.

What am I doing wrong?

Start with print_r to see what's available:

<pre>
<?php print_r($data); ?>
</pre>

You will likely end up using $data, something like:

$data->_field_data['nid']['entity']->field_facebook_page['und'][0]['value']

If that doesn't work, take a look at
http://drupal.org/node/1140896#comment-5945164


How do I add a user as a field in Drupal 7? References claims that it is now deprecated in favor of Entity Reference.  But I can't quite connect the dots on how an Entity Reference can point to a specific user.  Ideally, I would have this field simply be the user that originally submitted the node.

Basically, all I want is a "File" content type that includes the user who uploaded the file.  I feel like I am over-complicating it.  Please help.

Is this what you need?

Add a field to the File content type.  For FIELD TYPE choose "Entity Reference".
Save and configure the new field.  For Target type choose "User".


Entity reference edit link I have two simple content types

Parent
Child

The Parent content type has an unlimited value entity reference field which allows it to reference Child nodes.

The Parent content type Manage display for the Child entity reference field is set to "Rendered entity".

Now when viewing a Parent node, each of its Children nodes are displayed as well. Great.

However, I'd like to see an "Edit" link next to each Child node when viewing a Parent node. How can I achieve this? I'm hoping for a hover feature that would pop up a cog icon.

I thought the "Show links" option on the field's display settings would show some type of link(s), but it appears none are showing.

I hate to answer my own question, but all you have to do is enable the "Contextual links" module. This is a Drupal core module, and it can be enabled here:

admin/modules

Or with Drush via:

drush en contextual

This module is automatically enabled with a "Standard" Drupal installation, but if you use a "Minimal" installation this module will not be enabled.


How do I migrate dates? In my Drupal 7 site, the date is stored in the database as 2020-08-10 00:00:00.
When I migrate those dates without any formatting (field_blog_post_date: field_blog_post_date), the date is migrated into the Drupal 8 table with the same exact formatting. However, it doesn't show when a node is viewed.
I tried to use a format_date plugin.
field_blog_post_date:
  plugin: format_date
  source: field_blog_post_date
  from_format: 'Y-m-d H:i:s'
  to_format: 'Y-m-d'

When I use it, it causes the following error.

DateTime::createFromFormat() expects parameter 2 to be string, array given
DateTimePlus.php:251

this worked! found the answer here https://www.drupal.org/project/drupal/issues/2923723#comment-12343660
 field_blog_post_date:
        plugin: iterator
        source: field_blog_post_date
        process:
          value:
            plugin: substr
            source: value
            start: 0
            length: 10