Customizing User Profile - adding lots of extra parameters retrieved from my own database tables I would like to customize the User Profile so that I could display very much extra parameters that the user can set - and display them for users that watch other user's profiles; but these parameters would come from my own database tables.
I have to create a dating site, where users can set their own parameters like eye color, hair color, height, etc.

I already made a class from which these data can be retrieved and set, I just have to build it in the User Profile - or I could also place it anywhere else, but I thought it would be a more comfortable way to display these among other user parameters - and even set them when the user is watching his/her own profile.

Besides, I will have to make a page where users can search for their "future partners" depending on the different parameters that the users select (for example someone looks for a user with blue eyes and blond hair, or anything else :D) - my own queries would run and search for given users.

What do you suggest? Should I make a module? Or should I override my template files? What would be a nice solution? How would You do that in Drupal 6?

I hooe I could clarify what I would like to do, if something isn't quite clear, please ask!
Thanks in advance!

Don't put business logic into template files. Override the template files to present the information differently, not to calculate the information in the first place.

Profiles can be extended with the built-in Profile module or with Content Profile module. The latter uses nodes as profile categories, which means you can use CCK fields. You can also write your own profile module. For for this, you have to implement hook_user. You need to react to at least the following values for $op:

categories to provide your own profile categories,
form to show the form for editing items of the categories you provide (in case the $categories parameter is one of values you returned via categories),
delete, insert, update to persist changes to the user,
view to show the profile information for your categories.

For the matching, I suggest custom views handlers. Use the Advanced help module to access the developer documentation that comes with views.


What are best practices for supporting and upgrading a list of contributed and custom Drupal module? My organization has made the decision to build the next version of our website on Drupal 7 with the assistance of a consultant. The consultant will be responsible for the initial build and supporting the modules required by their functionality.

We will be responsible for supporting and upgrading the contributed and custom modules we install.

We anticipate the module list will be fairly long and management of module responsibilities will become an issue. We’re trying to come up with an easy way to track the modules installed on the site and whether they are the responsibility of the consultant or us. In a perfect world we would also be able to add notes as to why a particular module is needed.

Anyone know of anything already out there that would allow us to do this? We've looked but came up empty.

Using an Install Profile can really help with these situations.  Have the consultant create a profile and manage the modules they are responsible for in profiles/[PROFILE NAME]/modules.  You will be responsible for everything that is in sites/all.

You can use https://www.drupal.org/project/profiler_builder to easily generate an install profile from an existing site.  https://www.drupal.org/project/profile_switcher can be used to convert a site started with a standard install to use a profile.

https://www.drupal.org/project/profile_status_check is also useful to visually see which modules are being loaded from profiles/[PROFILE NAME]/modules vs. sites all as well as break out custom modules (regardless of location) vs. contrib.

Install profiles are as easy as developing a custom module.  Most people are only familiar with the Install Profiles that are included in Popular Drupal Distributions like OpenAtrium and Acquia Commons. Distributions are more difficult to manage.  They require drush make and/or .make files to manage contrib modules as well as 3rd party libraries.

While going to a full blown Distribution makes sense in some use cases, just using an Install Profile could be an elegant solution to defining who is responsible for different modules in your use case.


url alias not working when logged in as admin When I'm logged in as admin, the urls are un-aliased ("node/24"). When logged out they appear aliased ("about/us"). It might have something to do with the module admin_menu as suggested in a post over at drupal.org – but applying the recommended patch didn't work for me.

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

Hope somebody knows a way out? Thank you! t

update: thank you for suggesting to investigate first, if it REALLY is the admin menu – and of course it's not. I switched it off, but same situation. So I guess I'll better do some further 'research' by switching off and on various recently installed modules first…

-closing-

After dealing with this exact issue for a while in drupal 8, this thread made it click as to what the solution was.

For me, it was my choice of detection for the language that was causing the issue.

Go to /admin/config/regional/language/detection

And make sure that the only checked is the "selected language"

I had the User method checked "Follow the user's language preference." and that was what was causing the issue.

Now this might not work for a multi language site, but my site was originally in danish and I only wanted to have an english version.


Simplesamlphp Auth Role Assignment I've set up my Drupal installation as a Service Provider using Simplesamlphp and the Drupal Module Simplesamlphp Authentication (https://www.drupal.org/project/simplesamlphp_auth).  I'm successfully able to login using the www.example.com/saml_login method provided, but I haven't been able to setup the automatic role assignments.

From this page:
https://www.drupal.org/node/1931394

I've attempted comment #3 but was unable to get it to use the friendly name.  Here is what is being sent to me from my IDP:

<saml2:AttributeStatement>
         <saml2:Attribute FriendlyName="uid"
                          Name="urn:oid:0.9.2342.19200300.100.1.1"
                          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                          >
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >landy</saml2:AttributeValue>
         </saml2:Attribute>
         <saml2:Attribute FriendlyName="eduPersonAffiliation"
                          Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1"
                          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                          >
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >member</saml2:AttributeValue>
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >staff</saml2:AttributeValue>
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >employee</saml2:AttributeValue>
         </saml2:Attribute>
         <saml2:Attribute FriendlyName="eduPersonPrincipalName"
                          Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.6"
                          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                          >
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >landy@uab.edu</saml2:AttributeValue>
         </saml2:Attribute>
     </saml2:AttributeStatement>

But I'm unable to get it to automatically populate the role.  As an example, I've tried this:
3:uid,=,landy

It's never assigned him to RoleID 3.  I've been able to do this from the Rules module, but I'd like to be able to use it in this module if possible because the eventual plan is to use those Affiliation attributes as well which Rules cannot use.  Thanks for any help!

I've figured out the issue.

From here:
https://simplesamlphp.org/docs/stable/simplesamlphp-authproc

I had to rename the attributes to friendly names so I could use them in the assignment feature of the module.  The previous URL attempted to do that, but it wasn't quite as easy as the one line.  I had to add each URN to change to the friendly name that I wanted.


How to read the session cookie with javascript? I'm trying to detect with javascript if a user is logged in.
For some reason the drupal session cookie is not showing up when I use

alert(document.cookie);

It does show "Drupal.tableDrag.showWeight=0" and  "has_js=1" cookie.

When I use a cookie tool I see that the SESS... cookie is set.

Update:

I'm trying to fix a browser caching issue: Varnish sets a "cache-control max-age" header of 30 minutes which causes the browser to cache the page. When a user logs in and then clicks on a link that's already been cached in the browser it will appear to the user that they have been logged out again.

If I could read the Drupal session cookie from Javascript to see if a user is logged in I could then reload that page.

If your theme is somewhat standard, you should be able to look to see if the body has a class of "logged-in" or "not-logged-in" and key off of that.  Eg,

if ($('body').hasClass('not-logged-in')) {
  // do whatever you want for anon users
} else {
  // do whatever you want for logged in users
}

or if all in jQuery:

$('body').hasClass('not-logged-in').doWhatEverHere();

EDIT ADDITION DUE TO COMMENTS :)

It appears that drupal uses httpOnly with its cookie:

https://www.owasp.org/index.php/HTTPOnly

so you won't be able to access it from the client.  So..... given that, you might want to investigate setting your own cookie upon login and deleting it on logout and looking for that, but suggesting that makes me make Bill the Cat noises :)


How to put my FB code in a block? Im noob in Drupal and I don't know how can I put the FB code for display the last post in a block. I'd create a block with php code text format, but doesn't work, the block does not render the code.
This is the code from FB, if I put it into a plain html file it works fine

How can I put this into a block?
I'd created a block--fb.tpl.php cloning the block.tpl.php and pasted the code but this doesn't work either.
This is for not use the FB module because I should create an app and FB request my data and I don't want an app, just render the last post of the profile
can someone give me some gide with this?
Thank you so much for your help

if you using ckeditor firstPut your block text format on FULL HTML then   click on soruce  and finally paste your markups there.


Is it possible that search could index token content? Using the Token module with the Token Filter module, one can put a token in the body of a node.

When visitors search for a content they would like to find whatever is show in page, no matter how is it placed there. However, tokens are only replaced before node renders. Is it possible that the search mechanism could index the token content?

The search index includes the content of the nodes after they are rendered.

node_update_index() is an implementation of hook_update_index(), the hook that is invoked when the search index needs to be updated; it calls _node_index_node() which contains the following code.

  $node = node_load($node->nid);

  // ...

  // Render the node.
  $build = node_view($node, 'search_index');
  unset($build['#theme']);
  $node->rendered = drupal_render($build);

  $text = '
' . check_plain($node->title) . '
' . $node->rendered;

  // ...

  // Update index
  search_index($node->nid, 'node', $text);

Similar code is present in _node_index_node() for Drupal 6.

  $node = node_load($node->nid);

  // ...

  // Build the node body.
  $node->build_mode = NODE_BUILD_SEARCH_INDEX;
  $node = node_build_content($node, FALSE, FALSE);
  $node->body = drupal_render($node->content);

  $text = '
' . check_plain($node->title) . '
' . $node->body;

  // ...

  // Update index
  search_index($node->nid, 'node', $text);

In your case, if the node body contains a token such as [global:test], whose content is test, the search index will contain test, not [global:test].


How to create custom commerce order states? I want to create custom order state's and in a view use a "button" or a "select list" to toggle those states.

For example I have view that display's a table of all orders that are marked completed.
I would like to add a "button" or "select list" to each row so that I can toggle the state for each order.

Can this be done?

Two things there:

A. Define your custom order states with one of the Order info hooks.

hook_commerce_order_state_info
hook_commerce_order_status_info

