Is it possible to notify users by e-mail when receiving a private message except when a specific user sends a message? I also opened a thread on this on Drupal.org but since it's been awhile I thought I'd try asking here.

Use Case: In general, I want users to receive notifications for new private messages.  I can do this using the included submodule for e-mailing private messages.

So that the private message inbox has a message when users log in for the first time, I used the Rules module to automatically send a "welcome" private message upon registration on behalf of an administrator account. However, this triggers the "send e-mail on private message" behavior.  Since users already are receiving a "please validate your e-mail address" e-mail, I don't want them to receive a second e-mail notifying them that they have received the "Welcome" private message.

Is there a way to prevent messages from certain users (or, alternately, certain messages) from triggering the e-mail notification?

I also looked into implementing this using rules instead of the included submodule but this would mean I couldn't use the functionality for reducing the number of notifications (currently, I have it set to not send additional e-mails if the user has yet to log in and read the first e-mail in a thread from a given user).

Note: this is answer for Drupal 7.

As Letharion said, you can use hook_mail_alter() but you should detect somehow is this a welcome message from admin or not.
I suggest Context module for this task, but you really can just compare a subject of message in this hook.

Update

  First I suggested to use Context module, but it is no so simple to set context in Rules. If you are interested in that way, you can see history of an answer.
  Current code is using information about Author id and subject of message:

/**
 * Implements hook_mail_alter().
 */
function YOURMODULE_mail_alter(&$message) {
  $WELCOME_USER_ID = 1; // PM author from your rule
  $WELCOME_SUBJECT = 'Welcome to the site'; // PM subject from your rule
  // 'pm_email_notify_notice' is an ID for message notifications
  // from Privatemsg Email Notification module
  if($message['id'] == 'pm_email_notify_notice') {
    $privatemsg = $message['params']['message'];
    if ($privatemsg->author->uid == $WELCOME_USER_ID && $privatemsg->subject == $WELCOME_SUBJECT) {
    // If special context is set it means that we don't want to send an email
    //if(context_isset('context', 'my_privatemsg_stop_email')) {
      // Stop email
      $message['send'] = FALSE;
    }
  }
}


Breadcrumbs for a view page with arguments How do I set the breadcrumbs for a view page with arguments? I've used the "User: username" argument, and the following PHP Code as default argument, but it doesn't work:

$breadcrumb[] = l('Home', NULL);
$breadcrumb[] .= l('Our Team', 'team');
drupal_set_breadcrumb($breadcrumb);

I believe when you are creating a view that has an argument you can the opportunity to set a breadcrumb from within views itself.

Substitutions will also be available based on the arguments present.

For example, if you view is

/blogs/2011

Where blogs is the path to the page, and 2011 is the argument, you could set the breadcrumb of the page with the argument to be:

%1

This would leave breadcrumbs that would look like:

Blogs > 2011


Disable an parent link for dropdown menu but keep css i have this menu : http://jsfiddle.net/aL7Xe/1000/

And I disabled the href link "bewerken" with

a[href="/test4/disabled"] {
  pointer-events: none;
}

But now my css does not show on that link, does anyone have any idea on how I can keep my css on that link but still have it disabled ?

Adding

  e.preventDefault();

