Two login forms on a same page (user/login) I've used hook_form_FORM_ID_alter() to alter the user/login form.
Now I have to create another form that will have different submit handler because will be connecting with web service.

The hook_form_FORM_ID_alter() is altering the existing default login form and cannot create another form.
We have sellers and customers users.

The reason for creating 2 forms is: On the first form the submit handler is connecting with the web service for the customers method and the submit handler of the second one it should connect with the method web service for the sellers.
Is it possible to do this?

Here are some quick thoughts that should help you thinking.

I'm not sure yet if it's the best option (have to think about it for a while and I don't know all your details) but:

Create a new page via custom module, say /login.
Implement hook_page_alter() in the custom module and redirect all requests from /user/login to /login. Simply by:

if (arg(0) == 'user' && arg(1) == 'login') {
  drupal_goto('login');
}

Create an alternate login form through your custom module with different submit handlers etc.
On /login page, create any markup you need and pass the two forms. First form will be the regular drupal login form (you can get it by drupal_get_form('user_login')) and the second one will be the one you created manually. This way you have 2 login forms on the same screen with different submit handlers.

Check out user_login() function in the user.module file. That is the function that creates the login form.

Important: I didn't test this. Check it in and out to make sure there are no conflicts with other modules or workflows.

Hope this makes sense!


Adding stylesheets for an internal page only I am trying to add a CSS file to a specific internal basic page in Drupal 7 with no success.
After enabling the clean URL paths and add a path for my internal basic page I am able to capture the path using $path=drupal_get_path_alias();.

After that, I am trying to put condition statements so when a specific path is loaded a specific CSS file is loaded. I have this piece of code in ninesixty_preprocess_page(&$vars, $hook) in the template.php file.

if($path == 'about/advantages') {
  drupal_add_css(drupal_get_path('theme', 'ninesixty') . "/page-about.css");
}

I have tested the IF-statement by echoing the $path variable with total success. The page-about.css file does not load at all, though.

Please note that I am using Drupal with WAMP server, and the page-about.css file is located under drupal/sites/all/themes/ninesixty/styles/framework.

The path is incorrect; it should be as in the following code.

if ($path == 'about/advantages') {
  drupal_add_css(drupal_get_path('theme', 'ninesixty') . "/styles/framework/page-about.css");
}


more fields on a content type or more content types I know this is a situational/subjective question..... but I am trying to figure out a site architecture for a drupal site.

I have multiple products with different attributes/properties. I could either make one content type called 'products' with multiple fields for all possible attributes ..... or I could could make multiple content types; one for each type of product.

I am just looking for a 'best practice' kind of answer.

should I make one content type with more fields (that may go unused more often)

....

or should I make more content types.

Thanks in advance.

My personal preference is to limit the amount of content types, for user friendly reasons. Clients can get confused when you throw a whole list of content types at them. Unless your products are very different to each other (car, washing machine, house), I'd go for the fields.

Maybe the Field Group module can help to keep things tidy in the backend part of a product node.


Two Login Forms for the Site in Drupal 7 I've a site setup in Drupal 7 where every user who is not authorized is shown a username/password page through Logintoboggan Module.

All went good, until a unique requirement came.

First Scenario:-

I need to have a universal login page which will only have a password field. So whenever a user comes to the site and is not logged in, he will be shown a page with only Password Entry, where he will enter a password and will enter the site. The role of this user would be Authenticated User.
(I guess this can be done if I hide the username field somehow and pass a hidden username field along with the form )

Second Scenario:-

Whenever user, who is not logged in, wants to log in as an admin, he/she will enter the URL as www.site.com/admin and should be shown normal authentication page, which will have username/password field. One can then, enter the credentials and enter the site as an admin (normally, as we are doing now with every page).

Hence, I need two login page forms; one would have only password field and other would have normal username/pwd fields at a specific URL.

I'd be very thankful if you can help me in any regard.

Thanks.

If you are talking about a single account that everyone who uses the site will use, the security implications are horrible. In the context of a business site, what happens if an employee is terminated. Does everyone have to learn a new password. What about the case of one disgruntled user who does something malicious? Do you want to have to track responsibility by back-tracing an IP address? There are so many reasons not to implement this requirement.

Drupal looks up password by user (user name or unique email) and being able to attribute site changes to an individual user, and to control access by individual user is extremely important with most sites. To deviate from the tried and true method will require a custom module, and I seriously doubt it is a good idea simply to alter the user experience.


How to expose $user->data to views? Do I need to use hook_views_data like a custom table?

Actually, this can be done within the Views UI by selecting the user:data field and then choosing a key.


Check for empty field I'm using the following method to check whether a variable is set before printing

if (isset($content['field_name'])):
print render($content['field_name']);
endif;

But when the field is empty, unknown is printed.

Is there a Drupal method for checking empty variables?

$content['field_name'] is always set.
You can check if it's empty.

if (isset($content['field_name']) && !empty($content['field_name']):
  print render($content['field_name']);
endif;


Updating core with Composer doesn't work I am on D 8.3.0-rc2 and want to update to D 8.3.0 stable. Composer is my only option (requirement of address module). Composer core update doesn't bring me beyond 8.3-0-rc2, not even forcing it. Running drush composer require "drupal/core:^8.3@stable" gives me the following output:

  ./composer.json has been updated
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Nothing to install or update

The content of composer.json is the following.

{

"name": "drupal/drupal",
"description": "Drupal is an open source content management platform powering millions of websites and applications.",
"type": "project",
"license": "GPL-2.0+",
"require": {
    "composer/installers": "^1.0.21",
    "drupal/core": "^8.3@stable",
    "wikimedia/composer-merge-plugin": "~1.3",
    "drupal/address": "~1.0",
    "drush/drush": "^8.1"
},
"replace": {
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
    "preferred-install": "dist",
    "autoloader-suffix": "Drupal8"
},
"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php."
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }
},
"autoload": {
    "psr-4": {
        "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
    }
},
"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},
"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
}
}

I read about deleting vendor and composer.lock, but I don't understand why this would work.

Instead of trying to update Drupal directly with Composer, instead try starting with drupal-composer/drupal-project as a starting point. This project definitely works with Drupal 8.3.0.

Set up a new project with drupal-composer/drupal-project, and use composer require to add any modules you need. Once your code is the same in the new project as the old, you should be able to just copy the database over (or just point to your existing database with settings.php) and run updatedb.


Is there a Drupal.org issue queues module? Which module does Drupal.org use? Does Drupal.org use a module for its project issues tracking? I would like to implement it on our D7 site.

Does this exist as a module or is this something proprietary to drupal.org? If it is not a module, what is the closest I can get for Drupal 7?

The Project project, and Project issue tracker project, together make up most of the functionality that you are looking for. Since you ask about D7, it's worth noting that the modules are currently under upgrade to D7.

Project:

  Projects are generally assumed to represent software that has source code, releases, and so on.

Project issue tracker:

  It allows users to submit issues (bug reports, feature requests, tasks, etc) and enables teams to track their progress.


How to Style in Drupal Please, I need help.

I have a site design that has a totally different home page than the rest of the pages. The interior pages might present problems too, I don't know...everything in Drupal seems like a mighty struggle that takes days or weeks to understand.

At any rate, i'm using a zen sub-theme. I created all my blocks from scratch in the admin interface and then styled them in _custom.scss (imported to styles.scss) such that they all had styles to set them up exactly as I intended...It took awhile but I finally made it look like I wanted it to look.

Then I thought I should try using zen grids to do the layout since it was included in zen package and thought I would be able to utilize all the benefits of that system by doing so. So I re-did the entire home page by editing the responsive.scss in /layouts folder specifically for my home page layout with the blocks all over the place. But now I realize this won't work because I need to have a different layout on the other pages...possibly many different layouts...so maybe zen grids won't work for me, but I don't know that for a fact...I just don't know.

So I looked into creating a template.php function to call a different css file for the home page but after reading a bunch of articles on this site and other sites I couldn't get that to work either. I tried calling a different stylesheet if it's the front page from my .info file but couldn't get that to work either...maybe I don't know how to call the 'home page' correctly.

Does anyone have any tips for moving forward with what should be a fairly simple design using the zen sub-theme and about 6-7 other sites pages (including one custom module which is almost done and some views pages)?

The problem you are facing is that Drupal is so versatile that you may feel swamped by the many ways to accomplish this goal.

The things you need to do:

provide the correct body class
override the correct theme template at the appropriate context
inject the correct style sheet at the appropriate context (optional)

This is how you do it:

You must make sure that you have a body class that identifies the page you want to CSS style. Front page already has 'front' class. You can inject body class via template_preprocess_html (example here). Your CSS can then target the body class in the same style sheet (no need for separate style sheet).

To provide separate style sheets you need to inject different style sheet for different contexts. When using the info file the style sheet is always loaded. To do it conditionally, you will need to use drupal_add_css, and as you wish to do it at a page level you need to add that function probably in template_preprocess_html. You will need to detect the page that you are on by inspecting the url, then load the CSS file that you need. Example here: Adding style sheets

Style sheets can also be removed/altered via hook_css_alter

To target different layouts for different pages, look at Drupal 7 Template (Theme Hook) Suggestions. You can use the available theme suggestions, and you can also add your own (by ading to the theme_hook_suggestions key in an appropriate preprocess_function.)

If some of this sounds too complicated, just go with the Context module. That module has a slew of plugins that can do everything I described above. There are many tutorials, as in Drupal 7 Context module - Daily Dose of Drupal episode 72.

There are also many video tutorials available on theming with Drupal Zen and Zen Grids


Classes to differentiate between different status messages? After enabling my custom theme, I noticed that while Drupal adds special classes for different status messages being put out by the drupal_set_message() function, e.g. messages and messages--status. However, when I use drupal_set_message() in my module, the messages get displayed but no classes are added to the container that is displaying these messages, thus it makes them hardly stylable.

