Minimum password length for registration form For user registration, I have disabled "Require e-mail verification when a visitor creates an account." to allow user create their own password at the registration form. Now, I wonder how to limit the password characters to minimum 6? I have tested several times, it seems drupal doesn't restrict any password characters even user keys in just 3 characters.

You might be looking of Password policy module

Features
Current constraints include:

Complexity constraint

Digit constraint

Letter constraint Letter/Digit

constraint (Alphanumeric)

Length constraint

Uppercase constraint

Lowercase constraint Punctuation constraint

Delay constraint Username

constraint Digit placement constraint

History constraint (checks

hashed password against a collection of users previous hashed

passwords looking for recent duplicates)

Also checkout this Quick demo.


Why is the subtheme_style.css not being called? On a Drupal Commerce Kickstart installation, I have created a subtheme of Omega Kickstart, following the process described here.

Subtheme is saved to:
public_html/sites/all/new_theme

I kept only two of the *.css files for customization:

new_theme_style.css
new-theme-alpha-default.css

I updated the new_theme.info file as follows:

name = New Theme
package = Commerce Kickstart
core = 7.x
screenshot = screenshot.png
base theme = omega_kickstart

No changes to the Regions / Theme Settings. Updates to the Optional Stylesheets:
    ; OPTIONAL STYLESHEETS

css[new_theme_style.css][name] = New theme global style.
css[new_theme_style.css][description] = This file holds all the globally active custom CSS of Monkey theme.
css[new_theme_style.css][options][weight] = 12
settings[alpha_css][new_theme_style.css] = 'new_theme_style.css'

Changes made in new-theme-alpha-default.css are working, but changes made to new_theme_style.css are not showing. When I use "Inspect element" tools, I see that global.css is called instead.

Is this an issue with the weight I am assigning here? I copied the css over from another subtheme that is working. I cannot pinpoint the problem...but know it is likely a noobie mistake.

Thx - keb

Turns out, I had everything set up correctly, but hadn't toggled "ON" the style sheet.

Navigate to: Site settings >> Appearance >> Settings >> Toggle Styles
Click "ON" checkbox next to New Theme global style. (all) - new_theme_style.css

I slept on it and woke early in the morning, remembering that not only do you need to enable your theme, you need to turn on the style sheet.


How to split up a View up amongst different Panels panes? Context display? I know there's a way to take a view, and then put different slices into different panes in Panels or Page Manager. I've done it before, but not for a few years now.

I thought it was something that Views and Panels did 'out of the box', and I'm sure the Context module stopped being necessary a few years ago, but it's possible that's changed. I'm sure it involved a special type of views display (not blocks or pages, I think it was called a context display) then loading the view as a context in Panels/Page Manager. Then, each pane had appropriate options to choose the range of records e.g. 1-3 in one, then 4-6 in another, etc.

However, I have no such options in Views or Panels, and despite having a wealth of possible search terms here, I can't find the crucial step to enable this. It doesn't help that the word context is used in so many other contexts, I'm getting a wall of unrelated search results.

Did I remember this right, and if so, what do I need to do to access this "context display mode" in views that allows me to chop up the view in Panels?

The module I needed to enable was Views content panes. I was looking for something like it in the Views and Panels section of the modules list - it was in neither, it's bundled with ctools and listed under Chaos Tools Suite.

Then, once enabled, you get two new Views display mode options:

Context is the one to allow a view to be loaded as a context behind a panel.
Content pane is like a smart block where you can allow settings to be set per panel pane (e.g. offset and pager, allowing the view to be sliced up), toggling fields on and off, changing titles, etc. A few gotchas:

All such options are disabled from being edited in Panels by default, you have to enable them each time using the "Allow settings" option in the middle in Views
Panels can be a bit fussy about showing newly added view panes. You might need to save/update the panel/page manager page before it'll register the new view displays, even though it seems to load everything new each time. If even that doesn't work, try clearing caches.


Does unset($form['field']); in hook_form_alter stop entity reference views select list queries from running? I have a slow load time in a node form and I suspect the reason is that I am populating entity reference select lists using views & therefore a number of queries are being run to populate those select lists when the form is loaded.

As most of the entity reference fields don't need to be on the node-add form but only the node-edit form I tried using unset($form['field']) and hook_form_alter to remove those fields from the $form array but there is still a slow load time.

Could it be that the fields that get unset in hook_form_alter are still running their views queries?

Thanks very much and have a great day!

Short Answer: Unsetting the form element won't stop the view from being called. You may want to use an autocomplete widget instead if that is an option (if only to test your theory is correct - that the views are slowing the page load).

Long Answer:
When hook_form_alter is called, what you get is a form that contains elements from the Field API. Modules such as Entity Reference typically do not create new Form API elements - instead they provide field widgets.

Such modules contain code that generate their widget using the base elements in the Form API. This is typically done when field_attach_form is called, and it is at this point that the view would be called.

This is done before hook_form_alter is called. So what you get in form alter is the low level Form API elements - not the high level widget. Unsetting the field won't make a difference, since the low-level elements that contain the list of options have already been created.

It is possible that some module would actually use hook_form_alter to populate their widget - I have seen this done, and must say it is very bad practice - but I do not think this is the case with Entity Reference.


Create an advanced and complete search I want create an advanced and complete search, like the one on http://www.lib.muohio.edu.

I want to enable search in my CCK fields.
I don't know what module this site use; please help me to know that module(s) used in this site.

Help me to style my site like this site.

It looks like they use the multifacet module.
As for "help me to style like this site,“ that's a very broad request.


How do I ensure that a 'no results' view block is still refreshed by Block Refresh I have Block Refresh enabled on my site.  It does a great job refreshing content blocks unless the original block load contains zero results.  If a block is loaded without results, and a new node (which should appear in the block) is created, the new node will not appear in the block unless the page is refreshed.  It seems that the refresh code is not active unless the view is loaded with at least one item of content.  Is there a way to ensure that the view always loads?  I'm thinking that I need to change the 'no results' behavior in my view.

Edit =========

I am currently setting the 'no results' behavior to 'Global: Result summary' and setting the response to 'Empty'.  This seems to work.

Set the 'No Results' behavior to 'Global: result summery' and add some text to give as a response.  This will ensure that the view is rendered and active, even if there are no results.

This will allow block refresh to add new content as it become available.


Administration views change filter on my content type fields I'm using Administration views and I would like to be able to search by the last name field in my "Registration" content type. Currently, I can search by first name via the 'title' field on the content type as I replaced title field with my "first name" field. But now I would like to search on "Last Name" field.

Please provide a recommended approach to resolve this.

Go to admin/structure/views/view/admin_views_node and add a filter criteria on the field "last name". While adding the field check "Expose this filter" and you will be able to search on last name


How can I use a content type field on the body of the e-mail message template on the Webform module? For usability matters, I would like to let the editor create his own confirmation message on my Event content type. So I create a field for that. I also have another field to select which webform is going to be used as a reference (I am doing that the same way that was done on the Event Demo that comes on the module).

Is there a way to use this content type field on the e-mail handler on the webform as a token or something like that?

After looking more the examples, I found this token:

[webform_submission:node:field_name_of_the_field]

I needed only to replace field_name_of_the_field with the field I want to use.


How to filter nodes on a view based on user role shared by both nodes authors and current user? Working on Drupal 8.9.1
I need to list nodes with Views and filter them based on user role shared by both nodes authors and current user.
If I add a relationship to content author and a contextual filter on (author)User ID with default provided by logged user ID, I only get nodes authored by the current user.
Let's say we have a role "Staff A", I need any user with this role to be able to see any nodes from any users with the same role "Staff A".
Thanks for any tip here.

Finally, using role as contextual filter was not a good choice. It is working now but with a different option.
Using a term reference field for both user and node with the same vocabulary was my solution.
In my example, let's say I have a taxonomy field called Staff (field_staff), related to a vocabulary called Staff too.
I have added this field to user account and content type (the one(s) I need in Views).
Then, within my View, I have added two relationships:
Content using field_staff and
User using field_staff with a relationship to the previous relationship (reverse__user__field_staff).
Finally, I have added a contextual filter on User ID provided by default (logged in user) and with a relationship to User using field_staff.
And voilà, the view is listing any nodes filtered by field_staff equal to the current user field_staff.
Hope this helps.


How should I get data from the node table? I am creating a Drupal Dashboard (PHP 7.2, Drupal 8.9). I'm trying to query the node table using the following code.
$database = \Drupal::database();

$query = $database->query("SELECT field_advertiser_id_value FROM {node__field_advertiser_id} WHERE entity_id = :entity_id", [
    ':entity_id' => $entity_id
]);

$result = $query->execute();
print_r($result);

I am not sure why $query->execute() returns false. This table exists in the l database.
The database contains both the node and the node__field_advertiser_id tables.

Inserting data in the node__field_advertiser_id works correctly.
$database = \Drupal::database();

$database->insert('node__field_advertiser_id')
    ->fields([
      'entity_id' => $advertiser_nid,
      'revision_id' => 1,
      'delta' => 0,
      'field_advertiser_id_value' => $advertiser_id
    ])
    ->execute();

I am trying to fetch details from the node__field_advertiser_id from hook_node_delete(). The data is still there in the table when I try to run the SQL query.
It would be great if anyone can help me out with this.