under

 $('.topmenu').click(function(e){

will disable link redirection.


How to create an Enquiry form with ability to submit a collection of enquiries I am building a new site which has a large selection of different products/services on offer, the information for each is shown in  it's own node.
If the user has interest in a number of these services then I would like to give them the ability to 'add' the item to their enquiry along with a message. When they have added all of the items they are interested in they can then submit the enquiry.
Overall, the process shares similarities with an e-commerce workflow

View product
Add product to enquiry form builder with comment  (choose options and add to cart)
Browse other products and repeat steps 1&2.
Once happy, review enquiry (checkout)
If all is ok, submit enquiry (process order)

Using Drupal 7, how would you suggest I tackle this?
I only compared the process to e-commerce as it helped me think things through, the site isn't actually going to be selling the products. Strictly a tool to submit a detailed enquiry.

Switch to Entityform. This uses the core field APIs. Add an entity reference field on your products and services types. Details from the project page:

The Entityform module enables you to create front-end forms (fieldable entities), which contain fields that you define! These forms use the standard Drupal fields. This means that out of the box, you can use any standard Drupal node field! As of the time this article was written, there were over three hundred "field" modules. And since Entityforms are "Drupal entities", you will automatically be able to use future "field" modules!
The forms can be used to create custom surveys, petition, and personalized contact forms, and other customized form. (For those of you who have used Webforms, this module brings Webform's functionality into the "standard" Drupal field / entity world.)
As with everything in Drupal, there are Pros and Cons to using Entityform. All though Entityform is a powerful tool, it is not always the best solution. The article When to Use Entityform discusses the advantages and disadvantages that Entityform may have over other methods of creating user "submittable" forms. Do not use Entityform for forms that will contain 150+ form elements

Entity form works well with other modules like Rules so you can get really custom with your behaviours.


Views: Multiple Rows & Mutliple Columns I've been twisting and turning the View module but can't get simple tasks done. Well it should be simple but yet Drupal don't have a good solution ...yet.

How to create 2 columns where column A have an image that spans from top to bottom and column B have 3 rows?

I am afraid you will have to write custom code in this situation to get this done.
What you can do here is create tpl file for your view with format as table and then in that tpl you can have your condition to make a table inside td.

You can fetch your views fields in tpl inside foreach ($row as $field => $content)

Make sure you have all the fields in your view which you want to display in table format.


How do I write to location field in an Entity? I am having a custom entity called Micronews which has a bundle microupdate created in it. I am able to write entity to db for all fields but I am not able to figure out how to write location (using location module). It seems to be stored in db in multiple tables. Is there any standard way to store location to db?

function p_save_entity($name, $issue_type, $constituency, $location){

$name = "Testing programmatically";
$issue_type = "electricity";
$constituency = '22';

$e = entity_create('micronews', array(
    'type' => 'microupdate',
    'name'=>$name,
    'created'=> time(),

));

$ew = entity_metadata_wrapper('micronews' ,$e);

$ew->field_type->set($issue_type);
$ew->field_constituency->set($constituency);

$ew->field_location[latitude]->set('65.000000');
$ew->field_location[longitude]->set('65.000000');

$fl = $ew->save();

if ($fl){
    return "";
}

else{
    return "Something went wrong";
}

I am using this module.

This works, but (here's the trick), only if you enable the location_entity module, which ships with location.

$location = array(
  'latitude' => $latitude,
  'street'   => $street,
  // etc, other elements added here ...
);

$ew->field_location->set($location);
$ew->save();

May no one else lose as much time on this ever again.


Is there an equivalent of view modes for form editing? I have a content type with a lot of fields. End users need to create content of this type, so I want to provide them with a simplified form so that they can create a content item and edit it without knowing about the majority of the options. Then those who want to dive into the complexity could have an advanced form which exposes them.

View modes looked like the kind of thing I'm trying to do, so I used hook_entity_info_alter to create a custom view mode and started trying to figure out how to control the view mode used by node/add/my-content-type. After digging into the code I've realised that view modes are used by node_view and that adding or editing a content item uses drupal_get_form instead.

Is there some "form mode" which allows different field type and grouping configuration for different "views" onto a form?

1 - Panels/Page Manager
If you're using Panels and Page Manager (part of Chaos Tools) then you can break up the node/add form by enabling/overriding the node_edit page manager handler and creating a Panels layout to show the individual fields.
Just set a variant to only react on creation of your particular content type, and then arrange the form fields as you wish. This will let you split out any form fields, as well as provide a General form pane that will add any fields that you've missed out.
IMPORTANT NOTE COURTESY OF LETHARION
Something I didn't realise due to the fact that I always put the general form on the page, is that if you DON'T output ALL fields, then "form api will interpret it as "the user deleted the content of those fields" and will send back empty values. This could result in the loss of existing data, so be careful.

2 - Solely Fields/Field contrib
You could also try Field Permissions if the form is permissions based, or use a Field group with some collapsed fieldsets or tabs etc to initially hide the fields if they are not permission based.


Auto translate content of nodes I am developing a Drupal 7 site, where i store the content of a cotent type(with several fields).
So by default, i enter the English text for the content and save it.

Is it possible in Drupal to automatically translate the content in English to other languages like French, Spanish, German, etc? I have been experimenting with several modules like Content Translation, which provide the option to enter content manually in other languages. But i don't like to enter the content separately for each language, rather i like to automatically translate it with the click of a button. Is there such a module or feature in Drupal 7 ?

As a final alternative, i thought to use an API like Google Translator in the background, when saving my node content, but i hope there is a module available for automatic content translation.

Note: I am not interested in using any widget on the front end, for content translation. Instead, i prefer admin to translate content with one click in the backend.

It will never be good. Human languages are not something perfectly unambiguous and logical*, so no computer software will ever be able to translate them perfectly. You need a human to properly translate human languages.

Google Translate is bad, but I haven't seen anything better. Sadly, Translate API got deprecated in 2011. This means that modules using it may work for now, but may stop working without notice. See GTranslate and i18n auto translate.

You can always use some code from above modules, and try another machine translator. See Comparison of machine translation applications article - deciding which one to implement is outside the scope of Drupal Answers, just remember that you want GPL software if you want to mix it with contrib modules' code without fees or legal risk.

* OK, there is Lojban, but that's an exception.


Show translated content in view listing page when accessing translated site I have a view that filters for a specific content type (accommodation) and shows a paginated list for the user.

The site has a second language (Welsh) and a few of the content nodes have Welsh translations.

In theory, I should be able to visit the accommodation view, and if I was on the Welsh site (http://www.example.com/welsh/accommodation) I should see the Welsh nodes listed.

Sadly, this is not the case exactly.

My view is able to filter the Welsh translated nodes, but the view is spitting out the English text (title, URL, description etc) and not the Welsh versions.

This makes it pretty pointless, especially the fact that the URLs are rendered as the 'normal' English URLs and do not point to the Welsh site.

I've tried a tons of various view options but cannot fathom how to render the translated information.

Have you added a filter to the view for the translation language?

You should be able to set one to only show content in the language of the current page (Which should be welsh if your language detection is setup and working correctly)


Drupal site is compromised by backdoor My Drupal site has been compromised.

Although I applied all modules updates and update my Drupal core to 7.35, it is still compromised.

What would the next logical step to take be?

Sorry to hear that. The steps you should take are as follows:

If you have drush access, install drupalgeddon by typing drush dl drupalgeddon.
Run drush drupalgeddon-test. You will likely find several accounts which you did not create. Remove them.
Install hacked to find out which (if any) files have been changed.
Read this article.


How to add a condition for an array on an entity query for a config entity? I want to execute an entity query on a config entity type. However when I want to add an IN condition on a property which is an array I am getting an error.

For example, I want to retrieve all user roles that have the administer nodes permission:

$query = \Drupal::entityTypeManager()->getStorage('user_role')->getQuery();
$query->condition('permissions', ['administer nodes'], 'IN');
$query->execute();

This gives the following error:

PHP Warning:  mb_strtolower() expects parameter 1 to be string, array given in core/lib/Drupal/Core/Config/Entity/Query/Condition.php on line 166

A config entity doesn't use a normalized table structure, so the normal array conditions which use JOIN don't work. Instead do a condition on property.*:

$query = \Drupal::entityTypeManager()->getStorage('user_role')->getQuery();
$query->condition('permissions.*', 'administer nodes');
$query->execute();


How to prevent User Roles from getting reapplied? For whatever reason when I remove a role from a user's profile, at url site/user/user-id/edit it just comes back a few days later. I tried to check users_role table but I do not have that table.

.

We do import every employee every night, based off Active Directory, but I do not touch their roles in the import.

I imagine the best way of solving this is finding the table that has every user's roles, then just removing that entry from the particular user.

Try to run this: show tables like '%role%'; MySQL statement. In the results returned you should see a users_roles table (not users_role). To that table's columns are stored the uid and rid, therefore you will be able to find all users that have assigned with a role or more, and possibly an answer to your question.

I would kindly suggest you, since those roles are appeared again and again, to search any by chance or forgotten user_save implementation within your code.

Hope this help!


How to make the content fills the space after the sidebar ends in a drupal site? The client I work for won't accept the fact that the sidebar region continues until the footer. If that happens, the client wants the sidebar to stop when the sidebar content is finished, and the main content should fill the space that the sidebar is using now.

How to make the content fill the space after the sidebar ends in a Drupal site?

This really boils down to what theme your using, and how your content is laid out. But it should be doable with CSS if your theme is laid out correctly. Let's take Bartik for example (one of Drupal's default themes). Simply changing the sidebar-first class to float left and changing the float of the content to none will give you something like this:

And here's a really basic version the same idea running on JSfiddle.

The basic answer of it is, yes, it can be done, but you need to do it through the theme and css. Depending on where blocks are placed, the css already in place on your theme, how you go about doing it might change, but the answer is you need to use css.


How to show related nodes in a view block based on taxonomy terms? I have two Content Type, Apartments and Events.
Both have a Term reference field (field_location).

I want make a view block that displays in the nodes of Apartments Content Type some fields of Events Content Type based on field_location term.
If in Apartments the field_location is Rome the block must display only the field of the nodes Events with field_location Rome.

How I can do it?

Thank you in advance.

  SOLVED

SOLVED

Add a Contextual Filter->Has Taxonomy Term ID
When the filter value is NOT available:

Provide default value Type: Taxonomy term ID from URL
Check only: Load default filter from node page, that's good for related taxonomy blocks; Limit terms by vocabulary; Vocabulary: my-vocabulary; Filter to items that share my term.

When the filter value IS available or default is provided:
Check only: Reduce duplicates.


How to add another navigation bar/block at the top of your site? I want to add a custom header/navigation block at the very top of my page like so, it's essentially a menu item. For example, it has two items:
Home and Business. Once clicked it stays highlighted and menu items below it change.

The default is Home, and it has its own header and page underneath.
If a user clicks 'Business', it will load another page with a different header/menu items.

I am wondering: How would I do this in drupal? Would I do it all in the navigation block? Would customization be required and where exactly?
Any advice on how I can approach this best?

For example,
These two menu items will be the top parents of every page.

Home
|
|___menu item/page 1
|   |
|   |__Another page, etc
|___menu item 2/page 2
|___menu item 3/page 3

Business
|
|___a different menu item/page 1
|___a different menu item/page 2
|___a different menu item/page 3

The layered navigation that you're asking about (where you always see primary menu items, but the secondary items are related to a particular primary item and they only show when their parent is active) is called Primary and Secondary menu in Drupal.

Drupal 7 Menu settings Primary and Secondary navigation

In Drupal 7 and older there was a Menu setting where you could choose which menu to use as Primary and Secondary level of navigation:

You could use separate Menus for Primary and Secondary levels, but it makes more sense to create one Menu with two or more levels (depths):

Then you would choose the same Menu under both Menu settings and Drupal would automatically only use the first level for Main links and lower levels for the Secondary links.

When you have that set up, and if you have the Main and Secondary links available and enabled in your theme:

you will see the Secondary items related to the parent item when you visit the parent page. Secondary items will appear in the place where the theme predicted it. In Bartik it's at the top right corner of the Header:

Check out this question: How can I make my menu children display horizontally below my main menu?

Drupal 8 Menu blocks configuration

Drupal 8 made changes to this system: Global menus (primary links, secondary links) have been converted into blocks.

This means that in Drupal 8 you still create a Menu with more than one level for your navigation, but the theme won't have a setting to display them or not (under Appearance). Instead, you will go straight to Blocks and place two of the same Main navigation blocks in regions of your choice. You can even include it twice in the same region which can be useful in your case where you want them one below the other.

Then configure each Menu block differently. The first one should always be visible and only show one level (image from D8 Docs: Menu Configuration):

The second one should only show when the parent from first level becomes active:

Although there are no theme settings anymore to turn on special areas that are styled specially as primary and secondary links, themes can still provide this through special regions. Bartik in Drupal 8 has regions called Primary menu and Secondary menu that look very similar to what they looked like in Drupal 7:

If you're creating your own custom theme you might want to create a special region for the two menus that would be displayed on top of the page.


Drush command can't find Drupal module function I created sample command in Drush.

I put it to sites/all/drush.

I am on my site root and calling this command works ok. But when I try to call any Drupal function in drush_MY_COMMAND function I am getting:

  Error: Call to undefined function

Could someone give me any hint how to solve this issue?

It sounds like your site is not being selected.  Try calling your command with your cwd in the same folder as your settings.php file (e.g. cd sites/default); that should work.  You may also create an alias for your site, and call your command from any directory via drush @site mycommand


Is Google causing problems? I have been getting the following notice from Google's IP address:

  Unable to generate the derived image located at public://styles/large/public/field/image/imagefield_b9xgKB.jpg

Why does it happens? It started a week ago, and now it happens few times in a day. Sometimes the filename varies.

This is an error saying you have a link to an non-existing resource.

You should use Webmaster Tools to dig deeper, if I remember correctly, it should provide the URL for the page with the bad link.


Translating "Content: Link" in a Drupal 7 View I am working on my first Drupal 7 site that has internationalization. My site is in both English and Spanish. Generally I am pretty happy with the way it's going so far. The basis of my translation is using the Entity Translation Module and it works great, Views are translated seamlessly.

However, I have run into a snag, When I create a View and add "Content: Link" as a field, essentially a "read more..." link to the node, I am finding no way to translate the "Read more..." text that I enter into the "Text to display" textbox. My guess is because it's not actual content in the node that's been translated. I've looked around here, on drupal.org and my google-foo is failing me too. Just looking for some suggestions on how to do this.

I won't didn't put this as an answer as it may not be exactly what you want, the Translation Table module will let you set translations for arbitrary strings in the system.

Since Views is almost definitely going to pass the 'Read more...' string through the t() function that module will make your translation work for as many languages as you like across the site


How to create user profile theme hook suggestion for custom template? I'm using the Chaos tools display suite module to create a 'mini_teaser' view mode for my user profiles, but I can't seem to get drupal to read a custom template 'user-profile__mini_teaser.tpl.php' in my theme folder. In my user preprocess function, I'm adding theme suggestions, but they don't seem to work. Any ideas?

It's hard to tell without seeing your code but off the top of my head your preprocess function should look something like this:

function MYTHEME_preprocess_user_profile(&$vars) {
  if ($vars['view_mode'] == 'mini_teaser') {
    $vars['theme_hook_suggestions'][] = 'user_profile__mini_teaser';
  }
}

Or a more generic solution:

function MYTHEME_preprocess_user_profile(&$vars) {
  $vars['theme_hook_suggestions'][] = 'user_profile__' . $vars['view_mode'];
}


Globally rewrite broken image links in node bodies I'm migrating my site from Drupal 6 to Drupal 7, and while most of it just worked after migration, the change from the Image module to the core image handling left a large number of broken images on the site.

Images that were inserted in the node body were not handled at all by the migration, and the links are now in an invalid format. Fortunately, fixing those links is pretty straightforward, I just need to change

http://mysite.com/sites/default/files/images/[image-name].[style].jpg

to

http://mysite.com/sites/default/files/styles/[style]/public/images/[image-name].jpg

This looks like it should be relatively straightforward to do, but I didn't find an easy way to do this replacement. I found the Search and Replace Scanner module, but that doesn't seem to allow using parts of the original match in the substitution.

How can I fix these image links all at once without having to do it manually?

Assuming MySQL, you can fix that up with a search and replace SQL query.

Perhaps easiest from the MySQL command line, though could also use db_query.

The pattern is:

UPDATE tablename SET fieldname = REPLACE(fieldname, 'search', 'replace');

Something like:

UPDATE field_data_body SET body_value = REPLACE(body_value, 'sites/default/files/images/', 'sites/default/files/styles/[style]/public/images/');

UPDATE field_revision_body SET body_value = REPLACE(body_value, 'sites/default/files/images/', 'sites/default/files/styles/[style]/public/images/');

Backup the database first.

You may need to do it one image style at a time, or else make all the images uses a new standard style.

More info: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace


Export multilingual settings with features I'm using features to export 10 content types, but I don't get the multilingual settings. My question is, whether this is even possible, maybe with strongarm or I'm stuck having to change those settings by hand?

I use the i18n module and want the content_type to be translatable, in the content_type edit menu i set:

Publishing Settings->Multilingual Settings-> Enable with Translation
Multilingual Settings->Extended language options->Require language (Do not allow Language Neutral).

Yes, you can do this with Strongarm.  You'll want to add all the variables that are prefixed i18n_, language_, and locale_.


Calendar in date exposed filter? I'm looking for a Views exposed filter for node creation date that:

Shows a calendar (not popup)
Highlights days corresponding to existing node creation dates
Allows to click those days to see nodes created on that day

Does such a thing exist?

This issue will help you out
http://drupal.org/node/502824


how to manipulate entity field values in drupal 7 in custom module I am creating a Payroll entity in which I have to manipulate different field values based on another field value (see below).

I have the following fields and I want to calculate the bottom four field values from the value of the basic salary field. Is there any function/hook available for this or do I have to write my own custom function?

basic salary field
da salary(daily allowance)
ta salary(travel allowance)
epf salary(Employee provident fund)
save_salary(Save salary)

My suggestion, now that I understand you're trying to calculate certain values' amounts based on the amount of a different field, would be to use the Rules module.

Then you can accomplish what you need without writing a custom module.  Rules are sometimes a little clunky to create, but the module is really reliable - I use rules for all sorts of things, and once you set it up, it works beautifully.

Here are (roughly) the steps you'd need to take to create a rule that modifies a certain field based on another one.  Adjust as you need to, so it suits your particular needs.

After enabling the module, go to /admin/config/workflow/rules to add a new rule
Set the 'Event' that triggers the rule to be something like 'After updating existing content'.  That will trigger this re-calculation any time the node is updated
Next you'll see that the rule also has 'Conditions' and 'Actions'.  Set the 'Condition' for your rule to be 'Content is of type' and select the content type you want to apply this rule to from the given list.

Finally, let's go onto the actions.  You'll have to do two steps for each of the fields you're modifying 1) First calculate the value from the base_salary field (and store in temporary variable -- that's how it works) and 2) set the appropriate field with the value of this temporary variable.  Here are the 'Action' options that correspond to these

When you're calculating the value for one of the fields, the interface has, by default, a field to select from the top, an operator, and then a text field into which you can enter a number.  If you would rather add/multiply/etc two fields, just change the bottom one to a data selection option with the following button

If your calculation is more complicated than simply adding/subracting/etc two values, just keep selecting the 'Calculate' value action and keep working on the number with multiple chain operations until you're ready and then add the 'Set a data value' at the end.

Hope this helps! I can't do an entire tutorial on using Rules here, as it's a complicated module, but the above should get you started and point you in the right direction. :0)


How I use fields on a custom template? I'm attempting to build custom template for specific content type.
So, I created node--my-content-type.tpl.php and tried to write some text: it works!
Ok, now I want to render my fields. I have $content['field_title'], field_author, field_cast (is a field collection) etc.

I need values of these fields, so I tried to assign some variables:
$title = $content['field_title']['value'] etc, but it doesn't seem to work.
I can only call render function to render these fields, but I want to format page in custom mode.

How can I get field info in order to use correct values?
Thanks!

Download and enable the devel module to use dpm() on $content. This will show you the proper structure of the $content array. Sometimes entities and fields will have different structures depending on their type or how they're being implemented for that content type.


Does change of .info file need reinstallation of module to take effect? Does changing a module's .info file require reinstallation of the respective module to take effect?

No, it doesn't. It needs a cache clear though.


How can I print Views Exposed Filter widgets individually using views-exposed-form--mypage.tpl.php? I have five exposed filter widgets that appear on this page.  I would like to group three of them together and add a title above that group of three so that my layout goes from:

views default

A
B
C
D
E

what I want

A
TITLE

B
C
D

E

Since this customization is specific to one page, I added a views-exposed-form--mypage.tpl.php in my theme's template folder.

The code looks like this:

    <?php foreach ($widgets as $id => $widget): ?>
      <div id="<?php print $widget->id; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>

        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>

            <?php print $widget->operator; ?>

        <?php endif; ?>

          <?php print $widget->widget; ?>

    <?php endforeach; ?>
    <?php if (!empty($sort_by)): ?>

        <?php print $sort_by; ?>

        <?php print $sort_order; ?>

    <?php endif; ?>

Instead of the foreach loop, how can I print the individual widgets?

    <?php foreach ($widgets as $id => $widget):
       if ($id == 'SOMETHING_ID_THATIDENTIFY_B') {
         print '
'.t('TITLE');
       }
       else if ($id == 'SOMETHING_ID_THATIDENTIFY_E') {
         print '
'; //Closing #BCD
       }
    ?>

      <div id="<?php print $widget->id; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>

        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>

            <?php print $widget->operator; ?>

        <?php endif; ?>

          <?php print $widget->widget; ?>

    <?php endforeach; ?>
    <?php if (!empty($sort_by)): ?>

        <?php print $sort_by; ?>

        <?php print $sort_order; ?>

    <?php endif; ?>


Twitter Block translation I've got a TwitterBlock on my website. It works fine but all texts are in english.
Even if I change t('') function with my language (french) desired, it's still in english.

ex:ln422 twitter_block.module

'#title' => t('Tweets by @username', array('@username' => $config['username'])),

to

'#title' => 'Tweets par @me',

It still display 'Tweets by @username' in my page.
The language input seems to be ignored to in admin/structure/block/manage/twitter_block/1 when I wrote 'fr' in it.

I hope that my problem is a minor oversight on my part. All tips are good (even the simplest).

Thanks in advance.

PS: when I try to do a dsm($block) in twitter_block.module or dsm($content) in my override block I get all my values in french.

Do you have French language on you site?
You should not change code of contrib modules. You can override, extend it in your custom module.
If you have fr  language on site , back t() with EN labels, go to admin/config/regional/translate/translate try to search EN labels and translate them.

Another way to get translations, use module l10n_update, it can get translation if they available on Localization servers.


Hiding the field label when creating a content type I have created a content type called "Design" in which there are 3 fields. When creating this content type I want to hide the label of fields. How would I do that?

Please go to admin/structure/types/manage/[your-content-type]/display

And you can hide labels accordingly.


Views - create relationship on relationship? I'm confused with Views' query altering and adding joins. Need help (or at least a comprehensible documentation with code samples, because I've never found one).

Here is what I'm trying to do: I have 2 node types, Writers and Books. I use taxonomy to group Books by Writers. I've created a field in my taxonomy terms that references respective Writer articles. It looks like this:

Books by Writers (dictionary)

Books by Isaac Asimov (taxonomy term, WriterId = 1 - references Isaac Asimov node)

I, Robot (Book node)

Books by Harry Harrison (taxonomy term, WriterId = 2 - references
Harry Harrison node)

West of Eden (Book node)

Now I'm trying to build a view that looks like this:

Isaac Asimov (Writer node title)

I, Robot (Book node title)

Harry Harrison (Writer node title)

West of Eden (Book node title)

All in all, I need something like Book Nodes join Taxonomy Terms join Writer Nodes. In Views UI I'm able to display Book titles and add a relation to Taxonomy so that I can display all Taxonomy term fields. It looks like this:

1 (WriterId from taxonomy term)

I, Robot

2 (WriterId from taxonomy term)

West of Eden

How do I join Taxonomy and Writers to get access to Writer node titles?

As I understand you don't really need taxonomy here. Instead you can reference Book node to Writer node directly.
Of course, you can solve the problem without modifying your current structure. I will show how to create such View using Entity reference as referencing field. I recommend this module for creating references in Drupal 7 as it is powerful and stable.

First, create new View for Books content type:

Add relationship to taxonomy term:

Now you can add one more relationship to Writers nodes. Here Entity reference comes into play:

Now you can output all you want from Book node, from relative taxonomy term or from relative to that term Writer node. Just select appropriate relationship to use:

Here I added title from Writer node and excluded it from display.
You may want to group output by writer and it can be done in Format settings:

If you didn't use unnecessary dictionary, you would not need the second step.

About a year ago I started with NodeOne series Taming the Beast: Learn Views with NodeOne and Using the Reference modules by Johan Falk and I hope this information will help you too.

Done with love to Isaac Asimov.


get the content type 'machine name' by the 'human readable name ' I have a content type whose human readable name is Post your blog. How can I get the content type machine name by the human readable name?

Is there a function in Drupal 7, or do I have to query the node_type table to get what I want?

You can easily build a query to achieve this. However, as Molot mentioned, you have to handle human readable names that aren't unique.

  $machine_name = db_select('node_type', 'n')
  ->fields('n', array('type'))
      ->condition('name', 'Basic page')
      ->execute()->fetchField();


How do I change the output of a database query from an integer to a string? I'm working on a module that has a form that that submits to a database table and then queries that database to place that information in a table on another page. Everything works like I want with the exception of the 'country' entry which is a select box on the form and returns a numeric value (0,1,2, or 3). I would like to display in the table the text of the country instead of the numeric value. I have tried elseif statements and arrays and have been able to get the text string to display on the page but not replace the number in the table. I just learning to write modules and any insight would be greatly appreciated.

function drupalform_form1_submit($form, $form_state) {
  $d_id = db_insert('drupalform')
    ->fields(array(
      'name' => $form_state['values']['name'],
      'last_name' => $form_state['values']['last_name'],
      'email' => $form_state['values']['email'],
      'country' => $form_state['values']['country'],
    ))
    ->execute();
   drupal_set_message("Form has been submitted");
}

function drupalform_submissions() {
  $query = db_select('drupalform', 'df_list');
  $query
    ->fields('df_list', array('d_id', 'name', 'last_name', 'email', 'country'))
    ->range(0, 50)
    ->orderBy('df_list.d_id');
  $results = $query->execute();

  $header = array(t('ID'), t('First Name'), t('Last Name'), t('Email'), t('Country'));
  $rows = array();

  foreach ($results AS $result) {
    $rows[] = array(
      check_plain($result->d_id),
      check_plain($result->name),
      check_plain($result->last_name),
      check_plain($result->email),
      $result->country,
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows));
}

The numeric value from the country is essentially a database lookup value to either a Taxonomy Term, a Countries entry ... or whatever module you're using to reference the location. This is typical DB usage, store keys -- not (text) values of the data. If it was a taxonomy term you could do:

function drupalform_form1_submit($form, $form_state) {

  // Lookup the value for the country id key, somewhere, here I assume Taxonomy.
  $country_term = taxonomy_term_load($form_state['values']['country']);
  $d_id = db_insert('drupalform')
    ->fields(array(
      'name' => $form_state['values']['name'],
      'last_name' => $form_state['values']['last_name'],
      'email' => $form_state['values']['email'],
      // Store the country text value, for Taxonomy Terms thats the name value of the object.
      'country' => $country_term->name,
    ))
    ->execute();
   drupal_set_message("Form has been submitted");
}

Assuming your using Taxonomy Terms as countries, and the TID is in only 1 Taxonomy. You would use the same approach with any 3rd party location module.


Marking objects from view for later use If I have a table containing, say, images, how can I be able to select an image from one view, one from another and have them added/marked for later use (i.e., some sort of "add to cart" feature). So then I could select an image from slideshow1, one image from slideshow10 etc and then be able to do whatever I want with them (perhaps create another view?)

This sounds like a perfect job for Flag module.

From the module description:

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, or users. Some
  possibilities include bookmarks, marking important, friends, or flag
  as offensive. With extensive views integration, you can create custom
  lists of popular content or keep tabs on important content.

For your use case, I would create a new flag for your image content type. Add the flag operation to your current views of images. Create a new view that uses that flag as a filter.


Change the Source DB for migrating via Drush A few days ago I originally ran the full migration via the UI to get the site up and running and cleaning up any bugs from a DB instance that is a copy of the current live site. However, now that the site is up and running, I would like to re-migrate just the users from a NEW copy of the current live site in order to have an up-to-date data before going live (instead of losing any changes users made over the last few days).

I don't want to re-migrate through the UI because I just need to migrate users
I tried adding a $databases['migrate']['default'] setting in the settings.php file but migrate-import doesn't have any option like --legacy-db-key
drush migrate-status gives me an error because I deleted the backup db after I successfully migrated, but can't figure out a way to change the source DB

How can I change the source DB for the migrate drush commands in order to run a migration on just users via the drush migrate-import command?

in settings.php add the connection to the source database (that contains users you want to migrate)
$databases['myuserssourcedb']['default'] = [
  'database' => '',
  'username' => '',
  'password' => '',
  'host' => '',
  'port' => '',
  'driver' => '',
  'prefix' => '',
  'collation' => '',
];

in your migration yml file reference the source database as 'key' in the 'source'
id: migration_of_users
label: 'Migrate users from old database'
migration_group: migration
source:
  plugin: mypluginforusers
  key: myuserssourcedb  <-----This is the important line
process:


Redis and Internal Page Cache? I just set up Redis on a site that has been having some performance problems, and it seems to be running well so far. Does anybody know if it would be recommended to also run the Internal Page Cache and/or Internal Dynamic Page Cache module(s) in addition to Redis, or is this redundant? There isn't much documentation around yet regarding Redis and D8.

The Drupal modules decide what to cache (and for how long etc), Redis is just where the cached data is stored.

Having both/all enabled is not inherently redundant (though as 4k4 noted in the comments, there's a theoretical chance that one cache will improve speed so much that it renders the other redundant in terms of further speed improvements).

Enabling the lot will probably be common practice, and if not with Redis as the storage backend then Memcache, etc.


Media/file repository - asset autocomplete widget? Does anyone know of a module which would install an autocomplete widget for file and image fields on admin-side?

The purpose of it would be to allow admin/editor to re-use a reference to an already uploaded file by typing its name. The widget would then auto-complete the path/reference based on the actual contents of directory where the asset is supposed to be uploaded. Otherwise, the file would have to be uploaded repeatedly.

Or, to rephrase the question: how do you folks solve such a media repository issue?

You can use Media module to store Images in a specific location,but you cant get the auto complete function with this module but you can select and reuse the old photos from the Image location.

The another good thing using this module is it is already integrated with the Ckeditor.


Hide node created messages programmatically I'm trying to the node created messages for a certain content type, but I can't use Disable Messages because it has a conflict the Commerce Add to Cart Confirmation module.

All the other methods (like the ones here) I've found either hide all status messages, or hide all status messages after a content type is created, which are inappropriate for me since I'm using rules to show a messages after a node is created, but I need to hide the default "__________ has been created" message, and I appreciate any help you can offer me.

drupal_set_message is not hookable. But the message you want removed comes from node_form_submit, so you can get rid of it using hook_form_FORM_ID_alter on node_form. Either replace node_form_submit as form's submit handler with it's clone, sans messages, or set second handler that will remove what you want removed from $_SESSION['messages'][$type].


Passing custom fields as parameters in a REST query I am creating a REST Get request using Services 3.3 module on Drupal 7.15 which should get all the nodes filtered by a custom field field_asset_type

http://sharedrive/?q=rest/node&parameters[field_asset_type]=13

It returns following error
Invalid query provided, double check that the fields and parameters you defined are correct and exist. SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_asset_type' in 'where clause'

Kindly tell me how to resolve this problem. The articles on the internet explains how to pass built-in fields which is working but I also need to pass custom fields.

Please help

The default functionality only works with node properties, not fields. Fortunately you can use the Services Entity API module to get what you need:

Integration of Services and Entity API.
You can define an endpoint via Services and publish any entity data relying in Entity API.
This module allows to get entities by properties or fields and also paging and related entities that are defined properly.


How to add 1000 nodes of the same content type in just one step? I need some advice with the following situation:

I have a content type called: "Flats".

I have to add 1000 nodes for this content type.

The only field I need to complete for all of them is the 'title'

I have the 1000 titles in a comma-separated-value format file called: title.csv

Is there any way to upload this file and add all the nodes in just one step.

Thanks

Feeds module will also allow you to import content/create nodes via CSV.


Add a breadcrumb to a view page? How can you just add a breadcrumb to views?
Easy breadcrumb leaves out views.
Views breadcrumb does not work correctly with Drupal 8.
Is there a simple way with hooks?

EDIT 2:
Maybe I mean something else?

In Drupal 7 (with custom breadcrumb) it looks like this:
The view "Informationen" is called:

One node out of the view is called:

In Drupal 8 (with Easy breadcrumb) it looks like this:
The view "Informationen" is called:

One node out of the view is called:

I hope I could explain the difference.

You should create a custom module (use core >= 8.3). Use this code as a base to start:

custom_breadcrumb.info.yml

name: 'Custom breadcrumbs'
description: 'Custom breadcrumbs implementation'
package: 'Custom'
# core: 8.x
type: module

version: '8.x-1.0'
core: '8.x'
project: 'custom_breadcrumb'
datestamp: 1443649740

custom_breadcrumb.services.yml

services:
  custom_breadcrumb.breadcrumb_views:
    class: Drupal\custom_breadcrumb\Breadcrumb\ViewsBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 1 }

src/Breadcrumb/ViewsBreadcrumbBuilder.php

<?php

namespace Drupal\custom_breadcrumb\Breadcrumb;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\LinkGeneratorTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Link;

class ViewsBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  use LinkGeneratorTrait;
  use StringTranslationTrait;

  /**
   * @inheritdoc
   */
  public function applies(RouteMatchInterface $route_match) {
    // This breadcrumb apply only for some views.
    $parameters = $route_match->getParameters()->all();

    if (isset($parameters['view_id'])) {

       $views_id = array(
         'VIEW_MACHINE_NAME_1',
         'VIEW_MACHINE_NAME_2',
       );

       if (in_array($parameters['view_id'], $views_id)) {
         return TRUE;
       }
       return FALSE;
    }
  }

  /**
   * @inheritdoc
   */
  public function build(RouteMatchInterface $route_match) {
    // Breadcrumbs set up (cache settings are so important!).
    $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
    $breadcrumb->addCacheContexts(["url"]);
    $breadcrumb->addCacheTags(["view_id:{$parameters['view_id']}"]);

    $parameters = $route_match->getParameters()->all();
    if (isset($parameters['view_id'])) {
      if ($parameters['view_id'] == 'VIEW_MACHINE_NAME_1') {
         $breadcrumb->addLink(Link::createFromRoute(t('VIEWS NAME 1'), '<none>'));
      }
      else if ($parameters['view_id'] == 'VIEW_MACHINE_NAME_2') {
        $breadcrumb->addLink(Link::createFromRoute(t('VIEWS NAME 2'), '<none>'));
      }
    }

    // Reverse order for this to work!!!.
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
    return $breadcrumb;
  }
}

Remember to replace VIEW_MACHINE_NAME_1 and VIEW_MACHINE_NAME_2 with the machine name of your views. Also replace VIEWS NAME 1 and VIEWS NAME 2 with the breadcrumb title you want for each view.


How do I programmatically close webform by node date field? Background:
I'm adding an events (custom content type) & registrations feature to an existing drupal 8 website. My experience in drupal is pretty minimal. But I can find my ways around code.

These events can be conferences, seminars, training spanning 1-N days with N number of seats.

What I have got so far is creating content type & referencing webform.

What I want
Ways to disable/close form before event starts or as per a date field (ie, registration will be disabled).

What I have found which looks pretty close to what I want

Disable (Close) webform form dynamically

Close a webform when total seats reach a maximum

I haven't tried this module, but you might look at "Scheduled Updates"

Here's a walk through:
https://www.mediacurrent.com/blog/scheduling-content-changes-drupal-8/


Move “Submitted By” from node.tpl to page.tpl I'm looking to move "Submitted By" info from node.tpl to page.tpl however when I add the following from node.tpl into page.tpl I get errors. Im assuming I dont have access to those variables, but would like to know how I can set up a pre-proccess to get it to display as it does in the node.tpl

  <?php if ($display_submitted): ?>
    <div class="submitted">
      <?php print $submitted; ?>
    </div>
  <?php endif; ?>

you can construct your own with something like this, adjust as desired:

if(isset($node))
{
    $nodeUser = user_load($node->uid);
    print 'Submitted By ' . l(t($nodeUser->name), 'user/' . $node->uid) . ' on ' . format_date($node->created);
}


What is causing pathauto to generate unwanted text in these URLs? I have configured pathauto to generate URLs for content according to this pattern article/[node:author]/[current-page:title]-[node:nid]. article is a literal input, to reflect the content type description Site Article not token generated.

The content type description is Site Article

The node title is: this is a title

The author's name is: nodecreator

The node id is: 101

When I generate the URL alias using the pattern article/[nodecreator]/[current-page:title]-[node:nid], the resulting path 's article/nodecreator/edit-site-article-this-is-a-title-101. The last section on the URL shouldn't be prefixed by edit-site-article.

What could be the cause?

Pathauto creates the alias when a node is being added or edited, so, if you are using current-page:title it will include the title that Drupal generates for that page, eg, in your case, "Edit Site Article: This is a title", and not just the title of the node.  So I would look into using node:title instead so as to remove any of those potential prefixings.


How to clone regions from panel? Is it possible to copy (clone) regions (or at least blocks) with their settings from one panel to another panel?
I have two different panel pages, but some of the regions are the same in both panels. Could I just set such common regions once and then "copy" them to another panel?

thanks for advice
Tomas

Panels supports cloning/exporting the whole panel page, as well as individual page variants. It doesn't support cloning/exporting individual content panes (afaik)

However, you could potentially do it manually manipulating the panel export code.

e.g:

Export source page with new panes to clone
Copy desired pane definition from code export
Export target page to save into
Copy pane definition back into the desired section of the export code
Reimport the exported target page.

Manual, but something like that would work. You could also do it programmatically with the ctools/panels api.


Triggers on node creation of certain content-type It is a question that always gets answered by "use rules module." Unfortunately, this site depends heavily on a few actions and triggers already, and a migration is not in order.

Are there trigger-addons, tricks or code to make a trigger on creation of a certain node-type only?

Rules and core triggers/actions can co-exist. If it can easily be done in Rules, then why not use both. You then won't have to migrate.


How to print date in format «long» on node.html.twig template? Try this code (at node.html.twig, Drupal 8.0.0-rc3):

{% set date = node.created|format_date('long') %}

And next:

{{ dump(date) }}

Return error:

Exception: The timestamp must be numeric. in Drupal\Component\Datetime\DateTimePlus::createFromTimestamp() (line 165 of core/lib/Drupal/Component/Datetime/DateTimePlus.php).

Drupal\Core\Datetime\DateFormatter->format(Object, 'long')

you are not using the actual timestamp. Here's what you should do:

{% set date = node.createdtime|format_date('long') %}

See? You only need to replace created with createdtime.
Hope this helps.


How to delete a variable during uninstall? I've never run into this problem before, but the variable I set in my module won't delete during uninstall. What am I doing wrong?

I set the variable in my module like this:

variable_set('marigold_nutrients', $nutrients);

All is good. The variable saves just fine and I'm able to use it as normal with variable_get.

Here is how I try to delete it:

In my module's .install file, I implement hook_uninstall...

/**
 * Implements hook_uninstall().
 */
function marigold_nutrition_uninstall() {
  variable_del('marigold_nutrients');
}

Using the UI, I remove the module then uninstall it. The database table the module creates deletes just fine, and it looks as though it's uninstalled. However, when I look at the variable table in Sequel Pro, the 'marigold_nutrients' variable is still there. I've run cron, cleared the cache... not sure what to do.

MORE INFO:
- Using the debugger, I see that when I uninstall the module, it steps into the uninstall function just fine, so I'm pretty sure that function is working.

The problem is probably here (from the comments):

  The variable gets set during installation when the hook_schema calls a function to iterate through an array to create database columns.

The uninstall process calls drupal_uninstall_schema(), which in turn calls drupal_get_schema_unprocessed(), which invokes hook_schema().

So the variable is being added again during uninstall, presumably at a later point in the process than your hook_uninstall() is invoked and variable_del() has run.


How to create pop up window for login page I want something like if i click on the login then pop window should open where in i should able to enter my Id and password to login, as as of now i tried with modules like

Fancy Login

Ajax Register

Modal Forms

above module i just installed and enabled.

But no luck can anyone tell me how to achieve this?

1)use this module
https://www.drupal.org/project/modal_forms

2)create a block and put this code in it :

 <?php