I've been looking for a solution but no site I've been able to find mentiones this. Is this a bug or am I doing something incorrectly?

Thanks a lot in advance.

I've been looking around in core a bit and found a solution from the classy theme. Copying its status-messages.html.twig file to my theme solves the problem since the type classes for each message are being set there.

{{ attach_library('classy/messages') }}
{% block messages %}
{% for type, messages in message_list %}
    {%
    set classes = [
    'messages',
    'messages--' ~ type,
    ]
    %}

I think this logic in views is a bit weird.


List Drush specific add ons, plug ins, extensions, or modules to use drush dl in automated script I'm writing a really basic bash script and want use drush dl to download the Drush extras add on.

drush dl drush_extras

But I need to check whether drush extras is installed before I try to install it (and then use it) because it prompts the following text.

  Install location C:\cygwin64\home\USER/.drush/drush_extras already exists. Do you want to overwrite it? (y/n):

How do I determine whether a drush add on/plug in/module (not sure what you call it) exists? So I handle that use case?

I'm trying to automate configuration, starting with assigning blocks to regions, and I have to make it work on Windows (first) and Linux. So I'm using Cygwin and Drush on Windows. There's probably different approaches, but this seems OK.

I would personally lean towards simply installing with -y. Adding -y onto the command you've listed will return Y accepting the default on any prompt that comes up (like the one you mention).

drush dl drush_extras -y

If you still want to check if it’s installed, you can check if the directory exists,

if [ -e $HOME/.drush/drush_extras ]; then
  # some logic here
fi

This won’t help you if the directory is empty though.

Another option is checking the output of

drush someCommand -h

Where someCommand is a command provided by drush_extras. You can compare the output of a valid one to an invalid one. If they match, it’s not installed.


Save as Draft functionality I have created a content type, and while adding content under this content type I wanted to provide author, the facility to save this content as draft which he later can edit and publish, ideally, a button with "Save Draft" besides "Publish" button. Is there any drupal module that provides such functionality. I have gone through "Save Draft" module, but I don't understands it exact functionality, it is just providing a button with label, what exactly is is doing is not clear to me. Please help me if I am missing something.

Thanks for your time.

What would the main use of this? If a content is kept as unpublished it is similar to saving the draft. It will not be visible to anyone else except the author and admin and any one else you have given permission to view the same. So this in itself is a good option. The save as draft module does the same thing it creates a button to uncheck or check the publish unpublish checkbox.

If you are looking for a workflow kind of feature then workflow module would be a better option. where you can define different workflow status and give different users permission to access the node in each workflow state.


Add permission to taxonomy programmatically I have certain content type .. when node is save it create: user,vocabulary
I used hook_user_save and taxonomy_vocabulary_save..
Which the vocabulary name is $node->title ..
All I need now.. How i give the NEW USER permission for NEW vocabulary?

permission for EDIT and DELETE the new vocabulary

By default, Drupal comes with a single permission to administer  vocabularies, so if you want your new user to be able to access only the new created vocabulary, you should take a look at the module Vocabulary Permissions Per Role. I never used it, but it sounds to fit your needs.

You'll need to explore how it handles the new permission and configure the module each time you create a new vocabulary.


Aggregating JavaScript generates errors and breaks JS functionality My website is working well but I was required to aggregate CSS/JS by enabling the system.performance.js.preprocess config key.
Once the JS code is within one single file I got some errors that doesn't show up when JavaScript is not aggregated:

Uncaught TypeError: Cannot read property 'bindAjaxLinks' of undefined
    at HTMLDocument.<anonymous> (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:579)
    at HTMLDocument.dispatch (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:3)
    at HTMLDocument.q.handle (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:3)
    at Object.trigger (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:4)
    at HTMLDocument.<anonymous> (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:4)
    at Function.each (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:2)
    at r.fn.init.each (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:2)
    at r.fn.init.trigger (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:4)
    at initContextual (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:500)
    at js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:532
Uncaught TypeError: $autocomplete.autocomplete is not a function
    at Object.attach (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:899)
    at js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:174
    at Array.forEach (<anonymous>)
    at Object.Drupal.attachBehaviors (js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:171)
    at js_gQksidT9DzO4kWsJTVsAaOllA_i35znbvgoaoo5Ut8c.js:356
    at HTMLDocument.t (js_BKcMdIbOMdbTdLn9dkUq3KCJfIKKo2SvKoQ1AnB8D-g.js:4)

This breaks the entire JS functionality of my site like drop-down menus and slideshows.

I'm using a custom theme based on Acquia's Cog. My theme looks like this:

name: 'My Theme'
type: theme
description: 'Custom Cog subtheme for my website.'
core: 8.x
base theme: cog
libraries:
  - mytheme/fonts
  - mytheme/fontawesome
  - mytheme/global_styles
  - mytheme/slick
regions:
...

And my theme's libraries file:

global_styles:
  css:
    theme:
      css/styles.css: {}
  js:
    js/dist/scripts.js: {}

The js/dist/scripts.js file is a JS file built with npm and gulp.

I have read in other answers this may be caused of undeclared dependencies since the undefined variables could be loading before the Drupal ones. I tried to split it into another library and set dependencies like this:

global_scripts:
  js:
    js/dist/scripts.js: {}
  dependencies:
    - core/drupal
    - core/drupalSettings
    - core/jquery
    - core/jquery.once

But there's no effect at all. Any hints on how to solve this?

This issue is usually -- but not always -- because someone has written Javascript without adding semicolons in the appropriate places. JS is valid without them but only when there is also a line-end at that point. Many JS preprocessors remove line breaks, so making the JS invalid.

This can be resolved by examining the JS source for missing semicolons and adding them; a good JS IDE will be able to guide you as to where.

Another issue that sometimes occurs is when the JS code has not been properly context-wrapped. Drupal standard practice is to include a function() { js(); code(); here(); } (); wrapper around code blocks because that limits the scope of names to that block; without it, the scope could be global and thus can be interfered with by other blocks of code.

The Drupal solution, which also solves another problem, is to use the "Drupal.behaviours". construct. Check the Drupal JS files for that string for examples.


Use Webform as Module Config Page? I am building a module that will create webforms for use with the Commerce Webform Order module. These must be somewhat constrained in their structure, so I have developed a form (using FAPI) to configure them.

Well, the form has become rather complex, with several "add another" fields and the like.  The Webform module handles these rather elegantly, and I'd love to use its capabilities for my module's config page, but feel that a traditional webform would be subject to error and fiddling.

The config page must look at a given webform (if specified) and use its content to pre-load values, or create fields, to allow for further settings adjustment (e.g. prices of items, additional fields, etc)

So, is it feasible to somehow invoke the webform module to create something that works like a webform but is under the control of my module?

Thanks in advance.

The Webform module just extends Drupal's Form API. Most of the elements available to a webform can be used in custom-built forms. For example, you can use the WebformMultiple element in any FAPI form.

@see https://git.drupalcode.org/project/webform/blob/8.x-5.x/src/Element/WebformMultiple.php


Relationships Between Content Types I have 3 content types that I have created: order, product and salesperson.

The fields for each are as follows:
Order: Purchaser Name, Product (entity reference to Product), Quantity
Product: Product Name, Salesperson (entity reference to Salesperson)
Salesperson: Name, Email

The way the system works is that a salesperson creates a product and then sells that product.  Each product will be tied to a salesperson (no other salesperson can sell that product). Once they receive an order, they would create "content" containing the name of the person buying the product, what product it was, and the quantity they sold.

I'm trying to figure out how to create a view that would let me allow a user to choose a product and have the view show how many of that product were sold.

Did I set this up the right way using 3 different content types with entity references or is there a better option?  If so, how can I show the sum of all the orders tied to a certain product?

What you are looking for is the equivalent of SQL aggregation. I have done this successfully in a Drupal 6 install using the Views Group By module. The process is pretty simple as long as you are reasonably familiar with views. Your setup sounds like exactly what you should have for this case.

In Drupal 7, the equivalent functionality is built into the default views module. You will need to open the "Advanced" section to see it.

An alternative approach would be to write a custom module that creates the SQL aggregation itself. But it sounds like you are already familiar with views and should stick with this approach.


How can I expose a view with date filter? I have a view and am listing a bunch of data from different content type .

What i need is , i have to list the data according to the date field given . That

is i have to filter the date in between two dates , Is this possible ?

WHAT I HAVE TRIED

I used the exposed filter as follows :

The problem of this filter is  i have to manually enter the date in date field .
can i have data field which can select the date as in datepicker ?

In 7 you can do this with Better Exposed Filters by selecting the jQuery UI datepicker option in the screen of your screenshot. There is an alpha out for 8.

  The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.

  Views Filters is a powerful tool to refine the results returned by a
  given view. When you expose a filter, you allow the user to interact
  with the view making it easy to build a customized, advanced search.
  For example, exposing the node type field as a filter lets your site
  visitor limit their search queries to just blog entries. Better
  Exposed Filters gives you greater control over the rendering of
  exposed filters.


What could cause the site to suddenly start dying with the "Call to undefined function entity_get_info()" error? So I was working away at trying to solve the problem I asked about in How can I combine the fields of two field collections in my theme? when suddenly Drupal died with this error message:

  Fatal error: Call to undefined function entity_get_info() in /path/to/drupal/sites/all/modules/entity/includes/entity.inc on line 57

This is the call stack.

Now since it seems to die when working with the field collection module, and I was working with that field, it is obvious that something I did caused the entire site to crash, but how, and how can I recover from it?  I can't clear cache to try to see if that fixes anything because drush throws the same error and I can't access the cache clear on the site itself obviously.

What I was doing

I was working on the theme_preprocess_field() function and had something like this:

<?php
function enviroscope_preprocess_field(&$variables) {
    $roles = array();
    if ($variables['field_name_css'] == 'field-doc-staff-contrib-fc') {
        foreach ($variables['items'] as $item) {
            $role = array_values($item['entity']['field_collection_item'])[0]['field_fc_doc_iges_role'][0]['#markup'];
            $user = array_values($item['entity']['field_collection_item'])[0]['field_fc_doc_iges_user'];
            $toreplace = $user['#object']->field_fc_doc_iges_user['und'][0]['entity']->name;
            $replacewith = $user['#object']->field_fc_doc_iges_user['und'][0]['entity']->field_user_family_name['en'][0]['#safe_value']
            $roles[$role][] = $item;
        }
    }
    kpr($roles);
}

I started adding some scaffolding for the next step, which was to be examining the field-doc-other-contrib-fc field collection field.

I meant to modify the code after kpr($roles); to read as follows:

    kpr($roles);
    variable_set('roles_to_pass', $roles);
} else if ($variables['field_name_css'] == 'field-doc-other-contrib-fc') {
    $roles = variable_get('roles_to_pass', array());
    // sort and mix these together
    variable_del('roles_to_pass');
}

My best guess about what possibly could have happened is that I accidentally wrote else if ($variables['field_name_css'] = 'field-doc-other-contrib-fc') { (note the = instead of the ==) which would have reset the field_name_css on every field except the first field collection field I was working on.  Would this explain the entire site going down in the way it has?  How can I recover from it?

In the morning if there is no answer I'll try deleting all rows from the various cache_* tables directly in the database, but for now I need to hit the hay.

Update

Clearing out the cache tables and commenting out my entire template.php had no effect.  Is my entire install hosed?

You have a classed FieldCollectionItem object in your variables table. Drupal 7 isn't designed to handle this.

When you use variable_set() to save an object to the variables table, the object must first be converted into a string using serialize(). Later, it will have to figure out how to convert that string back into a FieldCollectionItem object, and it will call the __wakeup magic method on the class to help it figure out how to do that. It turns out that __wakeup method requires code that isn't bootstrapped yet at the time that Drupal reads from the variables table, so you get the fatal error.

But you're not hosed. It looks you probably saved the object in the 'roles_to_pass' variable. If you can edit your database, try removing that record from the {variable} table, then clear your cache tables.


Skip confirmation page on node delete I'm trying to skip delete confirmation page only for a content type in my site.
I found this question but I can't figure out how to modify this code to affect only a nodes in a content type.
This is the code i found:

function mymodule_menu_alter(&$items) {
  $items['node/%node/delete']['page callback'] = 'my_node_delete_function';
  $items['node/%node/delete']['page arguments'] = array(1);
  $items['node/%node/delete']['module'] = 'mymodule';
}

function my_node_delete_function($node) {
  // Taken from node modules node_delete_confirm submit handler
  node_delete($node->nid);
  watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
  drupal_set_message(t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title)));

  // Do a drupal goto here to preserver the 'destination' parameter
  drupal_goto();
}

Just checking the node's type should be enough, and you can default to returning the standard deletion form:

function my_node_delete_function($node) {
  // If the node is of your custom type, delete it straight away.
  if ($node->type == 'my_type') {
    node_delete($node->nid);
    // ...
    drupal_goto();
  }
  else {
    // Otherwise, serve the standard node delete page.
    module_load_include('inc', 'node', 'node.pages');
    return drupal_get_form('node_delete_confirm', $node);
  }
}


Node object doesn't exist when not logged in I am trying to use the preprocess_page hook to add some twig variables.

All worked fine, until I logged out. When I'm logged out, the hooks $variables does not contain a node object.

Sample code:

function MYTHEME_preprocess_page(&$variables) {
  $variables['hero_image'] = '';

  if (!empty($variables['node'])) {
    $node = $variables['node']; // if logged in, this is set, logged out, it's not
    // other code here...
  }

}

Maybe you should check the anonymous user permisions
www.yourwebsite.com/admin/people/permissions/anonymous


How to hide View Page Menu if there is no content? I'm using the Views module (7.x-3.14) and I have a news view which shows all the articles on a page. I also have its Menu settings set to Normal, thus adding News to my navigation.

This works as expected; however, if there are no articles published, I would like the News link not to be added to my navigation. Essentially I would like a No results behavior for the menu.

Is there a way to accomplish this?

EDIT: I'm using Zurb_Foundation as my base theme which uses a custom function to create the menu that is called in preprocess_page. What I was attempting to do remove News from the menu at this point.

function theme_links__topbar_main_menu(&$variables) {
  // We need to fetch the links ourselves because we need the entire tree.
  $links = menu_tree_output(menu_tree_all_data(variable_get('menu_main_links_source',     'main-menu')));
  foreach ($links as $link){
    if(is_array($link) && array_key_exists('#title', $link)) {
      if($link['#title'] == 'News'){
        $view = views_get_view('news');
        echo count($view->result);
        echo $view->total_rows;
      }
    }
  }
  $output = _zurb_foundation_links($links);
  $variables['attributes']['class'][] = 'right';

  return '<ul' . drupal_attributes($variables['attributes']) . '>' . $output . '</ul>';
}

count($view->results) returns 0 and $view->total_rows returns NULL even though there should be results.

There are multiple options do do this, but all seem to require custom coding.

Maybe Hiding tab when view is empty or How to find out programmatically if a view has a result before rendering the whole view? give an idea of how to do that. They are both mainly about Drupal 6, but the same principles apply.

I would probably use some hook_preprocess or theme function, load the view using views_get_view(), execute that with all the necessary arguments if any, then check the result count and if that's empty, remove the menu link from the page. That last part is described in How to hide menu items without relying on permissions [SOLVED] and Customizing menu link output

Update:
So in your example you could do:

$view = views_get_view('news');
$view->execute();
$link['#access'] = count($view->result) > 0;


Add a New [content type] on each content type I want to create a block and put it in the sidebar of each content type that says "Add a new [content type]" So if the user was viewing an article, it would have "Add a new article", if the user was viewing a car, it would say "add a new car" etc.

Obviously I could make a different block and then control their display via context, but I'd rather create one block that essentially always links to add/new/[content-type] where content-type is whatever is being viewed.

Is there a way to pass in this argument via context?

In the hook that return the block content, call a function with a code similar to the following one.

function mymodule_node_add_link() {
  $node = menu_get_object();

  if (!empty($node->type)) {
    $types = node_type_get_types();
    return l(t('Add a new @name', array('@name' => $types[$node->type]->name)), 'node/add/' str_replace('_', '-', $node->type));
  }

  return '';
}

The hook calling this function should always check the value returned from the function. In the case the showed page is not a node page, menu_get_object() doesn't return a node object, and this function returns an empty string.

Notice that every string shown in the user interface should be passed to t(). When passing a string to t(), you should avoid concatenating string, but you should use the placeholders the function supports, as in the code I shown.


Anybody know how to create the filters to filter the content using views? Here my critical question is how to create filters in a menu which is having some child

filters too. Filters are taken from views based on (Year,and in child - dates,and in

sub-child - category's which we provide in taxonomy),so that while selecting the particular

fields in the child filters ,the result of contents should display. the filters should not be

a select list ,dropdown,or auto compete field.It should shown in a menu and filters are in

its child menu one by one.

anyone know how to do this Kindly reply for this shortly .Thanks in advance

When you are creating any filter in views then see the query string in the address bar. It gives you array.
You can use these query strings to create your custom menu links.
Use "AND", "OR" operators in filters.
Then do little custom code.
Also use $_GET to get filter values from filters.


Transactional entities? I'm working on a custom Drupal 8 module. In a form submit function, I need to create several entities of different types. I am worried about what will happen if something goes wrong in the middle of the operation, as it will be difficult to clean up the mess.

So my question is: is there any kind of transactional mechanism for entities, similar to SQL transactions, so that I could conveniently rollback in case of an error?

If not, what strategy would you suggest?

You can wrap all the entity save calls in a further transaction with Connection::startTransaction for a given database connection. Inject the database service into the form using FormBase::create

Catch using DatabaseExceptionWrapper and rollback :-). This is similar to Drupal 7 behavior as well.

It would be best to provide a unique name for the transaction as the transaction stack is fairly basic.


Edit/View Tab in Region other than Content I'm trying to set up two contexts for use with a sub-theme of Omega.

3 Column Context:
Uses the regions Sidebar First, Content and Sidebar Second. Content is 6 columns wide. The Sidebar regions are each 3 columns wide. This works fine.

2 Column Context
Uses "Content Second" (9 cols. wide) and Sidebar Second (3 cols. wide).

Content Second is an additional region added to the info file in the sub-theme.
regions[content_2] = Content Second

The problem that I'm having is getting the Edit/View tabs to display in that region, the way they do with region "Content".

I've added region--content_2.tpl.php to my sub-themes folder which seems to be working but when I add:

<?php if ($tabs && !empty($tabs['#primary'])): ?>
<?php print render($tabs); ?>
<?php endif; ?>

I get a "Notice: Undefined variable: tabs in include() " refering to that code.

Is it possible to get the Edit/View tabs in any region other than "Content"?

Have a look at the Delta Blocks module which is included in omega. It moves these tabs (and other things like Messages) into blocks.


DrupalQueue worker callback in separate file This is my first time using the DrupalQueue class, and I have two questions.

Does hook_cron_queue_info() HAVE to go in my mymodule.module file? I had some weird behavior before finally trying that, and it seems to be the culprit.

Can I put the queue worker callback in a separate file? I'm trying to keep all my queue functions in their own file, but it doesn't seem like I can do a file attribute like with a lot of other callback types; I just keep getting function undefined errors.

I tried...