I don't think you need an execute on a regular query like that. But the way to get any node data would be loading the node with the entityTypeManager service, and getting the field values with $node->get('field_advertiser_id')->getValue(). Its rare to have to get a value that way from the database.
The same goes for the insert or update - you definitely should be using the API for this and not direct database writes.
On top of that you don't need to do anything with the database at all in this example, because the node being deleted is already passed to this hook. Just look at its field values. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_delete/9.1.x
But in a case like this, hook_entity_delete may be too late to get values depending on what you need to do. Instead, you probably want to use hook_entity_predelete: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_predelete/9.1.x
Example:
function mymodule_entity_predelete(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity instanceof NodeInterface && $entity->getType() == 'your_content_type') {
    $advertiser_id = $entity->get('field_advertiser_id')->first()->getValue();

    // do something with id, like load that node
    if (isset($advertiser_id)) {
      $entityTypeManager = \Drupal::entityTypeManager();
      $advertiser = $entityTypeManager->getStorage('node')->load($advertiser_id);

      if ($advertiser instanceof NodeInterface && $entity->getType() == 'advertiser_content_type') {
        // Delete this other node.
        $advertiser->delete();
      }
    }
  }
}

You have to be careful with these hooks though, because it can trigger an infinite loop since these hooks are fired every time the actions are performed. Meaning, if you wanted to delete the advertiser node here for example, this hook would get called on that action too. So you need to be specific with your conditions check each value and logic. People get caught in presave hooks all the time.


How to render HTML into a variable programmatically Let's assume you have a "product" node $node, and for some reason you want to render HTML from $node into a variable $html using a Twig template. I'm a bit desperate yet, what would you do?

Additional info 1: We are not in a controller, but in a simple class that is registered as a service.

Additional info 2: 4k4 's answer does work if I call my class from a controller. But as soon I call it from a Drupal Console command I get an Exception "The theme implementations may not be rendered until all modules are loaded."

Edit: The complete solution

Obviously not all modules are loaded if we call the service inside a Drupal Console command. The Theme Manager will honor this with the aforementioned exception, so we have to force load the modules:

\Drupal::moduleHandler()->loadAll(); // Load all modules if not loaded already

Now it's safe to call the renderPlain() method as suggested below:

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$build = $view_builder->view($node, $view_mode, $langcode);
$html = \Drupal::service('renderer')->renderPlain($build);

Edit: But what about a full page?

If you intend to render not only the node content but a full page (from <html> to </html>) you have to have the kernel handle an appropriate sub-request .

To render a plain node view, for example for emails, use this code:

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$build = $view_builder->view($node, $view_mode, $langcode);
$html = \Drupal::service('renderer')->renderPlain($build);

If you want to customize the output, use a special view mode and a template node--[view-mode].html.twig.

Edit: Full page

You can build more complex render arrays:

  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $content = $view_builder->view($node, $view_mode, $langcode);
  $build = [
    '#type' => 'html',
    'page' => [
      '#type' => 'page',
      '#theme' => 'page',
      '#title' => 'Title',
      'content' => $content,
    ],
  ];

  $html = \Drupal::service('renderer')->renderPlain($build);

This is only a basic version of a page, if you want the full version with all features like attachments and libraries you need a request on Drupal.


D7 images not loading from css or from direct urls I have a site that I have developed off-line and now loaded onto the production server.  None of the images load on the server (despite being present in the appropriate directories).  This applies to images loaded by css (for example:

.section-contact div#header {
background-image: url('/www.bernwodebenefice.com/images/contact_banner.png');}

It also applies to direct links from nodes.  For example:

<img alt="" src="/www.bernwodebenefice.com/sites/default/files/StMaryDedication_1_20121202.jpg" style="width: 220px; height: 322px; margin-left: auto; margin-right: auto;">

(these samples are from the rendered code and are what I expected).

I do not have this problem with any of my other sites running on the same host.  For example:

div#header {background-image: url(/sites/all/themes/Endurance80/css/images/e80_2013.gif); height: 263px; }

This works perfectly.  And urls within the site work nicely using the same sort of link addresses.

I guess I have got some parameter somewhere not set right...  (I copied .htaccess and php.ini from a working site to the failing site in the hopes it was a rewrite problem... nope)

Any thoughts?

Peter

Have you tried

<img src="/sites/default/files/StMaryDedication_1_20121202.jpg">

and

.section-contact div#header {
  background-image: url('../images/contact_banner.png');
}

where images is a folder in your theme dir e.g: images/contact_banner.png relative to css file in e.g: css/style.css.


Getting Error 324 (net::ERR_EMPTY_RESPONSE) when saving changes to content/views/modules For a few weeks now, I've been getting an error when saving certain changes. This error, in Chrome, is

  Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.

After I click the save button, the page seems to load for a while (10 seconds or more), then directs to that Chrome error page. But, if I reload the page manually, the changes I've added have actually been saved. I've noticed this happening when: adding a new content type, adding a new field, saving changes to a view, disabling or enabling a module, and even clearing the cache.

After some digging, I found out that this error gets posted to Apache's error log every time this happens:

  [Fri Mar 30 09:27:11 2012] [error] [client 74.142.25.146] PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 12893929 bytes) in /var/www/drupal/includes/database.mysqli.inc on line 329, referer: http://mysite.com/admin/content/node-type/typename/fields/field_looptest/remove
  [Fri Mar 30 09:27:12 2012] [notice] child pid 17934 exit signal Segmentation fault (11)

I have two sites I work on, one of which is simply a week-old backup version of the other. Interestingly, the error printed to the log for the up-to-date site is slightly different: The file that seems to be generating the error is includes/database.inc, line 225 instead of includes/database.mysqli.inc. In both cases, the line mentioned is simply an escape string function. mysqli_real_escape_string() and db_escape_string() specifically.

I'm at a loss. The fact that it's a Drupal core file generating the error is bothersome. Does anyone have any idea why this is happening?

So, after a few days of trial and error, I managed to fix this problem. (Although I still am not really sure what caused it...)

The fix that I found was to disable modules until the problem disappeared, then to re-enable those modules. That was it. The problem has not resurfaced for the past few weeks.

Now, some details: I first attempted to fix the problem on my "sandbox" server, disabling modules one at a time with the hope that the problem would go away. It did, and I noted which module(s) were the last to be disabled. However, taking that information back to my main site did not help. Instead, I disabled modules in bulk (everything that could be disabled on a first pass; i.e. all modules not required by another module). After a few passes, the problem did indeed disappear. I'm not sure what caused it or why. If my searches while trying to fix it were any indication, nobody else knows either. Just a quirk of Drupal 6 I suppose.


pager is not working on update of Views 7.x-3.7 to Views 7.x-3.8 Hi i have recently update one of project and so views module also updated now views pagignation is not working (from views 7.x-3.7 to views 7.x-3.8 version)
any help appreciated
thanks.

I recently had the same problem. Issue for me was Views 7.x-3.8 changes the file plugins/views_plugin_query_default.inc to move the following code from the execute function to the query function.

I fixed it using the following patch:

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


Recaptcha not working in user register form I am using google recaptcha in drupal 7 for user registration. The captcha works fine in the normal user register page but doesn't appear in the pop up dialog box for user registration?

some more info:

i created the pop register form using ajax
i checked the css of the site and the <div> of the captcha is present but doesn't have any content inside it like when it does when it is working.

After some browsing, i found the Patch for the Recaptcha module that enables it to be used in ajax register form.

Please find the link to the node  here

Cheers.


Colorbox plugin installed but status report is not recognizing it I have installed the Colorbox plugin version 5.1.14 in /sites/all/libraries/colorbox but on the status report page I get the following:

  You need to download the Colorbox plugin and extract the entire contents of the archive into the sites/all/libraries/colorbox folder of your server.

Sometimes what happens with these libraries is that the download you get from the library site (colorbox in this case) packages its code in a folder itself. For the master download of colorbox, for example, the code comes in a folder called colorbox-master. If you unpack it into

sites/all/libraries/colorbox

then the code ends up in

sites/all/libraries/colorbox/colorbox-master

What you may need to do is unpack it into

sites/all/libraries

and then rename

sites/all/libraries/colorbox-master

to be

sites/all/libraries/colorbox


Views API - how to replace PHP fields So a client that I inherited has multiple PHP fields in each of their views.

I'd like to replace them. They're using PHP Code module as well as Views Customfield.

Would I have to write a custom views handler? Or is there some sort of alter that would allow me to basically replace each of these fields/data sources with my own information, without exposing a PHP filter to a user (even an admin user).

Basically I am trying to increase site security.

In cases like this, I usually use:

https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7

For pre-processing the views render array.


Field value as Views 3 block title I have a Views 3 block whose block title I would like to set using PHP in the header section. This would enable me to use tokens from the views results, which is not possible from the UI.

In the case of a views page I was able to set the page title via the following PHP command in the header section:

$view = views_get_current_view();
$view->build_info['title'] = 'My Page Title';

However, I was not able to do the same thing for block titles via

$view = views_get_current_view();
$view->build_info['title'] = 'My Block Title';

This is probably because the build_info['title'] command only edits the page (or node) title. Does anyone know of an analogous command to set block titles?

