The 'drupal' way to implement delete button UI I think I'm missing something fundamental here. What's the 'right' way to implement a delete button on the UI-end?

My app has a classic list-type data model: User has wishlist(s) -> wishlist has item(s) -> item has properties. (These are represented in several tables, of course).

The several views are loaded via tpl files using hook_theme(). When the app has a view loaded for any step of the way (looking at an item in a list, for instance) I want to have edit/delete buttons that act on the item.
The CRUD methods are in place, they just need to be wired to the button.

In some places in the app, I've exposed methods via hook_menu(), and that works fine by passing the target to l() - I'm using this for many of my "View Item" UIs. Is there another way, though? This seems to be exposing a ton of core logic to the address bar if I keep going that route.

In a nutshell: How do I have a button action similar to pseudocode button.click=$this->bluenose_app_remove_available_property($property->id);? Preferrably without routing through hook_menu()

What you listed is what we normally do.

A menu router item (what you define in hook_menu actually serves a lot more than just pointing logical actions to functions/methods. It also makes sure than the items exist, they are accessible, and delivered correctly.

In hook_menu, you can definite how the access should be granted (with permission system or anything else). You can use wildcard loaders to load items, so you don't have to throw 'page not found' errors yourself.

You don't have to put your logic in the URLs. If you deal with entities, have your entity build the operation URLs, so they become part of your entity class, and not part of the template (the "View" of traditional MVC).

When the entity gets complicated, I often end up writing a single menu router to handle them all. The operation argument of a menu path (edit, delete, clone, disable, etc) can be a wildcard loader as well, and you can easily validate it using a method_exists() call.


Colorbox module has no effect I'd like to use the colorbox module to show the images in my nodes which are comming from flickr.

I'm using the flickr input filter which works fine. Now I'd like to get a colorbox to show one image after the other when the user clicks on one of the images of a set.

I installed the colorbox module and the jquery plugin. If I look at the HTML source file everything looks ok, but clicking on the images leads to flickr instead of opening a colorbox. According to the docs of the flickr module, colorbox support should be built in.

Any ideas what's missing?

You can see the non working page at my blog.

I am not familiar with the flickr integration, but in the included colorbox.js file, it appears that colorbox is looking for images with the .colorbox class.

Have you tried adding the .colorbox class to the img elements in that view? It's possible that the class may have beren removed by a drupal filter.

The relevant Javascript:

 $('a, area, input', context)
      .filter('.colorbox') // target class
      .once('init-colorbox')
      .colorbox(settings.colorbox);
  }


views query alter not working when view appears in sidebar I have a block view, and I want to change my query, to add contextual filter. I made a views query alter but when the view appears in sidebar as block view this function doesn't work.

function bpm_views_query_alter(&$view, &$query) {
   if ($view->name == 'single_job' && $view->display_handler->display->id =='block_1' ){
      $nid = _get_job_nid_from_url();
      $query->where[1]['conditions'][2]['value'] = $nid;
   }
}

If I add the same block view in page content then views query alter work as expected. The page is created by page callback and this is following code how i add block view in page content

$output = views_embed_view('single_job', $display_id = 'block_1', $category);

I think you problem is there that $nid not passed correctly,edit your views, instead of your filter, set filter by contextual filter then in your page passed it by contextual filter parameter with

$view= views_embed_view('single_job', $display_id = 'block_1', $category);
$view->set_arguments(array($node->nid));
$output = $view->preview();
print $output;

not longer  need query alter function

/*
function bpm_views_query_alter(&$view, &$query) {
  if ($view->name == 'single_job' && $view->display_handler->display->id =='block_1' ){
    $nid = _get_job_nid_from_url();
  $query->where[1]['conditions'][2]['value'] = $nid;
 }
}*/


Custom view with selective PDF output I'm hitting a blank, I need to be able to offer a print option on some views (a pdf) and not on others.

Does anyone have an elegant way of doing this?

Thanks for looking, I appreciate your time.

Take a look at the Views PDF module.  It will allow you to add a "PDF" display to the views you choose.  From the project page:

  With this module you can output a view as a PDF document. Each field
  of the view can be placed on the PDF page directly in the
  administration interface. Therefore a new display called "PDF" is
  added.


How can a module detect when the "access denied" page is output? How is it possible for a module to detect when Drupal is outputting the "access denied" page?
I know how to do it with Drupal 6; I need to know how to do it with Drupal 7.

You can set which pages are displayed when 403 & 404 errors occurs (admin/settings/error-reporting).

I guess you can add a new page in your hook_menu(), then set this page as the 403 error callback. When your custom menu callback is hit, you know you're outputting the "access denied" page!


how to test if a node is flagged in twig I would like to know how to test if a node is flagged.

In D7 : if ($ flag-> is_flagged ($ node-> nid)) But I discover D8 and I do not see how to do it with twig

thank you in advance

Write a function with hook preprocess_node in your custom module and set a custom variable isflagged ture or false
then check this variable in your twig file node is flagged or not
like

/**
 * Implements hook_preprocess_node().
 */
function yourModuleName_preprocess_node(&$variables) {
  $node = $variables['node']; // Just in case you need it

  if($variables['node']->getType() == "yourNodeType") {
    // your code
    if ($flag->is_flagged ($node->id())){
      $variables['isFlagged'] = true;
    }else{
      $variables['isFlagged'] = false;
    }

  }
}

now in your twig

{% if  isFlagged %}
  //do some thing
{% endif %}

hope this helps you


Drupal's 7 sites folder with its mysterious permissions and ownership The problem is that I had to give sites directory and all subfolders and files of it permissions 777 in order for drupal to recognize this folder and not redirect me to install.php page. But on a virtual hosting I noticed that sites is a protected folder and all of its content esspecially sites/default/settings.php with 550 permissions. I did not get the magic trick here, how does drupal recognized that folders. I have created drupal's folders and files both as root and other sudo users, but it did not help. And drupal still see only sites with 777 permissions.

You need to insure that the php process (web server) is a member of the group for the Drupal files.  You should make sure that the owner of the files is some user other than the php process / web server, because you do not want to allow the web server to overwrite the Drupal code files.

To change the group of all of the files in your root:

sudo chgrp -R webgroup /path/to/drupal

To add a group to the web server user:

sudo usermod -a -G webgroup www-data

For more advice on correctly setting file permissions for Drupal, see Securing File Permissions and Ownership.

Edit: It was suggested that this answer be expanded to point out that the above page contains a script for setting your permissions. There is also a Drush command for setting permissions in progress at http://drupal.org/node/990812. Both of these scripts can be helpful, but only if you set the user and group ownership of your files correctly, and insure that the web server user is a member of the applicable group as explained above. Please read the quoted page carefully, as it explains these concepts.


Attempt to get Image URL in D8 Twig Background:
Created a custom views block to use unformatted view showing fields set under 'Format'.
Also, created an override template as views-view-fields--bookstheme--block.html.twig and then created the HTML structure within this custom template and then I am simply printing the field like for example Eg:- {{ fields.booktitle.content}}

Below is attempt within to get the image field URL.

Observation:
Solution Attempt #1 worked for me and Solution Attempt #2 didnt. Request help on what I missed out.

Solution Attempt #1:  [ Works ]

{# Below image field from view o/p #}
{{ fields.field_books_theme_pic.content }}
{# Creating a Field URI post setting up relationship to image field fields.uri.content gives uri format eg:- public://image.jpg #}
{{ fields.uri.content|striptags|trim }}
{# and this gives the image uri for src ref #}
{{ file_url(fields.uri.content|striptags|trim) }}

Solution Attempt #2  [ Something missing, no output ]

{% set url = fields.field_books_theme_pic.content|render|striptags %}
{{ url }}

{% set url = file_url(content.field_books_theme_pic['#items'].entity.uri.value) %}

"file_url" needs a URI to convert.

Another options is to go to that fields display settings and change the display option from image to "URL to image". Then you can just render the field value:

{{ content.field_books_theme_pic }}

If you are working in twig template files, the only thing that changes is context. content.something, fields.something, paragraph.something...

If this is a field of type image, what you are looking for is the array key "URI".

I always use {{ dump(whatever | keys) }}. For your case try pasting this into your twig file:

{{ dump(fields.field_books_theme_pic | keys) }}

and see if you can trace down to the uri key (you must have devel enabled and the usual config in local files). If you cant find the uri key in your current setup via the twig template file, then you know you probably need to do some preprocessing to make it available to your template.

Personally, if I feel I need granular markup I would go after the field template itself: "field--field-name.html.twig" for example, and control my markup there. That way, whether I use that field in a view, or a content type, or anywhere, it will always render the same. Plus all I have to do then is print that field in other template files to get the same results.


Nesting a View in a View... or something like that THE SETUP

I have a View set up to create a page out of a particular content type called "enticements". For context, an enticement is something that would make a guest want to stay at a hotel. Things like local attractions and dining.

So my view uses the content types [machine_name] in this order

Image [field_image]
Title [title]
External URL [field_link]
Body [body]

All fields are set to hidden because I want them to be arranged just so, all within the [body]. The body rewrite result looks like this:

    [field_image]

[field_link]

[title]

    [body]

THE QUESTION
This all works fine except that the [field_image] can be one or more images, but no matter what I try it only shows the first image. Even when I tried telling views to show the [field_image] with "Multiple Field Settings" set to "Display all values in the same row" in an unordered list,  it still just shows the first image.

Why only the first image?
Is there a way to get Views to use every image in the rewrite?
Or can I somehow nest a Slideshow View inside the Enticement view?

Check out the Views Field View module.  I have not used it, but it is supposed to embed a view in another one.  Please post back if it works.


Drupal 7 - How do I disable media queries for selective pages? I have a custom theme and currently have media queries setup for my site and I want to disable media queries on certain pages on my site. How can this be done?

There are a few options, but this is not necessarily Drupal specific.

1) move your media query CSS in to its own file(s) and load them only on the pages you want using templates.

2) Use templating to set a class on your  tag, and create a new CSS rule that wraps all your media query stuff.

@media () {
body:not(.no-media-query) {
    //media query stuff here
}

3) Use javascript to set the "viewport" meta tag to a certain width.


Is there a way to avoid anonymous user can see a node of a specific content type? Is there a way to avoid anonymous users can see nodes of a content type, like a block or a view?

I can control the access with a view, but if I know the link for a node, I can  see it without first logging in.

You can control the access to nodes in the hook hook_node_access():

mymodule.module:

use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
  if ($account->isAnonymous() && $node->gettype() == 'article') {
    return AccessResult::forbidden()->cachePerPermissions();
  }
  return AccessResult::neutral()->cachePerPermissions();
}