function mymodule_cron_queue_info() {
  $queues['autopilot'] = array(
    'time' => 60,
    'worker callback' => '_mymodule_queue_handler',
    'file' => array('type' => 'inc', 'module' => 'mymodule', 'name' => 'includes/mymodule.queue'),
  );
  return $queues;
}

and

function mymodule_cron_queue_info() {
 module_load_include('module', 'mymodule', 'includes/mymodule.queue.inc');
  $queues['autopilot'] = array(
    'time' => 60,
    'worker callback' => '_mymodule_queue_handler',
  );
  return $queues;
}

but neither seem to work.

I was looking for this too. Turns out that it is not supported, judging from source in drupal_cron_run(). If your queue worker is sizable, one option is to create an intermediary worker callback in your .module file, then include and execute the mymodule.queue.inc worker from that function.


How to change order and depth of user account tabs With Tab Tamer we can change the weight/order of tabs in the user account under user/% (e.g. put user/%/edit after user/%/some_settings), but we can't set depth between the tabs (e.g. user/%/some_settings under user/%/edit/some_settings).

With User Tabs we can create some depth at least for user/%/edit (makes it as a subtab of Account), but it doesn't offer options to put other tabs as subtabs of Account.

So how to transform tabs to subtabs in the user account?

I forked User Tabs and added new subtabs (see NEW-SUBTAB in code):

/**
 * Implements hook_menu_alter().
 */
function usertabs_menu_alter(&$callbacks) {
  $callbacks['user/%user/account'] = array(
    'title' => 'Account',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
    'load arguments' => array('%map', '%index'),
  );
  //move the original edit and view items to below this container
  _usertabs_move_item($callbacks, 'user/%user/view', 'user/%user/account/view', MENU_DEFAULT_LOCAL_TASK);
  _usertabs_move_item($callbacks, 'user/%user/edit', 'user/%user/account/edit', MENU_LOCAL_TASK);
  _usertabs_move_item($callbacks, 'user/%user/NEW-SUBTAB', 'user/%user/account/NEW-SUBTAB', MENU_LOCAL_TASK);
  unset($callbacks['user/%user_category/edit/account']);
  if (($categories = _user_categories()) && (count($categories) > 1)) {
    foreach ($categories as $key => $category) {
      // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
      if ($category['name'] != 'account') {
        //it was too friggin complicated to support %user_category
        //see comments in user_category_load
        //all it does is check that the category name is valid
        _usertabs_move_item($callbacks, 'user/%user_category/edit/' . $category['name'], 'user/%user/account/'.$category['name']);
        $callbacks['user/%user/account/'.$category['name']]['tab_parent'] = 'user/%/account';
      }
    }
  }
}


Validate and submit functions not calling on template.php I have an user register form alter on my template.php and this is the code:

function mymodule_theme(&$existing, $type, $theme, $path){

  $hooks = array();
  $hooks['user_register_form'] = array(
    'render element'=>'form',
    'title' => 'Registro de candidatas',
    'template'    =>'templates/user-register',
  );
  return $hooks;

}

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

  $form['mail'] = array(
    '#type' => 'textfield',
    '#title_display' => 'invisible',
    '#attributes' => array(
      'placeholder' => t('Escribe tu correo electrónico'),
      'class' => array(
        'mymodule-form-email-input'
      )
    ),
    '#required' => true
  );
  $form['pass'] = array(
    '#type' => 'password',
    '#title_display' => 'invisible',
    '#attributes' => array(
      'placeholder' => t('Escribe tu contraseña'),
      'class' => array(
        'mymodule-form-email-input'
      )
    ),
    '#required' => true
  );
  $form['captcha'] = array(
    '#type' => 'captcha',
    '#captcha_type' => 'recaptcha/reCAPTCHA',
    '#attributes' => array('class' => 'captcha')
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Regístrate ahora')
  );

  $form['#validate'][] = 'mymodule_form_user_register_form_validate';
  $form['#submit'][] = 'mymodule_form_user_register_form_submit';

  return $form;

}

function mymodule_form_user_register_form_validate($form, &$form_state) {

  var_dump($form_state);

  echo 'This is my function';
  drupal_set_message(t('AN ERROR OCURED'));

  if (empty($form_state['values']['mail'])) {
    form_set_error('mail', t('Escribe un correo electrónico'));
  } else {
    if(valid_email_address($form_state['values']['mail'])) {
      form_set_error('mail', t('Email invalido'));
    }
  }

  if (empty($form_state['values']['pass'])) {
    form_set_error('pass', t('Escribe una contraseña'));
  }

  /*
  if (!$form_state['values']['sendgift']) {
    form_set_error(NULL, '', TRUE);
    drupal_get_messages();
  }
  */

}

function mymodule_form_user_register_form_submit($form, &$form_state) {

  echo ('This is my custom message');
  /*
  $newuser = array(
    'pass' => $form_state['values']['pass']['pass2'],
    'mail' => $form_state['values']['mail'],
    'init' => $form_state['values']['mail'],
    'status' => 1,
  );
  $user = user_save('', $newuser);
  $user->password = $pass; // Add plain text password into user account to generate mail tokens.
  _user_mail_notify('register_no_approval_required', $user);

  drupal_set_message('Tu registro ha sido procesado, ahora ve a tu email y activalo!');
  */

}

And I have the callbacks mymodule_form_user_register_form_validate and mymodule_form_user_register_form_submit inside mymodule_form_user_register_form_alter but these functions aren't called when I submit the form. Something wrong here? Please help. Thanks!

The hook hook_form_FORM_ID_alter does not return a variable. The $form variable is passed by reference so it can be modified inside the alter hook.

Remove the return $form; line from your mymodule_form_user_register_form_alter function.

Make sure you clear your cache after code changes to any of those functions.


how to create template file for single page in drupal 7 i have created "about us" page in drupal 7 admin interface of basic page type. I want to apply a specific layout for this "about us" page only.

But after goggling, i found solution of applying specific theme to specific content type like

page--content_type.tpl.php.

i dont want to apply layout for all pages in that content type, but only for this specific page "about us". If this can be done by overriding like this "page--node--nodeid.tpl.php", then where to find the nodeid for this page.

use "page--node--nodeid.tpl.php" template. you can find the nodeid for this page when editing.

edit "about us" page, you will got url like this http://www.example.com/node/1/edit

digit "1" in the url is node-id.


Adding (external) javascript to a theme I'm trying to add external JavaScript to my Drupal 8 theme. Can someone tell me what I'm doing wrong here? This function is in my MYTHEME.theme file:

      function MYTHEME_preprocess_page(&$variables) {
      $vars['ext_js'] = array(
        '#attached' => array(
          'data' => 'http://cdn.somelibrary.com/library/2.3.1/js/jslibrary.min.js',
          'options' => array(
            'preprocess' => TRUE,
            'every_page' => TRUE,
            'group' => 'NONE',
            ),
        ),
      );
}

Then in the theme I'm rendering it with:

{{ ext_js }}

Try adding 'type' => 'external', to the options array index.
By default, the type is considered to be a reference to a file hosted on your Drupal site; by using 'type' => 'external', you are specifying that data is a reference to a file hosted on a different host.


How to display batch progression with default theme of my site? I just created my first batch using batch API and it seems to work!
The progression bar is properly displayed during the execution and it uses administration theme, Seven for my site, which I guess is the standard behavior.
Is there a way to use the default theme of my site instead?
How do I do that?

In fact, my question was irrelevant.
It appears that I ran my tests of my batch using a user with administrator role. Hence the theme (Seven) used during the execution.
I checked that using another user (not being an administrator) and it was the default theme    of my site that was used.
By the way, I got the opportunity of some interesting readings. Thanks!


Drupal 6 memcache configuration I'm trying to use: Memcache API and Integration | Drupal.org w/ my Drupal6 and unable to determinate what am I doing wrong as when I hit memcache.php (MEMCACHE INFO) my Cache Usage shows me 100% of Free.

here is my info:

settings.php

$conf['cache_inc'] = './sites/all/modules/contrib/memcache/memcache.inc';
$conf['memcache_servers'] = array(
        '192.168.52.153:11211' => 'default'
);
$conf['memcache_bins'] = array(
        'cache'         => 'default',
        'cache_filter'  => 'default',
        'cache_menu'    => 'default',
        'cache_page'    => 'default',
        'session'       => 'default',
        'users'         => 'default'
);

drush

 Performance and         Memcache (memcache)                                 Module  Enabled        6.x-1.10
 Performance and         Memcache Admin (memcache_admin)                     Module  Enabled        6.x-1.10

system

# rpm -q php-pecl-memcache memcached
php-pecl-memcache-3.0.5-4.el6.x86_64
memcached-1.4.4-3.el6.x86_64
# service memcached status
memcached (pid  1482) is running...
#

SELinux

# getsebool httpd_can_network_connect_db
httpd_can_network_connect_db --> on
# getsebool httpd_can_network_memcache
httpd_can_network_memcache --> on
#

iptables

# iptables -L -n | grep 11211
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:11211
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0           state NEW udp dpt:11211
#

netstat

# netstat -an | grep 11211
tcp        0      0 0.0.0.0:11211               0.0.0.0:*                   LISTEN
tcp        0      0 :::11211                    :::*                        LISTEN
udp        0      0 0.0.0.0:11211               0.0.0.0:*
udp        0      0 :::11211                    :::*
#

First ensure that your cache confiuration are working witout Memcache. Disable memcache modules and enable caching through  the UI or in settings.php

$conf['cache_lifetime'] = '1800';
$conf['cache'] = TRUE;

Then check the response headers for anonymous users and look for x-drupal-cache. If it is a hit then you have it working if it's a miss then you must investigate further. You can check the cache_page table in the database table to start with.

If DB caching is working, proceed and add the memache settings and enable the module. Memcache integration only divert db cache to memcache. Once you do this, truncate the cache_page table, then check it after visiting pages as anonymous user. You can also check Memcache statistics. If the table fills up then memcache is not working fine and we will need more info. You can use drush to check the settings. drush vget |grep cache and post back.

