Adding more values to Drupal user status Are there any modules available for adding more values to the standard Drupal user status?

By default we have "Active/Blocked" values, but I would like to extend it with more values.

By default, I don't think there's any way of doing this.  The user status is used by other parts of user.module (as well as x amount of contrib modules), so extending it could cause conflicts there.

What you could do however, is add a custom status field to your users and use that.  You'll get most of the normal benefits of the Drupal user status, but it'll be as extensible as you need.

Combine it with Field Permissions to prevent users from being able to see or edit (or either one of those options) themselves should you need to.

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

If you still want a user status that disabled the user account, then you could create a value on your custom status field (let's call it Disabled and then configure a Rule that says:

  Event:

  After saving a user account After updating a user account

  Condition:

  Use data comparison to se if *field_my_user_status* is equal to
  disabed

  Action:

  Block user account

*NB If you do this, don't forget to create an opposite rule that enables the user account based on your field value :)


Problem using module_load_include I need to use node_add(), but when I called it in my module I get the "undefined function" message.

So I'm trying to include it using module_load_include('inc', 'node', 'node.pages'), but I'm getting the error message:

  Fatal error: Unsupported operand types in /var/www/vhosts/**.es/httpdocs/includes/common.inc on line 2946

Do you have any idea?

Maybe you are using an old version of PHP. Have you tried also running "php -l your_file.php". That will run just the parser to see if you have any php syntax problem.


Unknown option `--tail` when running `drush ws --tail` I am using Drush version 9.0-dev-dev.

When I run drush ws --tail, I get the following error:

[error]  Unknown option: --tail.  See `drush help watchdog-show` for available options. To suppress this error, add the option --strict=0.

I've used this with all other versions of drush with no issues.

It's all in the linked issue.

  Some existing Drush commands were simplified in Drush 9. I think that
  --tail would still be a welcome addition, if someone wanted to submit a PR.

But as of today the pull request is still unmerged. Maybe you can reanimate it and provide some help.


Should you use check_plain() prior to inserting into database? I am currently using check_plain() etc on displaying user entered data in HTML, and I am also using check_plain() etc prior to inserting the user data into my custom tables.

When inserting or updating the DB, I am always using db_insert or db_merge. Do I need to validate like I am, or are those functions doing it for me already?

If they are doing that already, do I need to use check_plain() on output still?

I downvoted Devaraj Johnson's answer because it suggests to check_plain() data before saving it to the database, which is wrong.

The idea behind check_plain, filter_xss and filter_xss_admin is to prevent XSS attacks, which are related to the front end.

When you handle database queries, use parameters and the DB API to prevent SQL injection attacks. Whenever you output data to the browsers, use check_plain, and other security methods.

Note that check_plain(), filter_xss() and such functions do change the data. When you save data into the database, you are only escaping specific characters, but you do not alter the original text. If you use check_plain() in database insert/updates, saving data a few times can mess up your data with a lot of &amp;, &lt;, etc character replacements and some HTML tags stripped out.

Here are some good reads:

Why Does Drupal filter on output (explains why you should not check_plain database data)
Handle text in a secure fashion


Grouping Taxonomy terms by their parents I have a Taxonomy Vocabulary for all types of cars. It has the following hierarchy:

Main Brand 1
- Sub0
- Sub1
- Sub3
Main Brand 2
- Sub1
- Sub2

and so on...

I want to have a webpage that displays the sub items when the main brand is selected.

Also, is there a way when assigning a specific value for the main brand field in my content type, for another field to appear populated by the sub brands of the main field?

Hope I'm not too late, but maybe others will find this helpful...

If I'm understanding the question correctly, this is what you do:

Add two taxonomy name fields to your view display—one excluded from display, the other not.
Add a relationship of "Taxonomy term: Parent term" (under Advanced) and then attach it to the field excluded from display.
Under in the view's format settings, group by the excluded field with the relationship.

Note: If the parent terms are being printed twice (not just as group headers), make sure you excluded the field with the relationship and check "Require this relationship" in the relationship settings.

I don't know if this works with tertiary+ levels. Probably not. In which case there's most likely a module.


When I clear cache, my menu ordering seems to go out of order When I clear cache, especially on high traffic times, my menu seems to go out of ordering. Usually I don't see any log messages except for one time:

  Message              Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction: INSERT INTO {cache_render}

That time my ram and CPU also spiked. What I mean about go out of ordering is this:

The ul.menu-level-1 is suppose to be inside the div.container, but for some reason, when I clear cache, sometimes it's rendered outside the div.container.

I am using the menu items extra module module. It does not have an issue related to this. My network team is pretty adamant that the resources I have are sufficient and i hover about 30%-40% utilization normally for my ram and cpu. The web and database nodes are separate.

I am self-hosted and have cloudflare in front of my website. I do not have caching in cloudflare turned on. Does anyone have any suggestions on what this could be. It normally only happens on my production site - of course - but it's happened on my test sites in the past as well. That's why I don't think its cloudflare.

I believe this had something to do with mysql's setting max_allowed_packet. Mine was only set to 1MB, when drupal recommended 16mb.


Slow views render time I am using Drupal commerce for one of my clients. I notice that the view with orders which are in a checkout status take several seconds to load. After i enable views statistics the numbers are

Query build time    23.51 ms
Query execute time  4.33 ms
View render time    209.68 ms

Which are pretty fast. But despite of the 200ms it takes 6-7 secs to load the view. What could cause this?? Any directions  in order to debug this??

My server is VPS and well configured. I only have this problem with this actual site.

Thank you in advance

Though view is a powerful module, it can cause a lot of performance problems if certain things are not handled. There a certain steps you can follow to fix this.

There are several things you can do to solve improve this:

Optimizing View:

Try to change left join to inner join using alter.
Enable Cache on views and clear it when order is updated.
Check if Distinct is marked.

Here is a sample views alter code:

/**
* Implements hook_views_query_alter().
*
* This disables distinct and turns LEFT joins into INNER joins. This increases
* performance.
*/
function my_module_views_query_alter(&$view, &$query) {
if ($view->name == "my_view") {
$query->table_queue['content_type_article']['join']->type = 'INNER';
$query->distinct = 0;
}
}

Optimizing view is a wider topic, there is a good write up on optimizing views that you can read to understand this better here.

Other than this you should check if your mysql configuration in my.cnf is optimized as per your system resources. For this you could use mysqltuner script or mysql-tuning-primer script.

Above that use of memcached with Drupal can also increase performance to great extend.


Custom variable in custom block template I'm trying to create a block that will pass a variable to its template. For now just some text but it will be an array later.

The default block variables such as label are working but I'm unable to get the value to show up in template.

Any ideas ?

FrontAppsBlock.php

namespace Drupal\custom_blocks\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
/**
 * @Block(
 *   id = "front_apps_block",
 *   admin_label = @Translation("Front Apps Block"),
 * )
 */
class FrontAppsBlock extends BlockBase implements BlockPluginInterface {

  public function build() {
    return array(
      '#theme' => 'front_apps_block',
      '#app' => 'test value',
    );
  }

}

custom_blocks.module

function custom_blocks_theme($existing, $type, $theme, $path) {
  return [
    'front_apps_block' => [
      'variables' => [
        'app' => null
      ]
    ]
  ];
}

block--front-apps-block.html.twig

test: {{ app }}

label: {{ label }}

After long hours of searching and trying I finally found a solution.
Not really sure why but it seems a naming convention has to be respected.

I changed the name of #theme and templates to start with module name, here the name is custom_blocks.

src/Plugin/Block/FrontAppsBlock.php

/**
 * @Block(
 *   id = "front_apps_block",
 *   admin_label = @Translation("Front Apps Block"),
 * )
 */
class FrontAppsBlock extends BlockBase implements BlockPluginInterface {

  public function build() {
    return [
      '#theme' => 'custom_blocks__front_apps',
      '#app' => 'test value',
    ];
  }

}

custom_blocks.module

function custom_blocks_theme($existing, $type, $theme, $path) {
  return [
    'custom_blocks__front_apps' => [
      'variables' => [
        'app' => null
      ],
    ]
  ];
}

templates/custom-blocks--front-apps.html.twig

Hello: {{ app }}

Base Label: {{ label }}


Hide and Reveal Sidebar Blocks in Drupal 7? I am working on a 1920px-wide site that will be displayed on HDTVs internally at an office. I'd like to place text and other info into (ideally) sidebar blocks, but I'd like for those blocks to be hidden when the page loads. Then, when someone clicks a block's title, that block alone would expand, displaying its content over the primary content area. I have attached an image to illustrate what I mean.

Does anyone here know of a module that can accommodate this type of functionality? If not, any recommendations on how to achieve this would be most appreciated. The sidebar content does not necessarily have to be in blocks.

In the themes .info file you can add a line like this

"scripts[] = myscript.js". This is eplained in the drupal theming guide -> http://drupal.org/node/171205.

Drupal will then load your js file and automatically insert jquery too.

This is the code that you need to put in the js file. Be aware that every region has a div with the class name. Example "region-footer". So thats how you can target them easilly. Make sure you set a width in you css file for the element.otherwise jquery cannot toggle the width.

(function($) {
    $(document).ready(function() {
        $('.region-footer .block h2').click(function() {
            $(this).parent().children('.block-inner').animate({
                width: 'toggle'
            },5000, 'swing');
        });
    });
})(jQuery);

You could also animate/toggle the margin instead of the width. If you do that remember to declare the negative margin for the element in your css file.

Do not forget to clear the cache after altering your themes .info file.

Tip : You could add a nice animation with http://gsgd.co.uk/sandbox/jquery/easing/


How can I restrict view pemissions to a node related child nodes? Let's say I have a parent node with ID equal to 233 that has the following related nodes: 234, 235, 236 (in a relationship field).
Is it possible to restrict access to paths node/234, and node/235, if they are a specific content type, but still show them for the same users in a embedded view inside a local task of ID equal to 233?

Looking at the comments I realized that in my case at least the best way of limiting the access  for unauthorized users (anonymous mainly) is to not publish the child nodes. And I removed the 'published'='yes' filter in the view itself so I can show those nodes in the parent template. And it works nicely. Thank you for the tips.


mrss(Media RSS) feed for drupal 6 Is there a MRSS module for drupal 6? I have been asked to create a mrss feed of a site video content. This will enable AOL to access all the videos of the site via mrss. Will I have to create a custom module to achieve this?

MRSS is just an XML.

There are many Views plugins to export data as XML. Specifically for MRSS, there is Views RSS. Or you can simply use template files to output data with proper tags.

It should be possible to use Feeds XPath Parser module to import MRSS, too.

The Views RSS module is only for Drupal 7 and 8.


Overriding template without killing the page? I would like to override the template for node creation. In the past when I've overridden a template, I've usually just copied the theme's generic template for that type (page, node, etc), given it the proper name, and edited it as I saw fit.

Now, for the first time I need to override a template that I can't simply make a copy of. I'm editing the node editing template and I have created a file with the correct name and location and everything, and it overrides the edit form, all right. Now there's nothing on the page except what's in my new template (unsurprisingly).

So, how do I create a template without getting rid of what was already there? Or, where can I find the template that Drupal is using to create my node edit form?

I'm using Drupal 7 and the theme is a custom one written by the previous maintainer of the site. It's not a child theme of a base theme, it's all by its lonesome.

Because the Node Edit page is a form, it is recommended that you use hooks for theming it.  You can create custom template file for it, but theming it within template.php is the most common solution.

Theming Node Forms in Drupal 7 is the best resource I've seen so far for this.


Render node fields in the views-view--[view_machine_name].html.twig I have a view called customfeedview showing contents of a content type viz. customfeeds.
View Setting are given in the picture below:

I created views-view--customfeedview.html.twig to customize the view. Code of the file is given here under.

{{ fields.title.content }}

{{ fields.body.content }}

But {{ fields.body.content }} & {{ fields.title.content }} does not render title and body of the contents of type customfeed.

Please help me in this issue as I am totally a beginner in drupal 8. Thank you...

N.B.: Here I am using show-type content instead of fields as only show-type content only give read-more option in the view page. Using show-type fields {{ fields.body.content }} is working fine but whenever I changed it to content {{ fields.body.content }} is not rendering the values.

You can call the node field in the view template

 node.field_(your-field).value

This will print the html tags as well, If the node field has the html structure.

node.field_(your-field).value | raw (or) node.field_(your-field).value |render|striptags

This will clean the html structure and useful to print the node value inside the view.template

NOTE: using node. instead of content. , because content. will be used only the node.html.twig


Block not showing up in Custom Blocks for Panel I've made a simple text block and now want to display this on a panel. However, the block does not appear on the list of available blocks on the Custom Block page. I've tried clearing the cache, and making different blocks, but it appears that all new blocks aren't showing up in that menu.

I'm not sure what I'm missing. I found this disucssion, Block doesn't show up in blocks listing. But I don't really understand what their solution was (manually edit db entry?).

I made a custom block from code and it is listed in "miscellaneous" section insted of "custom blocks". Maybe your modules are there.


Theme CSS overrides my CSS. How do I fix this? Trying to customize this theme called Emon, but any theme styles I write bootstrap.css/template.css takes precedence even if we use identical selectors. I don't want to edit bootstrap.css/theme.css obviously, or use !important all over the place.

The theme offers a "Write your own CSS" section which has it at an inline-level, but it's not the easiest to maintain this way (though it's looking more attractive every minute).  I saw libraries-override/extend, but wasn't able to accomplish what I want like this.