global $user;
 global $base_url;
if($user->uid == '0')
{
?>
<a class="ctools-use-modal" href="<?php print $base_url; ?  >/modal_forms/nojs/login">Login
 <?php
}
else
 {
 echo '
Logout
';
}
?>


Template for specific content type I've read documentation about name suggestions but I don't get it.
My goal is to create a specific template used only with a specific content type (Drupal 8).

I've copied page.html.twig to edit the code inside a new file, named page--recette.html.twig (recette is the name of my content type) but this doesn't work.

html--node--recette.html.twig doesn't work neither.

Link : http://ofhjfqaj.preview.infomaniak.website/cms/recette-sans-gluten/tarte-tatin-comme-la-vraie

You can provide node level content type templates with the pattern node--node_type.html.twig.

So, for an article it would be node--article.html.twig.

In your case, it would be node--recette.html.twig. You can also provide view mode level twigs the same way, with node--node_type--view_mode.html.twig files.

Lets say you wanted to customize the teaser display markup:

node--recette--teaser.html.twig

If you enable twig debugging, you can see in your HTML source (comments) which template is being used, and what other template pattern names are available to you:

https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

Going any further than that, you would need to implement hook_theme_suggestions_alter to get more custom template names based on some sort of logic.


Can I use hook_uc_add_to_cart to ask for a yes/no confirmation before adding to cart? For certain products in my ubercart catalog, I need to show a legal disclaimer before actually adding them to the cart.
I was thinking to use hook_uc_add_to_cart for this, because it allows me to return a message in the result array :