B. Create a commerce_order based VBO view and add an operation to change the order state. It won't be a button on each row, just a checkbox or radio button, but you can batch update that way.

Alternatively, edit the order and set it's state on the edit form.


custom generate pdf with the header displaying only in the first page I'm using print module to generate pdf files from the drupal content. Here I use tcpdf library. The pdf files are working fine. But I want to customize the pdf files, here I want to display header in only the first page of the pdf file and the rest of the pages should display no header, but the footer should be common.

How can I customize the pdf generation? Is there a way that I need to change some thing in template files or library files. I tried to look into the tcpdf's lib-handler files - print_pdf_tcpdf.pages.inc. But I could find nothing related to restricting header.

Help is appreciated.

This might only be possible if you are printing multiple individual nodes to one PDF by overriding the provided print themes.

A solution that will work no matter what is to add your own class that extends the PrintTCPDF class. You should ideally do this in your own module, but I will show you here how to hack the print_pdf_tcpdf module.

Add a new file to the folder print_pdf->lib_handlers->print_pdf_tcpdf and name it

print_pdf_tcpdf_no_headers.class.inc

Add the following contents to that file:

<?php

class PrintTCPDF_No_Headers extends PrintTCPDF {
  public function Header() {
    if ($this->page > 1){
      return;
    }
    parent::Header();
  }
}

Open the print_pdf_tcpdf.pages.inc file and change line 65 - 66 from this:

// create new PDF document
  $pdf = new PrintTCPDF($orientation , 'mm', $paper_size, TRUE);

to this:

// create new PDF document
  $pdf = new PrintTCPDF_No_Headers($orientation , 'mm', $paper_size, TRUE);

Open file print_pdf_tcpdf.info and add the following:

files[] = print_pdf_tcpdf_no_headers.class.inc

Clear your cache and your pdf's will print with a header on page 1 only.

If you want to also print other nodes with headers on all pages you will have to implement some conditional logic in print_pdf_tcpdf.pages.inc file which creates the class needed ( PrintTCPDF or PrintTCPDF_No_Headers)


Which contextual filter should I use to make proximity filter get the URL param as center? I am following How to create a nearest node view / Sorting by proximity, which at the fist point says:

  Under Advanced, add a contextual filter returning the center entity's ID. For example, if you want to show the view on a node, as a block, select the "Provide default value" radio button and underneath for Type, select "Content ID from URL".

Which contextual filter should I use? I tried Global: Null, but it doesn't seem to be the right one.

The idea here is that you are creating a block to display on the node and need to add a contextual filter to return the nid to filter the results. You need to add the "Content: Nid" contextual filter.

You can do this by:

Add contextual filter
Select "Content: Nid"
Under "When the filter value is NOT in the URL" select "Provide default value"
Then under "Type" select "Content ID from URL"

This will automatically get the nid from the URL (node/nid) and apply the filter to the results.


Panels creates different pane number for any mini-panel inside a panel-node It's kind of hard to explain this but I'll try in a pragmatic example:

You have a mini-panel in a block, somewhere around a panel-node (say node/1, your homepage):

in the first panel-node (your homepage) this mini-panel has a CSS class named (For example): .pane-1
in the second panel-node (your "about-us" page) this mini-panel has the CSS class .pane-6
in the third panel-node (your "customers" page) this mini-panel has the CSS class .pane-11
in the forth panel-node (your "contact-us" page) this mini-panel has the CSS class .pane 14

And so on and so forth, you get the idea.

I would like to know why Panels creates different pane classes for mini-panels that appear inside panel-nodes?... It makes the CSS development very very hard, forcing me to fill the Style.css file with different classes that all has the same properties. It is also problematic in the sense that we shouldn't and can't adding a class to the Style.CSS each time when creating panel-nodes...

What is your most efficient way to handle with this and to achieve working just with a single general class for this same pane?

Please help,

Notes:

This problem doesn't occur in Nodes, it occurs only with Panel-nodes. In regular nodes it uses the same basic panel-pane class (for example .pane-1).
I Could supply direct links for examples in my site.

Here is but a very gentle example for the inefficacy of this method Panels works with that forces filling of Style.css with repitative lines of code.

I recommend using the pane configuration itself under CSS Properties to provide semantic class names for each pane. Create some sensible defaults for .panel-pane and extend it by adding classes. Eg users or themed-list list-striped. If necessary extend the concept using CSS ID's. But I think that's taking it a little far.

If that isn't enough then sometimes I create a custom panel layout with additional wrappers, classes and regions.


Disable vertical tabs by content type or user role Some users may only have the ability to edit one of the fieldsets that shows up in vertical tabs on the node edit form. In such a case it looks rather silly to be using vertical tabs since there is only one vertical tab to choose from. See screenshot:

So, is it possible to disable vertical tabs by user role? Or, barring that, disable them altogether for certain content types? For my use case I just want Location to not be displayed in vertical tabs.

I tried Renderable Fields and Field Group together but they managed the form incorrectly (buggy, I think). Arrange Fields can't separate out Vertical Tabs.

There are few ways to do this:

You can use the Renderable Elements module (as you mentioned above). It enables you to register any piece of build on your installation and manage the display through Field UI. It will make (additional) elements available of existing entities on the manage forms/display screens or you can for example register the contact form and rearrange the fields through Field UI. Works currently fine on forms, support for other is coming in a second iteration.
Or add the following to your custom module:

$config['yourcontenttype_node_form'] = FALSE;
variable_set('vertical_tabs_forms', $config);

A sandbox module that disables vertical tabs

Here is this core issue that refers to this.


How to add GitHub repositories in Profile Installation How to add Git repositories to install module while installing Drupal 8 Profile. Is any way to add repositories path in .yml or .profile to module installation?
Is this possible?

The easiest way is to add the dependencies to your profile's composer.json file, and use Composer to install the profile into your project. The dependencies will be automatically downloaded with it.

Failing that, it'll be a custom script job which will take whatever shape makes sense for your workflow/config.


How to restrict tagged content based on user? I'm using drupal 7.39, but I don't know how to restrict users to access some specific content.

I have created a content type called person. Then I have created 5 nodes, like so:

2 nodes tagged with manager term.
2 nodes tagged with lead term.
1 node tagged with worker term.

This is where I struggle:

the worker user must see node tagged with worker.
the lead user must see node tagged with lead and worker.
the manager user should see all nodes.

Is there any solution to get this to work (without writing custom code)? Because a configurable job is always easier.

Seems like using the Taxonomy Access Control module is the most straight forward solution to answer your question. Some details about this module (from its project page):

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

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

Together with using this module, you should also define 3 roles, i.e.:

Lead, granted to any user considered as "Lead".
Worker, granted to any user considered as "Worker".
Manager, granted to any user considered as "Manager".

With those roles and permissions in place, you have everything to configure your access rules as provided by the Taxonomy Access Control module.
PS: note that this has nothing to do with content type "Person" (as in your question). Not sure why you need/use that content type, but to get the above to work you don't need that.


Securing folder in Custom Module for Drupal 6 I wrote a custom module, which logs errors to an external text file.  The files are kept in

/sites/all/modules/custom/my_module/logging/

The problem is, if the user know the name of the file, they can go directly to it.  For example, if they go to:

http://localhost/MySite/web/sites/all/modules/custom/my_module/logging/

The will get a forbidden error.  But, if they know the name of the document and go to:

http://localhost/MySite/web/sites/all/modules/custom/my_module/logging/myFile.txt

the full file is rendered to the browser.  Is there a way to prevent this?  Ideally, I would like to show the files to certain users but at the very least prevent it all together.

The real problem here is that the files shouldn't be written into the module directory. There are actually two reasons for this (one of which you've run into):

it becomes harder to upgrade the module codebase (i.e. because you have to worry about accidentally overwriting the log files)
anybody can access the files (i.e. this question!)

You mention that you'd like certain users to be able to access the log files. You have a few options:

Move the logfile directory outside of the webroot

In other words, if your Drupal site resides at e.g. /home/foo/public_html, create a new directory at /home/foo/module_logs and write the files there instead.

This prevents Apache (or whatever webserver) from delivering the file, but lets it remain accessible to PHP which access it directly from the file system.
Deny access to the files in their current location

Assuming you're using Apache, you can use a .htaccess file in the directory where the files are written to deny access to them. Some variant on this should work:

<FilesMatch "\.txt$">
Deny from all
</FilesMatch>

As in #1, your module will still be able to read the files (this is what also happens in Drupal's default .htaccess file--you can see that it denies access to e.g. .info files, but Drupal can obviously still read them...)
Turn on private file downloads

I don't really suggest this to solve your problem, as it's kind of the 'nuclear option' and would affect every file controlled by Drupal. You can find this under the file system settings in the administration area.

In options 1 and 2, you will have to alter your module. In this one you probably wouldn't need to, but you might need to modify everything else in your site :-)
Use file system permissions

Again assuming this is running on an Apache webserver, you could also have your module set the o ('other users') bit of the log files' permissions to zero using PHP's chmod() function.

In other words, your files are probably being created with permissions 644, so you might try creating them with permissions set to 640 instead. Your PHP scripts (i.e. Drupal) should be unaffected unless you change the first or second digit.

In addition to being Apache-specific, this item also might work differently than expected if your Apache-PHP setup is different than I'm expecting.


Import to Entityform via Feeds? Feeds entity processor module? I've built an Entityform and now would like to use Feeds importer to add entries. Feeds does not seem to offer a processor for Entityform. I've done some digging and found the Feeds entity processor module.

Will this module allow me to target my Entityform via a Feeds importer?