Lastly check cache settings at admin/performance/cache if it is set to external you need to change that to normal for Memcache to work.


ckeditor yellow buttons I have installed ckeditor module for drupal 7.
Whenever any drupal form loads up, it comes up with yellow ckeditor buttons.
I have checked the configuration page to hide the yellow background of ckeditor ,but there's ain't any settings.

So how can I hide this yellow background color. Is this CKEDITOR theme or just configurable?
Has anyone experienced this issue?

It is Configurable. Go to

  Admin -> Configuration -> CKEditor

And Edit the relevant profile in the text formats.(In your Case choose edit the fullhtml) Choose
Editor Appearance
and there will be a Drop down to choose User Interface Color, Select CKEditor Default. If its already default then there must be some CSS override.


In hook_form_alter how can I attach libraries on frontend only? I'm trying to attach a js file to a form using hook_form_alter() but I don't want to js to be loaded on the administration template.

How can I achieve something like this? With what do I need to replace the THEME != ADMINTHEME part in the following code snippet?

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (($form_id == 'node_CUSTOM_edit_form' || $form_id == 'node_CUSTOM_form') && THEME !== ADMINTHEME) {
    $form['#attached']['library'][] = 'MYMODULE/myLib';
  }
}

To answer your question, you can get the active theme name using below code in module file.

$activeTheme = \Drupal::service('theme.manager')->getActiveTheme()->getName()

and check if $activeTheme !== 'Your admin theme'.

Recommended way:

In your case as you want to add library specific to theme, it should be added in theme file and not module file.


Cannot Add Registration to cart: SQL Error with Registration and Drupal Commerce I have drupal site running core 7.42 and Commerce 7x-1.11 with Commerce Registration and Entity Registration. The modules all seem to be working fine as I can create registration products and product displays and add registrations to pages and such.

The problem is when a user tries to add the registration to cart it produces the following error

       PDOException: SQLSTATE[42000]: Syntax error or access violation:
       1064 You have an error in your SQL syntax; check the manual that
       corresponds to your MySQL server version for the right syntax to use near
        '))  LIMIT 1 OFFSET 0' at line 1: SELECT registration.registration_id
        AS entity_id, registration.type AS bundle, :entity_type AS  entity_type,
NULL AS revision_id FROM {registration} registration WHERE (registration.entity_id
         = :db_condition_placeholder_0) AND (registration.user_uid = :db_condition_placeholder_1)
     AND (registration.state IN ()) LIMIT 1 OFFSET 0; Array ( [:db_condition_placeholder_0] => 5
        [:db_condition_placeholder_1] => 1522 [:entity_type] => registration ) in EntityFieldQuery->execute()
    (line 1192 of /home/phislub9/public_html/includes/entity.inc).

I'm not sure what is causing the error, or how to debug it. It looks like a bad query is getting passed to the a drupal_alter function to modify query's in entity.inc.

So, the error was the result of missing registration states. I found the details in this post on the Entity Registration Issue Queue Pdoexception Error. I added a default "active" registration state, and this solved the problem.


Using Drush to upgrade Drupal I'm trying to determine if I can migrate a site from 6 to 7 with Drush 7. I get this, "Error: Call to undefined function drush_sql_empty_db()", and I did some searching and this function does not seem to exist in Drush 7. On the drush_sup page it says to use Drush 6 or later, which would insinuate that Drush 7 is compatible. Any insight would be appreciated, I'm not in the mood to downgrade my Drush installation.

Thanks!

The function drush_sql_empty_db() has been removed in Drush 7.  You have two choices:

Downgrade to Drush 6 (it is possible to install Drush 6 at a different location, and alias 'drush6' to point to the older version).
Fix the site upgrade command.

The equivalent function to drush_sql_empty_db() in Drush 7 is:

$sql = drush_sql_get_class();
$sql->drop_or_create();

There may be other issues with Drush site-upgrade and Drush 7; I have not tried it in a while.


No wysiwyg filter present in text format I keep reading you select the wysiwyg filter in configuration->content authoring-> text formats but it doesn't exist for me.

How can I get that filter to appear in list?

I have the wysiwyg module correctly installed and enabled.

I recommend you to do the following:

first add new text format from admin/config/content/formats
then check the correct options for your new custom text format
now go to wysiwyg configuration page admin/config/content/wysiwyg
you should see your new custom text format along with dropdown list to choose TinyMCE editor
make sure to select TinyMCE editor and click save

Note: in order for you to see/select different text format you need to have more than one text format (other than Plain text)


How to define settings from an install profile I am looking for the way to set some settings at the install step.

function genius_profile_final() {
  // Enable default permissions for system roles.
  $filtered_html_permission = filter_permission_name($filtered_html_format);
  user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('access content', 'access comments', $filtered_html_permission));
  user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array('access content', 'access comments', 'post comments', 'skip comment approval', $filtered_html_permission));

  // Create a default role for site administrators, with all available permissions assigned.
  $admin_role = new stdClass();
  $admin_role->name = 'administrator';
  $admin_role->weight = 2;
  user_role_save($admin_role);
  user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));
  // Set this as the administrator role.
  variable_set('user_admin_role', $admin_role->rid);
  // Assign user 1 the "administrator" role.
  db_insert('users_roles')
    ->fields(array('uid' => 1, 'rid' => $admin_role->rid))
    ->execute();

  // Create a role for webmaster
  $webmaster_role = new stdClass();
  $webmaster_role->name = 'webmaster';
  $webmaster_role->weight = 3;
  user_role_save($webmaster_role);
  user_role_grant_permissions($webmaster_role->rid, array_keys(module_invoke_all('permission')));

  variable_set('taxonomy_menu_vocab_menu_rubric', 'menu-genius-navigation-menu');
  variable_set('taxonomy_menu_vocab_parent_rubric', 0);
  menu_rebuild();

  // Set the regional settings First day to Monday
  variable_set('date_first_day', 1);

  // The return message is optional, if you omit it the default will be used.
  return '
'. (drupal_set_message() ? t('Please review the messages above before continuing on to your new Profile Name site.', array('@url' => url(''))) : t('You may now visit your new Profile Name site.', array('@url' => url('')))) .'
';
}

In genius_profile_final(), where as I understood Drupal is fully bootstrapped, I have variable_set('date_first_day', 1), but the first day of the week still is set to Sunday,  after the installation. So it is not working as I expected.

I am using the taxonomy_menu module, and I would like to set at the installation step the menu to be linked with the taxonomy. Because I am installing something known, I know the variable names that might be set are:

variable_set('taxonomy_menu_vocab_menu_rubric', 'menu-genius-navigation-menu');
variable_set('taxonomy_menu_vocab_parent_rubric', 0);

This is not working neither.

I have been following https://www.drupal.org/node/1022020 and looking at other examples but I have had no luck to find how to do this.

Is it possible to change settings in an install profile or are there any restriction? In that case, what restrictions are?

What am I doing wrong?

I can't find a hook called hook_profile_final on drupal.org. I also can't see where you found it on the link you're using (https://www.drupal.org/node/1022020). You are using an outdated version of the tutorial (https://www.drupal.org/node/67921).

You need to implement hook_install_tasks_alter https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_install_tasks_alter/7 and change a task, or do a form alter of the config page.


drush aegir and drupal I have created a platform on my aegir dev server and I found myself wondering once the platform in drupal7 is installed is there a way to create websites using that platform via the commandline.

Yes there is: it's a two or three step process, but automatable.

Step 1) Create a Drush alias, or in Aegir terminology, 'context' for the site using drush provision-save (arguments)

Step 2) Install the site using drush @(site context name goes here) provision-install

Step 3) (optional but recommended) Verify the platform in the Aegir interface to have it automatically detect the site and 'import' it into the frontend so that you can do other things to it later via the web interface. You can also run this verification from the command-line with drush @hostmaster hosting-task @(platform context name goes here) verify

For specifics on the syntax of provision-save etc, see my article, "Manage your Aegir system from the command line": http://mig5.net/content/manage-your-aegir-system-command-line.


How to add profile fields on Ubercart 3 checkout page? I used to use the uc_profile module to add user profile fields to the D6/Ubercart 2 checkout page, but I cannot find a suitable solution for that same functionality in D7/UC3. Can anyone guide me toward an alternative solution? I need to add things like "birthday" and "shoe size" to the checkout page, and I need those items to be displayed on the users' profiles.

Thanks!

You can try out the Extra Fields Checkout Pane module.

  This modules allows an administrator to define additional (billing and shipping) address fields (i.e. VAT) as well as custom order fields in Ubercart e-commerce suite. These fields will be available during checkout process and in order handling pages.


Content type / block or page .. how do we create a small text for a page in D8 Let's say, I have a footer where I want to show a simple text not menu or link just a simple block of text. So, since it's neither a page, an article or block ... is there any way to create a text and show it somewhere in D8?

Blocks can be used for many things including showing simple texts. Go to /block/add and create a block. Here you can provide a description and some body text. After saving your block you are redirected to the block configuration where you can place it.

By placing the block Drupal creates a block instance. For more information please see: https://www.drupal.org/docs/8/core/modules/block/overview


Restore a revision order in a command I have the 1288 revision, 1498, 1499, 1500 I want to restore the 1288 revision and remove the 1498 revision, in 1499, 1500 can I do this in my database?

Thank you

By looking at the database commerce_order and commerce_order_revision I don't think order revision is implemented in a way that is revertible. Probably that is the reason we can't find revision revert functionality either in commerce core or as a contributed module.


Is it possible for two drupal views to share the same pager limit I have two separate views 'now' and 'next', they both collectively must only have three items. Is there a way for them to share the same pager limit for example if the 'now' view has one item the 'next' view can only display two items as the pager limit is three.