http://api.ubercart.me/api/drupal/ubercart!uc_cart!uc_cart.api.php/function/hook_uc_add_to_cart/7

I could return a html enriched message holding the anchor to the final cart addition, in case the legal notice is read and confirmed.

For example : How do I translate this submit input form to a query string like alternative ?

<input class="node-add-to-cart form-submit" type="submit" id="edit-submit-144" name="op" value="Add to cart">

As an alternative I could ask the 'shopper' to hit this submit a second time as confirmation.

Then: To bypass the hook a second time, I could add a confirmed Boolean into the $data array which is returning into this hook as 3th parameter.

If I add this Boolean into the $data as a new key->value pair, will it be available again in the next submission ?

I was able to solve this issue using the first answer on this stackoverflow question : https://stackoverflow.com/questions/10490253/how-to-save-a-session-variable-in-drupal-7

In general: Drupal's static $_SESSION array variable allows to store key=>value pairs between different node pages, in my case the same page.

My code snippet inside uc_product_minmax_uc_add_to_cart hook :

    if (!empty($disclaimer)) {

        $confirmed = lists_session("s_key");

        if(! $confirmed) {

            $message[] = t($disclaimer, array('@qty' => $minmax->pmin_multiple, '!item' => $node->title));
            $result[] = array(
                'success' => FALSE,
                'message' => theme_item_list(array('items' => $message, 'title' => t('Read this note from medical department before confirming your reservation :'),
                'type' => 'ul', 'attributes' => array())),
                'silent'  => FALSE,
            );
            lists_session("s_key", TRUE);
        }
    }