The Feeds entity processor page offers this info:

  This module provides a generic processor for all entity types that
  support CRUD operations through the Entity API module.

I've done some digging into this too, but can't quite determine if this will do what I need. If there are other ways/modules that will help, I'm all ears!

FYI: Due to restrictions in my development environment, I can't simply give it try (wish I could!). I need to make requests for new modules to be installed... so I need to be pretty darn sure something is going to do what I need before I make the request.

CONFIRMED! Feeds entity processor module will allow importing directly into an Entity form via a feeds importer.


Clearing theme cache I added new code to the template.php and tried clearing the cache but it does not seem like the cache is being cleared. I tried the Admin ->settings->performance and drush (not sure if I installed it properly). Would there be any suggestions?

Drupal 6.

What's the new code that you've added to the template.php file? When I run into problems like this, in the 95% of cases I make a mistake and the cache clearing works, but my new code won't be recognized because of errors.

Basically, if you're able to run

drush cc all

without any warnings or errors, the cache clearing succeed and it should tell you that

'all' cache was cleared [success]


A menu block won't show up for second language I have 3 separate menus in my header. They are not connected. I don't used secondary menus.

My site is bilingual: english + spanish.

All 3 are created using menus and placed in the same region using blocks. They are all translatable: checked Make this block translatable. And they all have translated strings edited already.

However, when I switch to Spanish one of the menu dissapears and won't show up. I check in the DOM and is not build at all.

Another mention: the menu that won't show up is a category menu: it points to the a page that display article based on the specific category.

Can someone give me a clue?

In the specific menu edit mode: structure/menu/manage/your-menu/edit alter the Translation Mode.


Responsive Grid in Drupal 7 Views with 5 columns I'm trying to build a responsive Views grid in Drupal 7 and bootstrap3 sub-theme.
On Views I am using the Responsive Grid module as format.

In my Views format settings I configured the grid to 5 columns.

In order to support 5 columns in bootstrap I made an addition to my less file, according to this article: https://stackoverflow.com/questions/10387740/five-equal-columns-in-twitter-bootstrap in the answer given by lightswitch05.

My HTML markup created by Views would look like this

...

...

...

...

...

It all works just fine for the 5 column grid in Medium devices Desktops (≥992px) using the col-md-2-4 class.

The problem is for Small devices Tablets (≥768px) using col-sm-4 and Extra small devices Phones (<768px) using col-xs-6.

Since class "row" is already wrapping 5 elements when trying to display 3 or 2 grid columns there is either 2 or 1 element out of the grid row.

So the question is: Is it possible to create a responsive grid with 5 column grid for col-md, a 3 column grid for col-sm and 2 column grid for col-xs, in Drupal 7 Views ?

I think i figured it out.

If I set columns to 1 then I can use any responsive number of bootstrap columns according to the width.


Custom version of DateFormatter service I want to create a slightly different version of the formatInterval function. Normally I do this:

echo \Drupal::service('date.formatter')->formatInterval($seconds);

I want the final string to say not "1 hour 40 minutes", but "1h 40m" instead, so I was thinking about making a subclass of the core's DateFormatter class, and just change the protected $units property to define what I want.

How do I do this elegantly in a custom module, "the Drupal way"?

The full story can be found at Altering existing services, providing dynamic services, but essentially you need to add a service provider to your module, e.g. (mostly copied from the d.o page above):

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the date formatter service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides date.formatter class for custom interval formatting.
    $definition = $container->getDefinition('date.formatter');
    $definition->setClass(DateFormatter::class);
  }
}

(assuming your replacement class is \Drupal\my_module\DateFormatter)


How to give href links in custom modules for multilingual site? I've created a custom module,having a href links like follows.

Let's say the following link appears on example.com/somepage/another-page/nid