This controls the direct access to the node, not the access in views. But this is what you probably want.


Autocomplete Widget for Hierarchical Taxonomy I would like to be able to use a widget along the lines of active tags autocomplete that would allow me to maintain a taxonomy hierarchy. I need to be able to select multiple terms, including multiple children for one parent. Any recommendations?

There is a module for that. Probably the only way to select multiple is to allow the field to have multiple values.
http://drupal.org/project/term_ref_autocomplete


Output of entity_metadata_wrapper does not dump to dsm()/dpm() Given this code in a theme_preprocess_page($vars)..

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
dsm($wrapper);

Why doesn't $wrapper produce a debug dump in dsm() or dsp()? I can get data using print_r. Can someone please explain this?

Never mind, I found it. Leaving the answer here for anyone who follows

Basically, dpm($wrapper->getPropertyInfo());

https://drupal.stackexchange.com/a/42542


Prepopulate entity reference field from url in node create form block please help. I have tried so many ways to solve the following problem but did not succeed. I really need your support on this one.

Here is the problem:
There are 2 content types : Fruits and Apple.

Apple content type has an entity reference field to fruits content type.

Now, whenever I view a node of type fruits, the entity reference field in apple add form should prepopulate to fruits node title.

Please see the image below. It will make everything clear.

Is it possible to prepopulate the field? If yes, how? Thanks.

The modules I am using right now:
1.Panels
2. Entity reference
3. Form Block
4. Entity reference prepopulate.

As per the suggestion from Sinan Erdem , I checked http://drupal.org/node/494008 . The code is below . It still doesn't work. :( Can you tell me why?

    <?php
/** hook_form_alter **/

function pp_form_alter(&$form, $form_state, $form_id) {
// Check for a particular content type's node form. Form name is [content_type_name]_node_form
  if ($form_id == 'apple_node_form') {
    // Add an after_build function to process when everything's complete.
    $form['#after_build'][] = 'pp_after_build';
  }
}

/**
* Populate entity reference field
*/
function pp_after_build($form, &$form_state) {
  // Obtain node object from nid in url
  $entityreference_field_category = node_load(arg(1));
  //populate autocomplete entityreference field with node title. Name of field is field_[field_name].
  $form['field_category'][0]['nid']['nid']['#value'] = $entityreference_field_category->title;

return $form;
}
?>

Please check the following issue: http://drupal.org/node/494008


How to get alternative text on image hover How to display image's alternative text when an user hovers on that image.

I have come across few posts that displays popups and views, but not the alternative text of the corresponding images. Some of the modules like qTip and Beautytips looks relevant but I suppose those modules doesn't deliver my requirements. If I'm wrong, please let me know how to use those modules to get the alternative text displayed on hover.

Are there any suggestions regarding how to get alternative text on image hover (possibly without views)

Here, I've created a basic page and in the body I've added an image using advanced text editor.

In the field settings for the image, make sure to 'Enable Title field' - this will present a text input for each content under the upload button.  You can include the title here, and it will show on mouse over.


How to prevent duplicate URL patterns and not have "-#" appended to the URL alias? We have a situation where we need to prevent the same URL from being generated within the same language.

Current situation (all for en):

Create nodeA with a URL alias of "page/node-title"
Create nodeB with a URL alias of "page/node-title"
Create nodeC with a URL alias of "page/node-title"

Results of current situation

nodeA generates "page/node-title"
nodeB generates "page/node-title-0"
nodeC generates "page/node-title-1"

Expected results:

get created as expected
user is prompted to modify the url since for the en language, that alias already exists
user is prompted to modify the url since for the en language, that alias already exists

That is not the expected results however. When nodeB and nodeC are generated, then the user should be prompted to let them know that the URL alias is a duplicate and thus it must be changed so it is unique. We have reviewed a lot of the documents for URL generation in Drupal but cannot find the correct configuration to prevent duplicate node alias from being generated.

As Clive mentions, Pathauto does not have a configuration to disable uniquification (suffixing "-#").

If you look through the main function that builds paths, pathauto_create_alias() you can see that the only way to prevent pathauto_alias_uniquify($alias, $source, $language) from running would be to trigger one of the scenarios in which pathauto gives up on alias creation (e.g. empty pattern, updating an existing alias, etc.) which wouldn't help where you need it still generated in some cases.

Your best bet to cover this scenario is to have a custom node validation function execute pathauto_create_alias()'s logic with $op = 'return' to see what the generated alias would be  before generation, and throw back errors upon duplicate uniquified paths.


Entity Tokens + Date Field + Custom Format... unable to use spaces I have a content type (Question of the Week)... with a Date field (Used for "Publish Date". Questions won't be published until that date).

I am trying to custom format the Title for it without changing the default (Long, Medium, Short) date formats.

For "Pattern for the title"...
If I [node:field-jcqotw-date:custom:l] it shows the day (ex: Sunday).
If I [node:field-jcqotw-date:custom:lF] it shows the dayMonth, no space (ex: SundayJune).
If I [node:field-jcqotw-date:custom:l F] it shows "[node:field-jcqotw-date:custom:l F]" (ex: SundayJune).
If I [node:field-jcqotw-date:custom:l F] it shows "Sunday June" (ex: SundayJune).

I've tried "l F", 'l F', l\ F,   (non breaking space),   (Space), etc... Nothing I do seems to let "Custom" use a space.

Edit: After some research... it seems to be an Entity Tokens + CCK Date Field issue... I'll have to put an issue up in those places.

Why can't I use a space in the "Custom format"?

Also... I've created a "Date Type" simply called "myDate" => 'l F j, Y' ('Sunday June 5, 2011'). Is there a way to get Token to show that format? Long, medium, raw, short... "myDate"...

Edit: Updated Title and Question to be more correct. The problem has something to do with Entity API, Context, Date Field

In this commit to Date module, token integration was removed, because field tokens aren't working yet.

The error you got it reproducible with an older copy of Date module, but doesn't seem to be related at all to Automatic Nodetitles, just Date/Token.

I would wait until the above Token issue and the Date issue Re-Add Field Token Support are committed.


Boost Module: Delete Cache for single node on update I use Boost module for Drupal Commerce.
How can i clear the cache for only one cached node after updating that node.
I don´t want to clear the cache for all nodes but only for the one i updating.

You should be able to do this using the Cache Expiration module:
https://www.drupal.org/project/expire

You might use the rules integration:

event: a node is saved
condition: (type of node, etc - depends on your scenario, might be nothing)
action: expire URL


XMLSitemap- Is it OK to add nodes both by content type and menu? I'm making a sitemap using the XML Sitemap module.  The module and its submodules allow nodes to be added to the sitemap from the content type configuration screen as well as the menu configuration screen.

So, for example, I can add all nodes of type Basic page to the sitemap, and then I can add all links in the Primary links menu (many of which are nodes of type Basic page) to the sitemap as well.

My question: Is doing this OK?  Should I be worried about having duplication between adding the content types and adding the menus?  Or is this nothing to worry about?

There is no harm in adding both by menu and by content type (I have tested this before).  In my experience, paths will not be duplicated.

If you also add by content type, then that priority will be used, even if it is lower than the one you have set for the menu.  Also, the last modification date will be used; it doesn't get used when you add by menu.  The XML Sitemap module also checks node access rights, so only ones visible by anonymous will end up in the sitemap.

If you add by menu, the module will not output links that the anonymous user doesn't have access to.

I don't recall explicitly testing paths that exist in multiple menus, though.


Drupal commerce update to 1.14 from 1.13 - breaks checkout screen I have also a different problem with commerce update with latest 1.14 version. After update via drush, order created and it reached checkout:shipping step, but when I do final order confirmation step, it stuck at payment page [checkout:payment] step, it shows blank page, actually I've skipped the checkout payment step on my previous 1.13 version and it worked fine.

what will be the issue? how to track drupal page and functions execution?

There is no way for anyone to diagnose the issue with the information given. A blank page typically means a PHP error has interrupted the page request. When you encounter situations like this, look to your PHP / Apache error logs to see what clues is gives you.

I'm not aware of anything in the Commerce 1.14 release that should cause the checkout form to suddenly break, but perhaps it's related to some other contributed module on your site. If you track it down to a core problem that you can reproduce on a clean install of Commerce Kickstart 1.x, feel free to open a bug report in the Drupal Commerce issue queue.


How to use Drupal 8 ajax API for Menu links I have a taxonomy menu on the left side of the screen. When I select a menu item I want the results to appear in the main content area of the screen.

I want this to happen using AJAX. I have been reading the AJAX API documentation from Drupal:
https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.4.x

It says I can add a "use-ajax" class to the link, which I have. But then there is no documentation regarding how to get the link to load in a target ID.

You can try this for adding 'use-ajax' class to menu link:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function MYMODULE_menu_links_discovered_alter(&$links) {
  if (isset($links['MENU_LINK_ID'])) {
    $links['MENU_LINK_ID']['options']['attributes']['class'][] = 'use-ajax';
    $links['MENU_LINK_ID']['options']['attributes']['data-dialog-type'] = 'modal';
  }
}


Drupal / Ubercart says it's not saving CC data... then what's "_save_cc_data_to_order"? I'm using Drupal 6, Ubercart 6.x-2.4, and the Stripe payment module.

I wanted to double-check my PCI compliance and make sure I'm not storing credit card data in my database, but I looked at my database and found encrypted CC data in the uc_orders table.

In modules/ubercart/payment/uc_credit/uc_credit.module there is a method called _save_cc_data_to_order. If I comment out this method's contents, the orders still go through my test gateway but the database is no longer populated with cc data.

Hacking up ubercart module code is an effective way to stop from saving cc data in my database, but I didn't think this should be necessary.

What is going on? I have debug mode off in admin/store/settings/payment. I don't understand why it would save ANY cc data--I don't need persisted users and turned anonymous checkout on intentionally.

_save_cc_data_to_order() is called from 3 places:

uc_credit_order()'s Save operation.  When Debug mode (uc_credit_debug) is on, it saves the full payment details.  When Debug mode is off, it saves the last 4 digits of the credit card number (and all other payment details except the CVV).
uc_credit_order()'s Submit operation.  When Debug mode is on, it saves the full payment details.  When Debug mode is off, it's never called.
uc_credit_terminal_form_submit().  When Debug mode is on, it saves the full payment details.  When Debug mode is off, it's never called.

So, under normal circumstances (when Debug mode is off), Ubercart is storing some sanitized information.  I can't speak to whether this meets your level of PCI compliance requirements, but this answer might be helpful.


Config import constantly showing configs to import Recently after doing a config import via drush (drush cim sync), the config files don't seem to import properly, as the files are listed after a supposed successful import.
(and doing a cex sync shows configs to export, despite nothing being changed in the backend)

The only thing I have done recently is import a copy of a database from one of our live test servers, to get the content.

Is there a UUID I need to change or something?

Check that the UUID of the remote and local drupal sites match.

drush config-get "system.site" uuid

You can also get the id from the remote site, by looking into  system.site.yml of your config folder you are trying to import.

To set your local UUID use drush

drush config-set "system.site" uuid "UUID-GOES-HERE"


How to use check box in select list for multiple selection in content type? I simply want a select list like this.

Is there any options to add a field like this.

You can simply achieve that by following way.

Choose Field Widget Type 'Checkbox' instead of Select list.

If you want to make appear checkboxes field as multiple select list,Add the following line in your CSS file

   #field-id-name{ height: 100px; overflow: auto; width: 100px;  }

Note: replace field-id-name with id name of the field; change the width and height according to your requirement.

After applying CSS, the checkbox list field in content type appears as follows.

I hope this simple solution helps


how to hook checkout pane defined in another module? I try to make a small change to Drupal Commerce Coupon pane (add a div to it). I tried to hook this function:

    function commerce_coupon_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
              // Allow to replace pane content with ajax calls.
              $pane_form = array(
                '#prefix' => '
',
                '#suffix' => '
',
              );
        (..)
}