How to remove unwanted div from view rendered block? In D8 I've created a view and assigned it into a block,

I've created corresponding template for both view and block.
Most of the unwanted addition of div's and classes has been removed.

But the following empty div is still there in the rendered HTML

<div class="js-view-dom-id-e0cc1fe812f18c9b5d6660b04594c41b597ae5ee9b28cf43f718dc43b43a2f42">

Anyone experienced the same issue?

Is the view empty? AFAIK that's the div where the view results should be (may somebody correct me if I'm wrong).

And here's some info in general about what this class is all about: https://www.drupal.org/node/2573529


White screen of death errors I have come across an error that I have been having difficulty fixing.
I am suspicious the problem is the "Primary script unknown" error, but I am lost. There is an reoccurring Fatal Error, but it is a core file that has never been modified..

Any help would be greatly appreciated.

See below for an example of the nginx error log.

  2016/01/09 08:08:17 [error] 1082#0: *315 FastCGI sent in stderr: "Primary script  unknown" while reading response header from upstream, client: 188.68.224.62, server: , request: "GET http://dhg.pisz.pl/httptest.php HTTP/1.1", upstream:  "fastcgi://unix:/var/run/php5-fpm.sock:", host: "dhg.pisz.pl"

The error you've shown is from someone running a hacking script.