Again, I'm looking to tell Drupal to honor my stylesheet over the others without removing them.  What is the right way to accomplish this?

Copy html.tpl file from your core module and place it in your themes folder ,look at the head element of your template then copy the path(link) of your CSS file and place it (at the last)after the
themes CSS into the head tag.


Send an email when the roles are changed I'm trying to send an email to users after their role has changed. So far, the rule is triggered every time the profile is saved (even without role change); I suspect that the data comparison is not handling the array correctly?!
Any help to improve the following rule or to achieve the same feature with a different condition will be very much appreciated.
{ "rules_role_changed" : {
    "LABEL" : "Role changed",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "NOT data_is" : { "data" : [ "account:roles" ], "value" : [ "account-unchanged:roles" ] } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "account:mail" ],
          "subject" : "Role change for [account:name-raw]"
        }
      }
    ]
  }
}

To detect 'any' change to the users roles, you can use the following PHP via the condition "Use PHP code"

return (count(array_diff_key($account->roles, $account_unchanged->roles)) + count(array_diff_key($account_unchanged->roles, $account->roles))) <> 0;

The other PHP answers will not necessarily fire when a user has been 'removed' from a role.


Reference an Image from a Scald ID I am using the Services (7.x-3.7) module to provide a REST API to our website content. However I have a problem with returning images. I am using Scald (7.x-1.1) to manage our media items. This means that when I attempt to GET a node (example.com/rest/node/25592) I get each field for the node in question nicely wrapped in JSON but for the image instead of an image path and file-name I get the Scald ID as follows:

field_event_image: {
und: [1]
0: {
sid: "15775"
}-
-
}

How can a client application reference the image path from the SID? I know I can use example.com/atom/15775 but this gives me back a themed node page containing the image - it contains the menu and default theme elements so it is not trivial or efficient to retrieve the image path from the source - though it could be done with some client side parsing. What I am looking for is a means to reference the image path directly using the SID. I am trying to keep the number of API calls to a minimum. Alternatively is there some way to configure the Services module to return the image path?

Found a way – this is how to retrieve image url and image html from given sid:

if(isset($vars['node']->field_teaserbild['und'][0]['sid'])) {

    $img = $vars['node']->field_teaserbild['und'][0]['sid'];
    $atom = scald_atom_load($img);
    $image_uri = $atom->base_entity->uri;
    $vars['img_style_url'] = image_style_url('my_img_style', $image_uri); // style_url
    $vars['img_html'] = theme('image_style', array('style_name' => 'my_img_style', 'path' => $image_uri)); // html

}

Just in case somebody is still hoping for an answer…


Render form in template I have made the following .tpl.php template:

<?php print drupal_render($element["term"]); ?>
<?php print drupal_render($element["search"]);?>
<?php print drupal_render($element["advanced_search"]);?>
<?php print drupal_render_children($element);?>

But the form tag is not generated, so the form cannot be submitted ... what am i doing wrong?

You can add search box in a preprocess function in your template.php:

<?php
/*
 *  Preprocess page.tpl.php to inject the $search_box variable back into D7.
 */
function MYTHEME_preprocess_page(&$variables){
  $search_box = drupal_render(drupal_get_form('search_form'));
  $variables['search_box'] = $search_box;
}

Then you just need to print the variable in your page.tpl.php:

<?php print $search_box; ?>


How do I add drupalSettings info from an AJAX callback I have a custom Drupal 7 module that does a zipcode lookup to return town and county. I set Drupal.settings.zip_code_success to true within the callback. This is the code I am using.

drupal_add_js(array('zip_code_success' => TRUE), 'setting');
$commands = array();
$commands[] = ajax_command_html('#triage_city', $out);
return array(
  '#type' => 'ajax',
  '#commands' => $commands,
);

The zip_code_success value is then available in some processing code that runs on the js side.

In moving things to Drupal 8, the lookup and html replacement are working fine, but I can't figure out how to get the zip_code_success info into drupalSettings.  drupalSettings gets set up in the the initial page generation and shows within the DOM with the values that are passed initially through the hook_preprocess_html function.  I've tried a variety of things in the zipcode lookup function but haven't been able to update drupalSettings.  Here's the current D8 code snippet comparable to the D7 above:

$response->addCommand(new SettingsCommand(['zip_code_success'=>TRUE] ,TRUE));
$response->addCommand(new HtmlCommand('#triage_city', $out));
return $response;

I've also tried:

$response->setAttachments([
  'library' => ['core/drupalSettings'],
  'drupalSettings' => ['zip_code_success' => TRUE]
]);
$response->addCommand(new HtmlCommand('#triage_city', $out));
return $response;

Any wisdom as to how to handle this situation?

In Drupal 8, as you've discovered, drupal_add_js() has been removed.

There are two things you need to do this:

1) You cannot add JS in an ajax callback. It was a bad practices in D7, and cannot be done at all in D8. You'll need to add the JS in your form definition, not the ajax callback.