Sorry, I made a huge mistake. When I tried to achieve the same thing for the block title, I copied the code from the page header but didn't remove it from the page header. In other words, I used the PHP commands - exactly as described in the question - in the headers of two subviews of the same view simultaneously. To be more precise, the variable $view was used in two places, which caused an error.

When I replace $view = views_get_current_view();
$view->build_info['title'] = 'My Block Title'; with $view_block = views_get_current_view();
$view_block->build_info['title'] = 'My Block Title'; things work as desired!


Setup right field type and widget for field I'm using Drupal 7.23 to build an online catalog for a shop. I made an "articles" content type and I've built all the required fields.
I need to setup the Price field in a way that it's a list, and each row of the list will show something like "buy x at yx", like "buy 1 at 5, buy 2 at 9, buy 3 at 12" and so on, and I need it to be treated as numbers (5,9,12). How can I accomplish this?

I have also the image field, I need to have up to 10 images for the same article, and I want to show a gallery (more or less like Amazon does), where you click on the photo and it enlarges. It is handled by Drupal already? Do I have to setup something special to do this?

For the first issue you can actually add it as a key|label pair.

Where the key would be the number and the Label would be what is displayed. for example 5|buy 1 at 5

this would show "buy 1 at 5" in the dropdown but the value would be five. you want to work with numbers you might want to select List(integer) as your field type.

For the second problem you might want to take a look at the Cloud Zoom Module.

  This addon provides a small, thumbnail sized image, with an on-hover
  popup, zoomed and centred on a larger version of the image.

OR

jQZoom

  The jQZoom module is a wrapper for the jQuery plugin jQZoom. The
  module provides a javascript magnification effect for images. When a
  user mouses over an image, a larger version of the area under the
  cursor will be displayed beside the image.


Create destination directory with drush archive-restore? I'm using this terminal command to restore an archive created on a remote server locally:

drush arr archive.tar.gz default --destination ./newdir --db-url=mysql://user:pass@localhost/db

The archive was created with drush archive-dump, and the restore is on a Mac running the MAMP stack.  The archive is in the current working directory when I run drush arr.

In general, this works fine, but for some reason, the new directory (newdir) isn't created. All files are restored into a folder named "1" (which is created). Drush reports "Archive restored to 1"

Is there some way for me to modify the syntax so that newdir is created, and all files are restored there?

Try --destination=./newdir.  Drush always uses --flag=value; without a value specified, the default is 1.


Do I have to delete the default folder? Do I have to delete default folder which is located under /sites? Because I installed new theme and I think there is no need to keep the default theme.

And, if I can't delete it, please tell me why?

Unless you're running a multi-site or another non-standard configuration (and the way the question is phrased, I do not think you do), you can't delete the sites/default folder or the files within it.

The reason you can't delete it is because: This directory (unless you've set up a multi-site or similar) contains (among other things) the settings.php for your site. If you delete it, all you settings including the database credentials will be lost, and your site will stop working.

Please also note that the sites/default folder has nothing whatsoever to to with the theming of your site.

If you have installed a new theme, and have the problem that the new theme is not used, this problem is not related to the presence of the sites/default folder on your site.


Migrating content from older custom CMS Initial Question

Given an older CMS that kept data in a mysql database, how could we move this into a new D7 install?

It has a mysql database with a content table containing Title and Body (with HTML content) columns, could I do an import of this into Drupal and fill in the gaps as needed? I'm okay to rebuild menus and tie up other loose ends, but I'm fearing hours of cutting and pasting putting.

Follow Up and Outcome

:** After considering all the great advice below, I opened the older database in mysql Query Browser, executed a query on the profiles table to give me a CSV file with the following headers...

FirstName
MiddleName
LastName
Address1
Address2
phone
Email
title
cvFilePublic
pageContent
lastUpdateDate
pageName
pageURI
pageID

Then I created a Feed Importer with the following mapping:

If you know any php I recommend the Migrate module to easily write a SELECT title, body FROM old_content and map them to Title and Body fields of a Drupal Page type. You would do this with a Migration class. See documentation on the project page.

You could also try the Feeds project.

There are modules for Migrate to migrate from Wordpress or older Drupal sites. You could use that as example migrations to move content, menus, etc into a new drupal site.

I've migrated pages, and custom Joomla content for courses and instructor content into Drupal content types .... but every migration use-case is always unique; I'm just recommending tools I've used.


Disable page compression only on specific pages I am running drupal 6 and have page compression enabled. When page compression is enabled, drupal caches all the pages. But I do not want certain pages to be cached. How do I force drupal not to cache certain pages?

You're probably looking for something like the CacheExclude module? Here is a quote about it (from the module's project page):

  ... provides a simple way to exclude certain pages from being cached. Sometimes you want all pages to be cached for anonymous users except for one or two pages that have dynamic or random or rotating content. If those pages are cached, the dynamic parts cease to be dynamic. This module allows an administrator to selectively exclude certain paths from being cached so that dynamic content is actually dynamic.


How can I isolate *content* from *configuration* in the database? There's no obvious way (that I can see) to isolate a Drupal site's configuration (which is of course all in the database) from its content (which is of course in the same database) when doing any operations on the database.

For instance, it would be very useful to be able to be able to push your configuration changes from your development server to production,

drush sql-sync @dev @prod

and then push only your content back to development from production.

drush sql-sync @prod @dev

Short of going through the database and making a list of tables for each type of data, and writing your own script to dump and import just those tables (an approach which seems kludgey and error-prone), how can this be done?