If you want to create the blocks yourself, eg, not just via the Block UI and Views, you can hack it together with using various hooks available within Views.

First out the door, I could see using Views' standard block for the now View, but in the next block,  using views_get_view_result() to look at the results of the now View and depending upon its result, eg, how many results there are, changing the pager of the next View to be whatever you want, in this case 1 or 2.

Note that this of course entails running the now View queries twice, so you could create custom blocks containing both Views and statically save the information to be shared across the Page but that introduces other ugliness.

And then if any of these Views are cached, another set of issues crops up.

So, as @molot has mentioned in comments, there is a bunch to think about here.


Content Types and drupal_get_form I've created a content type for authenticated users to use, to create and edit & delete their own of. I have set up the permissions and can get access as a authenticated user to the forms directly via node/add/story & node/19401/edit.

Now i want to use the form on another page, to be used in a block within a panel.

$form = drupal_get_form('story_node_form');
return drupal_render($form);

using drupal_get_form doesn't seem to work correctly is there another function I should be using to pull in the form?

*UPDATE

I managed to get it to work using node_add

include_once(drupal_get_path('module','node') . '/node.pages.inc' );
return drupal_render(node_add('story'));

is there any security issues with this method?

This is no secure issues with this.

Drupal 6 return node_add('story')
Drupal 7 return drupal_render(node_add('story'))

  Returns a node submission form.

for more information checkout the node_add() function


Weird Add Content problem? I have been dabbling with Drupal 7 and I am not quite sure what I did but turns out that after the interval of that mindless exploring, if I decide to add a specific Content type, it redirects me straight to only one content type (a custom content type I created using the Add Content type option) without consenting me on what kind of content type I specifically want.

I am not sure where I goofed up but does anybody know how the 'Add content' redirects you to a specific content type happen. Maybe I disabled the existing content types somehow, but I am not quite sure.

Try looking at Content > Content Types.  If there is only one content type listed on this page, then it means you probably deleted all other content types.  This may be your problem.


My MYMODULE_config_preprocess_node(&$variables) is not displaying my variables I have 2 modules both implementing the same hook: hook_preprocess_node()

What I do is basically the same in both:

function MYMODULE_preprocess_node(&$variables) {
    $stuff_to_display = $variables['myfield'];
    $output = '';

$variables['my_stuff'] = $output;

}

When I use a debug function I can see my variable (my_stuff) there but is not rendering on the page

While is working for the first module is not working for the other.

I think you're halfway there! The thing is that it isn't enough just to set the variable in the preprocess function, now you have to go one step further and output it in your tlp.php template file.

So, find the correct template file in your theme that you want to use (is it a general node.tpl.php one or a one for a specific content type like node--article.tpl.php), and edit it to actually output the variable you've set.

So, in the tpl.php file you're using, you should have something like:

<?php print $my_stuff; ?>

Otherwise, you've set the variable, but never display it.  Does that make sense?  Is that what's going on in your case?


Differentiate between same nodes in Drupal Autocomplete Search I have implemented Autocomplete Search functionality. Autocomplete suggestion will be available based on characters typed in textbox. When user selects a suggestion then user will be navigated to the page.

Now I want to know that if any website contain same name then how to distinguish between these two.

Example - Website contain 4 Names of Person:- Sandy, Siren, Anita, Sandy.
When user type S in text field then 3 suggestion appear i.e - Sandy,Siren,Sandy.

How to distinguish between two "Sandy" using Drupal default Autocomplete feature.

Few Possibilities:

You can add a content-type name along with the node title when autocomplete shows the result to describe the user in which relation it goes. For e.g., "Sandy -- Content Type Name"
You can add a Nid along with the node title when autocomplete shows the result to describe the user in which relation it goes. For e.g., "Sandy -- Nid"
Nid I don't think is a good idea. But you can also set some relative name while getting result for user to know which "Sandy" should be chosen.

Hope it will take you on the right path.


Omega subtheme - Dropdown menus not working properly When on http://demo.drupalizing.com/?theme=corporateclean the source for About menu item is:

About

Our Team

Our Vision

However, on my site, when on the homepage, the source for Privacy (a menu item which has pages hanging off it) is as follows:

Privacy

It's only when I am ON the Privacy page, that the dropdown menus appear when I hover over the Privacy menu item. The source now is:

Privacy

Advice

Complaint management

What am I doing wrong, and why aren't the dropdown menus being displayed when on the homepage for example, but instead only when I am ON that page?

The usual behavior is for sub-menus to only expand when you are on the parent item; so if you have a tree like the one below, you would only see a dropdown containing "Child" when you are on "Parent":

Home

Parent

Child
Child
Child

SOLUTION:

Go into the menu list links  which is admin/structure/menu/manage/main-menu for the main menu and edit the item you want expanded ("Parent" in this case)
Check the checkbox "Show as expanded"

That item will now be expanded no matter where you are on the site.


How do I get the current node from a Block module? I'm looking to create a block that renders differently, depending on the content (metadata, really) of the node in which it is embedded.

The “Title” block is a good example of what I'm trying to do, I think. When you put “Page title” in a section (from the Structure menu), it displays the title of the node being displayed.

I'd like to do something similar. The end goal is to read the workflow state data from the node in order to provide large visual clues to readers that the document they are reading is approved/unapproved/et cetera.

There are some other similar ends to which I may put this technique as well, provided I figure it out.

Here's what I have:

/**
 * Provides a 'Workflow Block'.
 *
 * @Block(
 *   id = "workflow_tag_block",
 *   admin_label = @Translation("Workflow Block"),
 * )
 */
class WorkflowTagBlock extends BlockBase implements ContainerFactoryPluginInterface {
        protected $node;

        public function __construct(array $configuration, $plugin_id, $plugin_definition, $node) {
                parent::__construct($configuration, $plugin_id, $plugin_definition);

                $this->node = $node;
        }

        public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
                return new static(
                        $configuration,
                        $plugin_id,
                        $plugin_definition,
                        $container->get /*... something here, I think. I need this to be the node I'm rendering. */
                );
        }

        /**
         * {@inheritdoc}
         */
        public function build() {
                // do things with $this->node;

                return [
                        '#markup' => $this->t('Here Be Dragons! '),
                ];
        }
}

Obviously, there's an important line I don't have complete in there. The most obvious attempt would be: $container->get('request_stack')->getCurrentRequest()->get('node'). But that returns the WorkflowTagBlock object itself, not the primary content node.

I'm aware that multiple nodes might be rendered on the screen at once (for example, in a list), so I can't just try to snag the node id from the uri or anything like that.

This is done in other places, so surely there's a way to do it. How?

The Book module implements a block that needs to access to the currently viewed node, and it uses the following code, in BookNavigationBlock::build().

if ($node = $this->requestStack->getCurrentRequest()->get('node')) {
  $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
}

$this->requestStack is initialized from the following code.

  public function __construct(array $configuration, $plugin_id, $plugin_definition, RequestStack $request_stack, BookManagerInterface $book_manager, EntityStorageInterface $node_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->requestStack = $request_stack;
    $this->bookManager = $book_manager;
    $this->nodeStorage = $node_storage;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
    $configuration,
    $plugin_id,
    $plugin_definition,
    $container->get('request_stack'),
    $container->get('book.manager'),
    $container->get('entity.manager')->getStorage('node')
    );
  }

The code is essentially like the one you are using, but it seems that in your case, a module is messing up with what $container->get('request_stack')->getCurrentRequest()->get('node') is returning.

As workaround, if you find in which cases it happens, you could override BlockBase::blockAccess() to avoid your build() method is called in those cases.


Mass delete Drupal Commerce Coupons I have used Drupal Commerce Kickstart 2 + Commerce Coupons (fixed, %) + Coupons Batch create to create  coupons. Now, is there any way to remove all coupons?

The code below should do the trick. If you have Devel installed, just open the devel/php page and execute this:

// Get all coupons on the site.
$coupons = db_select('commerce_coupon', 'c')
  ->fields('c', array('coupon_id'))
  ->execute();

// We will store here all coupon IDs, so we can delete them at once.
$coupon_ids = array();
foreach ($coupons as $coupon) {
  $coupon_ids[] = $coupon->coupon_id;
}

commerce_coupon_delete_multiple($coupon_ids);


How to access the filepath of an image from a view on a content type I have a problem Accessing the file path of an uploaded image. I'm trying to create a custom Carousel and build it up in a Drupal Block. I'm pulling the array created from the view of the content type like so:

$slides = views_get_view_result('slide');

foreach ($slides as $slide) {
    echo $slide->_field_data['nid']['entity']->field_slide_image['und'][0]['uri'];
}

My problem is that URI prints out "public://someimage.jpg" instead of "someimage.jpg" or "sites/all/images/someimage.jpg." I know I could do a string replace on this, but Drupal must have a way of getting the right file path to the image. Any suggestions?

You can use file_create_url($uri) which will generate an absolute URL (including $base_url which contains your server domain name).

print file_create_url('public://someimage.jpg'); will generate something like http://localhost/sites/default/files/someimage.jpg if your website is installed in localhost and your files are located in the default directory.


Get current taxonomy in template_preprocess_html() I have a custom field on my taxonomy that I would like to access in template_preprocess_html(). How do I get the current taxonomy id, in Drupal 8, on a taxonomy listing page?

First, check if the route is for a taxonomy term; then, get the term ID.

if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
  $term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
}


Views api: how to create a 'conditional' join I have 3 tables:

Table 1      Table 2            Table 3
id_1 [...]   id_1, type, id_2   id_2 [...]

I want to join table 1 to table 3 by way of table 2. This is easy enough,eg.