2) You add JS through a two-step process. The first is to create a new library in the *.libraries.yml file. Add a dependency to core/drupalSettings`. Then, in your form definition, you add your setting like this:

$form['some_element'] = [
  '#markup' => '', // required to render the element
  '#attached' => [
    'libraries' => [
      'some_library', // The library you created
    ],
    'drupalSettings' => [
      'modulename' => [
        'zip_code_success' => TRUE,
      ],
    ],
  ],
];


How to list all nodes attached to a vocabulary? I have a custom vocabulary called "healthcare_terms" that has enabled terms attached to a custom content type called "health_posts".

I just want to find all nodes that are tagged with enabled terms from "healthcare_terms"

I tried the following but it does not seem to be working.

   $query = \Drupal::entityQuery('node')
      ->condition('type', 'health_posts')
      ->condition('status', 1)
      ->condition('field_tags.entity.name', 'healthcare_terms');
    $ids = $query->execute();

Clearly I am lost. Any help or tips?

Thanks guys

Are you sure that you are using the tags field for this?

You're filtering on the term name, but you want to filter on the term vid instead:

 $query = \Drupal::entityQuery('node')
  ->condition('type', 'health_posts')
  ->condition('status', 1)
  ->condition('field_tags.entity.vid', 'healthcare_terms');
$ids = $query->execute();

If you have a standalone field that only allows terms from your healthcare_terms vocabulary, which is usually the better approach, then you can just look for ->exists('field_something').


How to remove the status bar from CKeditor? It seems that the module CKeditor doesn't offer in the UI the option to remove the status bar which includes the HTML path (eg: body p strong) and the re-size button.

I managed to remove the status bar for a profile (admin/config/content/ckeditor/edit/some_profile) by adding this code in Advanced Settings > Custom JavaScript configuration :

config.removePlugins = 'elementspath';
config.resize_enabled = false;

Code found here on the CKeditor forum.


Domain Access: Subdomain -> same views-path - different view? I am a beginner by module domain-access and have a question.

standarddomain: example.com
subdomain: m.example.com

In my standarddomain i use a views-page with path example.com/myviewsgallery (Views A) - this viewspage show 50 results, has a special pager and so on.

On my subdomain I need the same path m.example.com/myviewsgallery but here I will use an other (minimized) Views (Views B) with reduced results and other pager (and so on). The mobile version is intended to display reduced content.

I would like to use a mobile-switcher that automatically redirects the mobile user to the mobile subdomain - to the same path as on the desktop version.

But the problem is, I cant use a other (reduced) View-Page on my mobile-subdomain which has the same Views-path like standardomain.

At the moment:

example.com/myviewsgallery (show Views A)
m.example.com/myviewsgallery (show Views A too, but i need Views B
under this path)

Is there anyone here who can tell me how to solve this problem?

Excuse me my bad English, I hope nevertheless that I could bring the problem understandably.

Many thanks in advance
Matthias

Based off @Sugandh Khanna answer, follow these steps:

Make View 2 as an attachment and attached to View 1.
In mobile view, add the css .view-content {  display: none  }
In desktop view, add the css .attachment {  display: none  }


Views Slideshow vs list View+jquery cycle lite? The rotating images on my work site's home page are created as a View in list format. I'm using the jQuery Cycle Lite plugin for the rotator effect. The cycle.lite.js file is set in the scripts array in my theme's .info file, and there's a bit of code in page.tpl.php to check whether this is the homepage, and if so, set up the rotator.

Now I'm working on a second rotator for another section, and I've been trying out the Views Slideshow module.

What are the pros & cons of each approach (theme vs module), especially from a server load or page weight point of view?

I personally try to avoid using any Views jQuery modules for popular jQuery plugins and prefer just to add the jQuery plugin directly to my theme by adding the .js file to my theme.info file. I will then create another .js file that runs on load that instantiates the jQuery plugin.

I use Semantic Views module which allows you to tune the output of the view to your liking. I will use this module to output the markup in a compatible format for use with the jQuery plugin.

I find that if you use a Views plugin module for something like jQuery Cycle or jCarousel for example, you are limited by the options exposed by that plugin. I prefer not to rely on a 3rd party module which may not support the latest changes or all the features of that latest jQuery plugin.

I would expect there would be a very minimal overhead using if any at all using a Views plugin instead of using the jQuery plugin natively.


Searching by sku number but some products and new product are not showing using search api drupal 7 Some products are showing by sku number but some products are not showing.please someone help me to solve this problem.

This is probably due to indexing by the search module. You need to run cron in order to build the search index.


Is it possible to create/manage Roles using a .yaml file? I'm trying to secure some REST URLs that are present in my ApiController.php so that users with certain privileges can access these REST APIs.
I created some users and assigned them with some Roles using the below link:

https://www.drupal.org/docs/user_guide/en/user-concept.html

As you can see, I'm creating roles in Drupal Admin following below steps:

Drupal UI → People → Role → Add New Role     // line 4

After that, I added a few permissions in permission.yml:

xyz.permissions.yml

edit permission:
  title: 'edit permission'

And updated routing file to secure APIs:

xyz.routing.yml

xyz.update:
  path: '/update'
    _controller: 'ApiController::update'
    _permission: 'edit permission'

This is working fine. i.e. users that have "edit permission" can access URL "/update".
But, I don't want to do step on line 4 rather I would like to use some .yaml file to create Roles.

User roles are defined in YML files called user.role.ROLENAME.yml.

Do a config export (drush cex) to get an idea how these files should look like (they will be written to your config/sync directory).

Then create your custom role YML files in my_module/config/install and they will be created when you enable your module (if you took a YML file from config/sync as blueprint, remove the uuid and default_config_hash keys)

The file should look something like this:

langcode: en
status: true
dependencies: {  }
id: my_custom_role
label: My custom role
weight: 1234
is_admin: null
permissions:
  - 'do fancy stuff'


Is there a table listing contributed modules that have been ported to Drupal 7? To date I have found no quick way to determine which Drupal 6 contributed modules have been ported to Drupal 7.

Do you know of one, such as an automatically updated table that provides this critical site-building and version-selection information?

There is the D6 Upgrade Status Module that will list what modules installed on your system have modules in the D7+ versions of Drupal.


Path breadrumb crumb displaying just first letter of title I am using the module path breadcrumb, is it possible to create a crumb which displays just the first letter of the title?

Maybe it helps someone so I will respond my own question: It resulted to be very easy using the module custom tokens with the following code:

    <?php
$node = node_load(arg(1));
$title = $node->title;
$rest = substr($title, 0, 1);
return $rest;
?>


How can I set some checkboxes to selected upon the first loading of the form? I have a form with checkboxes.

$form['my_checkboxes'] = [
    '#type' => 'checkboxes',
    '#options' => ['1' => 'one', '2' => 'two', '3' => 'three'],
];

And for example, I want to option '1' is selected upon form was loaded.

Could you clarify me, how can I set some checkboxes to selected upon the first loading of the form ?

Unfortunately, I couldn't find the solution in the examples module.

Use a #default_value:

$form['my_checkboxes'] = [
  '#type' => 'checkboxes',
  '#options' => ['1' => 'one', '2' => 'two', '3' => 'three'],
  '#default_value' => [1, 2],
];


KernelEvents::REQUEST is not fired on cached pages I am trying to implement a KernelEvents::REQUEST event subscriber to perform some action on page load.

I need this event to fire regardless of whether the requested page exists in the Drupal cache - it seems that KernelEvents::REQUEST does not fire when Drupal serves something from the cache.

Is there an event I can use to achieve this, or must I implement my requirements as some form of middleware?

The dynamic cache subscribes an event with priority 27. If you want that your code runs before that you have to use a priority >27:

  public static function getSubscribedEvents() {
    $events = [];

    // Run after AuthenticationSubscriber (necessary for the 'user' cache
    // context; priority 300) and MaintenanceModeSubscriber (Dynamic Page Cache
    // should not be polluted by maintenance mode-specific behavior; priority
    // 30), but before ContentControllerSubscriber (updates _controller, but
    // that is a no-op when Dynamic Page Cache runs; priority 25).
    $events[KernelEvents::REQUEST][] = ['onRequest', 27];

Which runs DynamicPageCacheSubscriber::onRequest..


How do I set the path to a custom view style template? I have created a custom view style in a module. It shows up in the list of view styles, but when I try to output the resulting block I get the message:

Warning: include(/var/www/core/modules/views/templates/mymodule-list.tpl.php) [function.include]: failed to open stream: No such file or directory in theme_render_template() (line 1491 of core/includes/theme.inc).
Warning: include() [function.include]: Failed opening '/var/www/core/modules/views/templates/mymodule-list.tpl.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in theme_render_template() (line 1491 of core/includes/theme.inc).

This obviously is trying to find my view template in the templates folder of the view module, but I want it to look in /sites/default/modules/mymodule/templates/.
My plugin class annotations look like this:
/**
 * Style plugin
 *
 * @ingroup views_style_plugins
 *
 * @Plugin(
 *   id = "mymodule",
 *   title = @Translation("My Module"),
 *   help = @Translation("Help text"),
 *   theme = "mymodule-list",
 *   path = "sites/default/modules/mymodule/templates",
 *   type = "normal",
 *   module = "mycarousel"
 * )
 */

I have also tried setting the path in hook_theme:
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule' => array(
      'variables' => array(),
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
      'theme' => 'mymodule-list',
      'theme path' => drupal_get_path('module', 'mymodule') . '/templates',
    ),
  );
}

Can anyone see what I'm doing wrong?

I think instead of path = "sites/default/modules/mymodule/templates" you should have theme path = "sites/default/modules/mymodule/templates".


display a view in admin theme I have a custom view for editing contents for the authors. When I'm logged in as a use with this author role this view is displayed with the 'frontend' theme. But I need it displayed in 'backend' theme.

I absolutely don't know how to get this view displayed in another theme.

Go to Admin -> People -> Permissions & search View the administration theme check the checkbox for author role. Check screenshot below:


Add fields to image upload option in CKEditor I make SVGs using LaTeX and would like to upload both the image and its LaTeX source code when I attach an imagine via CKEditor. I don't want the code to be displayed, just stored with the image so that I can change it later if I need to, or use it as a reference for making more images.

There are already some default fields for images in the upload widget, such as alt-text and caption, so this seems possible. I just want another field called "source" where I can dump the LaTeX.

Caption and alt text are not a good example because they are stored where the image is used, not together with the file entity. What you are looking for is File Entity to store the source data in a field of the image file. For new projects you shouldn't use it anymore, because it is deprecated in favor of the Media entity. Media is now in core and when the module is enabled you can add fields directly to the media type Image (/admin/structure/media/manage/image/fields).

Out of the box CKeditor does only provide a button to add file images, which you want to replace with Media. To add media types you need the module Entity Embed until this feature is integrated into core.


Skip required body field validation It's possible to skip required body field validation, if it's empty? I can add custom validation on the first place, like:

  $form_validate = $form['#validate'][0];
  $form['#validate'][0] = 'remove_body_field_validation';
  $form['#validate'][] = $form_validate;

function remove_body_field_validation($form, &$form_state) {
 $form_state['complete form']['settings']['body_field']['body']['#required'] = FALSE;
}

But i think the "required validation" runs before "remove_body_field_validation"?? :-/

Why don't you simply go to Structure -> Content Types -> [Your type] -> Manage Fields -> Body -> Edit uncheck "Required field"? Since Drupal 7, body behaves as any other field...

If you really need to do this in code, then you do it in form_alter like this:

function [mymodule]_form_alter(&$form, &$form_state, $form_id) {
  // some logic here to filter which form is affected (or use hook_form_FORM_ID_alter)
  $form['body'][LANGUAGE_NONE][0]['#required'] = FALSE;
}

Is there any particular reason for you to do it during validation and not on form render? You stated that you need to "skip required body field validation, if it's empty" which is equivalent to turning the "required" completely.

EDIT:
I found a way to do this (based on this - https://api.drupal.org/comment/28464#comment-28464):

function my_validate($form, &$form_state) {
  $errors = form_get_errors();

  if ($errors) {
    // Clear errors.
    form_clear_error();
    // Clear error messages.
    $error_messages = drupal_get_messages('error');
    // Initialize an array where removed error messages are stored.
    $removed_messages = array();

    // Remove all errors originated by the 'foo][bar' element.
    foreach ($errors as $name => $error_message) {
      if ($name == 'body][und][0][value') {
        $removed_messages[] = $error_message;
        unset($errors[$name]);
      }
    }

    // Reinstate remaining errors.
    foreach ($errors as $name => $error) {
      form_set_error($name, $error);
      // form_set_error() calls drupal_set_message(), so we have to filter out
      // these from the error messages as well.
      $removed_messages[] = $error;
    }

    // Reinstate remaining error messages (which, at this point, are messages that
    // were originated outside of the validation process).
    foreach (array_diff($error_messages['error'], $removed_messages) as $message) {
      drupal_set_message($message, 'error');
    }
  }
}


When a node has multiple locations (using location cck), is it possible to filter location results in views based on only one field? I have a content type with multiple location types attached:

loc_past (Places I've been)
loc_now (Where I am now)
loc_future (Places I'm going)

When I create a view that shows nodes of the content type, the node is shown once for each location in each field.  However, I would like to limit the results to one field (for example, show results only for where users are now).

Is there a way to configure Views/Location to do this?

Upon further research, I have discovered that no, this is not possible.  It's just not the way location is currently implemented; if a node has multiple location fields, they are all "seen" as a single field.


What could cause the Features create page to time out? The site I'm working on is timing out when I try to open the admin/structure/features/create page. I'm not experiencing the problem elsewhere in the admin, just there. What does this page do differently that might take more time?

On a related note, does anyone have any tips for determining what Drupal component/module is causing a slowdown aside from "turn everything off and see what happens"?

The features UI can be notoriously slow for large Drupal sites. We recently experienced a ~50 second delay in loading the aforementioned page (create a new feature). The reason why (after debugging it all) was it was loading every single menu item on the site (>3000 of them) and trying to render a checkbox for every single one.

I posted a simple workaround on drupal.org https://drupal.org/node/1153028 - it looks like my patch will never get accepted in features, but at least it got the module maintainers looking at the performance issue.

On a related note, you do not need to use the GUI in order to create a feature. With large Drupal sites I would recommend using drush only as it has the advantage of being much faster. Please see https://drupal.org/node/960926 for more details.


How can I edit the string "Send this user a private message" in Privatemsg Is it possible in the Privatemsg module (7.x-1.3) to edit the string "Send this user a private message" to something else without directly editing the modules code?

Have you tried String Overrides module? Here is a quote about it (from the module's project page):

... a quick and easy way to replace any text on the site.
Features:

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


Make variables created in preprocess_page hook available to content type templates I'm attempting to render a block plugin programmatically in a content type template. I understand how to render the block programmatically in a page template. like so

mytheme.theme

function mytheme_preprocess_page(&$variables){
    $myblock = \Drupal::service('plugin.manager.block')->createInstance('myblockid',[]);
    $variables['myblock'] = $myblock->build();

page.html.twig

{{ myblock }}

However in

node--contenttype.html.twig

{{ myblock }}

Produces nothing. Is there another hook I should be using? Or is there a better way to do this entirely?

I was able to accomplish this by placing the code into the preprocess node hook instead of the preprocess page. Like so

mytheme.theme

function mytheme_preprocess_node(&$variables){
    $myblock = \Drupal::service('plugin.manager.block')->createInstance('myblockid',[]);
    $variables['myblock'] = $myblock->build();


How to programmatically update node title? I would like to programmatically update some fields including the title of a node, when this node is saved.
To do so I am using a hook

function MY_MODULE_node_update($node) {
    $node->title = "Something new an beautiful";
    $node->filed_what_ever = "Something";
    field_attach_update('node', $node);
}

The problem is, that the title is not updated, I assume, that's because of the fact it isn't a field an the Drupal sense.
But I can not use

node_save($node);

instead, because that brings me in an infinite loop: the function hook_node_update() is called by the function node_save()... So what would be a clean why to do this?

To do this, you have to use hook_node_presave().

It's called before saving the node to the database. (both new nodes and edits).
Note that you must make sure that you are saving sanitized and formatted data.


Which newsletter module will fit my requirements? I'm trying to implement a newsletter for my users to subscribe to and I'm noticing that there are a lot of different newsletter modules out there. I'm was looking for one that will easily allow me to:

Send weekly newsletters with a summary of the top 5-10 posts from that week.
Allow me to have multiple newsletters for the different "Categories" of content on my site (I have a taxonomy term "Categories" which I would like my users to be able to pick which "Categories" they'd like to subscribe to).
Allow me to customize the look of the news letter.

I've already tried simplenews but can't seem to get it to do what I want. I feel that this may be beyond what it can do.

Try the Newsletter module. The features portrayed in the project page:

  Multiple newsletters lists configurable on existing terms.
  Plain text or HTML out of the box.
  Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new
  posts for this term.
  Centralized administration and configuration on a single page.
  Users can customize the terms in the list they subscribe to.
  Custom template per list.
  Statistics (CTR and Open-Rate).

It allows using HTML for the email (uses regular Drupal filters).


How to send mail based on date field? In a user profile I have start date and end date, I want to send the mail to user every months once based on the end date.

The end date also needs to get updated automatically, based on the start date i.e. every months from current date (start date).

Can anyone help me on this?

To achieve this you have to use Rules as well as Scheduler module. Please follow the documentation links: Rules documentation: https://www.drupal.org/documentation/modules/rules Scheduler documentation: https://www.drupal.org/node/108984

You can also refer: http://www.webwash.net/tutorials/how-send-follow-emails-using-rules-scheduler-drupal-7


drupal_set_message is visible only to those with permissions for the operation? API about drupal_set_message read:
"Set a message which reflects the status of the performed operation.
If the function is called with no arguments, this function returns all set messages without clearing them."

Does that mean, if the operation is not permitted for authenticated user or anonymous, then they cannot see the message but only visible to who has the permission to perform the operation?

No, it doesn't. It means that if you want to get the list of the messages set from other modules, you just call the function without any argument; this is what drupal_get_messages() does to get the list of messages set by the modules.

function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
  if ($messages = drupal_set_message()) {
    if ($type) {
      // …
    }
    // …
  }
  // …
}

If the message should be visible to users with a specific role, it is the caller that needs to first check the user's permissions with user_access() as in the following code, executed from comment_form_submit():

  if (!user_access('administer comments')) {
    drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
  }

This doesn't need to be done in a form submission handler, if who uses the form is already restricted to who has that permission.


Deleting nodes makes orphan records I have a content type "event" which has an image field.
I tried to deleted the nodes, but I got the repeated errors when deleted the nodes.

    Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 178 of D:\xampp\htdocs\mysite\includes\entity.inc).

I did not use any hook to delete nodes. I just deleted the nodes from the page "admin/content" by selecting "Delete selected nodes" in the UPDATE OPTIONS.

I checked the node related tables including field tables and I found that they were deleted as expected. When I tried to query the file tables, I found that some records were not deleted and the files in the file directory were not deleted too.

BEFORE DELETE

mysql> select * from file_usage where id = 41 order by fid;
+--+--+--+--+--+--+--+--+--+--+--+--+--++
| fid | module      | type | id | count |
+--+--+--+--+--+--+--+--+--+--+--+--+--++
| 30  | file        | node | 41 | 1     |
| 31  | file        | node | 41 | 1     |
| 32  | file        | node | 41 | 1     |
| 172 | file        | node | 41 | 1     |
+--+--+--+--+--+--+--+--+--+--+--+--+--++

mysql> select fid, filename, uri from file_managed where fid in (30,31,32,172);
+-----+------------------------------------+-----------------------------------------------+
| fid    | filename                        | uri                                           |
+-----+------------------------------------+-----------------------------------------------+
|    30  | Festival.jpg                    | public://Festival_0.jpg                       |
|    31  | Festival.jpg                    | public://Festival_1.jpg                       |
|    32  | Festival.jpg                    | public://Festival_2.jpg                       |
|    172 | Festival_465x350.jpg            | public://Festival_465x350_0.jpg               |
+-----+------------------------------------+-----------------------------------------------+

AFTER DELETE

mysql> select count(*) from node where type = 'event';
+----------+
| count(*) |
+----------+
| 0        |
+----------+

mysql> select * from file_usage where id = 41 order by fid;
+--+--+--+--+--+
| fid | module | type | id | count |
+--+--+--+--+--+
| 30 | file | node | 41 | 1 |
| 31 | file | node | 41 | 1 |
| 32 | file | node | 41 | 1 |
+--+--+--+--+--+

mysql> select fid, filename, uri from file_managed where fid in (30,31,32);
+-----+---------------------+-------------------------------+
| fid    | filename         | uri                           |
+-----+---------------------+-------------------------------+
|    30  | Festival.jpg     | public://Festival_0.jpg       |
|    31  | Festival.jpg     | public://Festival_1.jpg       |
|    32  | Festival.jpg     | public://Festival_2.jpg       |
+-----+------------------------------------+----------------+

They became orphan. What could that be why they are not deleted as expected?
Is there any fix for this?
My Drupal version is 7.15.

Incidentally, I got this error yesterday ;-) And after a bit of searching and looking into the documentation, I found that the cause was the functions which loads entities in Drupal and with the name like something_load(e.g. node_load()). I was using node_load() function to load the node and then delete it using node_delete_multiple().

This error was caused because, I was passing array as an argument to node_load(), by something like user_load(array("...; which is not the right way to do it.
The argument to anything_load() function must be a single id. So, you can search for the _load functions which uses array as an argument in your code.


Rendering a nested Paragraph's field using Twig We are using the Drupal 8 Paragraphs module and are have a Paragraph which contains a Paragraph type field, called "Steps" (machine name fs_steps), allowing editors to add a number of "Step" Paragraphs (machine name fss_steps) to the parent paragraph for rendering.

Within the twig file, we loop through the entities of the parent's Steps fields, but when we try to render a field of the nested Step paragraph field "Heading" using either (this code is within the context of a for loop):

{{ content.field_fs_step[key]['#paragraph'].field_fss_heading }}

or

{% set step = content.field_fs_steps[key]['#paragraph'] %}
{{ step.field_fss_heading }}

It fails with the following error:

Exception: Object of type Drupal\Core\Field\FieldItemList cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 476 of core/lib/Drupal/Core/Template/TwigExtension.php).

Here is our current code that successfully retrieving the "values" of the bested paragraphs' fields, but does not end up using the renderer (which would respect the field's formatting types) as we need (this is a rudimentary example retrieving text values, but in other cases we want to render more complex data such as links and images):

        {% for key, item in content.field_fs_steps if key|first != '#'%}
                    {% set step = content.field_fs_steps[key]['#paragraph'] %}

{{ step.field_fss_step_marker.0.value|raw }}

{{ step.field_fss_heading.0.value|raw }}

                            {{ step.field_fss_description.0.value|raw }}

                {% endfor %}

We're looking for help in understanding the following:

Why is it that the renderer triggers when calling a top level field against our parent Paragraph, such as {{ content.field_fs_heading }}, but attempting to render a subproperty of the "content" object or rendering a field of a referenced entity, generates an error?
If we are taking the wrong approach to "nested paragraphs", and/or how to render sub-entity fields properly from within the context of a Twig file? Do we need to (as a guess) create a separate template for the nested paragraph template? If so, how would we then pass in the contextual content data to that "partial" and have it properly render there?

For nested / referenced paragraph rendering, it's probably best to use a separate template as you theorized above by stating "Do we need to (as a guess) create a separate template for the nested paragraph template?"
A general rule of thumb for Twig rendering is, if you are starting to dig that far down in a render array in a given template, best to use the next template inline in the chain.
in addition, In Drupal 8 Paragraphs, there is a nice API function for referenced paragraphs called getParentEntity().
  public function getParentEntity();

  /**
   * Set the parent entity of the paragraph.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $parent
   *   The parent entity.
   * @param string $parent_field_name
   *   The parent field name.
   *
   * @return $this
   */

I wrote a blog post dedicated to that here: https://www.dannyenglander.com/blog/drupal-8-architecture-how-to-get-a-value-from-a-paragraphs-parent-entity/
The bottom line is, you will look at Twig template debugging and see the referenced paragraph template suggestion in the output. Then you can use that template with some preprocessing to pull any data you need from the parent paragraph entity. A common use case for this might be some kind of setting like a boolean in the parent entity that you need to pass to the referenced paragraph entity / template.


How to add other types of dynamic attributes in the BODY tag? i have this code to include node-ID attributes to the body tag on the page. My question is ... how can i modify this code to get additional dynamic attributes for the BODY class? The most important for me are classes for the current vocabulary and taxonomy term, possibly a panel page.. I has been searching for few days and found only solution for node-ID.

Thank you many times for help.

 /**
 * Implements hook_preprocess_html().
 */
function enar_preprocess_html(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  if ($node) {
    $variables['attributes']['class'][] = 'page-node-' . $node->id();
    if (empty($node->get('body')->value)) {
        $variables['attributes']['class'][] = 'no-padding-main-content';
    }
  }

   // Don't display the site name twice on the front page (and potentially others)
  if (isset($variables['head_title_array']['title']) && isset($variables['head_title_array']['name']) && ($variables['head_title_array']['title'] == $variables['head_title_array']['name'])) {
    $variables['head_title'] = $variables['head_title_array']['name'];
  }

  // Preloader configuration
  $preloader = theme_get_setting('preloader');
  $variables['attributes']['class'][] = $preloader;
  $variables['preloader'] = $preloader;
  // Go to top configuration
  $goto = theme_get_setting('gototop');
  $variables['goto'] = $goto;
}

I think, i found the right solution below:

  if ($node) {
    $variables['attributes']['class'][] = 'page-node';
}

  if ($tid) {
    $variables['attributes']['class'][] = 'term-page';
}

  if ($tid) {
    $variables['attributes']['class'][] = 'term-page-' . $tid->id();
}


Views/Views slideshow confusion I am trying to create a slideshow that would be showing 3 instances of my custom contant type "Slideshow Image".
After spending hours without any success I've decided to seek help! I noticed that Views changed a lot when I updated all modules, and it seems as if Slideshow is not among the options for display under "Format" in the control panel of my view. I have Grid, HTML list, Jump menu, Table, Unformatted list but no slideshow. Now, I think I remember seeing "slideshow" as an option before "Views" changed! My questions are:

Have Views changed so that Slideshow is no longer an option for display? Am I going insane?
If it has, what is the new way of doing things?
If it hasn't, what could I be doing wrong?
There is a module called "Views Slideshow". It seems to not be fully ready for Drupal 7 yet. Do I need it? Is that my only option (as a Drupal & web programming newbie)?

Can anybody please help me clear this out?

Views Slideshow does not come with the views module. Therefore you will not see it by default.  You have to download and enable the views_slideshow module to see this option.

There is alot of other contrib slideshow modules as well

Related modules

Views Slideshow Menu
Views Slideshow Slider
Views Slideshow Imageflow
Views Slideshow Dynamic Display Block  (My Favourite of this list)
Views Slideshow Galleria
Views Slideshow JCarousel Thumbs
Views Slideshow Xtra

Most of these module does not have a supported Drupal 7 version,  however most of their Drupal 7 dev version will be stable enough to use.  I know I have used views_slideshow_ddblock without any troubles.


Programmatically render a custom form in a view template while passing view argument to form I have built a custom form (in its own module using FORM API) and have exposed this form also as a block using Plugin API.

I can add this form fine to page and get it to render using Block Layout but it doesnt appear in the correct place.

I am trying to get it to appear in the main page content of a Page View which has a Header and Footer. The form seems to appear after the footer content, even after shifting the block around in the block layout.

So now I have been trying to use the various view template hooks by loading the form via the snippet:

$block = \Drupal\block\Entity\Block::load('auctioncataloguerequestform');
$block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
$variables['form_auction_cat_request'] = $block_content;

auctioncataloguerequestform is the machine name of the "form block" added to Block Layouts (Its in the content section, but disabled)

But in XDebug I cannot find the form_auction_cat_request variable and {{ form_auction_cat_request }} renders nothing.

Hooks I tried using where: template_preprocess_views_view, template_preprocess_views_view_field and template_preprocess_views_view_unformatted

At the moment I am simply trying to get the form to render but once this is done I then need to pass a string variable which is a field of the view in question to be passed to the form.

Am I on the right track or completely missing the mark?

View screenshot

Print form before the views:

function mymodule_preprocess_views_view(&$variables) {
  $form = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\DefaultForm');
  $variables['attachment_before'][] = $form;
}

===

Another way is to add your custom form and the views in own controller (and route),

In views add filters and expose them, set exposed in block = yes (this will detach the form from the views),

in exposed filters settings set the names as they are in your form - for each one,

make your form to redirect on submit to the route passing the values as query params (?param_name=value&param_name2=value2), for multiple select or checkboxes params are in format: param_name[6]=6&param_name[17]=17

the rest will be done by views - it will get params automatically

Controller:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\views\Views;

/**
 * Class DefaultController.
 */
class DefaultController extends ControllerBase {

  /**
   * Content.
   *
   * @return string
   *   Return Content string.
   */
  public function content() {

    $elements = [];

    $elements['form_search'] = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\DefaultForm');
    $elements['form_search']['#weight'] = 0;

    $views_name = 'machine_views_name';
    $display_id = 'page_1';
    $view = Views::getView($views_name);
    $view->setDisplay($display_id);

    $elements['view'] = $view->render($display_id);
    $elements['view']['#weight'] = 1;

    return $elements;
  }

}

example module with controller, form and exported views "Content list": https://github.com/svetlio/mymodule


Can this PHP node leak memory? I have a Drupal 7 installation that apparently leaks memory somewhere. The memory usage of nginx is going up in production until the server fails. This started basically when I added a new node with PHP content to it. My PHP code does basically this:

<?php

global $user;
$token = uuid();
$uid = user_load($user->uid);
$myprofile = 'main';
$profile = profile2_load_by_user($uid, $myprofile);
$birth_date= $profile->field_birth_date['und'][0]['value'];

$conn = mysql_connect ("my.sql.server:3306/somedb", "user", "pass");
mysql_select_db("somedb", $conn);
mysql_query("INSERT INTO special_table (TOKEN, USER) VALUES ('$token','$user->name')");
mysql_close ($conn);

echo 'output some html based on birthdate..';

In addition I use memcached module. That custom DB connection that I have to open and do a single insert is not the DB of the drupal installation, that is going into a separate database. Surely not the nicest solution, but I guess that should not leak anything.

Do you see anything in this code that can possibly lead to memory leak?

It doesn't look like this is causing a memory leak as @tenken said in his comment.  However, since this is going in a node, that whole PHP snippet is stored in the database which isn't recommended.  It will take more memory to grab this code from the database, then run it.

Try sticking the code in a function in PHP file and then running that function somewhere else on the site, i.e. a custom module.  This is a good tutorial on how to do that.


Submitting a form added using ajax I am adding content to my page using file_get_contents (I'm rendering the content to strip all template html as in this example: https://stackoverflow.com/questions/247991/displaying-a-drupal-view-without-a-page-template-around-it).

Some of the pages have forms which should be submitted normally, as in the page should be validated and redirected after submission. However submission is not working. For example, if the page is at http://mysite.com/myform and pressing the cancel button should call myform_cancel() and redirect me to http://mysite.com/, I instead get redirected to http://mysite.com/myform?response_type=embed and no submit methods are called.

What do I need to so to make my form submit as expected?

Edit:
A similar thing happens when I instead render the form using menu_get_item to get the callback and arguments, then render the html using: drupal_render(call_user_func_array($menu_item['page_callback'], $menu_item['page_arguments'])). This time I am redirected to my 'http://mysite.com/ajax-form' which is my menu url to the ajax call used to return the html.

I was able to solve this using the following code:

function bikebike_ajax_form()
{
    if (isset($_POST['url']))
    {
        $url = $_POST['url'];
        $menu_item = menu_get_item($url);
        $form = call_user_func_array($menu_item['page_callback'], $menu_item['page_arguments']);
        if (isset($form['#action']))
        {
            $form['#action'] = url($url);
        }
        $html = drupal_render($form);
        die($html);
    }
    die('');
}

As you can see, instead of rendering the page using file_get_contents, I simply grabbed the elements from the function defined in hook_menu. I needed to change the 'action' parameter of the resulting form structure.

If anyone has a better solution to this problem, I'll happily give you the answer.


What are the alternatives for storing client side encrypted data? I want to store client side encrypted data in Drupal 7, so that it is encrypted on the client end, and stored and transmitted in encrypted form. The password is never transmitted or stored on the server.
The only modules I have found which do this are CSE and Text jQuery Encode RC4 (+CCK) but they are for Drupal 6.
I need something that is user specific, so that different users can use different keys, rather than a single key or a set of keys used on the server end.
Are there any similar modules for Drupal 7?

Personally I would not trust any JavaScript or Flash provided by operator to safely hide my data from him. How can I know if data is really encrypted on my side, or is it just a smoke and mirrors? Probably that's the reason modules like that was never popular - they simply can't be trustworthy, so why to bother developing them if hardly anyone will trust them?

And if user is technological enough to know if data was encrypted on his side or not, he would prefer the other way. There is a way that allows user to be sure their data was encrypted on their side:

Make user install FireGPG plugin, or something analogous for his browser, to be able to encrypt any text field with his tool, that's under his exclusive control, and developed by Open Source teams not connected to you.
On Drupal side, Field Validation should stop Drupla from saving data that does not look like PGP block. Clientside Validation should stop user from posting it in the first place, but you never know for sure with client-side mechanisms.
Secure Pages should mitigate the risk of accidental access to data if user will manage to send unencrypted despite clientside validation.


Export Drupal Commerce Checkout Settings I'm wondering if there's a way to export Drupal Commerce's checkout pane settings to code?  I've tried commerce_features but it doesn't appear to do it.

For other commerce related things, like payment rules, I've been able to export them using features and using hook_default_default_rules_configuration_alter to make sure only the proper rules are in place.

However for checkout I've not been able to find anything.

The checkout configuration is all managed via standard Drupal variables, so the Strongarm module with Features is all you should need. All variables in our modules will be prefixed with commerce_* and typically with the module name (e.g. commerce_checkout_*).


Where do I add imagemap in drupal 7 I'm using marinelli theme and the rotating images. Now, I'm looking to add usemap to some of the images, as the images are rotating images and are not within a specific node. Moreover, I'm adding the banners through admin->apperance->settings->marinelli->banner management. So, I couldn't add the usemap html tag within the body or some-other place as within blocks/nodes. I tried various ways to add but couldn't get any idea.

I have found some module jQuery Map Hilight, where i can add features to the usemap not really adding usemap to an image.

Is there any way to add usemap tag? Is there any way like adding some code in page.tpl.php?

As none of my attempts were working, I tried a completely new approach using views.

I've created a new content type named 'banner'. And in the body field, I've added an html img tag and map tag(for image mapping). Now, I've created a view with format as slideshow and field as content:body. Creating a block for this view and adding it in the advertise region (in marinelli theme) replaces the rotating banner image in Marinelli theme.

Before adding the view in advertise region, we need to disable the original theme banner. For this, goto admin->appearence->settings->marinelli->Banner configuration and choose 'Drupal region (advertise) for the question Do you want to use marinelli banners or a classic drupal region?


Views template files not working I have two template files for a view but only one of them is getting picked up.   If I look under the Theme dialog for the view I can see that my two theme files are bolded.

The Display Output template file is working but the Row Style is not working.  I've also added this to my template file to try try and get it to work but I don't think it's doing anything.

function mytheme_preprocess_views_view(&$variables){
  if ($variables['view']->name == 'travel_extras_hotel_carousel') {
    $variables['theme_hook_suggestions'][] = 'views_view_fields__travel_extras_hotel_carousel__block';
    $variables['theme_hook_suggestions'][] = 'views_view__travel_extras_hotel_carousel__block';
  }
  return $variables;
}

Does anyone have any ideas about what else I could do?

I'm using views 3.3

Best way to learn something new about your project is not to ask "what is going on" but do own investigation. Try to debug as much things as possible. You can start by enabling Theme debug mode This is great feature implemented as of version 7.33

As Drupal documentation states:

  As of Drupal 7.33, Drupal core has a theme debug mode that can be enabled and disabled via the theme_debug variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments).

Place $conf['theme_debug'] = TRUE; variable in your settings.php file and use Developer Tool (F12) in your browser or any other tool that can help you see source HTML markup.

With theme debug mode you will be able to see all template suggestions and what tpl file was chosen to rendering. If your tpl file is really rendered you should see something like:

<!-- BEGIN OUTPUT from '(...)/views-view--travel-extras-hotel-carousel--block.tpl.php' -->

This way you will discover the cause and learn something new about your Drupal project.

Remeber to clear cache (at least theme registry cache) after each change connected with template files. This assures that your theme "knows" about tpl file. The same applies to preprocess or hook functions.

Remove mytheme_preprocess_views_view - try to solve initial problem first.


How to modify block menu path My goal is to have a menu block on my blog pages with a list of the terms used in the blog posts. So far I have set up a node view for the blog postings. And a term view called topics to display the terms.

It's working, but when I click on a term listed in the block the resulting path is category/topics/term-name. I would like to have a path such as blog/topics/term-name or even better just blog/term-name.

I have looked at the Taxonomy menu settings under the taxonomy/edit/vocabulary but haven't figured out if I can change these settings to get what I want.

I'm using the Pathauto module. Not sure where else to look for an answer. I'm using 6.

Pathauto gives you the option of defining per taxonomy path patterns.  Just set the value for your blog categories taxonomy to blog/topics/[catpath-raw] and regenerate your aliases.  These settings are controlled in http://example.com/admin/build/path/pathauto


Search page shows empty fields of unpublished content How can I make a filter to my search page that hides unpublished content?

In filter criteria I only have global, indexed and search.

In your view, besides FILTER click on add, select Content Published (YES)


Commerce payment for Rooms reserveration only after the order is confirmed I want to use Commerce + Rooms and wonder if there’s a configuration/module for the following procedure:

User reserves a room, checks out, but isn’t allowed to pay yet.
The room owner gets an email and confirms/declines the order.
If confirmed, the user gets an email and can now start the payment process in the checkout.

Rooms offers an "enquiry mode" (instead of the mode for booking directly), but as far as I understand it, this only sends an email (no order is created), so this enquiry never reaches Commerce.

Maybe you want to look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site.
Here are some more details about this distribution (quotes from its project page):

... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online.
It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts.
Easy booking profile is powered by Drupal Rooms and Drupal Commerce - widely used and popular contributed decisions, which means active maintaining and timely technical support.


How to add content to a block? I have created a few blocks via /block/add and assigned these blocks to various regions defined in my theme.

How am I able to add content to these blocks?

If blocks are added via /block/add you can edit the block content via /admin/structure/block/block-content. Click on Edit and you should see a body text area appear. You can enter your block content there.


query to retrieve all translations and nodes of a language that has been removed from the system? I am experiencing an issue after a language has been removed from the system. Every time I go on the admin/content page on a drupal 8 site I get:

Error: Call to a member function getId() on null in Drupal\Core\Entity\Entity\EntityViewDisplay->buildMultiple() (line 254 of core/lib/Drupal/Core/Entity/Entity/EntityViewDisplay.php).

This is a known issue on drupal.org but it has not been addressed yet.
I am afraid this may be a recurring issue and I am trying to build something to clean up content causing the issue (i.e. the content language was removed from the system).

I am looking for a Drupal query that would return all the nodes(entities)/translations which has a language that has been deleted from the system. I can load all content and loop through them to check $entity->language() == FALSE or $entity->language() == NULL but that does not seem to be performant even with using the batch API. Ideally, db query that returns the IDs of the offending content would be much better.
Then I could update them to language neutral or delete the content.

I am wrote something that does something similar to the way node update translations after a language is deleted:

  /**
   * {@inheritdoc}
   */
  public function clearRevisionsLanguage(LanguageInterface $language) {
    return $this->database->update('node_revision')
      ->fields(['langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED])
      ->condition('langcode', $language->getId())
      ->execute();
  }

I repurposed the above to:

function some_helper_to_update_node_lang($lang_code) {
  \Drupal::database()->update('node_revision')
    ->fields(['langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED])
    ->condition('langcode', $lang_code)
    ->execute();
}

But the above function requires the language code, which is reasonable but I am not sure how to make this a more flexible in as much to return all content that has a removed language.

I ended executing this function to clean up the content:

function delete_non_existing_language_content() {
  // 1. Get enabled languages
  $languages = \Drupal::languageManager()->getLanguages();
  $lang_codes = array();
  foreach ($languages as $language) {
    $lang_codes[] = $language->getId();
  }
  // 2. Get all the nodes that have langcode not in the language list.
  $result = \Drupal::database()->select('node_field_data')
    ->fields('node_field_data')
    ->condition('langcode', $lang_codes, 'NOT IN')
    ->execute();

  // @todo think I can use fetchAllKeyed instead?
  $nids = array_keys($result->fetchAllAssoc('nid'));

  // 3.Delete all of them:
  // @todo Or possibly update them to language neutral code if possible:
  $storage_handler = \Drupal::entityTypeManager()->getStorage('node');
  $entities = $storage_handler->loadMultiple($nids);
  $storage_handler->delete($entities);

}

This worked for my use case, but I don't think it will be performant for large databases.


How to set field value in custom webform submit handler? In a custom submit handler, I want to set a field value for a text field (my_field_machinename) in my webform. The handler is getting called correctly, but the value is not getting stored. What do I have to change in the code below to make it work?
I know I could use the presave hook, but I would prefer to make the alteration within the submit handler.
class CustomHandler extends WebformHandlerBase {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $this->submitMyFieldData($form_state);
  }

  /**
   * Set my field values
   */
  private function submitMyFieldData(FormStateInterface $formState) {
    $formState->setValue('my_field_machinename', [['value' => '123']]); // Does not work

  }

}

Only now did I realize there is not only a submitForm method but also a presave method. I therefore changed my code as follows which is woking fine for me:
class CustomHandler extends WebformHandlerBase {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $this->submitMyFieldData($webform_submission);
  }

  /**
   * @param $webform_submission
   *
   * Manipulate data.
   *
   */
  private function submitMyFieldData($webform_submission) {
    $data = $webform_submission->getData();

    // to get a value from a form field
    $form_value = $data['my_field_machinename'];

    // to set the value of a form field
    $data['my_field_machinename'] = $form_value + 1;

    $webform_submission->setData($data);

  }


Toggling not working properly in node--contenttype.tpl.php file I am theming a node of type "test".
I am using toggling in this "node--test.tpl.php" file.

Below is my code in "node--test.tpl.php":

Property

    MLS #:

    <?php echo $node->field_listing_id['und']['0']['value'];?>

code in javascript file is

 (function ($) {
        $('#block1 > a').click(function()
       {
        $("#block1_content").toggle("slow");

         });

  })(jQuery);

Loading the java script files in template.php

drupal_add_js("themes/bartik/custom.js", $type = 'file', $media = 'all', $preprocess = FALSE);
drupal_add_js("themes/bartik/jquery.min.js", $type = 'file', $media = 'all', $preprocess = FALSE);

jqueries and jquery plugins are enabled in modules.

but toggling is not working.

How to do toggling using jquery

Try writing it when document get ready like this:

jQuery(document).ready(function ($) {
        $('#block1 a').click(function()
       {
        $("#block1_content").toggle("slow");

         });

  });


How can I trim a field's value for display? In Drupal 7, on a content type's "Manage display" tab, it was possible to trim strings to a particular length, by setting the field's format to "Trimmed".

For example, you could trim a long text field to 200 characters for the Teaser mode.

This doesn't seem to be possible in Drupal 8 – I don't have the option to set a custom-field's format to "Trimmed". (The only option available is "Plain text".)

Has the "Trimmed" format indeed been removed for custom fields? If so, is there a way to get it back?

Your field type needs to be Text (formatted, long).

Then on the display settings page, you can change the display format to Trimmed, and edit the settings (by clicking the gear) to change the character limit.


Calculate the sum for 3 CCK fields with Rules in Drupal 7 I have 4 stock fields (Stock 1, Stock 2, Stock 3 and TOTAL STOCK) and I want to set up a rule to calculate ["+"] the sum of Stock 1, Stock 2 and Stock 3 fields, and automatically appear in TOTAL STOCK field.

example -> http://ucreateawebsite.com/DRUPAL/dalexgrup/pt

What event, conditions and actions Should I use?

Thank you.

I found the answer:

For Event I used:

After updating an existing commerce product

For Conditions I used:

Entity has field

Parameter: Entity: [commerce-product], Field: field_stock1

Entity has field

Parameter: Entity: [commerce-product], Field: field_stock2

Entity has field

Parameter: Entity: [commerce-product], Field: field_stock3

Entity has field

Parameter: Entity: [commerce-product], Field: field_totalstock

For Actions I used:

Calculate a value

Parameter: Input value 1: [commerce-product:field-stock1], Input value 2: [commerce-product:field-stock2]; Provides variables: Calculation result for Stock1  and Stock2 (stock1_plus_stock2_result)

Calculate a value

Parameter: Input value 1: [stock1-plus-stock2-result], Input value 2: [commerce-product:field-stock3]; Provides variables: Calculation result for stock1-plus-stock2-result and Stock3 (stock1_plus_stock2_result_plus_stock3)

Set a data value

Parameter: Data: [commerce-product:field-totalstock], Value: [stock1_plus_stock2_result_plus_stock3]

You can see what I wrote on http://ucreateawebsite.com/DRUPAL/dalexgrup/pt.


Can we fetch the depth of taxonomy from term load Term::load (termid) can we get the depth of term. If yes how can we achieve ? If no, how can we achieve this without loading tree nor children is there any other way we can fetch depth?

You can use TermStorage loadTree function. It will load the whole tree and the depths of each term will be avaiable.
A much more cleaner / efficient way can be to use the "taxonomy_term_hierarchy" table, (database service, select..). You query over and over again till the "parent" (or current examined) term parent is 0.

If you really feel you are being lost, take a look on this thread.


"Configure Block" region highlight missing in Drupal 7 The usual region highlight (a dashed-line border around the region) with a little gear icon that opens up a drop down saying "Configure Block" is missing on my custom Drupal 7 site. Which or What admin option is responsible for this?

I am logged in an an administrator.
I have actual regions.
Those regions have data.
"Demonstrate Block Regions" shows where the regions are correctly.

How do I bring this highlighting back?

Contextual Links module is enabled.

This is my block.tpl-

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

<?php print render($title_prefix); ?>

<?php print render($title_suffix); ?>

<div<?php print $content_attributes; ?>>
<?php print $content; ?>

Make sure you have the Contextual Links module enabled.
If you're overriding the default block template in your theme, make sure you're printing the $title_prefix and $title_suffix vars; I forget which one, but one of those contains the markup for the contextual links javascript.


How to show the number og members views members views How do you show the number of members in a group using views please?

I had a look at this post bu unfortunately the relationship have changed in drupal og 7.2

How to show the count of members that belong to a group?

Many thanks for your help

It's look the same, please follow instructions from image:

Full image: http://i.stack.imgur.com/45olm.jpg


How get commerce order total(excl vat, exlusive dicount), vat price, discount price, order total(incl vat and discount) in rules? I am creating a rule on event "When checkout process is completed".
I want to send an email to the user when order completes.
In the email I want to send the following information

Order total price Exclusive discount and VAT
VAT price
Discount price
Order total Inclusive discount and VAT

But I don't see any token for these values. Only for the order total inclusive vat is available.

How will I display these values?

There appears to be a feature request for this in the Commerce issue queue.

This post here describes what you'd need to do to add this to your site.


Variables in template files In my .tpl.php template files, I have several links and names of external websites. I would like to print these as variables, which are defined in template.php. That way, if I have to change a link, I can just change it in template.php and have them updated in all my tpl.php files.

How can I do this?

 Steps I have tried

In this tutorial, it says you can define your variables in themename_preprocess_page(&$variables). You can then call them with <?php print render($page['your_variable_name']); ?>

However, when I try this, I  just get a message stating Notice: Undefined variable: page in include(). The variable also doesn't print.

Also, if I use this method, can I use my variable in all tpl.php files or just the page.tpl.php file?

If you create a variable in themename_preprocess_page(&$variables), it should could be accessed using the variable name itself. Example

function themename_preprocess_page(&$variables) {
  $variables['my_new_variable'] = "String value";
  $variables['my_new_variable_array'] = array(); // Some renderable array.
}

And then in your template you could simply print the first variable directly

<?php print $my_new_variable; ?>

And render the renderable array using the render() function:

<?php print render($my_new_variable_array); ?>

Note: The array keys become the name of the variable, so please make sure to use a unique name to the keys.


8.5.6 Update not being recognized I converted a Drupal 7.xx site to Drupal 8.x manually. Updated it to 8.4.5 and tried to use composer to update it to 8.5.6 (Latest stable release). I have the original site as the public_html/drupal site and the 8.4.5 site is at public_html/drupal8/drupal-8.4.5. Composer, then drush seemed to work, but when I take the site out of maintenance mode, log in as admin, "Reports" still say it is at 8.4.5. Commands: composer update --with-dependencies and drush updatedb (I actually use vendor/drush/drush/drush updatedb) drush cr drush sset system.maintenance_mode 0 drush cr

I searched the docs,  found a few suggestions elsewhere, but can't fix this.  The bot on StackOverflow, where I have not gotten any response, suggested I post it here.

Unless you created your site using composer create-project drupal-composer/drupal-project, Drupal core is not actually a dependency of your project; instead your composer.json file likely contains the line "name": "drupal/drupal". Effectively, your root composer file is the Drupal core package.

In this case you can only upgrade by manually downloading the new release.

See also: Why does "composer update drupal/drupal" not work?

Edit:

If you want to convert an existing D8 site to the composer-based workflow, the following steps should get you most of the way.

In a different location, use composer create-project drupal-composer/drupal-project:8.x-dev <my-new-site> to create the new project. (Confirm the removal of the existing git history, and if you are using version control, use git init; git add .; git commit to initialize the new repository.)
Look at the contrib modules installed in your current site's modules/ folder, go into the new project, and use composer require drupal/module1 drupal/module2 [...] to install them. (Any custom modules should be copied into the folder ./web/modules/custom/ in the new project.)
Copy the contents of your sites/ folder into the ./web/sites/ folder of the new project.
After backing up your database, go into your new project folder, and use vendor/bin/drush updatedb or vendor/bin/drupal upex to update your database with Drush or Drupal Console (both are installed by default).

At this point, your new project should be ready to serve the site; change your webserver configuration or symlinks to point at <my-new-site>/web (the web subdirectory, not the project folder itself).


Views - Filter "Content: Authored by" to show only content by anonymous users When filtering content in Views using the filter Content: Authored by, you get these choices:

For the username, I typed "Anonymous", which gave me the UID of 0.

However, when I click Apply (All Displays), I get this error:

There are no entities matching "(0)".

Is there a way to filter a view in Drupal 8 to only show content posted by anonymous users?


flex slider with unique links and no links I have a flex banner that displays images from a content type I have created for the banner. In my banner view I can only link the image to the original image, the banner page or nothing. My goal is to be able to assign links to some of the banners. For example link slide 1 to a basic page, slide 2 to an article and slide 3 to another custom type page. My googling skills seem to let me down here.

I know that you can meet these requirements on different platforms for example on magento you can use 'Magestore_BannerSlider' where for each banner you upload an image, set up the dates to display from X to Y, add a unique link to each banner or if left empty it is not linked.

I am interested if I can get similar functionality using Drupal.

To do that you can simply:

Add new text field to your content type and name it Link for example.
Add this field into your view, hide it by check 'Exclude from display' in views field settings and move it above your banner image field.
Open views settings for the banner image field, under 'Rewrite results
' section check 'Output this field as a link' and put replacement pattern for your link text field in 'Link path' input, e.g. [field_link].
Save your view and now each banner is linked to any path you specify in the Link text field or is not if you leave this field empty.


How to do user relations, and User editing only their content? Doing Drupal 8.6 is hard (I come from Laravel and Wordpress world).

I manage to do by myself OAuth token authentication with Vue, but I stopped on User relations and content-type. I know that where is programmer there is a way, but I just want to see what you do things then choose best option.

How can I, for example, create a friends system? With normal table structure is like this:

+----+--------+-----------+---------+
| id | sender | recipient |  status |
+----+--------+-----------+---------+
| 24 |   11   |    25     | [0,1,2] |
+----+--------+-----------+---------+

Is there built way in Drupal 8.6 to do it or should I get plugin? Or just do content-type Friendships with thse fields?

And when I allow user to create a Portfolio, the right way will be to create Content-Type Portfolio with Gallery field, and just give access to peoples to add nodes? How I can give User access to only edit or delete their own content?

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

Some basics about he Group module to be aware of:

Make sure you enable gnode, a submodule of the Group module.
For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

With the appropriate permissions configured, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user.
Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Drupal 6 database has mixed InnoDB & MyISAM. Need to fix before migration I have a Drupal 6 database with tables which are a mixture of InnoDB and MyISAM. I'm using the Acquia Dev Desktop stack. The core module and other tables created at installation are MyISAM, and the tables for modules I've since installed are InnoDB. I didn't think at this issue when I started this project, and need to move my Drupal site to a new dev. environment I created on WebEnabled. So I have a couple of questions:

Since my Acquia MySQL default settings are set to InnoDB, can I safely change this to MyISAM without causing problems within my site?
I tried using the DB Tuner module to change all my tables to MyISAM. It worked but then I checked the status report and it said that all those tables that were converted were now "mis-matches". I restored from a backup at that point. Am I going to have to uninstall all the contributed modules and re-install them as MyISAM to avoid getting mis-matched errors.

Thanks a lot.

Jason

You could use the backup & migrate module to backup your DB. Then take this text file (UTF-8) and change all MyISAM strings to InnoDB. Save it and restore this backup. Done.


how to pass variables from a views style-template to the row-template it invokes I created a custom style-plugin for views, and a corresponding style-template (my-style-template.tpl.php).
Similarly, I created a custom row-plugin for views and a corresponding row-template.

The style-template loops through the views-rows, and invokes the row-template on each row:

print $row;

What I am trying to accomplish:

The style-plugin defines certain settings in the $options variable, which gets passed to the style-template.  The row-template needs access to some of these settings.

My question:

Is there a way to pass variables from my style-template to my row-template?
For example, rather than invoking print $row from the style-template, is there some other way of invoking the row-template, which allows me to pass variables to the row-template?

Thanks very much!

You can't pass variables from one template file to another.  That is not how things work.

However, a general rule is that every template file has a corresponding preprocess function for creating the variables available in the template.

So, you need to figure out what preprocess functions are being called.  The Theme Developer module can help out with this.  The theme.inc file lists all of the preprocess functions that the Views module uses.

With those, the standard way of handling things is something like

function mymodule_preprocess_views_view(&$variables) {
  $view = $variables['view'];
}

Once you have the $view object, you have everything you need.  However, you often need to dpm($view) to figure out what is there and/or look at the default preprocess functions.


Adding CSS class to fields (Content Types) I added a new content type with some fields

I have a field to upload image, I want to add a CSS class to this specific field,
Should I done it via node-file.tpl.php

or via the dashboard and where?

Try out Field Formatter CSS Class module.

  allows you to set any text/list/option/taxonomy field to render as CSS
  class on the node. This enables the node author to select predefined
  CSS styling per node.


(Views) How to style an image field conditionally based on term I have a Drupal website in which there is a content type named Article. In that content type, there is a taxonomy field called "Topic" which is term reference field pointing to a vocabulary called Topics.

Example article URLs:

mysite.com/topic-term/the-article-title
i.e
mysite.com/books/100-days-around-the-world
or
mysite.com/culture/chinese-and-medicine

Every article has a main image field called "image". The problem starts from here.

I want to style the main image for the articles classified under the term "books" differently; i.e., I want the image to have greater height than width.

The only way that I could think to do that is to make a new view for it. I tried to make such a view, but it only rendered the first article of books. The following screen shot shows the View settings:

The real problem, indeed, I don't know a view that render the articles content page! When I contacted the theme author, for previous modification request, they told me to do it by coding in node--article.tpl.php! So I have only two ways:

Creating a view that could be able to render articles by the access way described above mysite.con/topic-term....
Using code in node--article.tpl.php that set conditionally a style for the field image if the article topic term equals to books.

I don't know how to get what I need using the two approaches.

Method 1. Use a node preprocessor
Add this to your theme's template.php, then clear the cache:

function THEMENAME_preprocess_node(&$variables) {

  // This only applies to content type 'article' in teaser view.
  if ($variables['node']->type == 'article' && $variables['view_mode'] == 'teaser') {

     // Find out if node has at least one tag and an image.
     if (isset($variables['content']['field_tags']) && isset($variables['content']['field_image'])) {

      // Map tags to style names.
      $settings = array(
        'apple' => 'medium',
        'banana' => 'large',
      );

      // Build an array of tag names.
      $tags = array();
      foreach ($variables['content']['field_tags'] as $k => $v) {
        if (is_int($k)) {
          $tags[] = $v['#title'];
        }
      }

      // For each mapping, check if the tag exists in the $tags array;
      // if yes, apply the style.
      foreach ($settings as $tag => $style_name) {
        if (in_array($tag, $tags)) {
          $variables['content']['field_image'][0]['#image_style'] = $style_name;
        }
      }
    }
  }
}

Note that we could also do something similar in node--article.tpl.php, but generally you want to keep code logic out of the template files.

Method 2. Use Rules and Field formatter conditions modules (no coding required!)
The example below will set the image style of field_image to 'thumbnail' in the node's teaser view if field_tags contains a term with an ID of 18.
The Field formatter conditions module an image style to be conditionally set based on the outcome of a rule. It involves creating a rule, then going to Structure > Content types > [content type] > Manage display and adding the condition in the configuration options of your display (in this case the "Teaser" display).
Note: This example only checks for a single term. To compare against more terms, add more "List contains item" conditions, one for each term.
Here is the rule:

Here are the formatter settings:


Establish relation between node and gmap marker I have a gmap module (https://www.drupal.org/project/gmap) view that serves the map of locations. I also have a list of those locations under the map. I need to establish a relationship - a class, a rel attribute, or something like this, based on the node id, so that when I click the marker, the correct element in the list can be identified.

I tried adding identification to the marker objects so that they can be related to the list items on click. I have tried the hook_gmap() and the theming preprocess functions to add an attribute to the markers and failed.

I have also tried to hook into the Google Maps marker events, but could not do it without overriding the native infobubble events, which I don't want to override.

The actual question:

How can I pass information to markers created with GMap, so that they can be aware of the node id? Some html attribute like class or rel would be ideal. Adding it as a part of icon image path, like image.jpg?nid=1111 would also do the trick.

I suggest you to use this module to create views related to your nodes to create gmap with markers:

https://www.drupal.org/project/ip_geoloc