The nginx documentation offers many solutions to avoid running bad php scripts in their Pitfalls and Common Mistakes FAQ, but the one I like is the try_files directive to only run scripts that exist on your server otherwise return a 404 Not Found status code.

location ~* \.php$ {
    try_files $uri =404;
    fastcgi_pass backend;
    # [...]
}


Maintenance page is not loading anything in the head tag I have a template based on the Basic theme.

I have created the maintenance-page--offline.tpl.php, and maintenance-page.tpl.php templates in my template folder, using a similar markup as in the page.tpl.php file.

These pages are not loading anything in the <head> tag.

What did I do wrong?

Here is the full source of a typical maintenance-page.tpl.php

<?php

/**
 * @file
 * Default theme implementation to display a single Drupal page while offline.
 *
 * All the available variables are mirrored in html.tpl.php and page.tpl.php.
 * Some may be blank but they are provided for consistency.
 *
 * @see template_preprocess()
 * @see template_preprocess_maintenance_page()
 *
 * @ingroup themeable
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">

  <title><?php print $head_title; ?></title>
  <?php print $head; ?>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<body class="<?php print $classes; ?>">

        <?php if (!empty($logo)): ?>
          <a href="<?php print $base_path; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
            <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

        <?php endif; ?>

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

              <a href="<?php print $base_path ?>" title="<?php print t('Home'); ?>" rel="home"><?php print $site_name; ?>

          <?php endif; ?>

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

<?php print $site_slogan; ?>

          <?php endif; ?>

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

          <?php print $header; ?>

      <?php endif; ?>

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

          <?php print $sidebar_first; ?>

      <?php endif; ?>

          <?php if (!empty($title)): ?>
<?php print $title; ?>
<?php endif; ?>
          <?php if (!empty($messages)): print $messages; endif; ?>

            <?php print $content; ?>

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

          <?php print $sidebar_second; ?>

      <?php endif; ?>

        <?php if (!empty($footer)): print $footer; endif; ?>

Recheck your page against any missing variables.


offseting date by integer I've got a content type with fields:
starting date: Date (Unix timestamp)
duration: integer
ending date: Date (Unix timestamp)

User is setting only starting date (year, month, day) and duration (in days)
end after saving the content I would like to automatically calculate ending date (=starting date + duration)

I suppose I should use rules. I tried using actions like set value or calculate value but I failed. Could you help me?

Interval module may help you. It provides an interval field type and also a rules action: "Apply an interval to a date".


Prompt to translate a content after creating a new content In my drupal site, I want to add a prompt informing editors that they must add a french version of an article (or any content type).  I tried doing this using Rules but there is no way to check if a content type has been translated to French.. CAn anyone shed some light? Thanks!

In the answer to "How to implement side-by-side translation?", I describe how to do side my side translation by adding an entity reference field and linking back to the original English article.

For your case, you could use rules to create a French node when an English node is created, save the entity reference and redirect to node/*/translate where the French node would be displayed next to the English one.

If you want to take this approach, I can add more details. I think it would give a very nice workflow.


Search according to language We are using 3 different languages by multilingual module. If we search by the English word, then search content should be in English, and if we search by Marathi/Hindi word, then search content should be in that particular language.

How can I perform multilingual specific search?

I had the same requirements, and I used the Custom search module, which includes a submodule called Custom Search Internationalization : "search content from all or current language only, and all label and selectors translation handling" (note this module provides also several other helpful features like custom search blocks). Works perfectly.


How to clear form cache automatically? I am working on a Drupal 7 site. When I check the  cache_form table it reaches 4 GB daily so I have to manually truncate the cache_form  table. Is there any way to clear cache_form table automatically 4 times in a day?

There are several method to clear the cache_form automatically.

Use optimizedb module

  There is well-known issue with fast-growing table cache_form. This
  table stores Drupal form cache and it isn’t cleared when you flush all
  cache or run cron. Also you can struggle with problem of fragmentation
  with InnoDB tables on active delete/insert operations. This module
  provide functionality to solve this problem. Also its provide
  additional tools for maintenance database.

  Module OptimizeDB provide such features:

Ability to clean **cache_from** in administrative page or do it by cron.
Ability to optimize all database’s tables and display its sizes.
Configuration of notification about necessity to perform maintenance tasks.
Perform check and repair operation with tables.
Prevent crashing tables when perform all maintained actions.

If you have drush access  Safe cache_form Clear module

  Safely remove a limited number of items from the cache_form table.

  This module provides a drush command drush safe-cache-form-clear that
  can be run at a high frequency, keeping the table at a reasonable
  size. It requires that you use the database cache back-end for the
  cache_form table.

  Drupal's core cron can have problems clearing out the cache_form table
  when it grows extremely large. This module works around this by
  limiting the number of items expired from the cache in a single run,
  dealing with a manageable chunk each time.

  You can configure the number of items deleted in a single run by
  setting the $conf['safe_cache_form_clear_limit'] persistent variable.