To do this I created a function in my module:

function <mymodule>_form_commerce_coupon_pane_alter(&$form, &$form_state, $form_id) {
        $form['#prefix'] = '

You have coupon? Add it here.
' + $form['#prefix'];
        $form['#suffix'] = $form['#suffix'] + '
';
    }

but it do not work. I think that there should be other way to hook checkout pane but I cannot figure out how to do this.

commerce_checkout_form_PAGE is a form ID. Use it inside of HOOK_form_FORM_ID_alter to edit a particular page of the checkout process. Like so:

function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
    $form['#prefix'] = '

You have coupon? Add it here.
' + $form['#prefix'];
    $form['#suffix'] = $form['#suffix'] + '
';
}

Alternatively, you can also do a generic alter and check the build info in $form_state:

function MYMODULE_form_alter(&$form, &$form_state) {
  if ($form_state['build_info']['base_form_id'] == 'commerce_checkout_form') {
    // We're in checkout.
    $form[PANE_ID] ...
  }
}


cron error Fatal error: Call to undefined function filter_xss() I am running a remote command on my server to execute cron.php and I get this error : Fatal error: Fatal error: Call to undefined function filter_xss() in /home/k1004/html/www_dem
o/oan/srcs/includes/common.inc on line 655
Does anyone have an idea about where it comes from??

Can you make sure the filter module is enable.

I think this problem is because you have a function call to filter_xss() before the filter module load.

Is your Drupal is stand install or this problem exist after install other module?


Allow end user to choose sorting method How can I allow an end-user (site visitor) to choose a view sorting method themselves?

Or more specifically have the visitor choose Ascending or Descending based on an integer?

You need to set a checkbox "Expose this sort to visitors, to allow them to change it" in the "Configure sort criterion" window


Fire $.colorbox.resize() after overlay content is AJAX loaded? Im using the colorbox and colorbox_node module. Out of the box you have to specify a fixed height for the overlay. However I want the overlay to be the same height as its content.

This can be done with $.colorbox.resize. The issue is that it doesnt work if I call it on cbox_complete. The reason is that cbox_complete happens before the content is loaded with AJAX, so its as if there is no content and the height is set to 0 (plus padding).

Ive got it working with the following. Its not a great solution, Its not completely robust and the time delay before the resize isnt an ideal user experience.

        $(document).bind('cbox_complete', function(){
            setTimeout($.colorbox.resize,1000);
        });

UPDATE - I dont know if its best practice (I expect not) but the following placed in the tpl file works:

UPDATE 2 - I spoke too soon. This screws up in IE8 (im not testing on 7 or 6). For one node the 'x' to close the overlay is missing. For the other node only the top 20px or so of the overlay is visible.

<script type="text/javascript">
    (function($) {
        Drupal.behaviors.global_custom_two = {
                attach : function(context, settings) {
                        $.colorbox.resize();
                }
    }})(jQuery);
</script>

Drupal has behaviors for interacting after ajax events.
For more information on drupal javascript see http://drupal.org/node/756722

You should be able to do it using something like this:

(function ($) {

  Drupal.behaviors.yourBehavior = {
    attach: function (context, settings) {
      $(document).bind('cbox_complete', function() {
        setTimeout($.colorbox.resize, 1000);
      });
    }
  };

})(jQuery);

The easiest way to implement this, if you want it in your theme is to put that above code in a script.js file in your theme (you can name that file anything and have as many separate files as you like) then in your info file have

scripts[] = script.js

You can also put it in a js subdirectory and in your info file then put

scripts[] = js/script.js

You can then also put other behaviors in there too.

That will load your javascript on all pages though, which in some cases is desired but in some cases is not.

If you only want it to load on some pages then you call

drupal_add_js('path/to/js/file.js');

from wherever you want to load it.

For example, if you only want it to load on full node pages you could put this in your THEMENAME_preprocess_node() function in your template.php file.

// Only attach this on full node pages.
if (!empty($variables['page'])) {
  drupal_add_js(drupal_get_path('theme', 'THEMENAME') . '/script.js');
}

Or you could do it in a module using something like hook_node_view().


Update query with a dynamic expression in Drupal 7? db_update('warrior_members')
          ->fields(array('points' => 'points' +1))//This is not working
          ->condition('uid', $liv_user)
          ->execute();

How to increase the cell at 1?

Sorry for my bad English

You want to use an expression: http://api.drupal.org/api/drupal/includes--database--query.inc/function/UpdateQuery%3A%3Aexpression/7

Example:

db_update('warrior_members')
  ->expression('points', 'points + 1')
  ->condition('uid', $liv_user)
  ->execute();

Or to make the 1 dynamic:

db_update('warrior_members')
  ->expression('points', 'points + :amount', array(':amount' => 1))
  ->condition('uid', $liv_user)
  ->execute();


Is there an alternative for hook_views_ajax_data_alter in drupal 8? As the title says, is there a similar behavior like hook_views_ajax_data_alter in Drupal 8 like in 7?
If not has anyone achived the same result programatically?

Mybe you can try implementing an AjaxResponse Event Subscriber and alter the commands onResponse :
an example of this is here : https://www.linkedin.com/pulse/how-alter-ajax-commands-view-response-drupal-8-dalibor-stojakovic/


Dynamic pages through view I need to create dynamic page using Views.
I created many of static page using views, for this simply define page link in view, but when I create Dynamic page like 'practice-areas/%' then it is not working. Here % is using for node id.

All the pages should share the common path like
www.domainName.com/practice-areas/1
www.domainName.com/practice-areas/2
www.domainName.com/practice-areas/3

Like if we need to display a particular block on these URLs then we will write

practice-areas/*

Similarly % will only work if there is a common path.

Thanks.


Understanding Recruiter profile in detail I am trying to learn installation profiles. So i took up recruiter installation profile and trying to exploit it to learn.

I found the code like in the .profile file

<?php
// $Id: standard.profile,v 1.2 2010/07/22 16:16:42 dries Exp $

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Allows the profile to alter the site configuration form.
 */
function recruiter_form_install_configure_form_alter(&$form, $form_state) {
  // Pre-populate the site name with the server name.
  $form['site_information']['site_name']['#default_value'] = t('eq-Recruiter');
}

/**
 * Implements of hook_install_tasks().
 */