UPDATE: There doesn't seem to be any way to do exactly what I'm asking how to do.  Since both answers were very helpful, however (1st of all because they contain useful information, and secondly because they indirectly confirm that it's not currently possible to do in any practical way) I'm up-voting them and selecting one.  I hope that by selecting an answer no one is confused into thinking that what I described is possible.  (I've seen such things happen before.)

There are different ways of passing the configuration data between various environments;

1 - Features

  The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it declares its components (e.g. views, contexts,
  CCK fields, etc.) in its .info file so that it can be checked,
  updated, or reverted programmatically.

It can be used in combination with Strongarm .

2 - Configuration Management

  ability to keep track of specific configurations on a Drupal site,
  provides the ability to move these configurations between different
  environments (local, dev, qa, prod), and also move configurations
  between completely different sites (migrate configurations) without
  the use of modules with all configuration being owned by the site.


multi url allies for same node I have set my auto URL allies to something like this "store/[node:nid]/[node:title]"

having node title in url will make it more human readable and better SEO.
the issue is I want to be able to access the node using this url "store/[node:nid]" only

here is the question again

my url is "www.site.com/store/1234/title"

I want this url to work as well "www.site.com/store/1234"

and even this "www.site.com/store/1234/new-title"

and even this "www.site.com/store/1234/wrong-title"

cheers
cheers

You can use symlink for creating multiple urls you want. I try this and created multiple with pathauto too.


CKeditor: Add class to all ul and ol elements on output The ul and ol elements are often used in theming outside of the 'text'-context (e.g. category blocks, etc.). Therefore the bullets are removed by default.

Is there a way to add a class to all ul and ol elements outputted by CKeditor? For example class 'editor', so that we can theme the ul/ol elements differently if they are outputted by CKeditor (with bullets or decimals).

There is no reason to do that for styling purposes. You can target the ul and ol elements by their parent container. The classes depends on your theme output, but consider this for the Garland theme:

/* Style all ul and ol elements from the body output. */
#center .node .content ul,
#center .node .content ol {
  /* Styles here */
}

If you are missing classes you can add those in the page.tpl.php and node.tpl.php templates.


Set CSS class for a View programmatically in a hook I want to set an extra class for the first page of a paged View.

/**
 * Implements hook_views_pre_render().
 */
function my_module_views_pre_render(ViewExecutable $view) {
  if ($view->id() === 'my_view' && $view->current_display === 'page_1') {
    // Somehow set/override the css class here.
  }
}

How can I change the CSS class set in the advanced settings of the View?

Something like this should do it:

$view->display_handler->setOption('css_class', 'your_class');

Good luck!


Programmatically get webform submitted field values How can i print/echo the submitted value of specific field in from a webform? I need to do this in the webform 2 PDF module so i can better customize the output of generated PDFs. Im fairly new to Drupal so an example of how to get a simple f_name filed would be great.

I'd also like to start getting more involved with the Webform API too.

i.e

First Name: SUBMITTED NAME VALUE

In recent 3.x and 4.x versions of webform it has an hook based API to allow you do stuff with submitted webform values.

Look at like hook_webform_submission_insert() or hook_webform_submission_update() (if your webform has Drafts enabled for instance the final submission is an UPDATE call with isNew == False and isDraft == False).

The functions take a parameter $submission that is a PHP array of the submitted form values ... You can do whatever you want with them from there.


Programatically get a list of node ids of a content type for a specified language From the following code I get all the node ids of content type 'blog'

    $query = \Drupal::entityQuery('node');
    $query->condition('status', 1);
    $query->condition('type', 'blog');
    $query->sort('created', 'ASC');
    $entity_ids = $query->execute();

I want to retrieve all the node ids of specific language.
Eg. Node ids of content type 'blog' for 'French' language.

You can just add langcode to the query:

$query->condition('langcode', 'fr');


text formats - not allowed tags are saved anyway I have filtered html text format set to limit allowed html tags (<a> <em> <strong> <ul> <ol> <li><p>), I use also CKeditor with this format. I expected that Drupal would clean any other tags. This is happening after I save a node with text with some not-allowed tags and look at yet unpublished node's html - everything is stripped the way it should be.
However, if I open the node again and look on the code using ckeditors source button - the tags are there.
Were not the tags supposed to be deleted by Drupal? If not, what module can provide such functionality? Thank you.

Were not the tags supposed to be deleted by drupal?

No, the mantra in Drupal is "save the raw string, sanitise on output".

What you're seeing is the filter system working as designed.

As you mentioned in the comments, the Sanitizable (formatted text) module does exactly what you're looking for.

  The Sanitize module allows administrators to configure a text format to be applied to formatted text before storage. This is useful to ensure clean and valid data in the database.


form set error is not working properly I am using Drupal 7

i am tracking login and setting errors but my error is not working properly

here is my code

  <?php

    function zloginsecurity_form_alter(&$form, &$form_state, $form_id)
    {
        switch ($form_id)  {
        case 'user_login':
        case 'user_login_block':
           $form['#validate'] = zloginsecurity_validators();
          break;
      }
    }

    function zloginsecurity_validators() {
        return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate','zloginsecurity_validate');
    }

    function zloginsecurity_validate($form, &$form_state) {
           if (empty($form_state['uid'])) {
            //Check user Track Record
            echo "hello";
     form_set_error('name', t('hello test'));
          }else {
              zloginsecurity_removeevent();
            //Delete Track Records for Particualr user
        }

    }

 ?>

it is not showing hello test, it is showing default message .  Can anybody tell me how to solve this issue.   simple echo is working

Thanks

In form_set_error, the first parameter should be form name, if you are not sure of the name, just leave empty.

form_set_error('', t('hello test'));

This should work just fine.

UPDATED ANSWER

If you would like to have only your validation and skip the rest of Drupal core's validation for that particular form, you can unset the validator function and inject your own.

unset($form['#validate']);
$form['#validate'][] = 'zloginsecurity_validators';

Or

If you like to have both and give priority to yours first, then

$default_validators = $form['#validate'];
unset($form['#validate']);
$form['#validate'][] = 'zloginsecurity_validators';
foreach ($default_validators as $val) {
  $form['#validate'][] = $val;
}


How to use Views and Rules to activate a new node flag for existing OG members? We have a flag for nodes called subscribe_og.

From this point in time users will click that flag to join, or leave, a group.

If you are not a member of the group, the flag says 'Join'. If you are a member the flag says 'leave'.

Old members of a group currently see 'leave' as they have not clicked the flag.

Is it possible to use Views and Rules to generate a list of group members, check if they have have activated the node flag, and if not, activate the node flag for them?

I had a little look at Rules Components and came up with this, which seems to do nothing.

    { "rules_gerw" : {
    "LABEL" : "gerw",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "og" ],
    "IF" : [
      { "NOT flag_flagged_node" : {
          "flag" : "subscribe_og",
          "node" : [ "site:og-context--node" ],
          "flagging_user" : [ "site:current-user" ]
        }
      },
      { "AND" : [
          { "og_user_in_group" : {
              "account" : [ "site:current-user" ],
              "group" : [ "site:og-context--node" ],
              "states" : { "value" : { "1" : "1" } }
            }
          }
        ]
      }
    ],
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "subscribe_og",
          "node" : [ "site:og-context--node" ],
          "flagging_user" : [ "site:current-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Step 1: Fix your rules Component

The "... seems to do nothing ..."-part of your question, is like a variation of "it doesn't work" ... which is extremely hard to debug without access to your site.

However, what I find bizarre about your Rules Component is:

You're using token site:og-context--node, but there is nothing in your rule that assigns a value to it. So wild guess: it's value is blank or something like that. If my guess is correct, then your rule "works as implemented, ie "it is doing nothing", because not both Rules Conditions are satisfied.
It is related to user = site:current-user. So you've to be a bit lucky to have this Rules Condition satisfied (it depends if the current user is yes or no member of some group which might be blank).

What I think is needed, at a minimum, is that you use appropriate parameters for this Rules Component, actually for all of your tokens you're using that start with site:.

To do so, have a look at this improved version of your Rules Component. The main difference with yours is that I introduced 2 parameters, and replaced all site:

{ "rules_using_parameters" : {
    "LABEL" : "A Rules component using parameters",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "og" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "node_to_flag" : { "label" : "Node to be flagged", "type" : "node" }
    },
    "IF" : [
      { "NOT flag_flagged_node" : {
          "flag" : "subscribe_og",
          "node" : [ "node-to-flag" ],
          "flagging_user" : [ "flagging-user" ]
        }
      },
      { "AND" : [
          { "og_user_in_group" : {
              "account" : [ "flagging-user" ],
              "group" : [ "node-to-flag" ],
              "states" : { "value" : { "1" : "1" } }
            }
          }
        ]
      }
    ],
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "subscribe_og",
          "node" : [ "node-to-flag" ],
          "flagging_user" : [ "flagging-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

You should be able to just copy the exported rule above, and simply import this Rules Component in your own environment.

After you did this, navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Node to be flagged. Use a similar technique to specify the Flagging and hit the Execute mode.

If both Rules Conditions are satisfied, then the node you selected will be marked as flagged by the user you specified.

So please do some QA-testing of this variation of your rule. And make sure to select accurate testcase (different from your own userid, aka site:current-user).

And if this QA-testing results in "... it still does nothing ...", then perform appropriate Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".

Move on to Step 2 after your QA-testing is completed (and you're sure the rule works as designed).

Step 2: Let VBO do the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!


How to set a form field sizes based upon the screen size responsively? I'm building a mobile-first module in D7. I want to set the size attribute of a form (textfield, textarea) depending upon the screen size (i.e., using css media query). Is this possible?

Yes: you can use any CSS media query you want in your theme or module's CSS and affect form elements. You'll want to use a web inspector (like the built-in ones in Chrome and Safari, or Firebug for Firefox) to identify what selectors you want to target.

If, for example, you wanted to make the text fields on the node submission form responsive, you'd target the .node-form selector in your CSS file:

@media screen and (max-device-width: 480px) {
  .node-form .form-text {
    width: 200px;
  }
}

To attach your own CSS for your module's forms (or for any form), you'll want to modify the #attached property in your form:

$css_path = drupal_get_path('module', 'mymodule') . '/css/mymodule-style.css';
$form['#attached']['css'][$css_path] = array('media' => 'screen');

Where mymodule is replaced with the short name of your module. The #attached property is an array of CSS files: if you don't need to modify any options, you can just do:

$form['#attached']['css'][] = $css_path;

Otherwise, you'd set the key to $css_path and the value to an array that mimics the $options array for drupal_add_css().

If you wanted to modify existing forms, you'd do the same thing but in a form alter function. For example, if you wanted to add your custom CSS to the node submission form, you'd do:

function mymodule_form_node_form_alter(&$form, $form_state) {
  $css_path = drupal_get_path('module', 'mymodule') . '/css/mymodule-style.css';
  $form['#attached']['css'][$css_path] = array('media' => 'screen');
}


What message is throwing InvalidArgumentException(s) in my contact forms? When submitting a contact form it redirects to a WSOD and this is logged:

Uncaught PHP Exception InvalidArgumentException: "$string ("Message") must be a string." at /Applications/MAMP/htdocs/onb/core/lib/Drupal/Core/StringTranslation/

I've tried creating new forms and setting them as default. It didn't work. I've also tried uninstalling and installing the contact module without much luck. Any thought on how to fix it or dig up what exactly is causing it?

Thanks.

You're most likely passing an object or an array to a translation function call. The t() function expects a string as it's first parameter (see the function spec on drupal.org). Search for places where you call the t() function.

More information on how the translation functions are used in D8 can be found on the translation api page on drupal.org. This will give you an idea of how and where you could have translations so you can check those places in your code.


How to bypass CAPTCHA during Behat functional testing? We have a site that uses the CAPTCHA and CAPTCHA After modules to protect forms from invalid submissions. We're doing some functional and BDD testing using Behat and the tests are sometimes triggering the CAPTCHA After thresholds, causing the CAPTCHA to be displayed. Is there an easy way to bypass the CAPTCHA, when performing tests?

I realize that we can probably override the CAPTCHA After threshold settings in the database, if the tests are running on the same machine. However, it would be nice to also be able to run the tests from a different machine than the web server hosting the site. I think that something like an IP whitelist might work, but I haven't found anything along those lines yet. Before we start coding something like that, anyone have a better idea?

Thanks!

Using the API Driver you can, as you say, modify CAPTCHA After threshold and restore it at the end of test, but you need to execute tests in the same machine.

If you want to do it form another machine you have to set up a way to alter that variable from outside. You can define a hook menu that alters that variable, in a dev module that will not be enabled in production site. You can also set up a drush remote command that modifies the threshold in th remote machine and restores and the end of the test. You can add this drush command in the script that lauchhes behat tests or even inside behat in a behat hook.


Can't loop through $form_state->setErrorByName? I want to display an error message if the form field is empty.

  public function validateForm(array &$form, FormStateInterface $form_state) {
      $entry = array(
        'name' => $form_state->getValue('name'),
        'lastname' => $form_state->getValue('lastname'),
        'cardnumber' => $form_state->getValue('cardnumber'),
        'month' => $form_state->getValue('month'),
        'year' => $form_state->getValue('year'),
        'cvv' => $form_state->getValue('cvv'),
    );
    foreach ($entry as $key => $value) {
     if (empty($value)) {

      $form_state->setErrorByName($key, $this->t('cannot be empty.'));

        }
     }
  }

but I only get:

  cannot be empty.

If I use instead:

foreach ($entry as $key => $value) {
  if (empty($value)) {

    drupal_set_message(t('<b>%key</b> cannot be empty.', ['%key' => $key]), 'error');

    }
}

Results how I want it:

  name cannot be empty.

  lastname cannot be empty.

  cardnumber cannot be empty.

  month cannot be empty.

  year cannot be empty.

  cvv cannot be empty.

Except the problem here is that the form input box does not become highlighted in red.

How can I make it loop through the first method? or is it like that by design?

I think you simply need to replace:

$form_state->setErrorByName($key, $this->t('cannot be empty.'));

with

$form_state->setErrorByName($key, $this->t('<b>%key</b> cannot be empty.', ['%key' => $key]));

According to the docs, the first parameter will identify the field and the second will be the message to output.

In your code, the $message string is outputed as expected, you need to prefix it with the $key parameter, the same way you do with drupal_set_message.


using drupal 7 functions in external files I feel that the above title isn't very well worded since I can't figure how to state it properly using few words. Anyway, what I'd like to do is this:

$.post("foo.php", data, function(msg) {
   //the js part is easy enough to handle
});

This is simple enough but how do I get foo.php to use Drupal 7's functions? While it would probably make my life much easier to use ordinary php code to do all my database queries, I'd like to stick with Drupal functions to play it safe.

Make a copy of the index.php file and rename it to foo.php. index.php ships by default with Drupal 7 and can be found in the root of the Drupal source.

Remove the last call to menu_execute_active_handler() from the new file. This is the router that calls an appropriate page handler based on the query string. You wouldn't need this.

This leaves:

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
/* Stub */

As you can see, Drupal is now bootstrapped fully. This makes the API methods of Drupal core and all other enabled core and contributed modules available for use in this script from the fourth line.


Prevent multiple registrations from the same email using + character Gmail and other email services allow users to extend their address using the + (plus) character.
For example, mail to

spamme@gmail.com
spamme+sideways@gmail.com
spamme+tomorrow@gmail.com

will all be receivable by the owner of spamme@gmail.com
In its default configuration, Drupal 7 would allow the owner of spamme@gmail.com to register 3 separate accounts using the 3 addresses above... and more if they want!
I would like to prevent this type of multiple registration.
While I could just create a rule that blacklists email addresses containing the + character, there are legitimate uses of this.
I would prefer to be able to check for other equivalent email addresses, where in the above example, all 3 addresses are equivalent, because they are all collectable by spamme@gmail.com, and allow only one of them.
Is there some way to do that?

Check email before register user with add your custom validator in hook_form_alter, then check user email without +secondpart :

As a Example you can Try something like this (I didn't test this but it can give you a good clue to achieve what you want )

 function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id){
       if ($form_id == "user_register_form") {
            // add your custom validator
            $form['#validate'][] = 'my_custom_email_validate';
       }
     }

in your custom validator check it with regular expression

function my_custom_email_validate($form, $form_state, $form_id){
    // dpm($form_state['values']);
    $mail = $form_state['values']['mail'];
    preg_match_all('/(.*)\+.*(@.*)/',$mail,$matches);
if($matches){
    // this mean it has  xxx+xx@xxx pattern
    $clean_mail = $matches[1][0].$matches[2][0];
    $user_load = user_load_by_mail($clean_mail);
    if($user_load){
        form_set_error('mail',t('Sorry,This email used before.don\'t waste your time dear spammer'));
        return false;
 }
}


why does internationalization menu i18n_menu translate but never localizes? I have a menu set to :

Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized.

And I have include menu items that are "language neutral" and provided translations for said items.

Nothing but the original 'language neutral' language ever shows regardless of what the users profile language is set to (user's profile language is the primary way I have translation determining what language to use)

What do I have to do to get the Menu items to localize to the current users current profile language ?

As said in the 2nd choice Translate and Localize, there are two different ways for translating menus.

If you want to use the Menu items with language will allow translations option, set a link in each of your defined languages, but none in language neutral, and check in admin/structure/menu/manage/main-menu then in *admin/structure/menu/item/[ITEM_ID]/edit* for each set of translation, that it is correctly translated.

Now if you wish to work with the Menu items without language will be localized option,  make sure you create the menu item in the site default language (because localization always happens from the site's default language to other languages). And choose language neutral for the menu item when created.

Now in the opened up Translate tab, you'll translate the menu item title and description instead of creating another menu item. And you're done !

For a complete explanation read this nice tutorial about Drupal multilingual navigation.


Create a zip file from a list of selected files and make the zipped file downloadable in Drupal 8 How to create zip file programatically based on the files selected in Drupal 8? Is there any class already existing in Drupal 8?

As per below answer I'm using following code to generate zip file:

$file = \Drupal\file\Entity\File::load($fileId);
$fileUri = \Drupal::service('file_system')->realpath($file->getFileUri());

$zip = \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => '/foo/bar.zip']);
$zip->add($fileUri);

The bar.zip file above should exist in the referenced path above: /foo/bar.zip.
Also how do I flatten the the zip file folder structure so that the file sites/default/files/myimage.png is myimage.png?

Use the ArchiverManager and get the instance by calling the getInstance() method. A Zip class is returned. The Drupal Zip class uses PHP's ZipArchive class to perform the heavy lifting.

Example (edited after remark @Clive):

$file = \Drupal\file\Entity\File::load($fileId);
$fileUri = \Drupal::service('file_system')->realpath($file->getFileUri());

$zip = \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => '/foo/bar.zip']);
$zip->add($fileUri);


db_insert error delta "doesn't have a default" When I execute this code:

db_insert('field_data_field_room_rates')
    ->fields(array(
      'entity_type' => 'node',
      'bundle' => 'rooms',
'entity_id' => $roomno,
'revision_id' => 0,
'field_room_rates_target_id' => $mynode->nid
    ))
    ->execute();

It returns back an error saying "General error: 1364 Field 'delta' doesn't have a default value".  Any quick way to work around this without doing a count to respect the order?  I don't want to give it an arbitrary number.

Thanks in advance!

Without knowing the circumstances, I think you might better off loading your node,  adding to the field array, then using the node save function. But if you want to stick with DB operations, you could retrieve the next highest cardinality with this query:

  $next_delta = db_select('field_data_field_room_rates','rates')
    ->fields('rates', array('delta'))
    ->condition('entity_id', $mynode->nid)
    ->condition('revision_id', $mynode->vid)
    ->orderBy('delta','DESC')
    ->range(0,1)
    ->execute()->fetchField() + 1;


How can I make my main menu link text dynamic? How can I make my main menu link text dynamic?

My solution:

I tried to use Felix's answer, below, but it would not work for me. Obviously, the method suggested by Felix has worked for others and it is used in core (user.module, for example). However, I was able to conditionally alter my main menu link text at the theme level. I added this to template.php:

/**
 * Conditionally alters preprocess links variables.
 */
function MY_THEME_preprocess_links(&$variables) {
  if (MY_FUNCTION()) {
    if (isset($variables['links']['menu-562 active-trail']['title'])) {
      $variables['links']['menu-562 active-trail']['title'] = 'New blog';
    } elseif (isset($variables['links']['menu-562']['title'])) {
      $variables['links']['menu-562']['title'] = 'New blog';
    }
    if (isset($variables['links']['menu-563 active-trail']['title'])) {
      $variables['links']['menu-563 active-trail']['title'] = 'New notes';
    } elseif (isset($variables['links']['menu-563']['title'])) {
      $variables['links']['menu-563']['title'] = 'New notes';
    }
  }
}

Drupal menu's are cached and this makes it hard to change then on the fly when the page is rendered. It is possible though using the functions aimed at translating menu items: see hook_translated_menu_link_alter.

This hook is called before every menu item is rendered IF it has the property ['options']['alter'] = TRUE.

You can set this property to menu items using hook_menu_link_alter.

Example code would be:

function MY_MODULE_menu_link_alter(&$item) {
    // add in an if statement here to just target the links you want to change on the fly
    $item['options']['alter'] = TRUE;
}

function MY_MODULE_translated_menu_link_alter(&$item, $map) {
    if($item['mlid']==89) {
        // this line is actually to change the link however if you inspect the $item
        // variable then you will be able to see the other property that you can change.
        $item['link_path'] .= 'my-new-path';
    }
}


List returned by drush site-alias is correct, but drush @sites finds an incorrect list I'm using drush 7.x-4.5, Drupal 7.28, Apache 2.2.21, PHP 5.3.8. I have a multi-site installation, with a dozen or so sites, such as:

/path/to/drupal/sites/example1.com
/path/to/drupal/sites/example2.com
/path/to/drupal/sites/example3.com

Each of these is a symlink to some other location, which is not entirely uniform, e.g.:

example1.com -> /home/example1/drupal

...but another site might be:

example2.com -> /home/example2/www

If I run drush -r /path/to/drupal site-alias, I get a correct list of sites:

example1.com
example2.com
example3.com

However, if I then try to do something like drush -r /path/to-drupal @sites status, I get something unusable:

You are about to execute 'status' on all of the following targets:
  #drupal
  #www
  ...

So I can see it's just resolving the symlink and grabbing the last component of the path, then flattening that down to a set of unique last components of paths, which of course does not work at all.

I have tried filling out aliases with /etc/drush/aliases.drushrc.php, and while the aliases work in the single-site context (e.g. with $aliases['e1'] = array('root' => '/path/to/drupal', uri => 'example1.com'), the command drush /path/to/drupal@e1 status). The list that the @sites comes up with is unaffected.

Have I just set up this multi-site installation in an unusual way? It seems to otherwise be fine.

For what it's worth, I have a parallel Drupal 6 multi-site installation, and it has essentially the same problem.

The drush maintainers avoid multisite, so there is a possibility that some bugs might exist here.  The version of Drush that you are using is very old, though; upgrading to Drush 6 would be advisable.  @sites might even work for you then, as some work has been done for multisites and symlinks since Drush 4.

The best thing to do, however, would probably be to make an alias group.  Make a file called /etc/drush/groupname.aliases.drushrc.php, and define aliases 'e1', etc. as you show above, one for each of your multisites, all in the same alias file.  Then, simply:

drush @e1 status - show status on just one site

drush @groupname status - show status on all sites defined in the aliases file 'groupname'


Contextual filter that lists users who share a taxonomy term with current user? I have a view that lists all user profiles. At registration, every user selects, from a 'sector' taxonomy, the sector they themselves do business in. They also select from the same 'sector' taxonomy to record what sectors they want to do business with. So their user profiles may look like this:

uid: 1
name: fred
sector in: arts
sectors to do business with: tech

uid: 2
name: alex
sector in: tech
sectors to do business with: design

I want a view to list all the users that do business in the sectors that the current user wants to do business in.

So, using the above profiles, if Fred was looking at the view, Alex's profile would be displayed because the filter would be:

sector == tech

Obviously, the filter needs to be dynamic. It needs to grab the 'sectors to do business with' field from Fred's user profile. I think I need a contextual filter, but how do I configure it?

Thanks

Provided you have two fields on your user profile called field_working_in and field_want_to_work_with execute the following steps:

Add a Users view at admin/structure/views/add and set Display Format as Table
Add two fields User: Name and User: Working in
Add relationship with  User: Working in
Add relationship with Taxonomy term: User using Want to work with
Add a contextual filter: User: uid with Provide Default Value and Type: User ID form logged in User and set a relationship with field_want_to_work_with (see screenshot)
Under FILTER CRITERIA Add the following filter to exclude the current user from the results: User: Current (No)

Export of view:

$view = new view();
$view->name = 'user_sections';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'User sections';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'User sections';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: User: Working in (field_working_in) */
$handler->display->display_options['relationships']['field_working_in_tid']['id'] = 'field_working_in_tid';
$handler->display->display_options['relationships']['field_working_in_tid']['table'] = 'field_data_field_working_in';
$handler->display->display_options['relationships']['field_working_in_tid']['field'] = 'field_working_in_tid';
/* Relationship: Taxonomy term: User using Want to work with */
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['id'] = 'reverse_field_want_to_work_with_user';
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['field'] = 'reverse_field_want_to_work_with_user';
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['relationship'] = 'field_working_in_tid';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: User: Working in */
$handler->display->display_options['fields']['field_working_in']['id'] = 'field_working_in';
$handler->display->display_options['fields']['field_working_in']['table'] = 'field_data_field_working_in';
$handler->display->display_options['fields']['field_working_in']['field'] = 'field_working_in';
$handler->display->display_options['fields']['field_working_in']['label'] = '';
$handler->display->display_options['fields']['field_working_in']['element_type'] = '0';
$handler->display->display_options['fields']['field_working_in']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_working_in']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['field_working_in']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_working_in']['delta_offset'] = '0';
$handler->display->display_options['fields']['field_working_in']['field_api_classes'] = TRUE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'reverse_field_want_to_work_with_user';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: User: Current */
$handler->display->display_options['filters']['uid_current']['id'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['table'] = 'users';
$handler->display->display_options['filters']['uid_current']['field'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['value'] = '0';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user-sections';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'User sections';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['name'] = 'main-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$translatables['user_sections'] = array(
  t('Master'),
  t('User sections'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('term from field_working_in'),
  t('field_want_to_work_with'),
  t('Name'),
  t('All'),
  t('Page'),
);


How to determine the source (views/modules/blocks, etc) of content in different URLs? I am working on re-designing an existing site for which I need to edit the output of each page (i.e. each URL). Is there a good way to determine where the data is coming from? By "where" I mean, is it a 'View'? or from a module? or combination of blocks?

I have tried devel & theme developer but that only tells me which tpl.php file but not the actual source.

If you are comfortable looking through your database directly, the quickest way to find out where $content is coming from is to look at the menu_router table and reference the path and page_callback fields.  For example, path node is generated (normally) by node_page_default and it creates the default front page.  Looking through this table you can see where all the other paths on your system are referenced.

As for where all the other content comes from, eg, all the blocks in other regions of the page, there you have to look around through the blocks table and look at the various information there, eg, module and delta say which module creates the block and which one it is, region says where on the page it will be put, and pages have any restrictions as to what pages the core block module knows about.


How do I reroute a logged-in user after page access denied at user/login? My Drupal 6 site has the login form at /user/login. If I'm logged in already and I click it, I'm sent to the Access Denied page (though the login URL stays the same).

I'd like to send such users somewhere else. Anywhere else. /user would be fine. Is there anything I can hook into to achieve this?

That sounds like a familiar question ... Here is how I was able to solve it so far (not sure if there are better ways to do so ...):

within /admin/settings/error-reporting I entered a relative URL like no_access
then I created a no_access page, in which I described what might be causing the problem.

For a sample of such no_access page, visit http://www.inpetto.be/no_access (access allowed by anybody ...). Note bullet nr 2 there ...

Makes sense?


I'm unable to select and saveany text filters except for "Filtered HTML". I've tried to edit a field in a few content types to set the filtered text format to something other than filtered html, but after I save, it has no effect. I go back to the content type, and it's back to filtered HMTL. If I select "Plain Text" form the "Text processing" setting, I can pick plain text in the "Text format" dropdown, but otherwise, it always saves back to "Filtered HTML". What am I doing wrong?

As far as I know, this functionality is "broken" in D7, meaning that the UI is at least misleading. Here's some discussion https://drupal.org/node/1003262

What you can do is change the order of text formats at admin/config/content/formats. The default text format available to users will be according to permissions and the order of text formats.

Also see http://drupal.org/project/better_formats. That will give you more options.

Also see How do you set a default input text format per content type?


How to make node edit form meta panel accordions default to closed? When editing a node the meta panel fieldset accordions default to being open if they contain data.
I understand why this has been done, but I think it makes for a very noisy and potentially confusing UI for my editors.
How could I go about making these closed by default?

There are different approaches to change this behaviour. For instance, you could choose between these two at least:

CSS + JS: using a selector like .layout-region-node-secondary (depending on Theme), you could loop using a jQuery $.each() over the different 'details' and, if you find the 'open' property, remove it.

PHP: Using Hook Event Dispatcher, you could attach to the node alter event and upon firing, you could just alter the form accessing the $form / $form_state variables and removing the CSS from the items you'd like to.


Provide access among the users I need a requirement like this. In my site, there will be 2 types of user role.

1) Role A
2) Role B

Role A users can able to create the new users and assign them a Role B. I want to provide the access among the Role A users.

Let say User 1 of Role A created 3 users of Role B and User 2 of Role A created another 2 users of Role B.

I need to provide access to Role A users like the users who have been created by User 1 of Role A cannot be accessible or editable for User 2 of Role A and vice versa.

Is there any custom module to achieve this or we need to go for custom implementation?

I don't follow exactly what you're asking, but if you want to give lower level users the ability to assign roles without needing the 'administer permissions' permission or other high level permissions, you can add the module RoleAssign.

  RoleAssign specifically allows site administrators to further delegate
  the task of managing user's roles while withholding the Administer
  permissions permission.

  RoleAssign introduces a new permission called Assign roles. Users with
  this permission are able to assign selected roles to still other
  users. Only users with the Administer permissions permission may
  select which roles are available for assignment through this module.

  RoleAssign is ideal for smaller sites with a system administrator and
  one assistant administrator role that should be reasonably restricted
  in what it allows. For larger sites with multiple levels of
  administrators or whenever you need finer-grained control over which
  role can assign which other role, check out Role Delegation.


hook_entity_presave() doesn't work I want to save some details before saving the node, and I tried with hook_node_presave().

function hook_node_presave(Drupal Core Entity EntityInterface $node) {
  if ($node->id() && $node->moderate) {
    // Reset votes when node is updated:
    $node->score = 0;
    $node->users = '';
    $node->votes = 0;
  }
}

Then with hook_entity_presave().

function hook_entity_presave(Drupal Core Entity EntityInterface $entity) {
  $entity->changed = REQUEST_TIME;
}

Both hooks don't work. Why?

Your function should be named according to your module's name. If your module is called "foo", then:

function foo_node_presave(Drupal\Core\Entity\EntityInterface $node) {

Note also the use of backslashes, not spaces, to separate namespaces.


Custom Save and Unpublished button for node While clicking Save as draft button, it will save the node but while it have to redirect to the created node it gives error The website encountered an unexpected error. Please try again later. and $entity->setPublished(FALSE); is also not working.

function MYMODULE_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['actions']['submit_unpublish'] = array(
    '#type' => 'submit',
    '#weight' => '-10',
    '#value' => t('Save as draft'),
    '#submit' => array_merge($form['actions']['submit']['#submit'],
    ['MYMODULE_draft_submit_callback']),
  );
}

function MYMODULE_draft_submit_callback(array &$form, FormStateInterface &$form_state) {
    $entity = $form_state->getFormObject()->getEntity();
    $entity->set('moderation_state', 'submitted');
    $entity->setPublished(FALSE);
    $entity->save();
}

You can't use

 $entity->set('moderation_state', 'submitted');

if you don't have Content Moderation core module enabled

Also make sure you declare the usage of FormStateInterface somewhere in your .module file

use Drupal\Core\Form\FormStateInterface;

Also look in your error logs found in admin/reports/dblog for other possible errors


Attaching comments to blog post promoted to front page I have 'blog posts' that are promoted to the front page. We would like to have the ability to have users posts comments on these posts through the front page without having to click through to get to the posts page.

The reason you do not see comment form on content promoted to front page is because by default comment form shows on full node view.So following code may help you.

function mymodulename_node_view($node, $view_mode, $langcode) {
  if(drupal_is_front_page() && $node->type == "your_content_type") {
      $node->content['comments'] = comment_node_page_additions($node);
  }
}


Will Lime the future test suite? Now that Drupal 8 is going to be based mostly on Symfony, is the TDD / unit testing going to change too?

For Symfony, Lime is the preferred testing suite. Is that true for Drupal 8 too?

Not sure about Lime, but Drupal 8 is set to use PHPUnit. See Deploy a PHPUnit system with a bottom-up approach.

  Deploy a PHPUnit system with a bottom-up approach

  Issue Summary

  Replace the SimpleTest framework with PHPUnit.

  Problem/Motivations

  The SimpleTest framework no longer has the same level of maintenance than the PHP Unit framework. PHPUnit has become the standard; most frameworks use it (ZF1 & 2, Cake, Symfony2, ...) and is actively maintained, sable and works great for every codebase, scenario.

  Replacing the testing framework with PHPUnit will allow better consistency in the drupal 8 codebase, by aligning ourselves with Symfony2 testing tools. Moreover, it integrates better with IDE (NetBeans, Eclipse, IntelliJ IDEA), Continuous Integration servers such as Jenkins/Hudson, and with Sonar for static code analysis as well. It has also code coverage which is a huge +.

EDIT

Following the comment from chx below about me posting the wrong issue, I'm pretty sure that this is the issue that noted the progress of PHPUnit: Start using PHPUnit for unit tests


Add language menu to the main menu I have menu structure like this:

Home | About | Products

if a user is currently on English page then I need like this:

Home | About | Products | Swedish

and if a user is currently on Swedish language then it will show like:

Home | About | Products | English

1: So how can I add a menu switcher link to the main menu which shows only one language link at a time?
2: What will be the pate for each of the language in the path field while adding a menu link.

You have two ways of doing this, one is to use HTML/CSS to position the language switcher block in the menu, probably a little harder to do with a variable length menu unless you right align it.

Two would be to add the language switcher to the menu, you can use something like http://www.liquidcms.ca/how-to-language-switcher-menu-item to do that.


How to override the core function format_xml_elements()? format_xml_elements() is defined in the core includes/common.inc file. I want to manipulate some parts of this code, but there is no way to hook into this.

How could I achieve this without hacking core?

You cannot directly make Drupal use a different function instead of format_xml_elements(), but you can replace those functions that (directly or not) calls format_xml_elements().
For example, to alter how the RSS page for a feed is printed, you just need to replace theme_aggregator_page_rss() with a function implemented from your module using hook_theme_registry_alter(); to alter the output for the 'blog/%user/feed, or the blog/feed, or the taxonomy/term/%taxonomy_term/feed, you implement hook_menu_alter() to replace the page callback Drupal uses with your own page callback.

What changes is the code you need to write in each case.
For example, taxonomy_term_feed(), the page callback for taxonomy/term/%taxonomy_term/feed, calls node_feed(), which calls format_rss_item(), which calls format_xml_elements(). In this case, you can use the same code taxonomy_term_feed() uses, except it calls another function (e.g. mymodule_node_fee()) instead of node_feed(), which has the same code, except it doesn't call format_rss_item() nor format_rss_channel(), but your own functions. For the latter two functions, you can use the same code they use, except your code will code your replacement for format_xml_elements() instead of format_xml_elements().

In the case of replacing theme_aggregator_page_rss(), you write less code.


sql:sync not working I'm using drush 9 on a remote server and I'm trying to perform a sql:sync.

This is my alias:

live:
  host: www.mysite.com
  paths:
    drush-script: '/home/wodby/drush-wrapper.sh'
    files: files
  root: /var/www/html/web
  ssh:
    options: '-p 9191 -o "AddressFamily inet" -o "StrictHostKeyChecking=no"'
  uri: www.mysite.com
  user: wodby

The "drush-wrapper" is a script (on remote server I've docker, so  I use ssh to connect into the container. The wrapper is this:

export PATH=$PATH:/usr/local/bin
/home/wodby/.composer/vendor/drush/drush/drush.php $@

This alias works (for commands like drush cr or cim) but doesn't work the sql:sync command.

If I try to run drush sql:sync @d8.live @self I obtain:

 Error: no database record could be found for source @d8.live

How should I add this configuration about database?

I just had a similar issue and found out I needed to edit the database login-information on my remote site as it had the local site's info in it since that's where the files came from.

Maybe that's the case on your site too?

In short: Check that the remote site's settings.php-file has the database information from the remote site and not the local site.


Make a Views form collapsible I have a search form in my header. Instead of using the core search, I used a custom block that takes the search string and passes it to the Advanced Search page, built in Views, where users can further filter their results. That's working.

What I want to do is have the form fields collapsed by default, with some text that says "Filter Results" that when you click it expands to show the fields.

How do I do this?

Just use some JavaScript to hide the div, similar to the following code:

jQuery(document).ready(function() {
  $('.view-filters').click(function() {
    $(this).next().toggle('slow');
    return false;
  }).next().hide();
});


Issues with file upload fields I'm working on a site where someone did a lot of security updates. After reviewing the site, we found a bug. When you try creating a node with a file upload, when you click the save button, instead of saving it actually downloads the file to your computer. I'm not really sure where to start looking for this issue.

Has anyone had this issue before?

I found the issue. I found this stuck in the node template:

<?php if (!empty($node->field_white_paper_file['und'][0])){
  drupal_goto(file_create_url($node->field_white_paper_file['und'][0]['uri']));
 }?>


Anonymous users can't access to image style field Entity

Type : block
Field : 'Reference to entity : image style' (field_image_style)
Manage display : I display the Entity ID

Twig

In my twig template, I get the field_image_style data from content.field_image_style.

Issue

Works great on admin user, but not when browsing the website as an anonymous user.

This is not a image style generation error, or a wrong permission to files folders : you can access to both original image and generated styled image on anonymous.

And this is where it gets weird. It's working when you give the "Administer image styles" permission to anonymous users.

Dump

Just to show you what result I have, here's a dump of content.field_image_style with an admin user :

And with an anonymous user :

The purpose of a field configured in a view mode is to render the output.

To process field values in code use the entity object. You'll find this in a block template in this variable:

$variables['elements']['content']['#block_content']

So in TWIG you can try to access the field value like this:

{%
  set style = elements.content['#block_content'].field_image_style.target_id
%}


Cloning the Base theme bartik, seven, and stark in Drupal 8 I tried copying the seven theme from /core/theme into my own /theme folder. I renamed all the files that starts with seven to sevenx and also renamed the seven_ functions to sevenx_ and it still not showing up on the theme pages.

What else do I need to change to make drupal 8 see this new cloned theme?
Is there a quick tool to get this done without having me to rename everything?

A few things that could have been missed -

Cache clear,
Changing the name of the theme in .info.yml of the new theme,
Not putting the base theme in the .info.yml.

If none of those work, this is a pretty good guide. https://www.drupal.org/theme-guide/8/creating-a-sub-theme


How to add a table to a Webform or EntityForm I am using a Drupal 7, and I want to have a customized form which includes:

Simple questionnaire with textfield, checkboxes and dropdown lists.
(I am able to configure this part of the form)
The same form includes a table with multiple rows and columns where users can enter their data. I am not able to configure this.

I tried webform module + webform table module, but I am not getting the expected result. Then I tried entityform module(a better module than webform) but I am not able to configure a table.

Please suggest me a way to include a dynamic table in my customized form through entityform module or any other module.

A combination of EntityForms and TableField should get you going.

  This module allows you to attach tabular data to a node in Drupal 6 or
  any entity in Drupal 7.


How to add a display format for the field I have a field of list type in my custom content type. The display format of list type field has two options default(value) and key.  In my case i want third option which will display "key and value". How can i add third option or get the key/value for the field.

Here is an example on how to create custom field formatters

https://github.com/npinos/drupal8-field-formatters

You can directly specify the markup like this extending the FormatterBase class:

<?php
/**
 * @file
 * Contains Drupal\drupal8_field_formatters\Plugin\Field\FieldFormatter\MainHeadingFormatter.
 */
namespace Drupal\drupal8_field_formatters\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
/**
 * Plugin implementation of the 'main_heading_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "main_heading_formatter",
 *   label = @Translation("Heading 1"),
 *   weight = "10",
 *   field_types = {
 *     "string",
 *     "text",
 *   },
 *   quickedit = {
 *     "editor" = "plain_text"
 *   }
 * )
 */
class MainHeadingFormatter extends FormatterBase {
  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];
    foreach ($items as $delta => $item) {
      // Render each element as markup.
      $element[$delta] = [
        '#type' => 'markup',
        '#markup' => '<h1>' . $item->value . '</h1>',
      ];
    }
    return $element;
  }
}


Add a new role using the Drupal Services Rest api I'm trying to create a new role using the drupal services module. I am able to update a user with an already created role but can't find a way to add a new role. I'd rather not build a custom service for this so wondering if anyone knows of a way to do this without resorting to that.

First of All you could create the custom resource in a custom module and enable it, for doing that follow that tutorial

Second in the callback function use that code to create a new role

$role = new stdClass();
$role->name = 'editor';
// $role->weight = 10;
user_role_save($role);

Let the role name be an argument taken from the request.


How to use Rules with Profile2 I want to send an email to the site admin whenever a user changes any of their Profile fields.

The tokens Rules offers are Updated Profile and Unchanged Entity, however I can't seem to figure out how to show ONLY changed items.

When I use any of the Updated tokens it merely just outputs what is there, which isn't much use in this case.

Can anybody help?

You may have to create a custom rule if the profile2 fields are not available individually.

This guide is a good example on how to make a custom events, conditions, and actions for rules.

If you have any questions about the guide feel free to ask.


Share one User Table with two Drupal Sites I have a drupal site which has thousands registered users. (I also added fields like age,dob country etc at /admin/config/people/accounts/fields)

I have another site which is hosted at the same hosting with different database.

Is there a way that i can use first site USERS table in the second site ?
(user registration, forget password and login etc will be connected to first site)

Any clue?

thanks

I believe this module does what you need Domain Access


How to rebuild a cached page when it expires? I'm using views caching after reading this great Q&A and getting good results. I have to keep the expiration short because I'm showing the "last comment" in the view and those changes often.

I'm thinking about using views content cache to expire the cache every time a comment is added. Or cache actions to do it with rules.

What I would like to do is rebuild the cache immediately after it expires? I read that boost module offers that but I need a solution for authenticated visitors (already use Varnish for anonymous).

The cache graceful module seems to offer that but only has 20 installs (plus requires a couple of other modules).

Are there any other solutions that allow expiring a cache and "warming" it up right away?

If you know what functions need to run in order to warm a cache, checkout httprl. httprl_queue_background_callback() is the function to look into using. Simple example of calling watchdog in the background http://drupalcode.org/project/httprl.git/blob/24a88acd2180191d0b54696e577f14615e37302d:/README.txt#l268

In terms of graceful varnish cache clears this has a good example: https://www.varnish-cache.org/trac/wiki/VCLExampleGrace Example of it in use: http://groups.drupal.org/node/63203


How to restore $form_state when rebuilding a form after a redirect We have a site where either authenticated or unauthenticated users can submit a form. When the form is validated, we check whether they are logged-in, and if not, we redirect them to authenticate, with a destination parameter of the original page. At this point, we cache the $form and $form_state in $_SESSION.

After authentication and redirection the form is redisplayed on the page (by retrieving the $form from $_SESSION) and ask them to confirm the submit.
Note the form is dynamically-generated which is why we have to store it.

What I can't seem to do on redisplay is set the form values to the choices that the user previously made, even though these are stored in the cached $form_state. What is the best way to do this?

I got this working in the end. The solution was:

$form_array = drupal_retrieve_form($cached_form, $cached_form_state);
$form = $form_array['#form_id'];
$block['content'] = drupal_render($form);

where $cached_form and $cached_form_state were the $form and $form_state values that had been stored in $_SESSION. Note that '#form_id' is a literal string, I've no idea why drupal_retrieve_form returns an array with that string as a key.

This redisplayed the form in the block after the authentication challenge, with the user's pre-challenge selections populated into the form elements. I couldn't get it to work with either drupal_get_form() or drupal_build_form().


Why does drupal create revision table? From database design perspective, Why does Drupal even create these tables? They are so much alike. There are modules & methods for getting rid of these tables, But why are they there?

MariaDB [park]> describe field_data_body;
+--------------+------------------+------+-----+---------+-------+
| Field        | Type             | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| entity_type  | varchar(128)     | NO   | PRI |         |       |
| bundle       | varchar(128)     | NO   | MUL |         |       |
| deleted      | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id    | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id  | int(10) unsigned | YES  | MUL | NULL    |       |  ONLY DIFFERENT ONE
| language     | varchar(32)      | NO   | PRI |         |       |
| delta        | int(10) unsigned | NO   | PRI | NULL    |       |
| body_value   | longtext         | YES  |     | NULL    |       |
| body_summary | longtext         | YES  |     | NULL    |       |
| body_format  | varchar(255)     | YES  | MUL | NULL    |       |
+--------------+------------------+------+-----+---------+-------+
10 rows in set (0.00 sec)

MariaDB [park]> describe field_revision_body;
+--------------+------------------+------+-----+---------+-------+
| Field        | Type             | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| entity_type  | varchar(128)     | NO   | PRI |         |       |
| bundle       | varchar(128)     | NO   | MUL |         |       |
| deleted      | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id    | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id  | int(10) unsigned | NO   | PRI | NULL    |       |  ONLY DIFFERENT ONE
| language     | varchar(32)      | NO   | PRI |         |       |
| delta        | int(10) unsigned | NO   | PRI | NULL    |       |
| body_value   | longtext         | YES  |     | NULL    |       |
| body_summary | longtext         | YES  |     | NULL    |       |
| body_format  | varchar(255)     | YES  | MUL | NULL    |       |
+--------------+------------------+------+-----+---------+-------+
10 rows in set (0.00 sec)

MariaDB [park]>

The revision table has been set up to track the revisions of a node.  Like Triskelion noted, there already is a thread up on D.O. Furthermore the reason the table is populated is for denormalization purposes, per The aforementioned issue.  Inevitably. this has some drawbacks.  The first of which is bloat.  Write speed is also affected, especially under a load.  The community has seemed to coalesce around using contrib to deal with this issue e.g. Field SQL norevisions.  At some point it would be nice to have this in core, but a rock solid contrib module is the next best thing.


CSS edit rules page does not open I logged in as admin. I opened the css configuration page. I clicked edit rules page. After that, css edit rules page should open but my site is stuck at screen 2(home page). After I click edit rules many times, sometimes, I get the edit rules page. I feel that this is a site wide issue not css injector issue.

Example: If I click Save on views page, it does save but my page gets stuck at the home page. I have to hit the back button to come back to view and I see that views is already saved.

If I click clear cache in performance page, I have similar issue. It does clear the cache but the site is stuck at home page. I hit back button to come back to performance page again.

I simply do not know where to start troubleshooting. I am not getting any error messages. If you could point me to right direction to solve this issue, it would be very helpful.

enter image description here

Screen2:

Turned off overlay module. Problem has fixed.


Custom Filter in Views using Drupal 7 i have a content type having two major fields.

A  and B

Now i want to get all resutls of those nodes .

if A having value of 1 or B having value of 2.

if anyof node matched with one field i need to show result.

How to do this in views ?

Thanks.

You can follow this using below step:

Go to Administration -> Structure -> Views
Edit your existing view or create new new.
Add Filter 'A' and B in your view
Click on "Rearrange" filter icon in Filter section
Click on "Create new filter group" and move filter "A" and "B" in new filter group.
Select Operator as "Or" in new filter group and save the form.


Count the number of views How can I count the number of views for a video? I am using the Profile2 module to display user's information.

Users add videos which any user can see. I would like to count the number of video's views, and use that number to sort the result shown by the Views module. Is it possible?

I believe the reason there is not common "Out of the box" solution for this, is that the statistics module has a long-standing reputation of ruining performance, as it performs a lot of database writes.

While it could certainly be "upgraded" to being entity agnostic, I guess there's little interest in doing so.

The most common solution then, I think is to use a tool like Google analytics for counting impressions, and exposing your video (or other entity) in ways/with urls that make their views easily countable in your tool of choice.

For Views integration, the easiest options seems to be Google analytics statistics, (Thanks Chapabu), but other interesting modules could also be GA counter, GA reports and GA importer


How can I find specific block name in structure->blocks in drupal-7? I can see specific block in the home page. I need to show this block in specific roles. How I can find this block in the list of blocks in structure->blocks?

You could enable the contextual links module and hover over the block and click the small gear icon to edit the block.
you could figure out what region the block is in using firebug or similar which will narrow it down in the block administration page assuming the block is set that way.

If the block is still not visible, the specific user/role may not have the permissions to see whatever content you are trying to view.  Check the permissions for the role at /admin/people/permissions