$data['table3']['table']['join']['table1'] = array(
  'left_table' => 'table2',
  'left_field' => 'id_2',
  'field' => 'id_2',
);
$data['table2']['table']['join']['table1'] = array(
  'left_field' => 'id_1',
  'field' => 'id_1',
);

However, the intermediary table also has a 'type' attribute in it. What if I want to specify, as part of the join, what the type is? eg. I want something like this:

SELECT id_a.table1 FROM table3
LEFT JOIN table2 ON table3.id_2 = table2.id_2 AND table2.type = 'blah'
LEFT JOIN table1 ON table2.id_1 = table2.id_1;

To be clear, I want the condition to the part of the join, not after the fact (as a filter will remove null rows).

I havent done this in Views 3, but try the following, adopted from Views2 blog post applied to your code:
http://www.agileapproach.com/blog-entry/views-2-table-aliases-and-extra-criteria

# I think you had typo in your join for table2 where
# you had as the final key 'table1'.
$data['table3']['table']['join']['table2'] = array(
  'left_table' => 'table2',
  'left_field' => 'id_2',
  'field' => 'id_2',
  'extra' => array(
      array('field' => 'type', 'value' => 'blah'),
    ),
);


How does Drupal Commerce store Addresses for anonymous users I'm trying to figure out how exactly does Drupal Commerce store Addresses for anonymous users?

Let's say an anonymous user creates a shopping cart and fills in the shipping information, but has not yet completed the checkout (payment for example, so shipping information is already stored with the order). At this point, has the system already created a shipping entity, if so, then to whom, as the anonymous user ID is 0.

Else if the Shipping information gets stored only upon checkout completion, still, to whom is it assigned? Who is the owner of the address.

Commerce also allows for an anonymous user to later create an account that has all their order history and shipping addresses, has there been assigned a new unused user ID for the user, just in case they decide to register, to associate all this information, or is the address originally only tied to the order it self, with owner ID 0, and the user profile is created upon registration based on the order details?

Why I'm asking for all this, is that I'm creating an order process where the address is assigned for each product separately, and on checkout each product with different shipping address is moved to a new order with the specific shipping address. And with this in mind I still wish to keep the possibility for making anonymous purchases, and am trying to figure out the dynamics of the shipping addresses :)

Best regards,

Alari

Commerce will always create a new user upon completion of the checkout process of anonymous orders. This happens in a rule named "Create a new account for an anonymous order":

admin/config/workflow/rules/reaction/manage/commerce_checkout_new_account

If you want to clone the order, then, just act after the aforementioned rule has executed by creating a rule with a higher weight.


Where is the field exclude checkbox in Content type > Manage display in Drupal 7 When editing a content type in Drupal 6, in "Display fields", there was a checkbox to "exclude" field (not just a dropdown for hidden).

Is there something like this for Drupal 7?

Clicking and dragging the 4-arrow handle, you can move the field (which one you want to exclude) under "Hidden" (In Drupal 8 this is now called "Disabled".) in admin/structure/types/manage/{content type name}/display.


Drush DB connection on MAMP I have a slight issue in connecting Drush to my MAMP localhost DB. Already tried multiple solutions like changing host from localhost to 127.0.0.1, and editing MAMP files like this suggestion.

It seems my socket location is slightly different from most examples I see on the web, being var/mysql/mysql.sock rather than tmp/mysql.sock. I installed via homebrew, if that's helpful.

Super new to drush, and command line in general, so any help much appreciated. All file transfers (like dl) work fine, just anything DB related throwing an error. Thanks!

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

Drush was attempting to connect to:
 Drupal version        :  7.24
 Site URI              :  http://default
 Database driver       :  mysql
 Database username     :  root
 Database name         :  DB_name
 Default theme         :  garland
 Administration        :  garland
 theme
 PHP executable        :  /usr/bin/php
 PHP configuration     :
 PHP OS                :  Darwin
 Drush version         :  6.1.0
 Drush configuration   :
 Drush alias files     :  /Users/UserName/.drush/pantheon.alias
                          es.drushrc.php
 Drupal root           :  /Applications/MAMP/htdocs/landmark/landmark-l
                          earning
 Site path             :  sites/default
 File directory path   :  sites/default/files

OK, finally got it working:

sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

Thanks to Remy for putting me on the right track, and This drupal.org post.

Seems it was that I needed to make a directory first... Rookie move.


Assign specific template to specific pages H i I am quite new in Drupal and have been trying to figure out a way to assign a specific template file to some specific pages following the taxonomy like page--user--edit.tpl.php works but I don't want to create a single template file for each page I require to change. I have been trying the following code but this doesn't work for me is there any cleaner way to achieve this in drupal 7

function phptemplate_preprocess_page(&$vars) {
 if (arg(0) == 'node' && (arg(1) == '10')) {
   $vars['template_files'][] = 'page-sometest';
 }

See here Drupal 7 Theme Hook Suggestions

For nodes You can use

  node--[type|nodeid].tpl.php

  base template: node.tpl.php

  Theme hook suggestions are made based on these factors,  listed from
  the most specific template to the least.  Drupal will use the most
  specific template it finds:

  node--nodeid.tpl.php

  node--type.tpl.php

  node.tpl.php

Also Drupal 6 Template Suggestions

To use same tpl for multiple pages you need to use theme_preprocess_node Like

function theme_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  if(in_array($node->nid), $myuids)
   $vars['template_file'] = 'your_template_file';
}


Date format in another language I have a multilingual site. English and Dutch are the languages. I need to display date format in Dutch, ie  I need to display a timestamp in Dutch(nl), as 16 oktober 2017. Tried the below code and format_date(), but didn't do the trick.

$date = $node->getCreatedTime();
\Drupal::service('date.formatter')->format($date, 'custom', 'd F Y', $timezone = NULL, $langcode = 'nl'); //not working for me

format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = 'nl');

Above code returned date in "en" language. Am I missing something here.. Thanks..

The Drupal way of handling and translating Dates is through Configuration > Regional and language > Date and time formats, as Hudri mentioned in his comment.

The same date and time Pattern between languages

What you should do depends on what pattern you want your date to be in English, if it should also be 'd F Y' as in Dutch. If yes, then you should edit the relevant Date format through the interface. Content types use Medium as default for the “Submitted by” so edit that to keep things simple.

I expect you'll have the date and time related terms already translated into Dutch, so you'll get oktober and not October on the Dutch side.

Different date and time Pattern between languages

If you want the Pattern of the same Date format to be different between laguages, for example you want English to be “10/16/2017” with Dutch “16 oktober 2017” you need to translate the Date format Pattern.

What is important to mention is that you need to have the Configuration Translation module enabled to be able to translate Date format Patterns. This will add the Translate link to the Operations button drop-down:

This enables you to have a different Pattern for different Languages under the same Date format.

Don't forget to Flush cache if you don't see the changes on existing content!

Code manipulation

The format_date() is Depricated, more info: Date formats API changes, public function DateFormatter::format.


Twig template print all comments but not the comment form For context:
in my template file node--some-node.html.twig i have a grid of items which have a custom comment form on them. The form creates a comment through an API. The form passes the ID of the grid item it is under to the API and the created comment then has a field_profile_id with the item's id in it. Now, in the template file I need to output JUST the comments that belong to that grid item.

When I write this into the template file:
    {{ content.field_comments }}