function recruiter_install_tasks() {
  $tasks = array(
    'recruiter_import_vocabularies_batch' => array(
      'display_name' => st('Import terms'),
      'display' => TRUE,
      'type' => 'batch',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
    ),
  );
  return $tasks;
}

/**
 * Defines batch op for importing
 */
function recruiter_import_vocabularies_batch() {
  $batch = array(
    'operations' => array(
      array('recruiter_import_vocabularies', array()),
    ),
    'finished' => 'recruiter_import_vocabularies_finished',
    'title' => t('Import terms'),
    'init_message' => t('Starting import.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Example Batch has encountered an error.'),
  );
  return $batch;
}

/**
 * Import batch operation for vocs
 */
function recruiter_import_vocabularies(&$context) {
  if (!isset($context['sandbox']['progress'])) {
    $vocs = taxonomy_vocabulary_load_multiple(FALSE);
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;
    $context['sandbox']['max'] = count($vocs);
    $context['sandbox']['vocs'] = $vocs;
  }

Here i saw code like $vocs = taxonomy_vocabulary_load_multiple(FALSE);  He is just saying FALSE here. Does it now require any parameters? If no how is it fetching the values?

taxonomy_vocabulary_load_multiple(FALSE)

will load all vocabularies. If you wanted a specific one you'd pass in the relevant id instead.


Assigning css classes to menu items I need to assign different classes to all of the menu items in my primary links because each item is preceded by a different icon. How could I go about doing this?

EDIT: I found a module that seems to achieve this -- http://drupal.org/project/menu_attributes. Has anyone used it? Is it an effective solution?

Yes, the Menu Attributes module works well.  I used it on nearly all projects.


Drupal 6 site running slow on my localhost Hi I am working with a drupal 6 site and have a setup for this on my localhost the site is very huge and consists of almost 290 tables but the site is working super slow on my localhost specially the admin pages. It took almost 1hr to create a simple content type and 20-25 min to load module page, 30 min to enable/disable a module if not using drush about 10 mins using drush. This is becoming really time consuming for me to work like this. I have also configured the site performance but still no change. Rest of drupal 6/7 sites on my localhost are running fine.

Profile it; it's on your local box, so it can be done. Until you do that it's a bad guessing game. What all contributes to drupal page execution time?


Menu items disable and weight resets on save Under Admin => Structures => Menus (select any menu item), I am able to create menus with no problem. However if I click save two things happen, 1. any drag/drop positioning I do is not saved and 2. all the menu items get disabled.

In order to keep them enabled I can edit each individual menu item and check the "enabled" box and manually edit the weight in that area and it works. Otherwise it doesn't work.

Also when ever I clear the drupal cache the "show as expanded" ends up disabling and all my drop down menus disappear.

I stepped through drupal and confirmed those fields are passing blank on save. I'm at a loss what to do and not sure how to fix this.

Update: Just to update I discovered one of the issues is my 1st level menu item "Products" was generated from a view. I then manually created drop down items in the menus area and placed them underneath the "Products" link. When ever I would clear the cache the menu would no longer show as expanded and all weights reset to 0 so my menu orders would tank.

Still trying to figure out why the enable/disable check boxes and weights are getting reset on save.

Final Update:
O.k. I've traced it down to the fact that my server is ignoring the those specific form fields. For example the "enable/disable" check box form name was:
name="links[menu_plugin_id:menu_link_content:2e7779b8-6668-4b9f-8a04-049cca46c13b][enabled]

My server would simply ignore this form field name and not pass it to the global _POST variable. I changed the form name too:
name="links[menu_plugin_id:menu_link_content:1][enabled]

and it worked. I thought maybe it was mod_security so I turned that off but had no effect. At this point I'm not sure what it is in my server settings
 CENTOS 7.2 x86_64 standard that's causing these fields to be ignored. I'm not entirely sure what to do right now to work this out.

Hopefully somebody will come across this post someday and it will be of help.

I think I have discovered this issue with Drupal 8 too.

I have the default Menu navigation from the Bootstrap theme, which I am trying to add a menu item for an "About me" page.  When I edit the menu item link and save with correct weight and Enabled set, the menu item is ticked. However, when I click the Save button on the main Menu page, the About Me item is disabled. Two items remain ticked - the Home menu and a View.

There seems to be a bug in the global Save button for the Menu. I guess the workaround is to modify menu items by clicking Edit, rather than directly on the menu page.


Populate a field in form alter with user name and one with user ID can someone tell me why this works

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

  global $user;
  if ( $form_id == 'node_test_form'){
    $form['field_owner']['widget'][0]['value']['#default_value'] = 'test';
  }
  return $form;
}

but this doesn't

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

      global $user;
      if ( $form_id == 'node_test_form'){
        $form['field_owner']['widget'][0]['value']['#default_value'] = $user->uid;
      }
      return $form;
    }

I'd also like to know how I get the current users name too, if someone can assist with that it would be much appreciated.

The D8 uid property reference isn't something that can be cast into a string as you could in D7.

In D7, user objects use a generic PHP object class (stdClass) with a uid property containing a string. In D8, user objects use a Drupal\user\Entity\User class. This class does't have a direct uid string property.

In D8 the uid property magically retrieves the User entity field property instead of a simple uid string.

As such, there are other new methods/properties (as you've mentioned) to retrieve the underlying uid value.


Would enabling 'Use Ajax' for view content harm our SEO? Background:

We currently use a View to allow users to browse/search among the several hundred guidance pages on our website.

The current UX of the View is not ideal - using the exposed filters causes the whole page to reload, meaning that users have to:

a). Wait for full page reload
b). Scroll back down to the results grid

Question:

I was wondering if anyone had any experience using the 'Use Ajax' setting on a View - specifically in terms of any effect on their SEO?

All our guidance pages are listed on our sitemap, and most are linked to from other pages, but this View is the main, most trafficked area pointing towards them.

How likely is it that the switch would mean that search engines aren't able to/are less able to find/index them?

It will only have an effect if there is content that you want to be visible to the search engine crawlers that is only accessible after having run any JavaScript (aka an ajax call).

For example maybe you want to be optimising for the key word carrot, and there is lots of content about carrots that only appears on page 2 of your view. To get to page two you have to do an ajax request so crawlers will never get there and it will in this instance negatively impact your SEO.

This is quite specific though, and could easily be mitigated against by ensuring your important content on carrots appears on the first page of the view.

So I guess it could have an impact, but it's unlikely that it will be a very big one. But certainly something to consider.

Google has a tool that allows you to fetch a page of your website and preview how it looks to the crawler.
This could be useful for testing exactly what impact enabling ajax on your view will have.


How to rediret to specific page depends upon user roles I have 2 user roles. When a user logs in, I want to redirect the user to a specific page based on their role. I tried the Login_destination module, but it has not worked for me. I have also tried using the trigger action, but it has also not helped me. When I used this trigger action, the ajax module threw an unexpected error message.. SO please help me.. How do I solve this problem...

This is possible with rules
You can try the following

Create a rule with event as "User has logged in".
Add condition "User has role(s)" and configure it as in screenshot
Then save the condition.
Now add action to you rule and select "page redirect" under system in the select the action to add dropdown.
This will open a form which will allow you to set the redirection path, simply in the value field give the internal page path you want the user to be redirected to and then save it.Check the screenshot for better understanding

This way you can set redirect for one role and similarly you can create one more rule in a similar way for the other user role, if you want the other role to redirect to some other page.


VotingApi function takes time to update the database I have added a menu item that calls a function that calls votingapi_set_votes and delete votes. This function works locally fine but when uploaded to the hosting and when i call the function it takes like 5 minutes to update the database with the votingapi_set_votes function.

Menu_item's callback calls a function that contains votingapi_set_votes.
Locally: i call the menu item with the node id as parameter and the a vote is added to the node.
On Hosting: When i call the menu_item i need to wait five minutes or so to see the node vote updated.

I hope this code may work for you Try this code in your theme's js file:

Drupal.behaviors.Your-Theme-Name = {

 attach: function (context, settings) {

//add your class in click function

    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {

         location.reload();

        });

    });

  }

    };


Change title of webform I added a webform to my site. Everything works fine, except that the title (surrounded red) is saying "webform", but I want it to change to "Kontakt" (as the title in the form itself).

Theme is "TB Corpal".

Two questions:

What is the right terminology for this type of title? Is this just called "title" or what is the proper name in drupal?
How can I change that? (I already tried the module "Automatic Nodetitles" but this changes just the title in the form istself)

Or can I do this using "views"? If yes, how?

Sounds like the theme you are using is doing this. The answer may have nothing to do with the Webform module.
When you use a Theme provided by a company that sells themes, you are building your site ontop of a site that they already built for you. Yes, this saves some time, but sadly, you have to find out how that site works. Often times, they have made some "very interesting" decisions that can not be easily explained.

Do you have a link to this page? I am wondering if maybe that title is appearing in a BLOCK. If you mouse over that title, does a gear appear to the far right of that title?

As for the terminology, I do not know. This does not sound like the way Drupal handles titles. I suspect the crew that built this theme made interesting decisions.
The webform module simple creates nodes where the content is fields.
Each webform-node has a node-title in the same way that all nodes have titles.
To edit the title of a node, simply edit the node and change the title and save it. The new title should appear.
If this is not how your site works, then whoever built the theme is doing something very strange.

I hope that helps.


Entity reference in custom field type hello i am trying to create a custom field type in drupal 8 containing two text fields and an entity reference field to a user , but i get this error when i try to save .

  Error: Call to undefined method Drupal\Core\TypedData\DataDefinition::getTargetDefinition() in Drupal\Core\Entity\Plugin\DataType\EntityReference->getTargetDefinition() (line 51 of core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php).