t('
Back to My Page
');

The above links works by default but it won't work if user is in Spanish version (example.com/es/somepage/another-page/nid).

If user click on the link it redirects to default lang version (example.com/my-page)

I tried $GLOBALS['base_url'] but it doesn't work in this case.

So my question is how can I give href link for multilingual? Any ideas would be much appreciated.

You have a mistake in your code.

Wrong:

t('
Back to My Page
');

Correctly

'
' . l(t('Back to My Page'), 'my-page', array('attributes' => array('class' => array('stn')))) . '
';

For more information see function l();


How to configure a Slideshow with thumbnails in modal window I have tried to get the following scenario to work, with no success.
I have 3 images. They are displayed in thumbnail form, in the bottom of a div. A main, preferred image, is displayed in a larger size above the thumbnails.
I need that, when clicking on the thumbnail, the main image will change. So, in the image included, if I click on the green image, the main image will change from red to green.

Also I need that when clicking on the larger image, a modal window will appear, with a Slideshow of all the images, starting from the one clicked.

I have managed to make it work very easily with PHP-Javascript alone (10 minutes of programming) but I am not able to do it with none of the following modules: Colorbox, FlexSlider, Lightbox2.

Even when launching a View with FlexSlider content using Lightbox2, it works but it takes ages to load the content, even if I have disabled all extra HTML stuff by making a template tpl suggestion.

Sincerely, I don't think it is so complicated behaviour. Also there is the approach of FlexSlider with thumbnails, but I cannot manage to include the lightbox (modal window) effect.

I was able to find a perfect solution to this, very easily as always. I use module Lightbox2, with the Slideshow option. Now I don't put the href with the reference to the big images in the small images - that would be standard behaviour, but I create 3 empty href with the data (the data come from an array passed to the .tpl.php):

<a href="<?php print $image_value["filename"] . "-960.jpg"?>" id="imagelink<?php print $conti; ?>" rel="lightshow[products]<?php echo $conti; $conti++;?>" >

The images themselves have other code which just changes the main image:

function change_photo(filename, conti){
    var object = document.getElementById("product-photo");
    object.src = filename + "-480.jpg";
    contagen = conti;
} // function

And finally in the onClick of the main image, I launch the slideshow by simulating a click of the empty links at the begginning of the code:

function launchslide(){
    var object = document.getElementById("imagelink" + contagen);
    object.click();
} // function


Display custom URLs for individual tabs of quick tab I need to display seperate URL(Deep linking) for individual tabs in a quick tab. I found a javascript fix in this link . The URL that is displayed has the quicktab name and tab number. It looks something like /test-quicktab-page?qt-test_quicktab=2. I need a more meaningful url to be displayed. For example /test-quicktab-page/world
or /test-quicktab-page/local . How can this be done?

I tried creating a URL alias but that didn't help.

Add jquery in external : This is used for you

jQuery(document).ready(function(){
  var quicktab = jQuery('ul.quicktabs-tabs.quicktabs-style-excel li  a').each(function() {
      var url  = 'test-quicktab-page?qt-test_quicktab=2';
      var href = jQuery(this).attr('href');
      var arr = href.split('/');
      alert(arr['2']);  /* rechange the index value as your url path */
      if(url == arr['2']) {
        jQuery(this).removeAttr('href');
        jQuery(this).attr('href','/test-quicktab-page/world');
      }
    });
});


Can TableSort be used without a query? In my module, I'm using TableSort for some of my tables, but I also have some tables that are generated by code, so not directly linked to a query. These tables are also created with theme('table') and so have the $header and $rows arrays. Is it possible to use TableSort on those as well, maybe with writing my sorting function?

The documentation for tablesort.inc seems to suggest it is possible (All tables created with a call to theme('table') have the option of having column headers that the user can click on to sort the table by that column). However, I haven't found any instructions or example on how to do this. Everything I found so far is based on a query. I'm using Drupal 7.

Thanks to Berdir I got it working. This is how it works in more detail.

Tablesort is triggered "automatically" if the (column) arrays in the $headers array contains the keys 'data', 'field' and optionally 'sort'. This will create links with 'sort' and 'order' in the column headers and show the little arrow and such.

To do your own sorting, get the current sort settings with tablesort_get_order and tablesort_get_sort and use those values for your own sorting function. The key 'sql' in the array returned by tablesort_get_order contains the field name to be used for sorting.

A piece of (untested) example code with the array $users containing some details for each user:

// setup the table data that we want to show
$tableData = array();
foreach ($users as $userDetails) {
  $tableData[] = array(
      'name' => $userDetails['name'],
      'visits' => $userDetails['visits'],
      'views' => $userDetails['views'],
      'comments' => $userDetails['comments']
  );
}

// headers array, sorting by default on comments
$headers = array(
    array('data' => t('Name'), 'field' => 'name'),
    array('data' => t('Visits'), 'field' => 'visits'),
    array('data' => t('Views'), 'field' => 'views'),
    array('data' => t('Comments'), 'field' => 'comments', 'sort' => 'desc')
);

// getting the current sort and order parameters from the url
$order = tablesort_get_order($headers);
$sort = tablesort_get_sort($headers);

// sort the table data accordingly (write your own sort function)
$tableData = my_array_sort($tableData, $order['sql'], $sort);

// create the array with rows for theme table
$rows = array();
foreach ($tableData as $entry) {
  $rows[] = array(
      array('data' => $entry['name']),
      array('data' => $entry['visits']),
      array('data' => $entry['views']),
      array('data' => $entry['comments']),
  );
}

// add any attributes and sent everything to theme table
$attributes = array('class' => array('my_class'));
$table = array('header' => $headers, 'attributes' => $attributes, 'rows' => $rows);
$html = theme('table', $table);


How to get user.field value in node.twig I have a field_author with different values expert, moderator or contributor

For get this custom USER field in node.twig i using next function

function MYTHEME_preprocess_node(&$variables) {

if ($node = \Drupal::routeMatch()->getParameter('node')) {
                  $variables['author'] = $node->getOwner()->field_fname->value;
        }
    }
}

And then {{ author }} in node.twig

How to get vlue of this field? For example {{ author.0 or author.1 or author.3}}?

Thanl you for helping!

You can try using variable node

Get user.name

{{ node.uid.entity.name.value }}


Change background for authenticated user I'm pleased with my body background for my site; it looks great when not logged in.  But when a user is logged in I need a different one.  I need to specify a slightly different background because of the fact that my Marinelli-based D7 site's custom body background (2 horizontal bands of green and black) stays in position but all content moves down almost 100px due to the administrative menu at the top.

An authenticated user would not be able to see the navbar due to this color change  (green words on a now green background).

Can I specify an alternate background for authenticated users vs. visitors?  Or perhaps better:  Is there a way to specify that the body background should move down when the user logs in and all the admin menus show up at the top?

Here's my present CSS for body:

body.marinelli{
    background: #fff url(../img/backgrounds/body-background.jpg);
    background-repeat:repeat-x;
}

I think your solution would be the class "logged-in" and the CSS property "background-position" to move the background image down 100px for logged-in users:

body {
  background: #fff url(../img/backgrounds/body-background.jpg);
  background-repeat: repeat-x;
}

body.logged-in {
  background-position: 0 100px;
}


Re-use fields in a content type I have a content type with 4 different sections to it.  At the bottom of each section, there are 2 "Call to action" links.

These links all point to the same 2 urls.  I'd like to be able to set up 2 fields of the type "link" and then re-use those fields 4 times, instead of having to set up 8 links.

Is this possible?

Is there a better way of doing it ?

If these sections are text or similar, you can create field collections that enclose other fields.

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.


How can one add superscript character like TM or Reg on a block title I was wondering how to add superscript characters like trademark to Drupal block title.

Block Class Styles may be useful:

  Extends the Block Class module to incorporate styles (or themes)
  rather than css classes. Adds style-based tpl suggestions. Allows HTML
  in your block titles.

Other options would be to create your block in code, and set the $block->subject to be your <sup> inclusive title, or to override the block-XYZ.tpl.php for the your particular block and add the title in there.

By default, Drupal core runs check_plain on any UI created blocks, so through the UI I don't think there's another option.


Custom Form Block not displaying I'm trying to create a custom form displayed inside of a block.
[edited]

 <?php

function edit_node_block_info(){
    $blocks['edit_node'] = array(
        'info' => t('Custom Block to allow edit/delete/copy'),
        'status' => 1,
        'region' => 'Primary',
        'weight' => 0,
        'visibility' => BLOCK_VISIBILITY_LISTED,
    );

    return $blocks;
}
/*
 * Implements hook_block_view: sets how the block is displayed
 */
function edit_node_block_view($delta = ''){
    switch ($delta) {
        case 'edit_node' :
            $block['subject'] = t('Edit Nodes');
            $block['content'] = drupal_get_form('edit_node_form');
            break;
    }
    return $block;
}
/*
 * implements custom form/creating custom form for drupal_get_form named above.
 */

function edit_node_form($form, &$form_state) {
    $form['node-id'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter the Node ID'),
        '#max-length' => 8,
        '#required' => TRUE,
    );
    $form['edit-node'] = array(
        '#type' => 'radios',
        '#title' => t('Select Action'),
        '#options' => array(t('edit'), t('delete'), t('copy')),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

function edit_node_form_validate($form, &$form_state, $node){
    if ($form_state['values']['node-id'] != $node->nid){
        form_set_error('node-id', 'Node-id must match a current nid.');
    }

I see my block in the blocks list. But, my form is not showing up. I am wondering if I need to run a drupal_form_submit('edit_node_form', $form_state); at the end, but shouldn't that be ran during a submit function?

I'm also wondering if I need to update the form_state as I'm not creating a form_id currently (eg https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7)

if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
    $form['workflow']['upload_' . $form['type']['#value']] = array(
      '#type' => 'radios',
      '#title' => t('Attachments'),
      '#default_value' => variable_get('upload_' . $form['type']['#value'], 1),
      '#options' => array(t('Disabled'), t('Enabled')),

But I think that is related to hook_form_alter which I have not called.

I just got it working by changing the page's it was viewable on. Not really sure why that fixed the issue, but it did.


Is it possible to create a pre-filled select list field with Drush? The syntax to create fields is on https://drushcommands.com/drush-8x/field/field-create/

For those it works:

Images:

drush field-create article img,image,image_image

Text fields:

drush field-create user address,text,text_textfield --entity_type=user

text long:

drush field-create user address,text_long,text_textarea --entity_type=user

Decimal:

drush field-create user userpoints,number_decimal,number_textfield --entity_type=user

Boolean:

drush field-create content haspurchase,list_boolean

Is there a way to create a select list field pre-filled with values?

You can create select field also from drush command. Just type the command from drupal root directory drush field-create content_type_name and hit enter key and follow the instruction. Please see the attached screenshot.

Copy the last output which is edit url of your field where you can  refinement your field.


related content types - "top 10 best movies" functionality Been trying to achieve functionality like below.
- Article "Top 10 best movies" when you enter the article it is a landing page with short text and then there are links to all ten movies - 10 through 1 like below:

Tried to do it with two content types - top10(the landing page) and movie(each movie from the top 10 list). Entity reference field on the movie content type pointing to the top10(the landing page). Then made a view listing all movies and filtering by the NID of the main article. But then when I enter the movie content type the links disappear (the nid of the top10 content type is missing). Then tried to make the view to be filtering by the etitiy reference field but then links pointing to other top10 articles appear... Fairly new to drupal and seems like I have meesed it up.

If someone can advise some clean idea would be much appreciated. Thank you in advance.

It looks like you need to build functionality to allow users to see movies under different categories where diff categories are top 10, top 9 ....

Assuming we do not have any criteria to put movies under diff categories instead this is being handled while adding them through a content type.

I am not sure if this will be good solution but might help you,

Create a vocab as movie rating add terms to it as within top 10,within top 9,within top 8... and so far upto top 1st.
Add this vocab as term reference to content type responsible for
   generating movie nodes.
Now every time you add a movie opt the appropriate taoxonomy
   field.
Create a view for the same content type and keep the movie
   rating vocab as exposed filter as type links for this view, which
   will allow users to select the appropriate category as shared in the
   image in question.so this filter will automatically filter down the
   nodes as per the rating added while creating them.
Allow your view to use ajax for better user experience.


Check if ajax in the preprocess_node There seems to be a problem when I check if the node is served by ajax or not, I use this function :

function mytheme_preprocess_node(&$variables) {
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $variables['is_ajax'] = true;
    }else{
        $variables['is_ajax'] = false;
    }
}

The same code works great with preprocess_page or preprocess_html

Is there a way to make it work? or eventually get the page/html variable in the node preprocess ?

Thank you !

The node is cached and this function is only called for the first time the node is displayed for the given view mode.

If you really need to vary your output between ajax and non-ajax context, you need to add a cache context for that. See https://www.drupal.org/docs/8/api/cache-api/cache-contexts and the other related documentation pages. You could use the header:NAME-OF-THE-header cache context I guess.

As an alternative, do whatever needs to be done differently with ajax vs not  with Javascript/CSS


Drupal 6: Having issues with multiple paged tables in pages with multiple tabs (JQuery UI tabs) I have a series of pages that provide paged tables inside of tabsets. Using the Tabs module, I get JQuery UI tabs, and I am using that to create pages with multiple horizontal tabs; inside those tabs I have forms and paged tables, typically one form or one paged table per tab.

The paged tables are generated using pager_query(), where I am providing a pagerElement parameter to pager_query() because I have multiple paged tables on the same page (but on different tabs).

Likewise, when I call theme('pager'...) I am passing in my pagerElement so my multiple paged tables do not get confused, as well as an additional associative array for my active tabset parameter. The call looks like this:

theme('pager', NULL, $pagerLimit, $pagerElement, array('tabset'=>$pagerElement) );

The issue I'm having is the pager links being generated, for example: when first landing on one of these multi-tabbed pages, the pager links look like:

 http://blablabla/Projects-Dash?tabset=0&page=1

However, as soon as a pager link is clicked, the pager links look like:

http://blablabla/Projects-Dash?tabset=0&page=2&tabset=0

Notice that now tabset=0 is there twice? At least the links from the 2nd paged table are somewhat different, looking like this:

http://blablabla/Projects-Dash?tabset=1&page=1%2C1&tabset=0

But they still have that extra tabset=0 at the end... how to prevent that?

The problem was being caused by how the pager logic handles existing URI encoded parameters: it simply copies them, pre-pending any new URI encoded parameters used by the pager logic. The result being a duplicate of my 'active tab' parameter "tabset", the previous one present in a copy of the prior URI parameters, and the one I introduced in the paging link.

My solution was to parse the request URI myself inside my form logic, with knowledge that the first encountered "tabset" value is the active one, not the second (older) version at the end of the URI.

$activeTab = 0;
  $requestUri = $base_root.request_uri();
  if ($requestUri == '') {
    _devReport( '$requestUri is empty!' );
  }
  else {
    $requestArray = explode( '/', rawurldecode($requestUri) );
    // if course, this parsing logic is specific to my WebApp URI setup:
    if (($requestArray[0] == 'http:') &&
        ($requestArray[3] == 'WebApp')) {
      // this should always be true, but just in case:
      if ($requestArray[4] != '') {
        $split1 = explode( '?', $requestArray[4] );
        $split2 = explode( '&', $split1[1] );
        if ($split2[0] != '') {
          $split3 = explode( '=', $split2[0] );
          if ($split3[0] == 'tabset') {
            $activeTab = $split3[1];
          }
        }
      }
    }
  }

Now $activeTab has the correct value, even though it may be present a 2nd time in the URI with a different value.


Exposed filters and contextual taxonomy description A view called "Music".

Fields: "title", "image"
Exposed filter: "category" (is a taxonomy-field = rock, jazz, salsa,...).
Every taxonomy-term has a description.

When the visitor for example, selects "rock" the results are filtered.
So far, so good.

But i want also want that when a "category" is selected, the description of the selected term is displayed above the results.

I think that could be done with an attachment and contextual filters, but i can't get it working.

You may use tokens (replacement patterns). If you add the term description in your fields and exclude it from display, you will have access to [description] token in a Global: Text area, for example, added in the view header. Then, if you check Use replacement tokens from the first row and set your exposed form style on Input required, when a category is selected, results will be filtered and the term description related to this category will be displayed in the header.

EDIT : for Drupal 8 (sorry, still more a "7 guy" ^^), the token follows Twig syntax : {{description_value}}


Importing blog articles from a WordPress site I am looking for a module to import any blog written on a WordPress site. Is there any module to do this?

Maybe WordPress Migrate is what you are looking for? Excerpt from its project page:

  supports migrating WordPress blog exports (WXR format) into Drupal using the Migrate module. Import of posts, pages, comments, attachments, tags and categories is supported. Imports can be rolled back completely.


Split D7 User Account Edit Form in multiple blocks I need to split the user account edit form that shows up on one page to multiple pages. That means I want to separate change password fields, two custom fields i created - field_first_name and field_last_name and so on.  For moving the password fields to new block I used the solution provided in this link How can I display a change password form on its own? and it works great.

I am trying to use the same code except make some minor changes for modifying the custom fields (first name and last name).  The only difference is, I need to pre-populate these fields with the values from the current logged in users information.

// Get the currently logged in user object.
$form['#account'] = $GLOBALS['user'];

// Textfield for first name.
$form['field_first_name'] = array(
'#type' => 'textfield',
'#title' => t('First Name'),
'#size' => 60,
'#default_value' => what should I enter here?
'#required' => TRUE
);

Also if I enter a new value for these fields, it doesnt get updated in the user account. I am using the following code -

/**
* Submit handler for change_name_form().
*/
function change_name_form_submit(&$form, &$form_state) {
// Set up the edit array to names to user_save()
$edit = array(
'field_first_name' => $form_state['values']['field_first_name'],
'field_last_name' => $form_state['values']['field_last_name']
);

// Save the account with the new name.
user_save($form['#account'], $edit);

// Inform the user.
drupal_set_message(t('Your information has been changed.'));
}

What additions / changes do I need to make to the code to get the desired output?  Any help is greatly appreciated -

I haven't done this in code, but I split the user profile into multiple pages on my site with the Field Group module (as the module's page says, it is only client-side).

There is a screencast about how the multipage features work.

Another option is the Profile 2 module, which will create actual separate paths for different settings.


Add classes to these links I don't think this is hard at all but beeing a beginner at PHP and Drupal I need some help to do this.

I want to be able to add classes to my navigation elements that are outputted with this code:

function mytheme_menu_link__menu_block__1($variables) {

$element = $variables['element'];

$sub_menu = '';

if ($element['#localized_options']['attributes']['title'] != 'misc' && $element['#localized_options']['attributes']['title'] != 'something') {

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }

    if ($element['#original_link']['in_active_trail'] == 0) {
        $output = ''.$element['#title'].'';
    }
    else {
        $output = ''.$element['#title'].'';
    }

    $link = l($output, $element['#href'], array('html' => TRUE));

    return $link;
}
else {
    return '';
}
}

If the menu item is active, it should have class X, otherwise class Y.
Could someone explain how I add this?

------------------------- Correct Answer -------------------------------

Here is the correct code that longboardnode helped me come up with.

function mytheme_menu_link__menu_block__1($variables) {

$element = $variables['element'];
$sub_menu = '';

if ($element['#localized_options']['attributes']['title'] != 'misc' && $element['#localized_options']['attributes']['title'] != 'something') {

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }

    if ($element['#original_link']['in_active_trail'] == 0) {
        $output = $element['#title'];
        $class = 'activeClass';

    }
    else {
        $output = $element['#title'];
        $class = 'otherClass';

    }

    $link = l($output, $element['#href'], array('attributes' => array('class' => array($class)), 'html' => TRUE));

    return $link;
}
else {
    return '';
}

}

I hope I understand your question. If you want to add class to l(), then it must be an array, so your "$link=..." line would read

$link = l($output, $element['#href'], array('attributes' => array('class' => array('YOUR_CLASS_NAME')), 'html' => TRUE));

You can also read more and see other examples in Drupal's l() documentation

Hope this helps.


Pass a value from a block preprocess hook to a twig template that inserts that block I use the D8 book module to manage magazines and their articles.

In the node--magazine.html.twig template for a magazine, I use the built-in book_navigation block to add a table of contents. This is done by drupal_block("book_navigation", {block_mode: "book pages"}). Works fine.

For certain "featured" articles in the table of contents, I want to display an image. I use MYTHEME_preprocess_book_tree(&$variables) to add the image url to the items array in $variables. I've sub-themed book-tree-html.twig to get the image url from the items array and include the image in the table of contents. Works fine.

BUT, I need to know in node--magazine.html.twig whether there are any featured articles in the table of contents to present a proper heading on the page.

QUESTION: What is the best way to pass a variable from THEME_preprocess_book_tree() to node--magazine.html.twig? It's not a direct connection. Getting preprocess variables in book-tree.html.twig is easy, but I need to pass a variable through to node--magazine.html.twig, where the book tree is inserted.

What I have tried:

In the book-tree.html.twig template, if there is a featured article, I add a hidden "featured-article" label to the html and then in the magazine template, I test for its presence via {% if "featured-article" in <rendered block html> %}. This works, but it feels unsavory.
In MYTHEME_preprocess_book_tree(), I add $variables['featured'] = $feature_count; and in the magazine template I {{ dump(featured) }}. This doesn't work. I just get NULL. I'm not sure what--if any--connection there is between the $variables array available in the preprocess hook and variables available in the magazine template.
In MYTHEME_preprocess_book_tree(), I could set a global variable and then in the magazine template, call a custom twig extension to check the value of that variable. I haven't tried this yet, but it seems like this should work. Just seems like there should be a more elegant way.

After a lot more digging and trying things without success, I ended up solving the problem of passing a value from a block's preprocess hook to a twig template where the block is inserted as per my third option above. Here's what I did:

Follow the instructions at http://www.tothenew.com/blog/overview-of-twig-extentions-in-drupal-8 to create a twig extension. This wasn't very difficult, especially since I had already created a custom module. I just had to create a MYMODULE.services.yml file and a TwigExtension.php file as instructed.
In the twig extension file, create functions setTwigValue($name, $value) and getTwigValue($name) using the php $GLOBALS array for storage. Again, the above-mentioned instructions made this pretty easy.
In the preprocess_book_tree hook, count the number of feature articles and then save the count by calling

Drupal\MYMODULE\TwigExtension::setTwigValue('feature_count', $feature_count);
In the node--magazine.html.twig template, get the saved value using

{% set feature_count = getTwigValue('feature_count') %}

I'm happy to learn of better/safer ways to accomplish what I've done. But at least it works and it's pretty clean.


Query and sort by field on entity referenced object I have a custom content type that has an entity reference field, that refers to an existing node from a different content type.

I'm performing the query like so

$query = \Drupal::entityQuery('node')
->condition('status', NODE_PUBLISHED)
->condition('type', 'issue');

$nids = $query->execute();

Each of these issue nodes have a field_publication field that refers to a publication node. Each of these publication nodes have a field_permission_category that I'm grabbing like so.

foreach ($nids as $nid) {
   $node = NODE::load($nid);
   $pub = $node->field_publication->entity;
   $pub_permission = $pub->field_permission_category->value;
}

But I want to be able to order the results of the initial query by the value of field_permission_category from the referenced field, but I'm not sure how to go about that, and I'm not even sure that's possible. Basically I want to be able to do

$query = \Drupal::entityQuery('node')
->condition('status', NODE_PUBLISHED)
->condition('type', 'issue')
->sort('field_publication->entity->field_permission_category->value', DESC);

Can you sort a query by a field inside a referenced node?

The answer by Clive is correct.
I  used this query for a project :

$query->sort('field_projets.entity.field_date_mise_en_prod', 'DESC');

'field_projets' is the field name of the entity reference field on my node.

And 'field_date_mise_en_prod' is the name of a date field belonging to the referenced entity .

You can also use this syntax on conditions.
Exemple :

$query->condition('field_tags.entity.name', 'cats');

You asking for a tag with the name 'cats'.


Import xml with Feeds from a folder outside site directory I need to import data from multiple xml files. my site is in /var/www/sites/automationstats and the folder with the data is in subfolders of /var/lib/jenkins

If I use as directory in the import /var/lib, I get this error message: Directory needs to be a valid URI.

By the way, that folder (/var/lib) has owner and group jenkins. My first idea was to set that folder in the file system settings as private and then use private:// as URI but it says the folder is not writable.

So, is it possible to read from outside my site file structure or I have to get the files inside?

yes you were right the correct way is to add in file system configuration (/admin/config/media/file-system) a private file system path that you need "/var/lib/jenkins", and then use it in your feed fetcher with prefix private://.

Please if it is possible move yor files form /var/lib to a user subfolder to avoid security problems.


How to get the drupal version using phpMyAdmin query? How to get the drupal version using query ? Or
how do we detect using query the drupal version is 7,6,5 or 4?

This will work with Drupal 7 - I don't have other version to test it on but think it should work...

Because the version is stored in the text file CHANGELOG.txt we can write that to a table in the DB, read from the table, and then delete it again afterwards:

First run this: (make sure to change the path to your changelog file)

CREATE TABLE `drupal_version` (`data`  varchar(255) NULL);
LOAD DATA INFILE '/var/www/your_site/htdocs/CHANGELOG.txt' INTO TABLE drupal_version;
SELECT * FROM drupal_version WHERE data LIKE "%Drupal%" LIMIT 1;

This will return something like:

Drupal 7.26, 2014-01-15

And run this to delete the table we just made:

DROP TABLE drupal_version;

Whilst this is a long winded way of reading text from a text file it is strictly speaking getting the version using MySQL...

Second Option

As Topsitemakers suggested looking in the system table I had a look and found the version was hidden in there, but only against specific modules. I figured the field module would be in all version of drupal, however I very highly doubt that this query will actually work on any version other that 7 as it's so specific and a bit of a beast:

SELECT MID(info, LOCATE(':"', info, LOCATE('"version";', info)) + 2, MID(info, LOCATE('"version";', info) + 12, LOCATE(':"', info, LOCATE('"version";', info)) - LOCATE('"version";', info) - 12))
FROM system WHERE filename LIKE "%/field.module"

For me this query returns:

7.26


What effect does BigPipe have if my traffic is mostly anonymous and I'm serving unpersonalized content behind varnish? I've looked into this before and I swear, though I can't seem to find any documentation to confirm it now, that I read BigPipe only helps performance for authenticated users. (Note: I'm sure I'm just misremembering.)
I think this was due to the fact that anonymous users don't have regular sessions. I'm having trouble tracking this down too, but I did find the following quote:

If you run that chunk of code from the preceding section as an anonymous user, you'll note that the entry gets created in the database with a session ID, as expected. However, upon the next request, if you try to retrieve the value by key, you won't find it. That is because anonymous users do not necessarily have a session started. This means a new session ID is created for each request.

Anyway, my understanding is that the Sessionless BigPipe module fixes any issue with anonymous traffic and ensures that BigPipe will have an impact for those users.
On the Sessionless BigPipe module's project page I see:

This module uses BigPipe to accelerate the first unpersonalized response! And after that first response is sent, the response is stored in Page Cache. Which means that any subsequent requests for that unpersonalized page will be answered very quickly by Page Cache!

Does this mean that when a page is flushed from cache (Page Cache and Varnish) I'll see something like the following chain for subsequent anonymous requests for that same page?

First request: Varnish miss, Drupal Page Cache miss, BigPipe builds the page (This is the one case where BigPipe would have an impact)
Second request: Varnish miss, Drupal Page Cache hit, Drupal Page Cache serves the page
Third and all subsequent requests: Varnish hit, Varnish serves the page

Edit: I now see that this is explicitly outlined further down on the project page:

So, when using Varnish: the first request will be streamed by BigPipe, and not cached in Varnish. The second request will be a Page Cache hit, not a Varnish hit. The third request and all later requests will be Varnish hits.

Additionally, why does the second request bypass Varnish?

How does BigPipe have an effect if my traffic is mostly anonymous and behind varnish?
This really depends on the content of the page. Taking away any content depending on the logged-in user there might be no dynamic part left which could have any effect.
Additionally, why does the second request bypass Varnish?
As mentioned in the module description it is not possible the send the cache tag headers after the dynamically generated content has been streamed to Varnish. The Internal Page Cache can be controlled without sending headers because it is cached in the local database.


How do I access the node's uid in hook_node_access()? I have implemented hook_node access so that two users cannot view each other's posts if they do not have the right permission (I implemented the permission in hook_permission). I use a comparison with $node->uid as follows:

 function mymodule_node_access( $node, $op, $account)
 {
   global $user;
   $type = is_string($node) ? $node : $node->type;

   switch($type)
   {
    case "myCustomType":

      if ( ($user->uid != $node->uid) && !user_access("view other's posts"))
       {
              return NODE_ACCESS_DENY;

       }
       break;

   }

}

Everything works fine but I do get the following warning:

  Notice: Trying to get property of non-object in mymodule_node_access().

This is caused by this: $node->uid. Drupal complains that $node is a  not a stdobject (it seems to actually be string containing the node's type). Yet the code still works which I do not understand why.

What is the proper way to access the node's uid from hook_node_access?

The $node parameter is

  Either a node object or the machine name of the content type on which to perform the access check.

When that hook is invoked with the create op, there's no node object available, so $node is a string.

You're already handling that bit, but you're missing a check on the $op parameter. The reason it's working is because when your function is invoked with the op you're trying to target (probably view), $node is an object and has a uid property.

With your current code, you'll get one of those notices every time someone other than user 1 tries to create a node, because $node is not an object.

Try re-working your code like this:

function mymodule_node_access( $node, $op, $account)
 {
   if ($op == 'create') {
     $type = $node;
     // You can be reasonably sure that $account is the user who's trying to create the node here.
     // You'll probably want to ignore this bit and check $op specifically for the
     // actions you're looking for; this is just here to show the workflow.
   }
   else {
     if ($node->type == 'myCustomType') {
       // Be sure to use the $account var here, not the global $user object
       if ( ($account->uid != $node->uid) && !user_access("view other's posts", $account)) {
       return NODE_ACCESS_DENY;
     }
   }

   return NODE_ACCESS_IGNORE;


Create a view pulling in content that matches user profile Im am trying to create a view that pulls in content that matches to the user. This is done with two taxonomy fields that are added to the user profile and the content type. These are job role and speciality. I know how to set up the view to pull in content using just 1 of these fields but how can I get it so its an AND condition. I need to pull in content that has both the same job role and same speciality as the user. Is there anyway of achieving this through the views UI or do I need to alter the query?

Thanks

With Drupal 7 and Views 3 you can match on multiple taxonomy terms using contextual filters. I posted about this on drupal.org here. Maybe it can be adapted to your particular situation.


Alter Registration Form Text I am trying to alter the email description text on my user registration page. I have added the following to the bottom of my template.php file but nothing is happening. It seems like the function isn't even being called. Any suggestions?

function theme_form_alter(&$form, &$form_state, $form_id){
    switch($form_id) {
        case 'user_register_form':
            $form['account']['mail']['#description'] = t('E-mail Address');
    }
}

you need to call the function YOURTHEME_form_alter(), where YOURTHEME  is the name of your theme. Eg, the Bartik theme would have such a function called bartik_form_alter() ... you must also clear your drupal cache for the changes to take affect.

EDIT

you make your code like this:

function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id){
    switch($form_id) {
        case 'user_register_form':
            $form['account']['mail']['#description'] = t('E-mail Address');
    }
}

if you call your theme "sky" it would be sky_form_alter.


Insert a form to a Basic Page I created a contact form in Drupal 8 and would like to use that form on several pages across my website. Can I do something like Insert / Form or use some sort of shortcode to display the form?

Create a block for your theme with formblock and in visibility settings of your block put it where ever you want.


Filter criteria with entity reference field doesn't work I have a field called event_author, which is a entity reference to user. These are the settings for the view.

They produce the following output.

After I add the filter, there is no result anymore. It seems the entity reference is not matching up with author1.

Why does it happen?

I hover over the field. It says event_author_id. It should be the id of the author, instead of text. Or If I want to use text 'author1' in filter. I need to add a relationship in the view. Like a mysql join.


Why do my main menu tabs show up on two lines instead of one? In Drupal 8, I have a main menu in the "Primary menu" block of the default Bartik theme. You can see a screenshot below. This site was upgraded from Drupal 7.

Why does the menu show up on two lines instead of one? There is plenty of space available for the menu items. I have tried adjusting the menu and block settings, but have not managed to reduce these to one line. All of the menu items other than "WOW" and "About" have "WOW" as the parent item.

You can see the site here:

http://worldsowisdom.com/wow/

Thank you!

This is happening because of the CSS technique/code being used. Both <li> and <a> have been floated.

The first WOW item actually contains all the other WOW items as children, and it's reflected in the HTML structure, there is an <ul> inside the WOW <li>. Since <li> is floated but it hasn't been given a specific width, there are some cases that can happen, like this one, that seem a bit odd, but they're just following the code.

I guess the authors of that theme didn't anticipate the menu might be used in this way, to display two levels of menu hierarchy on one line.

Usually one level of the menu is displayed in one region, and deeper levels are displayed elsewhere or in a drop-down.

You could add two Main menu blocks to that region, and set one Block to display Initial visibility level and Number of levels to display to 1 and 1, and the other Block to 2 and 1. This way you'd get WOW and About in one row, but when you visit WOW a second row would appear with all the WOW-subitems.

If they are meant to always be displayed maybe it makes sense not to have two levels in hierarchy?

But in the end you can always adjust the CSS to make them display all on one row (you can use CSS edit module to override CSS if you don't have a subtheme):

.region-primary-menu .menu-item,
body:not(:target) .region-primary-menu .menu-item {
  float: none;
}

This will make them show on one row since now only anchors are floated. But the margin won't have affect so you'll need to add margin to the anchor elements instead, if you want them separate a bit like before.


How to access the view display's field list in row plugin options I am trying to create a row plugin that would be similar to the plugin in date_ical. The difference would be that it wouldnt use the entity display but the fields defined in the view, thus allowing for example to place information from related entities.
To do this I would need to setup options in the options_form where i would select form the defined fields whih is the title and so on. Somehow i cant access the information about the defined fields. I keep searching the $this->view object and around, but cant find it :(. I am sure it has to be there. Please help !

i found $this->display->handler->get_field_labels(); in views_plugin_style.inc and it seems to do the trick.


Edit "Read more" and "Add new comment" links in teaser I'd like to add a couple classes to the "Read more" and "Add new comment" links in my article teasers in Drupal 8.

I'd do this in Drupal 7 by doing something like this in my theme file.

function mytheme_preprocess_node(&$variables) {
  $variables['content']['links']['node']['#links']['node-readmore']['attributes']['class'][] = 'btn btn-primary';
  $variables['content']['links']['node']['#links']['comment-add']['attributes']['class'][] = 'btn btn-primary';
}

But this doesn't work in Drupal 8. I dumped the contents of $variables['content']['links'] and all I got was this:

$variables['...']['...'] array(2)
    '#lazy_builder' => array(2)
        string(40) "Drupal\node\NodeViewBuilder::renderLinks"
        array(4)
            string(1) "4"
            string(6) "teaser"
            string(2) "en"
            boolFALSE
    '#weight' => integer100

So how would I go about adding classes to these links in Drupal 8?

You can do this in a couple of different ways. By looking up the Drupal\node\NodeViewBuilder::renderLinks method, you can see how it works.

1. Implement hook_node_links_alter()

This should work for a module.

function mymodule_node_links_alter(array &$links, NodeInterface $entity, array &$context) {
  $links['node']['#links']['node-readmore']['#attributes']['class'][] = 'btn btn-primary';
}

2. Implement template_preprocess_links()

And I think this should work for the theme...

function mytheme_preprocess_links(&$variables) {
  // some logic enclosing this block
  $variables['node']['#links']['node-readmore']['#attributes']['class'][] = 'btn btn-primary';
}


Node reference autocomplete views issue Firstly, apologies if I use some incorrect terminology - I'm still very much a Drupal newbie!

I'm creating a band website using Drupal 6 with CCK, Views, Date, Calendar, Link, Location and GMap.  It has two content types of concern here - Gig and Venue.

The "Venue" content type has a Location field, which stores all the address information.  It also has some other fields, for example "Venue Website" (field_venue_website).

I want an autocomplete field on the "Create Gig" page to look up an existing venue from the "Venue" content type and display the venues in an autocomplete drop-down list in the following format:

[Location name], [City], [Country]

However, I want to extract more information to be available on the Gig page, preferably like this:

[Location name] <-- preferably as a link to the venue's page
[Street]
[Additional]
[City]
[State/Province] [Postal code]
[Country]
[Venue Website] <-- remember this is a separate field, not from the location field.

I have partially reached my goal, by doing the following:

Created a "Venue" field (field_gig_venue) of type Node reference.
Set up the field as follows:

Autocomplete matching: Contains
Size of textfield: 100
Required: Off (may change this later)
Number of values: 1
View used to select the nodes: venue_search

Created a View (venue_search) with the following settings:

Row style: Fields
Inline fields:
Location: Name
Location: City
Location: Country
Separator: ,
Hide empty fields: Yes
Relationships:
Content: Venue
Fields:
Location: Name
Location: City
Location: Country
Node: Title (Exclude from display: Yes)
Filters:
Node: Type = Venue

This results in the autocomplete drop-down list displaying as I required.  When submitted, the result is [Location name] as a link to the Venue's page.

However, I find that the only part of the venue recognised by the autocomplete is [Location name]. For example, if I have two venues as follows:

Kentish Town Forum, London, UK

Tunbridge Wells Forum, Kent, UK

When I start typing "forum", I'll get a drop-down suggestion list that looks like the above.  Great!  However, if I type "UK" or "London", I get nothing.

If it helps, here is the query generated when I preview the View:

SELECT node.nid AS nid,
   location.name AS location_name,
   location.city AS location_city,
   location.country AS location_country,
   node.title AS node_title
 FROM drupal_node node
 LEFT JOIN drupal_content_type_gig node_data_field_gig_venue ON node.vid = node_data_field_gig_venue.vid
 LEFT JOIN drupal_node node_node_data_field_gig_venue ON node_data_field_gig_venue.field_gig_venue_nid = node_node_data_field_gig_venue.nid
 LEFT JOIN drupal_location_instance location_instance ON node.vid = location_instance.vid
 LEFT JOIN drupal_location location ON location_instance.lid = location.lid
 WHERE node.type in ('venue')

Here are my questions:

How do it get it so that the autocomplete will work for the City or Country, too?
What is the best way to get the output that I require on the final page (i.e. an address block)?  I assume that I can add the other relevant fields and exclude them from display in the View, and they'll be available to use.  How should I best use them, though?  A single field with the data pre-formatted?  A field for each value?
How do I then get the data collected from the View into the field(s)?

Any help would be greatly appreciated! Thanks in advance!

[EDIT]

As mentioned below, I have discovered that what is happening is this:

The autocomplete field takes the text entered and looks to see what node titles in the "Venue" content type match this text.  It then displays the results using my View to format them.  Here is a picture to illustrate:

Why is it ignoring my view when checking the entered text, instead checking against node titles?

You can create a computed field in Venue with the content of the fields you want and use that field.
& 3.  Once you have the node reference you can show whatever fields you want using a template for the gig. Alternatively you could use a view.


How do I apply a global filter on view tabs? In Drupal 7, I have a view where I show different view tabs of different content types. I want to apply a global filter on those view tabs.

How can I achieve it?

You can use Global filter which creates filter widgets as blocks based on field or view of your choice and you can use the filter choices in ANY view as contextual filter.

Here is a simple example usage

For basic page create List (text) - field_choices with widget Select list and values choice1 choice2 choice3

Create some basic pages to include 1 of the 3 choices
Create or modify the view and make it display the choice for each result

Add contextual filter with choices as field and provide default value Global filter field

Go to Structure > blocks and add Global filter block 1 to a region of you choice and configure it to display choice field as a filter with default widget

Visit the view page that has the contextual filter (on choices) and you should be able to filter the view based on the Global filter (choices dropdown widget)

You can add the same contextual filter to as many views (or view displays) as you like


Views will not use pathauto URL Alias when listing programatically saved nodes I am programatically saving nodes, and everything is working fine. Pathauto is working correctly as well and generating aliases based on my url alias configurations.

However, when Views creates a list of the new nodes, it uses node/xx instead of the existing url alias.  Anyone know why this could be happening? All caches have been cleared, cron ran, etc. Here is the code

$node = new stdClass();
    //set other defaults
    node_object_prepare($node);

    $node->type = $page_data['content_type'];
    $node->body[LANGUAGE_NONE][0]['value'] = $page_data['description'];
    $node->body[LANGUAGE_NONE][0]['summary'] = text_summary($page_data['description']);
    $node->body[LANGUAGE_NONE][0]['format']  = 'filtered_html';
    $node->title = $page_data['title'];
    $node->field_product_price[LANGUAGE_NONE][0]['value'] = $page_data['price'];
    $node->field_item_location[LANGUAGE_NONE][0]['postal_code'] = $page_data['zipcode'];
    $node->uid = "1";
    $node->status = 1;
    $node->active = 1;
    $node->pathauto_perform_alias = TRUE;

$node->field_product_images[LANGUAGE_NONE] = $images;
unset($images);

$node->field_baby_clothes_category[LANGUAGE_NONE][0]['tid'] = $page_data['category'];

if($node = node_submit($node)) { // Prepare node for saving
    node_save($node);
}

note - when I add the same information through the content type form everthing works fine. It's almost as if my code is missing something that helps connect it to views.

Views doesn't see the alias.  When Drupal receives an alias URL, the first thing it does is change the URL to the default.  Views does not come into the process until after the URL is changed, so it does not know about the alias.


redirect multiple nodes on same page in core search results I'm using drupal's core search module with pathauto module for URL aliasing. I have one testimonials page where different contents under testimonials category get display in this page. Now, in the search results one of these content get display and lead to node/35 and  node/36 in same search result page.

In URL alias I tried to give /testimonials in each content but it gives error that this URL alias is already in use.

I want to redirect this link on the testimonials page (abcd.com/testimonials). Means

node/35 -> abcd/testimonials
node/36 -> abcd/testimonials
node/37 -> abcd/testimonials

How can I achieve this? Any suggestions or links will be appreciate.

Thanks in advance...

Finally got solution, but still I think this is not right way to achieve this. First enable the Pathauto module and make some pattern for particular content type. Then install the Redirect module. You can find URL Redirects under URL alias option in edit mode of content type.

click on Add URL redirect and add your desire path (in my case path to page /tesimonials). Thats it. It will redirect particular node to your given redirect path.

Hope this will help you...


How do I create a view with a 'Content pane' display type? I would like to create a new view that that I can use as a Content (panel) Pane. I cannot find how to do this. Would anyone know?

Ok I found it.

I was looking for the option on the first screen where you give the view a name and select if it's a block or not. Instead you must add a new Display instead, on the 2nd screen, and select it from the drop down list that appears


How to let users use my module? I've just created a module that concerns books (add book, edit books, etc). Of course the administrator can use it, but I want to allow users that are connected to use it as well. But with condition on uid like so:

User1: add book 1, book 5, book 7
User2: add book 3
...

The administrator can see all books (1,3,5,7) (that's done). But user1 (which is not superuser user/1 ...) has to only see his/her books (1,5,7), and similar for user2.

I'm sure I have to add a condition on my current module like:

if (uid = current user id) then show only user1's books)

But how to do that?

I know that the table "node" contains both informations of user id and nid (all books).

Note: I want to do that without using the Views module.

Have a look at the Node access user reference modules (with about 4,3K reported installs ...), available for both D6 and D7.
Some details from its project page:

Gives content access permissions to users for content that references the users with User reference or Entity reference.
This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

The above details seem to me like a perfect solution to answer your question. So either just use this contributed module in combination with your own module, or use it a inspiration about how you should enhance your own module in combination with User reference or Entity reference.


Aggregator custom template file is not overriding the default one on Drupal 7 I have the Aggregator module enabled in Drupal 7. I have one feed and I'm showing it on the front page in a block. The block has under the feed a 'more-link'.

I want to change the text depending on the language and feed that I'm showing.

I added a copy of aggregator-summary-items.tpl.php to my theme folder and customized the file.

My problem is that is still showing the default one. Is there something I'm missing?

I don't think it uses template files.

Just override the function in your template.php.
(replace 'mytheme' with your theme's name).

/**
 * Returns HTML for an individual feed item for display in the block.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: The item to be displayed.
 *   - feed: Not used.
 *
 * @ingroup themeable
 */
function mytheme_aggregator_block_item($variables) {
  // Display the external link to the item.
  return 'link) . '">' . check_plain($variables['item']->title) . "\n";
}


How do I programmatically "place" an order? When making a payment through the Commerce admin interface; the Orders do not get completed. I can see a Place Order button when viewing a cart Order; which seems to do the trick. I need to do this in code.

I know that i need to react to the the commerce_order.order.paid event but I am not sure what to do there.

I found this post: How do I programmatically update the order status? which suggests i need to "apply a transition". But the suggestion there doesn't work.

I opened a new question for this as I am specifically asking about "placing an order"; whereas that question was asking about simply changing Order status.

A little digging and I figured it out on my own:

Event handler for for this event: commerce_order.order.paid

and with this handler code:

  public function paymentCompletedHandler($event) {
    $order = $event->getOrder();
    $order->getState()->applyTransitionById('place');
    return;
  }


How can I rearrange a menu link programmatically? I created Menu Link Content entities and saved them in a menu.

$menu_link = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
])->save();

$menu_link_2 = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
])->save();

How can I rearrange $menu_link_2 to be a child of $menu_link?

Looking at menu_ui, they seem to update Menu Link Content in a given order, and then rebuild the menu tree; finally, the Menu entity is saved.

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link_manager->updateDefinition($menu_link_2->getPluginId(), [
  'parent' => $menu_link->getPluginId(),
]);

How can I rebuild the menu tree and save the menu?

Why? I'm writing a Kernel test for a module that fires when the menu link content has been saved AND then when the Menu itself has been saved.

You can rearrange a custom menu link when you set the 'weight' of the menu. See below code.

$menu_link = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();

$menu_link_2 = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();


Shortcut menu not showing after admin menu installed I have installed the admin menu module and now the shortcuts menu has disappeared.
This is quite confusing

Toolbar is the core drupal module which  displays the shortcuts near the top of the page, along with an Edit shortcuts link. After installing admin-menu we do not need core toolbar module otherwise it causes redundancy for admin menu,uninstalling the toolbar module causes vanish of shortcut bar with it.

Shortcut bar comes from shortcut module, which simply allows us to place the shortcut block by going to (Administer > Structure > Blocks) and look for Shotcut block which by default goes under disabled block.


Include full term name including "in" "and" etc when used for URL alias Im using taxonomy terms to create my URL aliases. At the moment the word "in" is stripped out.

So if the term was "Fun in London"

The URL created would be "fun-london".

How can I include the full path? So I would have "fun-in-london".

You can choose "strings to remove" on the settings page:

/admin/config/search/path/settings


Cant clear cache: Table cache_rules doesn't exist I just did a clear cache in the browser and also in the terminal with "drush cc all" and I'm getting the following error. I'm not sure what to do next as I can't clear the cache on the site, but it seems like the site is working fine. I'm on Drupal 7.32.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'phone_drup.cache_rules' doesn't exist: TRUNCATE {cache_rules} ; Array()

  in cache_clear_all() (line 167 of /home/phone/public_html/includes/cache.inc).

It's related to this: https://www.drupal.org/node/2160645#comment-9904817

it seems that this is a reoccurring problem for drupal 7 sites. I'm not sure why it happens but it seems the fix is to DROP the cache_rules table and then recreate it again. But sometimes it doesnt recreate the table as it might throw an error -1 on recreation.

I went into the terminal and to the mysql console and did the following:

DROP TABLE cache_rules ;

FYI: I had to set the engine parameter to blackhole in order for it to work. Default it is innodb. I'm not sure what blackhole is for. Just copy and paste into the terminal:

CREATE TABLE IF NOT EXISTS `cache_rules` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=blackhole DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';


Entity Validator failing Integer for not being integer I have a custom entity with an integer field with the following baseFieldDefinition:

    $fields['permission_level'] = BaseFieldDefinition::create('integer')
    ->setLabel(t("Permission Level"))
    ->setDescription(t("Sets amount of permissions owner has"))
     ->addConstraint('Range', ['min' => 0])
    ->setDefaultValue(0)
    ->setDisplayOptions('form', [
      'type' => 'number'
    ]);

because of the ->addConstraint('Range', ['min' => 0]), drupal throws an error anytime I try to create an entity through either the drupal generate:entity:content generated boilerplate form or json:api post requests.

I have used Xdebug to narrow the issue to the constraint validator range.
Something is passing a FieldListItem object instead of an integer to this constraint validator causing it to fail because its not an integer. The weird thing is that inside the FieldListItem object is the integer I input.

Why is drupal passing a FieldListItem object instead of an Integer?

You can add constraints to entities, fields or properties. You get then an entity, field object (FieldItemList) or a value to validate. So if you want to check the field value use FieldConfigInterface::addPropertyConstraints:

->addPropertyConstraints('value', ['Range'=> ['min' => 0]])


Calendar Pop Up - Extend year range A little bit of introduction:
I have a specific content type with the name "Database" where i can add content and with the views module and Search API, the user is able to search on my site for that content.

When I was creating the fields for the content type i noticed there were no fields for "date". So I installed Date module that allows me to have a Popup Calendar. On "MORE SETTINGS AND VALUES" i managed to extend the year range for 10 years. So, when i am adding content i'm able to choose from 2004 to 2022. So far so good!

In the view I created, i added some filters to make it easy for the users to search in the database. One of them is "Search by date" and I was able to display the same popup Calendar.
My problem is: the year range is not the same. It is only 2011 - 2017 and i have no idea how to change that. Since is the same from the previous configuration it should work...

Sorry for the confusing explanation, i don't know how else to put this.

Hope you guys can help me! Thank you!

The "Search by Date" Views field should be configuration (clickable) in the Views Administration and in its settings allow you to select the Year range, or the granularity of the date fields and their format.


Version control on Entity form type submissions A project collecting data from multiple entity forms was handed over to me. My client requested the implementation of a review mechanism for the data that are stored in entity form submissions.

The reviewers should have the ability to edit the submissions while they are keeping the initial content intact. The features extend to comparison between the various versions of the submission along with comments that can be attached to each version explaining the scope of the changes.

Pretty much the exact functionality that Node revisions are covering at the moment.

Unfortunately I just discovered that revisions are not available for entityform submissions (Add revision support to submissions) leading me to a dead end.

So, I seek some experienced guidance if there is a workaround to this, that I'm unable to see.

Could I create this versioning system somehow with the current data
structure?
Would it be able to migrate the data collected from form submissions to content type nodes so that I can use their revision framework (along with Diff and Node Compare modules)?

Trying to hack data out of an Entity form seems to make things unnecessarily more complicated, so I decided to redesign the whole form as a content type create form, while using entity reference fields to link the various instances.


Catch the selection of the values in select/drop-down-box prior to the node submission I have a Drupal 7 custom module with a couple of select/drop-down-boxes.  Is there a hook to catch the selection of the values in those boxes prior to the submission of the content node?  I am looking for a hook before the hook_node_submit occurs.

Thanks,
Derek

You might be looking for hook_node_presave()

  Act on a node being inserted or updated.

  This hook is invoked from node_save() before the node is saved to the
  database.

To attach a custom submit handler, create a custom module and do something like this:

function my_module_form_alter(&$form, $form_state, $form_id)
{
  if($form_id == 'form_abc')
  {
    $form['#submit'][] = "my_module_form_submit_handler";
  }
}

function my_module_form_submit_handler($form, &$form_state)
{
  drupal_set_message("The form is being submitted, do some extra stuff now...");
}


Any advice for dynamic radio butons I need a form that has a radio buton field. The field must not hard coded. Options must created dynamicly. The form will be a block and get radio buton options from given chosed node field.

For example if the form in node 1, radio options comes from node 1's given field, and so on.

Can you give me any advice to accomplish this? (entity form, web forms, custom form etc?)

(Sorry for my poor English)

Personally, I would create a custom module with a custom form and block. You're gonna want to study up on the form api. You can pass variables to your form, which for you would be your node object.

The block is really easy, just use hook_block_info() to define your block, hook_block_view to define a subject and callback function, and then just define a callback.

Something like this:

function mymodule_block_info (){
   $blocks[0] = array(
      'info' => t('radio thing'),
      'cache' => do_stuff
    );
   return $blocks;
}

function do_stuff(){
    //where radio_form is the implementation of your form (make sure it has a param for the node
    drupal_get_form ('radio_form', $node)
    return $stuff
}