i get the output of all the comments that belong to this node and underneath I get the comment form (which I don't need). Ideally I would like to do everything in the same template file, so I could do something like this:

{% if entity.nid.value == content.field_comments.someComment.field_profile_id %}
{# output the comment here #}
{% endif %}

Here the entity.nid.value is the node id of the grid items I was talking about earlier.

EDIT:
Theoretically what I need to do is:

Iterate through all possible comments for this node.
Check if comment has some ID value (that a grid item might have)
If the IDs match, print out the comment, if it doesn't skip it

You must add a file to your template called

field--comment.html.twig

Use the following code.

{#
/**
 * @file
 * Theme override for comment fields.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional title output populated by modules, intended to
 *   be displayed after the main title tag that appears in the template.
 * - comments: List of comments rendered through comment.html.twig.
 * - comment_form: The 'Add new comment' form.
 * - comment_display_mode: Is the comments are threaded.
 * - comment_type: The comment type bundle ID for the comment field.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 * @see template_preprocess_field()
 * @see comment_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'comment-wrapper',
  ]
%}
{%
  set title_classes = [
    'title',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

  {% if comments and not label_hidden %}
    {{ title_prefix }}

{{ label }}

    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}

{{ 'Add new comment'|t }}

    {{ comment_form }}
  {% endif %}


Loading taxonomy terms in a tree in Drupal 8 I have multiple level of vocabulary, I want to display all level in the hierarchy same as taxonomy display. My taxonomy is like.

All
   Drinks
      Alcohol Drinks
         Beer
         Vodka
      Alcohol Free Drinks
         Coca Cola
         Pepsi
   Fruits
      Fruits For Losing Weight
         Watermelon
         Blackberrie
      Fruits For Dogs
         Strawberry
         Orange

now I am trying to load this using code.

$vid = 'food';
    $terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, 0, 1, FALSE);
    foreach ($terms as $term) {
        $term_data_1[$term->tid] = $term->name;
            $terms_2 =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, $term->tid, 1, FALSE);
            foreach ($terms_2 as $term_2) {
                $term_data_2[$term_2->tid] = $term_2->name;
                    $terms_3 =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, $term_2->tid, 1, FALSE);
                    foreach ($terms_3 as $term_3) {
                        $term_data_3[$term_3->tid] = $term_3->name;
                    }

            }
            $term_data_1[$term_2->tid] = $term_data_2;
            $term_data_1[$term_3->tid] = $term_data_3;
    }

    kint($term_data_1);

and this code giving result like

Need help to get term in hierarchy.

TermForm.php has an example of how to do this.

Basically you loop through the tree and add dashes according to the depth of the term.

Here's an example you can use:

$options = [];
foreach (\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid) as $item) {
  $options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
}

UPDATE: If you want a nested array of terms, you can do like this:

$result = [];
foreach (\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid) as $item) {
  $parents = array_reverse(\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadAllParents($item->tid), TRUE);
  $r = &$result;
  foreach ($parents as $k => $v) {
    if (isset($r[$k])) {
      $r[$k] = array_replace($r[$k], [$k => $v->label()]);
    }
    else {
      $r[$k] = [$k => $v->label()];
    }
    $r = &$r[$k];
  }
}

That will work regardless of how many levels your terms are nested.


How do I create a nested tree with terms & nodes with Views 3? I need to create something similar like this:

Colors (Vocabulary)

Red (term)

Dark (term)

Node 1
Node 2

Light (term)

Node 3
Node 4

Blue (term)

Node 5
Node 6

Green (term)

Node 7
Node 8

(Bullet points are indents.)
Is there a way to do this with Drupal 7 and views 3? If not, is there another way to do this?

Thanks to refino, I found a nice solution using the following modules: Views Tree
Views Field View

Below you find the explanation:

First create a new Taxonomy (let's call it "Folder")
Then, create a new content type (let's call it "Element") with a term reference field to the "Folder" taxonomy
Create a new "Content" View (let's call it "Element View")
Choose Field Display
Add a Contextual Filter to your term reference field
Create a new "Taxonomy" View (let's call it "Folder Tree")
Add 2 fields (term name and term id). The second field can be excluded from display
In Relation: add a "parent term"
Add a third field (term id) and assign it to your parent relation. This field can be excluded from display
Choose Format "Tree (Adjacency model)" and select in the parameters : Ordered list + Main field (your first tid), Parent field (your tid assigned to the parent relation). You now should have a nice tree with all your terms nested
Add a 4th field "Global:View" (this comes with Views Field View) and choose your "Element view", display Master add [tid] in the Arguments textfield

Hope this help

Cheers

Edit by iStryker:   This is what I got.  The only thing I changed was make Element View a table view, and removed the default (row & strip) classes.


Disable CSS and JS from a contributed module I am using Simple Mega Menu module.

I want to disable the CSS and JS provided by this contributed module:

modules/contrib/simple_megamenu/js/simple_megamenu.js
modules/contrib/simple_megamenu/css/style.css

In the module description the say

  Simple Mega Menu provide basic styling. You can override the library
  (css/js) provided by this module simply by adding theses lines into
  your theme file my_theme.info.yml

libraries-override:
  # Replace an entire library.
  simple_megamenu/base: my_theme/megamenu

How do I disable the CSS and JS files properly in my_theme.info.yml?

I think setting the library to FALSE should work:

libraries-override:
  # Replace an entire library.
  simple_megamenu/base: false


PHP snippet: why comparing the term id with a number keeps getting the wrong result? I have a Drupal 7 site. I have this taxonomy field that I get printed out using tokens and Display Suite Module.

So, if I create a "code field" at /admin/structure/ds/fields, I can type: [node:field-suscriptor-estado1:tid] in order to get the term id of that particular node. In fact that outputs correctly the term id. It outputs a number.
field-suscriptor-estado1 is the field of type term reference.

If I add var_dump($tidNum); I get int(0).

In order to show some differences between different terms, I try to compare the term ID to the one that I've got stored in database, and if they do match, it shows the result in one color. If they don't, the color is different.

As I know that the only terms that I will ever get there are 867 and 870 ("abierto" and "cerrado") I've done a quick if statement in order to achieve that:

<?php
  $tid = "[node:field-suscriptor-estado1:tid]"; //I assign the term id to a variable
  echo $tid; // I tested to see if I get it printed out using php, and it does print it: 870
  $tidNum = (int)$tid; // I transform the string variable to a number

  //now, if the number that the variable $tidNum has is 869 print the field with the class suscriptor-estado-abierto, else, print it with the class suscriptor-estado-cerrado.

  if ($tidNum == 869) {
    echo "
[node:field_suscriptor_estado1]
";
    } else {
    echo "
[node:field_suscriptor_estado1]
";
    }
?>

The only differences are the css classes that I assign to the field. That way, if it is "cerrado" (closed) it's in red and if it is "abierto" (open) the color is green.

My question is, why if the number that I do get is 870, it keeps printing it out as if the did match? (with suscriptor-estado-abierto class).

I've tried different ways: ($tidNum == 869), ($tidNum === 869), and ($tidNum != 869). This last one changing the color rules, naturally.

The result is the same. I've tried also with a new if, asking for $tidNum == 870.  The result is the same.

Why it isn't working?

If I try this, for the sake of testing, it outputs as it should:

  $tid = "870";
  echo $tid;
  $tidNum = (int)$tid;
  if ($tidNum == 869) {
    echo "abierto";
    } else {
    echo "cerrado"; // it prints out cerrado
}

This happens because you can't use tokens in the snippet itself.

When you print the token, PHP outputs the token as-is, but Drupal catches this output with Output buffering, and tokens are processed later.

In the field, see if you get the field item or taxonomy term as a PHP variable. Then, use that variable to extract the term ID.
You need to refer to the information provided by your module. If you have Devel module, you can inspect those variables using dpm function.

You are probably looking for something like this:
$node->field_suscriptor_estado1[LANGUAGE_NONE][0]['tid']


Create multiple basic pages with different fields I have a question to create a site in Drupal 8.

It is a website with about 60 basic pages, but each of them has different relationships, paragrphs, media.

My question is, how can I assign different fields per page and that the type of content does not grow monstrous? I am trying to reuse fields, but it has been very complicated for me.

IIUC you need the Bricks module. This module is similar to Paragraphs but a lot more abstract and allows for the customized options you mention.

You will have to create all the possible "Bricks" that can be found on your pages, then it won't be difficult to create each page with the custom structure it's supposed to have.

You don't have to use the Layout builder if your cases aren't that complex. The most important thing is to create some strategy around your different cases, analyze your needs so you know what different combinations need to be created. Go for the simplest possible solution, don't overcomplicate needlessly or you'll create a mess that is difficult to maintain.


How to correctly configure Fivestar module with a node reference? I have a content type "review" with a node reference to "product".
I want to be able to have users rate the product while writing a detailed review.
I added a Fivestar "rating" field in "review" and selected as "voting targed" the "node reference field".
Users can enter the review and rate it at the same time. I created a view to show all the reviews for a product and it pulls the ratings nicely from the "rating" field.

However I can't get a view configured correctly to show an average rating for a product.
I setup a relation with "Content: Vote results", left the "required" box unchecked, "value type" = percent, "vote tag" = "vote", "aggregation function" = "average vote".
All the vote results fields come up empty.

What am I doing wrong?

thank you

You first need to go to path admin/structure/types/manage/product/fivestar and click the Enable Fivestar rating for the "vote" tag. For Full node display I choose Static display above node body because the voting widget will be on the Review form.

At admin/structure/types/manage/review/fields create a Node reference called Reference with a machine name field_review_reference. Add a field for Fivestar voting. Set the Voting target to Node Reference: field_review_reference. Under Reference Field Settings check the Product content type. At admin/structure/types/manage/review/fivestar the widget should NOT be enabled.

(edit: paragraph removed per suggestion of ericduran)

Now you can create another View with field to make a list of products that show fields from the product such as title, price, and image. Add the relationship Content: Vote results. Set Value type as percent, Vote tag as vote and Aggregations function as Average vote. Add the field Vote results: Value, set Relationship to Vote results, set Appearance to Fivestar Stars (display only).

That should be it.


Language name of translated node For a teaser view mode I want to display the language of the content. I can get the langcode in twig with: {{ node.langcode.value }}
But how can I display the language name? In the field display I get only the string with "Language English", but I want only the name without any other thinks like "Language ...".

One way is to use preprocess node:

function mytheme_preprocess_node(&$variables) {
  $variables['lang_name'] = $variables['node']->language()->getName()
}

in the template file:

{{ lang_name }}

Is there a pure twig solution possible?

If you want to use the method language() in Twig

{{ node.language.name }}

you have to add it to the whitelist of the Twig sandbox policy in settings.php:

$settings['twig_sandbox_whitelisted_methods'] = [
  'id',
  'label',
  'bundle',
  'get',
  '__toString',
  'toString',
  'language',
];


How to translate a menu item in Main Menu with a path to a page View I'm sure I've done before, but I'm working in a fresh drupal installation and I guess I missed some configuration related to translation.

1) I created a new View which generate a Page.
2) I set No menu for Menu  (see image 1)
3) I set /inmuebles for Path  (see image 1)
4) In the Main Menu I added 2 links one for each language (english and spanish)  (see image 2)
5) Each link are set to the correct language (see image 3)
6)The problem: both link are shown in both languages. (see image 4)

Of course I need the links to be shown ONLY in their respective languages.

Image 1

Image 2

Image 3

Image 4

I was a problem related to Superfish module which I'm using to generate the main menu. Here is the patch for the superfish module patch


How can I link the file name to the file? I created a content type with a "file" field type. This to upload a pdf file.
Now I want to create a link to open that specific file, in my twig.
If I do this :
{{content.field_menukaart}}
, it opens my file correctly. But I want another link text other than my filename. For example "open here".
This is where I get stuck. How could I do this ?
This is not working :
open here

Thank you for your help,
Basiel

You can solve by implementing a preprocess function
/themes/mytheme/mytheme.theme
<?php

/**
 * Implements hook_preprocess_HOOK().
 */
function mytheme_preprocess_file_link(&$variables) {
  $variables['link']['#title'] = t('Open Here'); // change title
  $variables['link']['#url']->setOption('attributes', ['target' => '_blank']); // open in a new browser tab
}

Rename mytheme to your actual theme name and clear/flush caches so hook gets picked up.