below is my custom field definition :

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    // Prevent early t() calls by using the TranslatableMarkup.

    $properties = [];

    $properties['street'] = DataDefinition::create('string')
      ->setLabel(t('Street'));

    $properties['city'] = DataDefinition::create('string')
      ->setLabel(t('City'));

    $properties['user']   = DataDefinition::create('entity_reference')
            ->setLabel(t('user'))
            ->setSetting('target_type', 'user');

    return $properties;
 }

Any help or tip would be very welcome , thank you :)

EntityReferenceItem is more complicated than just the "entity" DataReferenceDefinition.

It has a DataReferenceDefinition for "target_id" as well.

I solved a similar issue by extending EntityReferenceItem.

Then you can get the entity from the parent definition, which is a bit long and complex and then just add your custom fields on top:

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['street'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'));

    $properties['city'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'));

    return $properties;
  }

Here's the code I used to add one text field to an EntityReferenceItem:

namespace Drupal\mymodule\Plugin\Field\FieldType;

use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Plugin\Validation\Constraint\AllowedValuesConstraint;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Component\Utility\Random;

/**
 * Defines the 'entity_reference' entity field type.
 *
 * Supported settings (below the definition's 'settings' key) are:
 * - target_type: The entity type to reference. Required.
 *
 * @FieldType(
 *   id = "entity_reference_with_title",
 *   label = @Translation("Entity reference with title"),
 *   description = @Translation("An entity field containing an entity reference and a text field."),
 *   category = @Translation("Custom"),
 *   default_widget = "entity_reference_with_title_autocomplete",
 *   default_formatter = "entity_reference_with_title_entity_view",
 *   list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",
 * )
 */
class EntityReferenceWithTitle extends EntityReferenceItem {

  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
    return array(
      'target_type' => \Drupal::moduleHandler()->moduleExists('node') ? 'node' : 'user',
      'title' => '',
    ) + parent::defaultStorageSettings();
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
    return array(
      'handler' => 'default',
      'handler_settings' => array(),
    ) + parent::defaultFieldSettings();
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['title'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'));

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function mainPropertyName() {
    return 'target_id';
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {

    $schema = parent::schema($field_definition);

    $schema['columns'] = array(
      'title' => array(
        'type' => 'varchar',
        'length' => 255,
      ),
      'target_id' => $schema['columns']['target_id'],
    );

    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = FieldItemBase::getConstraints();
    // Remove the 'AllowedValuesConstraint' validation constraint because entity
    // reference fields already use the 'ValidReference' constraint.
    foreach ($constraints as $key => $constraint) {
      if ($constraint instanceof AllowedValuesConstraint) {
        unset($constraints[$key]);
      }
    }
    return $constraints;
  }

  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $manager = \Drupal::service('plugin.manager.entity_reference_selection');
    if ($referenceable = $manager->getSelectionHandler($field_definition)->getReferenceableEntities()) {
      $random = new Random();
      $group = array_rand($referenceable);
      $values['target_id'] = array_rand($referenceable[$group]);
      $values['title'] = $random->sentences(2);
      return $values;
    }
  }

}


Translation of a field overwrites the original language value I have encountered a problem with translation. When I try to translate a custom field of a custom node type it overwrites the original value.

Here is how it looks like

The custom field

I create a node and enter following information

Then I click Save, the node appears, so far so good.

Next I click

I can see that translation not available now, click Add

Then I have the following url link

/node/8/translations/add/en/<my language>

Enter the following value

Now I have two nodes.

Let go to the original node and see what is the value of the field.

It is the same as it was before, but on the web page, I have two nodes with different translations.

The interesting thing that both of the two nodes in admin panel have the same translation as currently selected language, even if I click the edit button from the Translate tab, I need to switch the language via a switcher for example to get the content of a node for the selected language.

And that makes me crazy, I cannot understand what is going on really, how can I edit a translation of a node without changing the language ?

Please help me to solve this problem, I am completely lost with this stuff.

P.S.

Database entries are added correctly I guess

EDIT

My detection configuration before

And set it like this now

Logically, I guess the Interface Language should be responsible for translating Admin Panel interface and other helper popups that are used for the development purpose. But Content translation should be exactly what I am looking for, but when I switch off the Interface Detection and leave it to by default (uncheck session), but check Session in the Content translation section, my language switcher disappears.

I suggest looking and experimenting with the following settings:

admin/config/regional/language/detection

You can also check if the checkbox "Enable interface translation to English" is checked. That may cause this problem.
admin/config/regional/language/edit/en

Question : One thing didn't become clear for me:
"It is the same as it was before, but on the web page, I have two nodes with different translations." - what is the url of the web page. Is it a page constructed with views, panels, or just node/nid ?
Regards,
Oleg


How to convert Drupal Field Collection to Node? I am using Drupal 7 and have a Field Collection that I would like to convert to a custom content type (Node) with the exact same fields. What is the best way to do this? The field collection has the following field types: Postal address, Geolocation, Term reference, Text, Office hours, List (text), Integer.

Unfortunately I am running into too many issues with some of my fields and the Field Collection module. For example, I cannot create a View and use "Has taxonomy terms (with depth)" on a term reference inside a Field Collection. If I switch to two separate fields for the taxonomy term (e.g. State and City) and try using the Reference field option limit module, the fields do not update inside a Field Collection.

I created a custom content type and have successfully been able to create and access the data as needed using Inline Entity Form. Can I modify the database directly? I noticed the Field Collection items do no exist in the Node table. I can create entries in the Node table but I'm wondering if I'll be missing something.

This sounds like a job for the Migrate module: https://drupal.org/project/migrate

I don't know if it can do what you need out of the box, but at least in the issue queue there are discussions about migrating between fields and field collections.

Migrate Field Collections documentation page: https://drupal.org/node/1900640

Editing the database directly is rarely a good idea.


Newbie Question: Modify forms before render I'm trying to style all the text inputs with and text areas from the forms.

They are complex images so I probably will have to build a div wrapper in order to do this. There is anyway to replace all the

<input>...</input>

to something like

<input>...</input>

before rendering the content in a theme?

I really wouldn't use jquery to wrap form elements renderend by Drupal. What if the user has javascript disabled ?

Drupal provides several core api functions for theming forms, one of those is
http://api.drupal.org/api/drupal/includes--form.inc/function/theme_form_element/7

place the function in the template.php file of your custom theme (change the function name from 'theme_form_element' to 'mytheme_form_element'

change the contents of the function to your liking, especially look at places where there's html markup involved


Fatal error: require_once() I tried to update my installation, but now I'm getting this fatal error:

  Fatal error: require_once() [function.require]: Failed opening required
       '/home/abel/www/lmwep/massteri/sites/all/modules/views/includes/admin.inc'
       (include_path='.:/usr/local/PEAR:/usr/local/share/pear:/usr/local/lib/php')
       in /home/abel/www/lmwep/massteri/sites/all/modules/views/views_ui.module on line 175

I have no clue what this means. Any help is appreciated.

It means that the file admin.inc (part of the Views project) is not found.

This file is supposed to be on the following path below your Drupal root sites/all/modules/views/includes/.  If you check, I'm sure that you'll find that it is no longer there.

Why this happens is more difficult to say.  I presume that you had the Views module installed on your site in sites/all/modules/views/ as indicated by the path (for the record: this is the right place), but that after the upgrade, it is no longer there?  Again, please check?

When upgrading, the sites subdirectory from the pre-upgrade site is supposed to be the sites subdirectory in the upgraded site.  If this, for some reason, in not the case, the contributed modules you've installed (such as Views) will be lost.

Please check if the files are missing (as I belive they are).  If they are missing, the solution is to make sure that the entire sites subdirectory hierarchy is properly moved into the upgraded site file hierarchy.


How do I generate PDF of HTML in a custom module? I want to generate PDF in my custom module. Using print module we can print node. But I have made html in my custom module and that I wanted to make pdf and save it in files.

I have tried custom dompfg library but its working.
i wanted to do something like this:

$html = "
Header

Pdf generated.
";

include ("mpdf.php"); /// This will be something to include for mpdf
$mpdf=new mPDF('win-1252','A4','','',20,15,48,25,10,10);
$mpdf->WriteHTML($html);
$mpdf->Output('../default/files/users/filename.pdf','F');
exit;

Any suggestions?

There is quite a bit more involved in integrating Drupal with the mPDF library than the code snippet you show.

As often with Drupal, there is a module for that. It is named PDF using mPDF, and this is what it will do:

  This module is used for Conversion of HTML pages to PDF documents using mPDF PHP Library. It allows you to generate a pdf document of any node.

Make sure you follow the instructions in the README.txt files carefully. You need to place the mPDF library in the right directory, and install the Libraries API, for it to work correctly.


Custom block that's always the first thing in a region? I'm trying to create a region for my Drupal 7 theme that will be clickable drop-down to allow the user to log in/out, access their profile page and a few of other things. The best analogy I can come up with is that I'm trying to create something similar to the sort of drop-down that you see on sites like Twitter. (It's not exactly the same as what I'm trying to build, but close enough to demonstrate my point.)

Now, neither styling the region nor implementing a show/hide behavior in jQuery is difficult. The key here is to add a bit of custom HTML to the region that will wrap outside the blocks, but inside the region itself.

The output should look something like this:

Click here

        < blocks go here >

It's also important to make sure users can't move or delete this special stuff, so I think this should probably go in template.php, but since I'm a Drupal theming newbie, I'm not sure.

Anyone have an idea how to do this?

Your "custom HTML wrapper" is only useful for the Javascript, so you are looking at this the wrong way: the HTML generated by Drupal should not contain it, and it should be the job of the Javascript to transform the markup of the region to fit its use.

You probably want something like this:

$('<your selector>').each(function() {
  // Wrap all the content of the region inside a wrapper.
  $(this).wrapInner('
');

  // Create a link and insert it into the region.
  var link = $('
' + Drupal.t('Click here') + '
');
  link.prependTo($(this)).click(function() {
    // Your custom logic.
  });
}


krumo()/dpm() not working I have a custom module and a template to alter the appearance of my node submission forms, á la these instructions.

My module consists of three functions:

A hook_form_alter() that works fine
A hook_theme() that doesn't do anything but return an array, even if you enter other code before return (not sure if this is by design)
A hook_preprocess_HOOK() that is currently empty

dpm() doesn't seem to do anything in hook_preprocess_HOOK(), although krumo() on the same variables sort of works. It sets a Drupal message that reads Array: [n] items but can't be expanded or inspected at all.

In my template, print_r($form); prints out the form array as expected. dpm('self-aware roomba'); sets a Drupal message of "self-aware roomba" as expected. but dpm($form); does nothing and throws no error.

Everything except my hook_form_alter() is exactly as it appears in the linked tutorial. I even tried pulling out the entire hook_form_alter() to see if it works without it; it doesn't.

What could be causing dpm()/krumo() to fail silently?

I have run into an issue where dpm() and some other messages were eaten up by a 404 request in the background.

Explanation:

If dpm() or drupal_set_message() is called before the messages are printed out with theme_status_messages(), then you get to see them on the same page.

If dpm() or drupal_set_message() is called after theme_status_messages(), then those messages are delayed in $_SESSION until the next request that does theme_status_messages().

Some types of requests do NOT trigger theme_status_messages(). E.g. a form submit will only do the form processing, and then do a redirect, so the messages remain in the $_SESSION.

Also, it will only trigger on requests by the same visitor/client (this is why it is saved in session, which is client specific).

However, some requests that happen in the background do trigger theme_status_messages(), and can eat up your messages.

In my case this were requests to missing images, which resulted in full-blown html 404 pages WITH messages (and I did not get to see any of this, obviously).

Solution:

The solution was to activate the "fast 404" feature.

Change notice 1296384 explaining this newly introduced feature.
Drupal 7 default.settings.php you might want to copy some code from here.


Views Module "Page" and Contextual Filters I have a /press-releases section of my site. The /press-releases url shows a summary of all articles (press-release content types) and there is a block on that page that is generated by a view which displays the latest press releases by release date.  That part works great.

When a user clicks on one of the listed articles, I need it to go to the full article, but use a special "View" for press releases (articles).  I think I need to use some combination with the page view's "Path" field along with the Contextual Filters, but I can't figure out the correct combination.

In other words, how do I show my Press Release (article) Page View when the url is /press-releases/anyarticle ?

You are close. Remove the "Global: Null" contextual filter and configure your "content: nid" contextual filter this way:

WHEN THE FILTER VALUE IS NOT IN THE URL => Display all results for the specified field
WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED => Specify validation criteria, content, type: press releases

To get the press release links changed, you need to:
- add field "content: nid", exclude from display, and rearrange on top, above title
- edit title and remove "Link this field to the original piece of content". In "Rewrite results" check "Output this field as a link" and enter "press-releases/[nid]".


Is there some module which detects untranslated strings? I am using the Admin en/admin/config/regional/translate/translate tab to translate strings of a multilanguage site.

As I have quite a few languages (9), and collaborators send the translated texts in Excel, and I enter manually the strings, I was wondering if there is some way (via options, contributed modules, etc.) of detecting untranslated strings, so I could avoid reviewing different Excels sent, and could collect in a fast and easy way those original strings (English) which do not have a translation in a given language.

I understand that Drupal should go through all the files in which a t() appears, but maybe some module does do exactly that?

To my knowledge, the answer to your question is = No there is no such module. Checkout the article Drupal's multilingual problem - why t() is the wrong answer to beter understand the various challenges to be addressed with anything related to the t() function ...

Drupal's translation system consists of 2 basic components: the translation of the interface and the translation of the content of a site.

The translation of the interface is about the translation of various text strings used throughout the site, like labels used on buttons such as submit, or on tabs such as view or edit. They are the same on all sites (no matter what actual content is contained in a site). This is also what the t() function is related to.

The translation of the content is about the translation of nodes and entities. It requires a place to actually store the translated versions of the content (in multiple languages) and a system to choose which content is to be displayed where. The systems available for translation of content are:

Content translation (used in earlier versions of Drupal, and still available in D7), which translates entire nodes in multiple languages.
Entity translation (its API was first introduced in Drupal version 7, though there is no UI for it yet), which translates fields attached to the same entity.

Typical (often used) modules (in D7) related to translation of the interface (apart from the i18n module of course):

Variable.
Localization update.
Entity Translation.

For D7 there are basically 2 alternatives available to facilitate the "management" of translation of content:

Translation Overview, mentioned as a recommended add-on on the i18n project page also. From its project page:

  ... provides a table listing the site's nodes and showing what's been translated into each language. It also lets you assign priorities for translating nodes into the various languages.

Translation Management Tool, considered as the successor of the previous module, and "the" module to move forward with in D8 also. From its project page:

  ... provides a tool set for translating content from different sources. The translation can be done by people or translation services of all kinds. It builds on and uses existing language tools and data structures in Drupal and can be used in automated workflow scenarios.

  This module does not make i18n or any other language module for Drupal obsolete. It does only facilitate the translation process.

PS: Obviously, translation of content is NOT what this question is about (at least not yet ...), but pretty sure a related challenge you 'will be' (or 'are already'?) facing in this multi-lingual site ... and which cannot be handled with the t() function. Though for the sake of completeness, I hope it's OK to add that part of my answer also ....


Overwrite a specific field on a specific node We have a content-type of 'offices' locations. There is a View that pulls all of them together and that view is used on a contact page, a buy and a representative page. It's also used on job postings as a field 'location'.

Now they want to post a job with at "TBD" location. If I add a "TBD" node type, it will then display in all of the places where that view display 'offices' is pulled.

So I need to tell Drupal "On this job posting only, show "TBD" in the location Field. That's the ideal thing ... to rewrite that field on a specific job posting. In this case, the node is specifically 11071, if that helps?

Can I use a page-node-11071.tpl.php and some function there?

As I understand, you want a to display the same block which lists some node information in different pages and want to avoide listing some specific nodes in some specific pages. You can make use of views filter with 'Global: PHP' and have code similar to as below :

if (arg(0) == 'node') {// Set your condition here.
  if ($data->nid == NID_YOU_WANT_TO_RESTRICT) {// Set the NID you want to restrict
    return TRUE;
  }
}

Note : To consider multiple job postings in future, you just need to set the path condition accordingly.

Hope it helps


Which user does the Rules module execute as? I've set up a rule which is triggered by "after saving a new user account". This rule simply sends an e-mail. The e-mail contains various tokens, one of them is the field [account:field_country].

I've enabled "custom permission" for this field, and through the Field Permissions module I've configured the following permissions :

All users (selected permissions):

Create own value for field Country
View own value for field country.

Moderators (all permissions) :

Create own value for field Country
Edit own value for field Country.
Edit anyone's value for field country.
View own value for field Country.
View anyone's value for field Country.

The problem is : the [account:field_country] gets replaced with an empty string when the rule sends the e-mail. Only when I let all users View anyone's value for field Country does the rule properly replace the token with the actually selected country value.

Why do I need to do this? Which user does the rule module run as since the rule apparently need to View anyone's value for field Country to be able to get the value for that field.

And here is a module that could assist:

Rules switch user

  This module adds two new Rules actions:

  Switch to another user
  Switch back from another user

  These actions could be useful when you have an operation that you want
  an unprivileged user to use but it fails because the user doesn't have
  sufficient permissions.

Create a fictitious user with sufficient permissions and switch to this user when performing the Rules action and switch back again when done.

EDIT This answer is just a workaround and does not speak to the question directly, namely why the current permissions doled out are not allowing the Rule to execute successfully.


Not getting along with the form API tutorial I am using Drupal 7, and I want to build a form. I tried to follow the tutorial in "Pro Drupal 7 Development"; I created a .module and .info file, which are supposed to work, I activated the module, and now I don't find the form.

How can I see the form in the front end, or at least at the back end? Is there a URL Drupal is giving to this module? How can I see it?

Use hook_menu().

function YourModuleName_menu() {

 $items['testform'] = array(
   'title' => 'Test form',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('your_form_function'),
   'access arguments' => array('access content'),
   'type' => MENU_CALLBACK
 );

 return $items;
}

Access the page from example.com/testform, where example.com is your site address.

You can also create a block from your form to access it.


Automatically create redirect for a file when the file is renamed? When a file is renamed in the file upload widget and the other file is set to temporary, is there any mechanism in the background happening with the Redirect module to create a redirect from the old filepath to the new one that was renamed?

Example, foo.pdf in a file widget, I remove it and upload foo.pdf again. foo.pdf is now called foo_0.pdf - but links that linked to the old filename in the site still exist, therefore is it possible to get those redirected to this one?

edit: linking to related dilemma.

Using hook_node_presave get the url of the old one (foo.pdf) and the new url of the new one (foo_0.pdf) and then create a new redirect as shown by 4k4 here.

To get the orignal value (ex: title), I know in D7 you can with $node->original->title not sure if this still works on D8, have not yet tried it.

Also, since your url ends with .pdf I am not sure if this will work, but hopefully it will.


Are service autowiring and class autoresolving not anymore supported? In Drupal 8, I needed to define services via the mymodule.services.yml file only, if I wanted to use them via the service container. I could also autowire them and the classes were automatically resolved.
services:
  my_module.twitter_feed:
    class: Drupal\my_module\TwitterFeed
    autowire: true

  domcrawler.crawler:
    class: Symfony\Component\DomCrawler\Crawler
    public: false

In Drupal 9, it looks like I must define all my custom classes inside the mymodule.services.yml file. Drupal 9 seems not to be able to identify my classes without an entry within the mymodule.services.yml file. There seems to be no autoresolving anymore. Symfony 4 and 5 are able to do that and Symfony 3.x (Drupal 8) was definitely able to autowire services and find classes by its own. Drupal seems to have its own service container, which suppresses that functionality.
Defining every single PHP class within a *.services.yml file is a huge amount of work for upgrading and maintaining my project. I cannot believe that Drupal 9 requires this work, because the Symfony framework already does that automatically.
Do you know any way to re-enable PHP class autowiring and autoresolving in an upgrade from Drupal 8 to 9?
I hope that anybody else was struggling with autowiring during an upgrade from Drupal 8 to 9 and knows any solution.

I found out, that in Drupal 9 some autowiring "magic" from Drupal 8 was removed. Drupal also overrides the Symfony dependency injection by its own logic. Therefor you must write your own service provider class in your module to autowire your service containers (basically all PHP classes, except e.g. Drupal Plugins or Drupal Entities, which Drupal 9 resolves by its own).
Like this (path: modules/custom/my_nice_module/MyNiceModuleServiceProvider.php):
<?php
declare(strict_types=1);

namespace Drupal\my_nice_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Finder\Finder;

class MyNiceModuleServiceProvider extends ServiceProviderBase {

  public function register(ContainerBuilder $container) {
    $containerModules = $container->getParameter('container.modules');
    $finder = new Finder();

    $foldersWithServiceContainers = [];

    $foldersWithServiceContainers['Drupal\my_nice_module\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\Transformer\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Transformer/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Transformer\RegionalCouncilMeeting\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Transformer/RegionalCouncilMeeting/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\DomCrawler\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/DomCrawler/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\MongoDBFetcher\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/MongoDBFetcher/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\Importer\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Importer/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Importer\MongoDB\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Importer/MongoDB/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Importer\RegionalCouncilMeetingsArchive\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Importer/RegionalCouncilMeetingsArchive/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\Entity\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Entity/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Extractor\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Extractor/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Service\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Service/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\DrushCommandFacade\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/DrushCommandFacade/')->files()->name('*.php');

    foreach ($foldersWithServiceContainers as $namespace => $files) {
      foreach ($finder as $fileInfo) {
        $class = $namespace
          . substr($fileInfo->getFilename(), 0, -4);
        // don't override any existing service
        if ($container->hasDefinition($class)) {
          continue;
        }
        $definition = new Definition($class);
        $definition->setAutowired(TRUE);
        $container->setDefinition($class, $definition);
      }
    }
  }

}

Here is a good presentation about this: https://events.drupal.org/sites/default/files/slides/drupalcon.2019.autowiring.pdf
The Autoservices Drupal module can also be a good example for your own solution: https://gitlab.com/upstreamable/drupal-autoservices


How to get rid of large classes with numbers from views? Which is the purpose of classes like that one:

class="js-view-dom-id-0fc70eec09ba01f6b7c7867ee7e19f7dcec1ee8b64de9dc8b791865caf299ec7"

It's safe to change this class from twig templates?

Thanks.

They are used to uniquely target views elements with javascript for AJAX purposes. If you have enabled the use of AJAX on your views display for pagination, filtering etc without page reloads, then removing or changing those might break it. If you are not using AJAX at all, you should be fine, although this comment is not a promise or guarantee!


Rendering arbitrary field values without a parent entity in Drupal 8 I would like to expose to the user their choice of field formatters and the respective field formatter options. The selected formatter would then render an arbitrary array of items in the same format as a value for that field type, without any kind of parent entity.

Again, I want to render what looks to be an array of field values, without having an actual field or entity with a field value.

In Drupal 7 I could accomplish this using the following code (Gist formatted version):

// Render a file using the 'Generic file' formatter (a nice link with an icon):
$file = file_load(1);
$field = array('type' => 'file');
// File fields are stupid with their field values.
$items = array(0 => array('fid' => $file->fid) + (array) $file);
$display = array('type' => 'file_default');
$output = field_items_render($field, array(), $items, $display);
return drupal_render($output);

// Render node 1 with an entityreference formatter
$field = array('type' => 'entityreference');
$items = array(0 => array('target_id' => 1));
$display = array('type' => 'entityreference_label', 'settings' => array('link' => TRUE));
$output = field_items_render($field, array(), $items, $display);
return drupal_render($output);
// Outputs Title of node 1

function field_items_render(array $field, array $instance, array $items, array $display, $langcode = LANGUAGE_NONE) {
  $field += field_info_field_types($field['type']);

  $display += field_info_formatter_types($display['type']);

  $instance += array(
    'entity_type' => 'node',
    'bundle' => '_fake',
    'settings' => array(),
  );
  $instance['settings'] += $field['instance_settings'];

  $entity_type = 'node';
  $entity = NULL;
  $entities = array(0 => $entity);
  $entity_items = array(0 => &$items);

  // Run hook_field_prepare_view() on the field module.
  $function = $field['module'] . '_field_prepare_view';
  if (function_exists($function)) {
    $function($entity_type, $entities, $field, $instances, $langcode, $entity_items);
  }

  // Run hook_field_formatter_prepare_view() on the formatter module.
  $function = $display['module'] . '_field_formatter_prepare_view';
  if (function_exists($function)) {
    $function($entity_type, $entities, $field, array(0 => $instance), $langcode, $entity_items, array(0 => $display));
  }

  // Run hook_field_formatter_View() on the formatter module.
  $function = $display['module'] . '_field_formatter_view';
  $result = $function($entity_type, NULL, $field, $instance, $langcode, $items, $display);

  return $result;
}

While I can do this in Drupal 7 very relatively easily, how can I accomplish the same in Drupal 8 (or at least help lead me down the right path through all the major parts of this)?

Yeah, you can't get around having an entity object, but it doesn't matter what it is, the only place where it's needed in the following code is FormatterBase::view(), to set #entity_type, which will later be used for the class name.

<?php

use Drupal\Core\Field\FieldDefinition;
use Drupal\node\Entity\Node;

// Load the node, you can also create a temporary object or have your own
// dummy object that implements EntityInterface. (Might need ContentEntityInterface, not sure).
$node = Node::load(1);

// Create the field definition, some might need more settings, it currently
// doesn't load in the field type defaults. https://drupal.org/node/2116341
// Field name is only set to avoid broken CSS classes.
$definition = FieldDefinition::create('entity_reference')
  ->setName('whatever')
  ->setSetting('target_type', 'node');

/* @var \Drupal\Core\Field\FieldItemListInterface $items $items */
// Create a field item list object, 1 is the value, array('target_id' => 1)
// would work too, or multiple values. 1 is passed down from the list to the
// field item, which knows that an integer is the ID.
$items = \Drupal::typedDataManager()->create($definition, 1, $definition->getName(), $node);

/* @var \Drupal\Core\Field\FormatterInterface $formatter */
// Create the formatter plugin. Will use the default formatter for that field
// type if none is passed.
$formatter = \Drupal::service('plugin.manager.field.formatter')->getInstance(array(
  'field_definition' => $definition,
  'view_mode' => 'default',
  'configuration' => array(
    'label' => 'hidden',
    'type' => 'entityreference_label',
    'settings' => array('link' => TRUE),
  )
));

// Prepare, expects an array of items, keyed by parent entity ID, not sure if
// actually used, just array($items) worked too.
$formatter->prepareView(array($node->id() => $items));
print \Drupal::service('renderer')->renderRoot($formatter->view($items));

Yes, finding this out is not trivial, but I disagree with you that the 7.x code is relatively easy, it's just that you know the 7.x field API and internal magic callbacks very well. The main difference is that instead of building arbitrary array structures and passing them around, you need to find the right object/class/service and call methods on there. Once you found them, it's not that hard, FormatterPluginManager::getInstance() for example documents very well what it expects.


How do I build a hierarchical form? In Drupal 8, I don't understand how build a "hierarchical" form.

I have this sample form

...
public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = array(
        '#type' => 'fieldset',
        '#title' => t('Main description'),
    );
    $form['description']['subfirst'] = array(
        '#type' => 'textfield',
        '#title' => t('subfirst'),
    );
    $form['description']['subsecond'] = array(
        '#type' => 'textfield',
        '#title' => t('subsecond'),
    );

    $form['content'] = array(
        '#type' => 'fieldset',
        '#title' => t('Main description'),
    );
    $form['content']['subfirst'] = array(
        '#type' => 'textfield',
        '#title' => t('subfirst'),
    );
    $form['content']['subsecond'] = array(
        '#type' => 'textfield',
        '#title' => t('subsecond'),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    dpm($form_state->getValues(),"getValues");
}
...

When I submit my form, my form_state->getValues() return :

The form_state->getValues() contains only the ['content']['subfirst'] and ['content']['subsecond'] values...
That means I must use uniques labels with the form api ? I find it weird...

Then, I change my form :

$form['content']['subfirst'] become $form['content']['totosubfirst']

$form['content']['subsecond'] become $form['content']['todosubsecond']

The new code :

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = array(
        '#type' => 'fieldset',
        '#title' => t('Main description'),
    );
    $form['description']['subfirst'] = array(
        '#type' => 'textfield',
        '#title' => t('subfirst'),
    );
    $form['description']['subsecond'] = array(
        '#type' => 'textfield',
        '#title' => t('subsecond'),
    );

    $form['content'] = array(
        '#type' => 'fieldset',
        '#title' => t('Main description'),
    );
    $form['content']['totosubfirst'] = array(
        '#type' => 'textfield',
        '#title' => t('subfirst'),
    );
    $form['content']['totosubsecond'] = array(
        '#type' => 'textfield',
        '#title' => t('subsecond'),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

And when I submit my form, my form_state->getValues() return :

I get the four values. But, they are in the same hierarchical level. How I use the form api for have a form_state like this :

'description' => 'subfirst' => string(3) "AAA"

'description' => 'subsecond' => string(3) "BBB"

'content' => 'totosubfirst' => string(3) "CCC"

'content' => 'totosubsecond' => string(3) "DDD"

?

I want get a hierarchical form_state because after I want create a custom function like :

foreach element in description
  do that
foreach element in content
  do that
...

Set #tree => TRUE on the parent elements, then the values will be nested accordingly


How to alter Core's user login final function In user.module, I need to alter the message that is displayed if the username/password is not recognized. I'm using the email registration module so I don't use usernames at all. I want the last form error message in the code below to show email/password instead, as well as add a custom redirect to it.

I've googled for quite some time, but cannot find how to hook onto this function. Any help would be appreciated!

function user_login_final_validate($form, &$form_state) {
  if (empty($form_state['uid'])) {
  // Always register an IP-based failed login event.
  flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
  // Register a per-user failed login event.
  if (isset($form_state['flood_control_user_identifier'])) {
  flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
}

if (isset($form_state['flood_control_triggered'])) {
  if ($form_state['flood_control_triggered'] == 'user') {
    form_set_error('name', format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or request a new password.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or request a new password.', array('@url' => url('user/password'))));
  }
  else {
    // We did not find a uid, so the limit is IP-based.
    form_set_error('name', t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or request a new password.', array('@url' => url('user/password'))));
  }
}
else {
  // Fix password reset messages
  form_set_error('name', t('Sorry, unrecognized username or password. Have you forgotten your password?', array('@password' => url('user/password', array('query' => array('name' => $form_state['values']['name']))))));
  watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
}

}

Override login form with hook_form_alter()

You need to replace validation function with your custom function.


How do I show a "read more" link in my RSS feed? I need to trim down my RSS feed so that people come back to the site to read the full article, how might I do this and is there a preferred / best method?

That's what Teasers are for — the Teaser is the shortened version of the content, presented in RSS feeds (among other places, such as the site's front page).

When editing a node in Drupal 6, use the "Split summary at cursor" button to split the node's body into a Summary/"Teaser" and "Full view".

Then go to your site's /admin/content/rss-publishing page, and set "Feed content" to "Title plus teaser".

Additionally, on your site's /admin/content/node-settings page, you can configure the default length to use to split nodes.

For some additional customization, try the Read More Link module (but be aware of this issue), or Display Suite, as @Decipher mentioned.


How to interpret the code: module_invoke_all('user', 'logout', NULL, $user);? How to interpret this line of code?

module_invoke_all('user', 'logout', NULL, $user);

Obviously, it logs out the current user, but how do the four arguments make it happen?

I read through the doc, but I can't find information about the four parameters.

Can anyone explain?

From Documentation:
module_invoke_all()

Invoke a hook in all enabled modules that implement it.

Parameters
$hook The name of the hook to invoke.
... Arguments to pass to the hook.

No, they don't log the user out. That is done by the call to session_destroy() in user_logout().

That line only invokes the hook to tell other modules that the user was just logged out so they can react based on that.

The passed arguments are simply those that match the executed hook. Note that the Drupal 7 version is different from what you posted above, which is the Drupal 6 version.


Related articles with comments I've been made module that shows related articles and based on taxonomy tags. My problem is that, it listed related articles where is no comments too.

So I want that shows only these articles where is comments.. At least one comment, but I can't get that working. Thank you

My code:

function related_articles($cat, $limit = 10) {

 //$nid = $variables['node']->nid;
 //$variables['num_comments'] = db_result(db_query('SELECT COUNT(cid) AS count FROM {comments} WHERE nid = %d', $nid));

$limit = isset($limit)?  " LIMIT $limit " : ' ';
$row = db_query('
    SELECT nid \'id\',title \'name\', field_category_tid
    FROM {node} n
    LEFT JOIN {field_data_field_category} fdft ON (fdft.entity_id = n.nid AND bundle = :article AND entity_type = :node)
    WHERE type = :article AND status = :status AND fdft.field_category_tid = :cat order by title asc
    '.$limit, array(':cat' => $cat, ':article' => 'article', ':status' => NODE_PUBLISHED, ':node' => 'node'))->fetchAll(PDO::FETCH_OBJ);

return ($row)? $row: array();
}

You will need to join in the comment table and check the comment count.

...
LEFT JOIN {comment} c ON (c.nid = n.nid)
...
HAVING COUNT(c.cid) > 0

The whole query would probably become something like this:

$row = db_query('
  SELECT nid \'id\',title \'name\', field_category_tid
  FROM {node} n
  LEFT JOIN {field_data_field_category} fdft ON (fdft.entity_id = n.nid AND bundle = :article AND entity_type = :node)
  LEFT JOIN {comment} c ON (c.nid = n.nid)
  WHERE type = :article AND status = :status AND fdft.field_category_tid = :cat
  HAVING COUNT(c.cid) > 0
  ORDER BY title asc
  '.$limit, array(':cat' => $cat, ':article' => 'article', ':status' => NODE_PUBLISHED, ':node' => 'node'))->fetchAll(PDO::FETCH_OBJ);

Final note, what you want can be easily achieved with the Views module without having to write a query.

UPDATE:

Count should be checked in HAVING.


change the list option based on the selection type In a form, user have an option to choose the submission type. Based on the selected submission type, user should get an option to choose sub-type. Please let me know how this is done in Drupal 7. Please suggest a module.

If user select e-book, sub-type should change to case:1 (see image)
If user select e-project, sub-type should change to case:2
If user select e-lab manual, sub-type should change to case:3

Seems like you are looking for Conditional Fields module...

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API. You can, for example, define
  a custom “Article teaser" field that is shown only if a "Has teaser"
  checkbox is checked.

See below image displayed in project page which suits your requirement.. Hope above module solves your problem..


I want to override the template of the contact page I use bootstrap as theme in Drupal 8, and I created a sub-theme. I want to override the contact page with a custom template.

I added debug: true in services.yml, but I didn't find the right template to recreate it in the sub-theme.

The contact page is a form, so you can theme it like any usual form:

Implement hook_theme in your theme to tell drupal you want to theme the form.
Create the template file

Example

/**
 * Implements hook_theme().
 */
function <your theme>_theme($existing, $type, $theme, $path) {
  return [
    '<your form id here>' => [
      'render element' => 'form',
    ],
    '<another form id, if you have multiple contact forms>' => [
      'render element' => 'form',
    ],
  ];
}

The form id depends on the machine name of your contact form. For example, if your contact form is named 'feedback', the form id will be

contact_message_feedback_form

Now drupal will by default look for the template file

contact-message-feedback-form.html.twig

Place the twig file in where Drupal can find it, i.e. under the templates folder in your theme.

At the minimum, what you need in that twig template file is

{{ form }}

But you can control what is printed by doing so:

  {{ form.mail }}

  {{ form.message }}

  {{ form.actions }}

{# Renders the rest of the form #}
{{ form|without('mail','message','actions') }}


What is the proper way to style pages in a new installation of a drupal theme? I'm currently working on a new theme for a new drupal site, and have created a new subtheme of the adaptivetheme and am looking to modify  it to match the two psd's I've been given (one for the main page, another for the content found in trhe rest of the site. Originally I was going to copy page.tpl.php over to the subtheme from the at_core/templates directory and modify it's structure, but am wondering if that's considered best proactices drupal wise, ior if i should use modules like panel and views to build the style that I want that way?

So in a nutshell, which is the proper drupal way to style a new site; to use panel/views to match the design that you want, or to modify the tpl files, or a combination of both, or possibly something else that I might have missed?

Both or either are just fine, it really depends on what you want to achieve.

Panels will give you a UI in which you can move sections of the page around, but you will still need template files for the layouts if you don't want to use the standard ones.

Rearranging a template file is fine, but much less extendable via the UI.

In short, it's a matter of choice.  I recommend trying both and seeing which fits your needs best.

Also, check out Omega 4.x, it's a beast of a theme with some extra layouts built in and a pre-built gemfile so that you can use SASS if you want.


Which preprocess hook do I use to fire some HTML altering PHP? I have some PHP that ultimately says 'If this class is present in the HTML, add this string to the $additional_classes array'. Eg, something similar to:

$leftcol_empty = empty($content['leftcol']);
$additional_classes = !$leftcol_empty ? 'medium-8 medium-pull-4' : '';

Currently, I've put this at the top of my .tpl file and it works fine. However, I've been told I should move it to the 'theme preprocess function'.

I looked through my theme's template.php file and tried adding it to my_theme_preprocess_page, my_theme_theme and my_theme_process_html but it stopped working.

I've tried Googling for theme preprocesses but haven't found anything that works.

Would anyone know what preprocesses function I can use here?

you can use theme_preprocess_html(&$variables) OR my_module_preprocess_html(&$variables)

in $variables you will see $variables['classes_array']

if(in_array('class_name', $variables['classes_array'])) {

  //Do your changes

}

Hope this will help.