for automatically clear the Drupal cache use  Cleaner module (it's not clear the cache_form table).

  The Cleaner module allows the admin to set a schedule for clearing
  caches, watchdog, and old sessions.

and another solution is create a custom route in your module something that not predictable by others (some hash url), on call back function truncate 'cache_form' table (or equivalent Drupal ) then on your server or your Cpanel create  a crontab,schedule it to run the code periodically.


How to setup the oauth module? I don't know how to setup the outh module right. I found also the question How do I configure the Services OAuth sub-module? but that answer is very old and ends with a "To be continued..." statement.

So far I get out that I need to generate a context (http://example.org/admin/config/services/oauth/contexts) and a oauth connector (http://example.org/admin/structure/oauthconnector). So I think I setted them correctly but I cannot see where the user may access that.

Could you point me to a tutorial or something like that? I'm not able to find the right words to google that myself. Sorry for that!

You can try the Drupal Services, REST Server and 3-legged OAuth tutorial here. Just be pay intention in this part :

$oauth->fetch("$api_url/node/1");

This is just for creating the GET request. If you want to create the POST request. It should be something like.

 $oauth->fetch("$api_url/user/vote.json",array('nid'=>10),OAUTH_HTTP_METHOD_POST);


Omega and Panels: Is there a way to change "Omega XX column grid" layouts? I´m trying to work with the 3.x Omega version and Panels.
I´ve selected "Omega 16 column grid" at the panel´s layout category.
Is there a way to change those layouts?

ie. There´s this "Two Column 8-8" and I need "Two Column 9-7"
I´ve tried with "create custom layout", but can´t make that work.

Thanks for your help!

What you need to do is update your region area in omega to adjust the # of columns each one takes up.


How can I alter the HTML output of the default 403 and 404 error messages without hacking core? How can I alter the HTML output of the default 403 and 404 error messages without hacking core?

I know I can create custom pages via the UI, but this doesn't work for me because I need to deny access to all published pages to anonymous users.

Notes:

I believe the default 403 and 404 messages come from lines 2624 and 2653 on common.inc. This is what is generating my output at the moment - I assume. I don't think I can use a node for my output instead because anon users don't have permission to view published content.
I wanted to alter/override the default 403/404 messages outputed by common.inc. I can't redirect to a node because anon users don't have permission to view nodes.

Implement a custom module providing the 403/404 markup as a page callback. Note that access can be granted to anybody by setting the access callback in the menu router items to TRUE.

After enabling the custom module, you simply set the error pages in Configuration » System » Site information to the paths you defined in your hook_menu implementation.

/**
 * Implements hook_menu().
 */
function acme_menu() {
  $items['acme_404'] = array(
    'page callback' => 'acme_404',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items['acme_403'] = array(
    'page callback' => 'acme_403',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page callback for custom page not found.
 */
function acme_404() {
  return filter_xss(variable_get('acme_404_markup', 'custom 404 markup'));
}

/**
 * Page callback for custom access denied page.
 */
function acme_403() {
  return filter_xss(variable_get('acme_403_markup', 'custom 403 markup'));
}


How to import content in markdown format? I have text in markdown format. How should I go about importing this into my site? I would think a Feeds Tamper plugin to convert markdown to html would be ideal.

Does such a thing exist? Is there a straightforward way to convert markdown to html in Drupal?

Why complicate things by importing markdown? If html format is what is desired, there are many options to convert it beforehand. For example this simple python implementation.

As tenken suggested, Markdown filter is an option to consider.


How can I get a count of users with a certain role? I have a rather complicated profile completion process on my site.  As users create their profiles, they are awarded more roles.

For my own information, I'd like to be able to quickly check the number of users with role ABC.  I'd also like to be able to quickly know how many users have role ABC and role XYZ, as well as how many users have role ABC and role EFG.

Is there a quick way to do this in Views or some other module?  I don't want to see a list of all users; I just want to know how many have a given role (or combination of roles).

You should create a view with filter criteria "role" then you expose it and allow multiple selection.

Then you can create an header or footer (always in view) and add this piece of code

<?php
  $view = views_get_current_view();
  print $view->total_rows;
?>

You should have the php filter enabled.
This works for me.


How to keep the non mapped paragraphs during migrations? I am migrating content that contains paragraphs also. So I have two migration files.
When the content is migrated. Everything is fine. I can see the paragraphs are attached with the nodes.
When I edit a migrated node and adds a new paragraph to the node, then when I execute the migration again, that new paragraph removes from that node. Is there any way to keep them?
The paragraph_import.yml
langcode: en
status: true
id: paragraph_import
label: My paragraph import
migration_tags:
  - paragraph
source:
  plugin: csv
  delimiter: ','
  enclosure: '"'
  escape: '`'
  header_offset: 0
  ids: ['personal_number']
destination:
  plugin: 'entity_reference_revisions:paragraph'
  default_bundle: my_paragraph
process:
  mail:
    - plugin: skip_on_empty
      method: process
      source: 'e-mail werk'
  cellphone:
    - plugin: skip_on_empty
      method: process
      source: 'gsm werk'
  phone:
    - plugin: skip_on_empty
      method: process
      source: telefoon
  langcode:
    - plugin: default_value
      default_value: 'nl'
dependencies:
  enforced:
    module:
      - migrate_source_csv

The node migration.
langcode: en
status: true
id: contact_import
label: Contacts
migration_tags:
  - node
source:
  plugin: csv
  delimiter: ','
  enclosure: '"'
  escape: '`'
  header_offset: 0
  ids: ['personal_number']
destination:
  plugin: 'entity:node'
  default_bundle: contact
process:
  type:
    plugin: default_value
    default_value: contact
  title: title
  paragraph:
    - plugin: migration_lookup
      migration: paragraph_import
      source: personal_number
  my_paragraph_field:
    - plugin: sub_process
      source:
        - '@paragraph'
      process:
        target_id: '0'
        target_revision_id: '1'
  langcode:
    - plugin: default_value
      default_value: 'nl'
dependencies:
  enforced:
    module:
      - migrate_source_csv

My migration execute code.
$migration = $this->migrationPluginManager->createInstance($migration_id);
$migration->getIdMap()->prepareUpdate();
 try {
   $executable = new MigrateExecutable($migration, new MigrateMessage());
   $executable->import();
 }
 catch (MigrateException $exception) {
   $this->logger->error($exception->getMessage());
 }

It is different from this question Because that question talks about the fields in the paragraph. While this question is about the paragraph entity itself.

I have created a custom source plugin for this to achieve.
Here is my source plugin code.
class MYSOURCECSV extends CSV {

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $database = \Drupal::database();
    $table = 'migrate_map_migration_id';

    // The migration removes the manually created entities from the system,
    // that are not present in the migration source. But we want them to be
    // ignored during the migration.
    if ($database->schema()->tableExists($table)) {
      $organisations = [];

      try {
        $results = $database->select($table, 'mmt')
          ->fields('mmt', ['destid1', 'destid2'])
          ->condition('sourceid1', $row->getSourceProperty('personal_number'))
          ->execute()
          ->fetchAll();

        if (!empty($results)) {
          foreach ($results as $result) {
            $paragraph_id = $result->destid1;

            $paragraph = \Drupal::entityTypeManager()

  ->getStorage('paragraph')
          ->load($paragraph_id);

        if ($paragraph instanceof ParagraphInterface) {
          $node = $paragraph->getParentEntity();

          // If paragraph is already attached to a node. Get the ids from
          // the node.
          if ($node instanceof NodeInterface) {
            $organisations = $node->get('my_paragraph_field')->getValue();

            if ($key = array_search($paragraph_id, array_column($paragraphs, 'target_id'))) {
              $paragraphs[$key]['target_revision_id'] = $result->destid2;
            }
          }
          else {
            $paragraphs[] = [
              'target_id' => $result->destid1,
              'target_revision_id' => $result->destid2,
            ];
          }
        }
      }
    }

    $row->setSourceProperty('my_paragraph_field', $paragraphs);
  }
  catch (Exception $exception) {
    \Drupal::logger('my_module')->error($exception->getMessage());
  }
}

parent::prepareRow($row);
  }

}

And then change the paragraph field mapping in the  migration file to:
my_paragraph_field:
    - plugin: sub_process
      source: organisations
      process:
        target_id: target_id
        target_revision_id: target_revision_id


How to use Rules to send an eMail containing a list of nodes with a selected value in a field? I try to send a list of nodes with certain value in a specific field via the Rules module.

This is what I have so far:

Event: "After updating existing content of type MyContentType"
Conditions: "Parameter: Data to compare: [node:field-status], Data value: sendmail"
Actions:

"Parameter: Entity type: Node, Property: Status, Value: [node:field-status], Limit result count: 100
Provides variables: Fetched entity (entity_fetched)"
"Send HTML e-mail"

Here is an export of this rule:

{ "rules_send_node_list" : {
    "LABEL" : "Send node list",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail" ],
    "ON" : { "node_update--mycontenttype" : { "bundle" : "mycontenttype" } },
    "IF" : [ { "data_is" : { "data" : [ "node:field-status" ], "value" : "0" } } ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "node",
            "property" : "field_status",
            "value" : [ "node:field-status" ],
            "limit" : "100"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "mimemail" : {
          "key" : "[node:title]",
          "to" : "to@example.com",
          "from_name" : "QX",
          "from_mail" : "from@example.com",
          "subject" : "Node flagged",
          "body" : "[entity-fetched:0]\r\n[entity-fetched:1]\r\n[entity-fetched:2]\r\n[entity-fetched:3]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

The list with nodes with the field-status set to "sendmail" is indeed send out. The problem I'm facing here is that I have to put in the email body tokens like [entity-fetched:0], [entity-fetched:1],  etc.

In the section Replacement patterns for Fetched entity I only have [entity-fetched:0] till [entity-fetched:3] available. But I have more nodes than that. I would like to have the complete list with these flagged nodes.

Any suggestions about this?

How to get a complete list

Your Rules Events and Conditions are pretty sure OK, but you're missing a crucial Rules Action: a Rules Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

The result of your first Rules Action is actually a list, which as per the "PROVIDE" that is shown in your exported rule, is stored in a variable named entity_fetched (BTW, try to use a more meaningful variable name for such variables, eg nodes_with_status_sendmail).

As you seemed to have understood already, the entity-fetched:0, ..., entity-fetched:3, correspond to your 1st, 2nd, 3rd and 4th node in that list of fetched entities (nodes).

What you need to do to repair your Rules Actions, are these steps:

AFTER your first Rules Action (which fetch those nodes, and which is fine), use the link "Add a loop" as the next (2nd) Rules Action. When doing so, specify these options for it (note the looooong variable name for my 'List item', I bet you get its meaning just from its name ...):

Parameter: List: [entity-fetched]
List item: Single node with status sendmail (single_node_with_status_sendmail)

Within that loop you added, use the link to the right of it (in the Rules UI), to "Add an action". That way the Rules Action you add, will be performed as part of the loop. The actual Rules Action to add is similar to the (last) Rules Action you already have, with machine name "mimemail". As you will notice while creating a similar Rules Action, you'll now be able to select/specify tokens that relate to ... single_node_with_status_sendmail. However, the content of your eMail message body should now only (repeat: only!) refer to the "List item" being processed in the current iteration of the Rules loop (instead of those 4 items in your existing "mimemail" action).

As you will probably understand, since you're now processing 1 single node in each iteration, and it doesn't matter how many nodes you have in your list of nodes, there is no more restriction to 4 nodes only.
After you completed the previous step, there is no more need for the existing (last) Rules action about "mimemail", so just delete that Rules Action.

With these changes you solve your limitation of 4 nodes maximum. However, in case you don't realize yet, you may have introduced a new challenge, as detailed below ...

Solution to your problem ... might (will?) change the problem

Using the approach detailed above, the result of your adapted rule is that you will get 1 separate eMail for each node fetched via that first Rules Action (which created the list of nodes to be processed). If you typically only have a few nodes that may not be a real issue to worry about. But if you have dozens (or more?) of such nodes then you might want to consider consolidating all such eMails in a single eMail, which contains (in its eMail body) the complete list of nodes.

A possible solution to implement such consolidation, is similar to what is shown in the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?". In your case, you could make it work like so:

Add some new Rules variable that will be used later on as part of the eMail body, before the start of your loop. Say you name the variable nodes_list_var_for_email_body.
Within your loop, for each iteration, prepend or append the value for each "list item" to that variable nodes_list_var_for_email_body.
Move your (new) "mimemail" action outside your loop, and after the loop completed. And finetune the details (configuration) of your (new) "mimemail" Rules Action. When doing so, you'll be able to select the token for nodes_list_var_for_email_body to include anywhere in your eMail body.

Summary

If you think about it, you'll end up more or less with a variation of the last Rules Action in the rule you already have, in which the body part now contains nodes-list-var-for-email-body instead of entity-fetched:0, ..., entity-fetched:3.

But for this (crucial) nodes-list-var-for-email-body token to be available, you need to (a) add the Rules Loop and (b) add 2 more Rules Actions to create the content (value) of  nodes-list-var-for-email-body.

Voilà

... That's really all it takes to get this to work.


how to remove duplicate in view search API? I get some duplicate article for the site. How can i remove the duplicate? There is no distinct setting.
Here is the setting of view

Depending on your setup there are different reasons why you can get duplicates. A common reason is, that you're using related entities (nodes, taxonomies). Let's say you got a content type car with a taxonomy term that shows the car's color. If you create a relationship between car and color in your view, you can see duplicates if a car has multiple colors.

There are three different options that allow you to reduce duplicates.

In the view's ADVANCED tab you can find USE AGGREGATION and QUERY SETTINGS. Try out which of them works for your use case.

Inside QUERY SETTINGS you can find the DISTINCT option.

If you enable USE AGGREGATION your fields and filters will receive a new option AGGREGATION SETTINGS where you can define the type of aggregation (ie. Group results, Minimum, Maximum, etc.)

When you add fields to your FILTER CRITERIA there is another setting to prevent duplicate entries when a filter is applies.

But beware, complex views tend to get slow when aggregation is enabled.


Delete a node after X weeks it was created How  can I delete a node after, for example, 2 weeks it has been created?

If you're looking for a developer-centric solution, you can invoke hook_cron() in a custom module to clean up old nodes:

function MYMODULE_cron() {

  // Other conditions can be altered/added as neeed
  $query = \Drupal::entityQuery('node')
    ->condition('created', strtotime('-2 week'), '<=');
  $nids = $query->execute();
  foreach ($nids as $nid) {
    $node = node_load($nid);
    $node->delete();
  }
}


How do I get a field rendered with translated labels? I have a node I render with the following code.

$render_controller = \Drupal::entityManager()->getViewBuilder($node->getEntityTypeId());
$render_output = $render_controller->view($node);
echo \Drupal::service("renderer")->render($render_output);

The rendered field labels are always in the original language (for example, German), even if I use $node->getTranslation("en").

I find it difficult to get translated labels to render properly. I've searched through the source code all the way from back to front to find an answer. I see my translated field label in the frontend under "/admin/config/regional/config-translation/node_fields" so it must be stored somewhere.

How do I access it or even better render the whole field correctly?

Neither $field->getLabel() nor $language_manager->setConfigOverrideLanguage($language) helped. Somehow Drupal must think it's very clever and uses some default language I don't want. I want to pick a specific language and render that. I would expect that usinggetTranslation()` on the node really gives you everything in the right language, but it doesn't happen. Why?

You have the change the current config translation language. user_mail() has an example for that:

  $language_manager = \Drupal::languageManager();

  $language = $language_manager->getLanguage('en');
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);

  // Do your thing here.

  $language_manager->setConfigOverrideLanguage($original_language);


Views Custom Condition Error I got the error

  Fatal error: Class 'RulesEventSet' not found.

I got this error on installing the views_custom_conditions module module.

Please let me know the cause of this error as I Googled but didn't find the solution.

Here is a patch that should fix your problem. Comment #10


Region doesn't show the blocks content I can't see a content of custom block (making by clicking on "Add new block").

I try to add block in region, but region doesn't show the block content. I use different kinds of block("Search form", "Powered by Drupal", etc.) and it doesn't help.

What should i do?

Add new block then yo have to specify whether the block should be visible in all pages or specific pages in the Show block on specific pages save it.
also while assigning the block to any particular region you need to save the block by clicking on save blocks button at the bottom of the blocks page.


Register a new namespace for autodiscovery I'm using a vendor library that isn't managed through composer. I want to register the namespace for the library so that it will be discovered through PSR-4. I'm not sure how to go about doing this in D8 though. Can anyone point me at something?

The autoload is still done using Composer. To add an extra namespace you'll have to run a composer command to rebuild the autoload file.

See https://stackoverflow.com/a/31505011/113057 for how to add a namespace to composer.

The key is in composer dump-autoload


How Do I Create a User Role that Can Only CRUD a Single Content-type? OK, so I know how to create roles and messed around with the People->Permissions->Roles screen.  My goal is to create a single user role that will have only one function -- to administer the calendar events for the client site.

The first thing I did was to create a view to act as the overview of the available content.  I added in the Login Destinations module and set it to send the user directly to the Events content overview view.

I checked the following role permissions at the Node level as:

Access the content overview page
View published content
View own unpublished content
View content revisions
Revert content revisions
Delete content revisions

And at the content-type node itself:

Calendar Event: Create new content
Calendar Event: Edit own content
Calendar Event: Edit any content
Calendar Event: Delete own content
Calendar Event: Delete any content

So, when I log in as my event administrating user, I am redirected to the overview page, as expected.  But when I click on the link to the node, I get this:

"You are not authorized to access this page."

So, my question is two-fold.  1) Is there a better way (read: built-in) to implement the "overview" of the content that I'm not aware of? 2) Am I using the People->Permissions->Roles as designed?  If not, what am I doing wrong?

Thanks in advance,

Scott.

The Permissions section is broken out across content types. You can create a new group, put that user into it, and give that group permission to CrUD one or more content types. Allow this user no other permission in any other content type (outside of calendar).

To overcome the 'overview' page problem, is View published content checked?


Why can't I reinstall my module after uninstall? With last beta version of Drupal 8, I have this error:

  Error message
  Unable to install Nature Theme - Structure and configuration, block.block.kyna_block_aboutus, block.block.kyna_block_blog_more_content, block.block.kyna_block_navbar, block.block.kyna_block_user_login, block.block.kyna_block_user_menu_account, field.field.node.article.field_kyna_article_slideshow, field.field.node.kyna_folio.body, field.field.node.kyna_folio.field_kyna_folio_client,
  [...]
  image.style.kyna_image_medium, node.type.kyna_folio, system.menu.kyna-navbar, taxonomy.vocabulary.kyna_client, views.view.kyna_blog, views.view.kyna_folio, views.view.kyna_home already exist in active configuration.

Why can't I reinstall my module? I don't have this error with previous version of Drupal 8 when I try to install my module after an uninstall.

How share my site configuration (block, field, view, etc.) without this problem please?

This is not so easy right now.

One way to do it is to put a forced dependency in those configurations, then they will be uninstalled together with a module. Core might even switch to doing that automatically, as I just discussed with @alexpott.

I'm not really sure how you are using that module. I have a feeling that is not what you want.

  How share my site configuration (block, field, view, etc.) without this problem please ?

Share how? With whom? Multiple separate sites, or dev/staging/production of the same site?

If the second, then do not use a module for this. Use the configuration staging folder and the configuration sync API/UI, that is designed to deal with updated default configuration.

If the first, keep in mind that default configuration is only designed for one use case: Initial default configuration when a module is installed for the first time. Modules are not meant to be re-installled to install updated configuration, the only way to do it like that would be first remove all the configuration and then create it again. That will not work for things like fields, because you will lose your data.


Get fields of referenced entity in view I have two content types, Project and Resource,

I have a view displaying fields from Projects, and I would like to display fields from resources referenced by projects in that view.

If I Twig debug, I can see the resource fields are available in the view, but I cannot output them using {{ fields.field_project_linked_resource.content }} or similar...

Any help much appreciated!

You can display information from nodes that are connected through Entity reference fields right in the Views interface.

In your case you're referencing Resources from Projects, so you need to add the Relationship for the Entity reference field, then you will be able to add Fields that you can find on the Resources Content type (they will automatically use the Relationship).

If it's a field that both Content types have (for example Title) then if you don't use the Relationship on it the title will be for the Project node, and if you do make it use the Relationship it will show the Resource title.


how to open desktop node link shared on facebook onto mobile device (mobile website version) I have a desktop link:
mysite.com/node/22

When I share this link onto facebook, and try to open it on desktop prowser it's work good.

But when I try to open it (from facebook) onto mobile it's back me to webiste (mobile version) home.
mobi.mysite.com

how can i make it on mobile go to
mobi.mysite.com/node/22

I use (mobile switch) and (mobile tools) modules, and they are works good

thanks

the solution is very simple, I just don't see it.

its in advanced sitting for mobile switch module, Multisite shared content must be checked.


How to use dependency injection to apply a class static method? I'm building a custom form (extending ConfigFormBase) and using static method File::load($fid). How to use dependency injection to call this method?
Thank you!

In __construct() you can implement like this:

use Drupal\Core\Entity\EntityTypeManagerInterface;

public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
}

and create() method

public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
    );
}

You can use this service to get the file storage:

$file_storage = $this->entityTypeManager()->getStorage('file');

and then load the file:

$file = $file_storage->load($fid);


Override remove entities link on module uninstall page When a module needs to be uninstalled, Drupal adds links indicating there is content associated with the module which should be deleted first and provides a link Remove module_name entities. This works fine for most modules, however we have a complex module that needs to perform clean up, is there a way to override this link and have it invoke a custom entity deletion method?
In our case the Remove links that are automatically added to the module uninstall page, don't end up cleaning all items, and leave the site in bad state.
Possibly related to this question asked earlier "How to remove custom module provided entity instances by the time the module being uninstalled?"

If you're solely looking to alter those messages & links, you could to override the required_module_uninstall_validator service with a custom class that extends ContentUninstallValidator and alters its validate() method:
// In your ContentUninstallValidator child class
public function validate($module) {
  $reasons = parent::validate($module);
  // @TODO find/alter the message & link relevant to the module
  return $reasons;
}

However, you'll have to deal with the issue of searching through messages and being able to find the string relevant to the module. This could be problematic depending on how you're searching through the messages array.
A better approach might be to add new messages via a new uninstall validator service that can provide its own custom messages & links that will initiate your own custom entity cleanup code.
A good working example can be seen in the book module:

Defines the service in book.services.yml:

      book.uninstall_validator:
        class: Drupal\book\BookUninstallValidator
        tags:
          - { name: module_install.uninstall_validator }
        arguments: ['@book.outline_storage', '@entity_type.manager', '@string_translation']
        lazy: true

Handles validation & generates new messages in BookUninstallValidator::validate():

    public function validate($module) {
      $reasons = [];
      if ($module == 'book') {
        if ($this
          ->hasBookOutlines()) {
          $reasons[] = $this
            ->t('To uninstall Book, delete all content that is part of a book');
        }
      }
      ...
      return $reasons;
    }


Count of entities with a certain field value, filtered by created date I’ve got users with a gender field and I want to display counts of how many males and females were registered on or before a particular date.  So:

COUNT(user.gender=male) and COUNT(user.gender=female) where user.created < {date}.

Using views aggregation I can easily get the male/female counts for ALL users, but when I try to add either a filter or a contextual filter on user.created I get no results (and my brain goes flatline—see “extra credit”, below).

Is it possible (within Views) to do what I’m trying to do, and if so, how?

Extra credit: 4,000 brownie points for anyone who can help me understand why when you add a filter you specify aggregation rules.  When filtering, I'm thinking about constraining the results, not aggregating them.  What am I missing?.

Thanks!

Found a work-around -- http://drupal.org/node/847698#comment-3174900

Disable aggregation, then add filter, then re-enable aggregation.