Enable  tags in CKEditor? I have the CKEditor module installed, and it has a place to configure the allowed tags, but the list of allowed tags that you are allowed to... allow is very anemic. Is there a way to stop it from stripping  tags (or any other tag for that matter)?

This answer is for future reference

Checkout the WYSIWYG Filter

  The WYSIWYG Filter module provides an input filter that allows site
  administrators configure which HTML elements, attributes and style
  properties are allowed. It also may add rel="nofollow" to posted links
  based on filter options. It can do so with no additional parsing on
  user input. That is, it may apply nofollow rules while parsing HTML
  elements and attributes.

  The filter is based on whitelists that can be defined from the filter
  settings panel. Rules for HTML element and attributes are defined
  using the same syntax of the TinyMCE valid_elements option.

  HTML attributes related to DOM events (on*) are not allowed for
  security reasons (to prevent XSS, etc.).

  The following elements cannot be whitelisted due to security reasons,
  to prevent users from breaking site layout and/or to avoid posting
  invalid HTML. Forbidden elements: applet, area, base, basefont, body,
  button, embed, form, frame, frameset, head, html, iframe, input,
  isindex, label, link, map, meta, noframes, noscript, object, optgroup,
  option, param, script, select, style, textarea, title.

Please refer to the project page for more details.


Cannot apply my custom styles to HTML tags in ckeditor I'm using Drupal 8 and am trying to make ckeditor truly wysiwyg.

To that end I've successfully gotten ckeditor to use a custom stylesheet by adding a ckeditor_sylesheets key to my theme's info.yml and my stylesheet's path as the value.

If within my custom stylesheet I create styles and assign them to a class, those styles are reflected within the form if I reference the class.

However, if within my stylesheet I define a style for an HTML element (e.g. h1, p, etc.) ckeditor ignores those styles.

This is the case regardless of how I set or unset "Limit allowed HTML tags and correct faulty HTML" and "Correct faulty and chopped off HTML" at /admin/config/content/formats.

As I mentioned, clearly ckeditor is accessing my stylesheet as styles assigned to classes work.  Also, I can see the stylesheet in Chrome's inspector.  If I inspect a HTML tag for which I've defined a style it shows me that user agent stylesheet is being used.

I don't think it matters but just in case; I'm using Seven for my administrative theme and my default theme is a sub-theme of bootstrap.

If someone could give me a clue I'd appreciate it.

So I resolved this problem by clearing cache.  Not Drupal's cache (I'd tried that about a zillion times) Chrome's cache.  Duh.


Using Left() with Drupal Custom Module I'm trying to return only the first 200 characters (if there are more than that) from a body field in a Drupal custom module. I've found the general php/mysql solution here:

https://stackoverflow.com/questions/2080860/mysql-sql-retrieve-first-40-characters-of-a-text-field

But when I try to implement it with my SQL query in my custom module it doesn't work (ie. it still returns over 200 characters). Here's my code (see the field I used LEFT() on is LEFT(fdb.body_value, 200) on line 6):

$result = db_query(
"SELECT n.title, n.nid, n.status,
fdfty.field_type_value, fdfi.entity_id,
fdfi.field_icon_fid, fm.uri, fm.fid, ua.pid,
ua.alias, el.field_experience_level_value,
**LEFT(fdb.body_value, 200)**,
fdfr.field_role_value, fdft.field_topics_value,
fdfed.field_event_dates_value,
fdfed.field_event_dates_value2
FROM {node} AS n
LEFT JOIN {field_data_field_type} AS fdfty
ON n.nid=fdfty.entity_id
LEFT JOIN {field_data_field_icon} AS fdfi
ON n.nid=fdfi.entity_id
LEFT JOIN {file_managed} AS fm
ON fdfi.field_icon_fid=fm.fid
LEFT JOIN {url_alias} AS ua
ON n.nid=ua.pid
LEFT JOIN {field_data_field_experience_level} AS el
ON n.nid=el.entity_id
LEFT JOIN {field_data_body} AS fdb
ON n.nid=fdb.entity_id
LEFT JOIN {field_data_field_role} AS fdfr
ON n.nid=fdfr.entity_id
LEFT JOIN {field_data_field_topics} AS fdft
ON n.nid=fdft.entity_id
LEFT JOIN {field_data_field_event_dates} AS fdfed
ON n.nid=fdfed.entity_id
WHERE n.status=:status AND n.type=:resource
AND (fdfty.field_type_value=:webinar OR fdfty.field_type_value=:conference) AND el.field_experience_level_value=:level
AND fdfr.field_role_value=:role
AND fdft.field_topics_value=:topic
AND ((fdfed.field_event_dates_value IS NULL)
OR (fdfed.field_event_dates_value >= CURRENT_DATE()))
GROUP BY n.nid, n.title
ORDER BY fdfed.field_event_dates_value",
array(':status' => '1', ':resource' => 'resource',
':webinar' => 'Webinar', ':conference' => 'Conference', ':level' => $level, ':role' =>
$role, ':topic' => $topic));

why not use substr() let the SQL statement bring it all then use this function in your result

would be something like this:

<?php

$result = db_query('Your SQL statement');

print substr($result, 0 , 199);

?>


Module to add keyword search capability to content admin page? Is there any module or technique for D7 that can provide this functionality?

The Admin VBO Views module provides a complementary content admin page, with a search by title (and other fields) enabled by default.

It wouldn't take much to edit the View provided by that module to provide further exposed filters to search the content with.


Menu items visible based on checkbox I want do show/hide menu items based on a checkbox that the user selects when he/she registers.

I use profile2 for register.  Should I use an external jquery script that calls on page load or should I use a hook_menu_alter() in my template file?  I am not too familiar with Drupal code yet and appreciate any input.

Solution 1

Add a custom access callback to your paths, that will then determine whether or not the user should have access to a path.

Important: the code below will deny access to those paths. If you just wanted to show a slightly different menu and not block the access to those pages, see solution #2.

For example:

function YOUR_MODULE_menu_alter(&$items) {
  $items['your_path']['access callback'] = 'YOUR_MODULE_menu_access_callback';
}

function YOUR_MODULE_menu_access_callback(){
  global $user;
  if ($user->uid) {
    // Load user's Profile2 profile.
    $profile = profile2_by_uid_load($user->uid, 'NAME_OF_YOUR_PROFILE');
    // Allow access only if the user selected the checkbox.
    if (isset($profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) && $profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) {
      return TRUE;
    }
  }

  // This assumes that anonymous users should not have the access to a
  // particular menu.
  return FALSE;
}

This code would go in a custom module.

Solution 2

Add a simple theme_menu_link() override in your front-end theme, and skip rendering of those links.

Important: this will not prevent the access to those pages, it will just skip rendering of those list items. Also, you must be rendering the links using a menu, e.g. place a menu block somewhere in your theme, and not render the menu directly (e.g. theme('links__system_main_menu', ...) or theme('links__system_secondary_menu), ...)).

For example:

function YOUR_THEME_menu_link($variables) {
  global $user;
  $element = $variables ['element'];
  $sub_menu = '';

  // Exclude certain paths.
  if ($user->uid) {
    // Load user's Profile2 profile.
    $profile = profile2_by_uid_load($user->uid, 'NAME_OF_YOUR_PROFILE');
    // Allow access only if the user selected the checkbox.
    if (!isset($profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) || !$profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) {
      // Define the list of paths that should be excluded.
      $paths_to_exclude = array(
        'sample',
      );
      if (in_array($element['#href'], $paths_to_exclude)) {
        // Stop processing here, meaning this list item will not be included in
        // the menu.
        return;
      }
    }
  }

  if ($element ['#below']) {
    $sub_menu = drupal_render($element ['#below']);
  }
  $output = l($element ['#title'], $element ['#href'], $element ['#localized_options']);
  return '<li' . drupal_attributes($element ['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

This code would go in the template.php file of your front-end theme.


I replaced a pdf file but google searches for the node turn up the old pdf file I replaced a downloadable pdf file that was uploaded to one of the nodes on my website. But a google search of the item still goes straight to the old file. I've tried deleting the node completely and recreating it with the new file, but it still won't work. (The file name is the same, it's just the content that's augmented). The google search will direct properly on my laptop, but not on my ipad. I can't figure out if this is a drupal issue or a google issue or a browser issue (I deleted all cookies and history on my ipad before googling, but it still won't work)--can you help? Thanks!

Inside your Drupal File System - determined at Admin/Config/Media/File System - there are 3 directories that store files uploaded to your Drupal site. I would recommend navigating to each of these directories to find your (old) .PDF file and deleting it ...

If you want to keep the old PDF, consider renaming it ...


I need to update jQuery version for drupal manually? For updating the drupal core jquery file i used the jquery_update contributed module. This module help me a lot to use some of the new function/method of jquery.

But In my view i'm using ajax for pagination and exposed filter form submission. My view containing very bulky data so most of the time most of the browser giving me a script error saying - script is unresponsive, file is ...jquery.min.js

And as my table data is growing up this script error is coming up frequently (that's halt every thing on browser).

Actually this file came into the picture when i install the jquery_update module. By my personal experience i know the reason (basically file conflict).

So i just want to know how to replace the drupal default jquery file with jquery's latest version file manually.

Any suggestion or guidance will really gonna help me a lot.

1- @see /misc/jquery.js

2- its better to add ur jquery to your theme .info file

go to your theme folder
insert your jquery file into the same folder of your theme (E.g theme name new_jquery.js)
in the same directory open yourThemName.info file
add this line  scripts[] = new_jquery.js

3- its not prefered to use Jquery 1.6 with Drupal 6

4- use jQuery.noConflict() to avoid conflict


style views_slideshow pager Is there a way to change views_slide show "image 1 of 3" to be 3 circles, where the active one is black and the rest are grey? I tried doing that in CSS but does not look like its the right approach for doing this.

@Scorchio Thanks for that. I was successfully able to convert the layout from '1 of xx' to '1 2 3 4 5 6 x' by overriding views-slideshow-slide-counter.tpl.php and modifying the views_slideshow.js. My changes are below.

views-slideshow-slide-counter.tpl.php

<div id="views_slideshow_slide_counter_<?php print $variables['vss_id']; ?>" class="<?php print $classes; ?>">
<?php
    $slide_count = count($view->result);
    for($i=1;$i<=$slide_count;++$i)
        print ''.$i.' ';
 ?>

views_slideshow.js

Drupal.viewsSlideshowSlideCounter.transitionBegin = function (options) {
  $('#views_slideshow_slide_counter_' + options.slideshowID + ' span').removeClass('active');
  $('#views_slideshow_slide_counter_' + options.slideshowID + ' .num' + (options.slideNum + 1)).addClass('active');
};


Is there a way to conditionally change the state of a collapsible field group in admin, ie without changing a template or module file? I want to move the Metatags, keywords and edit summary into collapsible field groups at the top of the node edit page, but keep it open the first time the node is created, but collapsed in subsequent edits.

Can some CSS or Javascript be used to accomplish that? I don't want to do it in the file system code, whether are module or a template file.. I'd prefer something using the Admin even if it means applying some PHP there. If a module like the Context module can be used to test whether it is a newly created record and change some settings that will be fine.

If you want it to be open on page creation, you can target the page using the node-add-CONTENTTYPE class on the body. Using some jQuery in document ready you can set it open.

Something like:

jQuery('body.page-node-add-<YOUR-CONTENT-TYPE> fieldset.#YOUR-ID-HERE').removeClass('collapsed').children('.fieldset-wrapper').show();


How to add IE specific stylesheet in drupal 7 in drupal way I want to add this into my Drupal site in a Drupal way!

<!--[if IE]>
<link type="text/css" rel="stylesheet" href="IE.css" media="all" />
<![endif]-->

I know it can be done easily by adding the above tag directly into html.tpl.php but I don't want hack the Drupal core and I want to follow a Drupal way for this.

What would be the best possible solution?

You don't hack Drupal core if you add that to your THEME's html.tpl.php but anyway you can try implementing hook_html_head_alter() in your theme's template.php


jQuery is not defined I just started my project which I haven't touched in a while. I got the most recent develop version of it using git and I up'ed my docker. Once I opened my website I saw, that something is off. Console is saying that "Drupal is not defined" and if I visit pages-> --any page-- -> content, the layout is off.

In the console here it says ReferenceError: jQuery is not defined.

What I already tried to do:

Rebuild my project
Resave configuration of jQuery update
Clearing cache (lol)
Checking if JS is enabled on my browser

Can someone help me out please?

For someone who might experience this, for me Minify module was causing this, I think I lacked some configuration to use minified JS, so my localhost couldn't load JS, after disabling Minify module, everything was fine. Not the best solution, but for fast results its okay.

P.S. DON'T FORGET TO ENABLE IT IF YOU TWEAK SOME JS CODE AND EXPORT IT AS FEATURE.


Clear only CSS/JavaScript cache when files are aggregated When aggregating CSS/JavaScript files using performance page in Drupal 8, drush cc css-js doesn't work, and I've to clear/rebuild all cache.
How do I properly clear/rebuild only the JavaScript/CSS cache?
I want that the filenames change too, so that the browser resets its cache too.

NOTE: I am using the s3fs plugin in order to store assets in an AWS S3 bucket, so if you are not using that your results could differ

This is probably not a suggested method of forcing the system to clear the asset cache, but I was in the same boat and for some reason my file systems got mixed up during multiple edits between local, development, and the live site. For the live site I was only able to get the styles working if the files were not aggregated using the Performance page.

As far as I know, the system will not update the CSS or JS files unless a change has been detected. Aside from going in and making a change to every file I started digging into the database. I found that the file location for the CSS and JS assets were located in the "cache_default" table with a value of something like below:

s3fs:uri:public://css/css_0WFR6_Et4WEJOkLOOpdg4f7EmvMRhsPkSk7KcrPyct4.css

and

s3fs:uri:public://js/js_-YxTfPGZervj7hTx1tF6zyt9ua2DxHPROTbub3I_WRg.js

BACKUP YOUR DATABASE BEFORE GOING FURTHER!
In case you mess anything up, CYA!

I went through and deleted all entries that were a CSS or JS file.
Be careful not to delete the directory reference entries that just
have the JS and CSS folders.
THEN, since I was using s3fs I went into the "s3fs_file" table and did the same thing.
I went back into the Performance page, enabled the CSS and JS aggregation, and saved.
Then cleared the site cache after that. This seemed to re-generate the
CSS and JS assets, re-built the asset table data, and the site was
back to normal!

I did have to dump the DB tables and import into my dev and local environments in order to mimic the new asset names, but this seemed to work like a charm.

SIDE NOTE: I am wondering if there would be some way for Drupal to add a style versioning system? Maybe that we could change the sites CSS versioning after major changes in order to have this done automatically? or maybe this is just something I will need to build my next module for!!


How to catch duplicate comments In my sites comments are moderated so (anonymous) visitors sometimes get confused and try to resubmit it.
It happenens within say 5 minutes only.

What is the best way to catch and reject duplicate comments by the same user?

One way is to look for same body text from same session within say 5 minutes and reject it.

I'm not aware of any module that would provide this particular functionality. First of all, I would reduce the risk for confusion. An example is: Store a CID in the users $_SESSION, and theme the comment form with "You have X comments awaiting moderation."

You could also add a custom validation function to the comment form with a hook_form_ID_alter, and simply deny comments that fall within your stated condition, "Same body text within 5 minutes from same session", or so.

I would definitely focus on the first one though. No matter what type of validation criteria you add, there will always be edge cases where there is a good reason for posting something that your will then reject. This will of-course be a tradeoff between how large a risk you are willing to take rejecting valid input, and the effor required to "un-confuse" users.


How attach a Custom Field do it by code to a Custom Type Page I create by YAML files a Field Custom, using the next documentation:

https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type

In this tutorial attach the field to Custom Type "car_brand" created by code, in my case I need attach the custom field to the Custom Type "page", he come default in drupal.

How I can attach the field to "page" content type?

Thanks a lot.

You just have to create or change the file attaching the field to instead be attached to the page content type:

First we'll have to rename it: field.field.node.page.field_brand_information.yml

Secondly, we should be fine just changing all the references from car_brand to the page bundle instead:

# field.field.node.page.field_brand_information.yml
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_brand_information
    - node.type.page
  module:
    - text
id: node.page.field_brand_information
field_name: field_brand_information
entity_type: node
bundle: page
label: 'Brand Information'
description: 'More specific information about the car brand'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  display_summary: false
field_type: text_with_summary

Generally this approach is quite tedious and I agree as also pointed out in the article that you rather do it through the UI and then export the files appropriately.


Remove link to terms page when printing taxonomy term on node--content_type.tpl.php? I have a node--content_type.tpl.php template where I want to print the taxonomy term associated with the current content as plain text so that I can surround it with a div class to print a special label for content with the selected term.

So for example I have chosen "Sold" as a taxonomy term and want to display the word with no link to the taxonomy terms page. It currently outputs as "<a datatype="" property="rdfs:label skos:prefLabel" typeof="skos:Concept" href="/taxonomy/term/6">Sold", so links to the taxonomy terms page.

I am currently using this code to print the term:

<?php

if(!empty($node->field_p_status['und'][0]['value'])) {
  $status = $node->field_p_status['und'][0]['value'];
}

?>

<?php if(isset($status)) { ?>

<?php print render(field_view_field('node', $node, 'field_p_status', array('label'=>'hidden'))); ?>

<?php } ?>

Any idea how to strip it down so it prints just "Sold"?

To print the raw value you can use this code:

<?php

if(!empty($node->field_p_status['und'][0]['value'])) {
  print $node->field_p_status['und'][0]['value'];
}
?>


Installing Drush on Mac I am installing Drush on my Mac following the instructions I found on https://linode.com/docs/websites/cms/drush-drupal/.

Everything works perfect, but I got stuck at the end while creating the symbolic link. Please find the error below.

Mudasirs-iMac:/ mudasir$ sudo ln -s /usr/local/src/drush/drush /usr/bin/drush

ln: /usr/bin/drush: Operation not permitted

You can't write to /usr/bin on OSX (since Yosemite).

Add your symlink to /usr/local/bin instead, and make sure that's in your path.

ln -s /usr/local/src/drush/drush /usr/local/bin/drush


Fivestar being cached for anonymous users! On enabling caching for anonymous users, it appears that the fivestar votes are also being cached, which is super-weird.

On disabling caching for anonymous users, things work great.

We use memcache, could that be a problem? Any suggestions about how I should go about this?

From https://drupal.org/node/285855

  "When "Caching mode" is enabled (admin/settings/performance),
  anonymous users don't see changes in rating. Every anonymous user see
  rating as it was when first anonymous user visited node.

  When cache is disabled anonymous users see rating correctly.

  Is there some way how to use Drupal caching and at same time make
  fivestar working for anonymous users?"

Fix -:

  "Change caching time to 1-5 minutes, will make it seem that as the
  amount of time it took for his vote to register."

Is this the only possible fix?

Rather than rendering the Voting widget with the rest of the page, I would add a delayed (ie. on page-load) AJAX request for every widget which would do a back-end call, render the widget (without pulling in a cached version) for the appropriate node/piece of content, and inject it back into the DOM.


Why is my custom module is not listed with the drush command pm-projectinfo? If you have drush >= 8 you can use drush pm-projectinfo to show a report of available projects and their extensions. If you use drush pm-projectinfo devel you should see the information about the devel module something like this:

 Name             :  Devel (devel)
 Type             :  module
 Version          :  7.x-1.3
 Status           :  1
 Extensions       :  devel
                     devel_generate
                     devel_node_access
 Drush Commands   :  devel-download
                     devel-reinstall
                     fn-hook
                     fn-view
                     devel-token
 Datestamp        :  1338940281
 Path             :  sites/all/modules/development/devel

I come from creating a custom module named my_custom_module, but when I use drush pm-projectinfo my_custom_module the output is:

 [warning] my_custom_module was not found.

It's very weird because I know that my module works fine, I use it every day, but the command doesn't work.

How can I solve this? Is it a problem with drush or is it a problem with my custom module?

The solution is very simple, you just need to add project property in your .info file.

In this case:

project = "my_custom_module"

The Drupal documentation page Writing module .info files (Drupal 7.x) says about the project property:

  project (Discouraged, packaging use only)

  Module maintainers should not use this at all. The packaging script on
  drupal.org will automatically place a string here to identify what
  project the module came from. This is primarily for the Update status
  module, so that Drupal installations can monitor versions of installed
  packages and notify administrators when new versions are available.

But as this is a custom module I think that I need to put this property in my .info file because if not, drush pm-projectinfo my_custom_module will not works.

Let's see why if you don't use the project property this doesn't works

Inside the drush code you can see the implementation of the drush pm-projectinfo command:

function drush_pm_projectinfo() {
  // Get specific requests.
  $requests = pm_parse_arguments(func_get_args(), FALSE);
  // Get installed extensions and projects.
  $extensions = drush_get_extensions();
  $projects = drush_get_projects($extensions);

If you use:

drush ev 'print_r(array_keys((drush_get_extensions())))' | grep my_custom_module

You will see something like this:

[112] my_custom_module

So, we need to test the next step:

drush ev 'print_r(array_keys(drush_get_projects(drush_get_extensions())))' | grep my_custom_module

Nothing to show

So, if we go inside the drush_get_projects() function we can found the following code in line 673:

  foreach ($extensions as $extension) {
    $extension_name = drush_extension_get_name($extension);
    $extension_path = drush_extension_get_path($extension);
    // Obtain the project name. It is not available in this cases:
    //   1. the extension is part of drupal core.
    //   2. the project was checked out from CVS/git and cvs_deploy/git_deploy
    //      is not installed.
    //   3. it is not a project hosted in drupal.org.
    if (empty($extension->info['project'])) {

And in number 3 we have our answer.


Module that will display certain facebook content? I realize there are quite a bit of facebook possibilities main having to do with facebook account connections. What I'm interested though, is content (especially videos!) that is being put up in a facebook group that was created and having that display on the drupal site. Is there a module out there that does that?

I think that you can use this jquery plugin http://www.neosmart.de/social-media/facebook-wall to put an specific wall inside a block or node, and then you can improve the javascript code (I guess in Parse feed data / wall section of jquery.neosmart.fb.wall.js file) to show only items with specific content, in this case, for example, a content using uiVideoThumb class (according my review uiVideoThumb is one class used to thumbns that link to videos).

specifically, in the js, in the section Parse feed data / wall line 81:

for(var k=0;k<max;k++){

you can add some lines to detect the specific content, for example:

var pattern=/uiVideoThumb/g;
var stringContent = JSON.stringify(data[k]);
if(stringContent.match(pattern)){

do not forget close this new IF declaration (near line 162).

Acording my test, only content with these condition is displayed.

one note: seems that the code has a Drupal´s module version http://drupal.org/project/fb_walls but not was clear to me how this module works over Drupal.


How do I create a block only for the user "owning" the profile page? I made so the logged in user have a recap of their last comments/added node on their profile with a view.
As I am making the profile page public, I need to be able to hide those blocks from others authenticated users.

How can I make the block visible to the user for which the profile page is?

So I found out :

Either you can directly go in view and add a "FILTER CRITERIA" > "(author) User: Current" and it will hide the content for user that are not the current logged in user
Or you can go in the block settings, select "Pages on which this PHP code returns TRUE (experts only)" and add in the box <?php global $user;
return $user->uid == arg(1); ?> and the block disappear totally if you are not the current user.


Get edit form from a webform submission I want to get the edit form from a Webform Submission to handle this in the logged in user area.
Like node/{node_id}/submission/{submission_id}/edit
How do I do this?

If I understand correctly your question,
you should click "Use the administration theme when editing or creating content" in admin/appearance

Even better, try Administration theme module which will allows you to use you Administration theme on more pages like:

node/*/webform-results
node/*/webform-results/*


Different front page depending on previous selection for anonymous users I have a D8 project where the client wants users to select a route they will follow depending on who they are (let's call the two groups Students and Employers), and then the next time they visit show the home page for the appropriate group.

So for example if they click mydomain.com/students, the next time they visit mydomain.com/ it will redirect them to /students

The users will always be anonymous, so not logged in.

I have seen various solutions to this (e.g. the Front module), but they all seem to be dependent either on user role (no use for anon users), a subdomain or browser locale, none of which help us.

What I have in mind is that when visiting one of the target landing pages (e.g. /students) with a Referrer header of the home page, we set a cookie or session variable. Then when the root URL is requested with no or an external Referrer header (so you can still go to the proper homepage via navigation), we check for this and send a redirect if appropriate. The actual paths used could be saved in config.

I'm sure there is a hook I can use somewhere in core to do this, haven't looked into it in much detail yet, but my biggest concern is caching. If the homepage is cached, the hook would never fire and we wouldn't get the redirect, but at the same time I don't want to disable caching on the homepage.

Any experiences/ideas here would be very much appreciated.

So... I think I have solved this, although cache testing has not yet been done (any thoughts on how to do this welcome!).

Credit to this post for the outline solution, and also to this one for D8 redirects.

First, I create a custom module called mysite_homepage_redirect - it needs the following mysite_homepage_redirect.services.yml file (apparently a priority > 200 means it gets fired before the cache):

services:
  http_middleware.mysite_homepage_redirect:
    class: Drupal\mysite_homepage_redirect\StackMiddleware\MysiteHomepageRedirect
    tags:
      - { name: http_middleware, priority: 250, responder: true }

Then we need the following in src/mysite_homepage_redirect/StackMiddleware/MysiteHomepageRedirect.php:

<?php

namespace Drupal\mysite_homepage_redirect\StackMiddleware;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Provides a HTTP middleware.
 */
class MysiteHomepageRedirect implements HttpKernelInterface {

  /**
   * Map of pages that should be redirected to from home
   * this coulde ultimately be put into config with an admin screen
   */
  private $navigation_map = array(
    '/employers',
    '/students',
  );

  /**
   * The wrapped HTTP kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * Constructs a MyModule object.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $kernel
   *   The decorated kernel.
   * @param mixed $optional_argument
   *   (optional) An optional argument.
   */
  public function __construct(HttpKernelInterface $http_kernel) {
    $this->httpKernel = $http_kernel;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {

    $current = $request->server->get('REQUEST_URI');
    $source = $request->server->get('HTTP_REFERER');
    $host = $request->server->get('HTTP_HOST');

    //cut the host string out of the referer
    $x = strpos($source, $host);
    if($x) {
      $source = substr($source, $x + strlen($host));
    }

    $redir = isset($_COOKIE['mysite_homepage_redirect']) ? $_COOKIE['mysite_homepage_redirect'] : false;

    if($current == '/' && strpos($source, $host) === false && $redir) {
      $response = new RedirectResponse($redir, 302);
      $response->send();
      return;
    }
    elseif(in_array($current, $this->navigation_map) && $source == '/') {
      //need to use native setcookie() because user_cookie_save relies on the user module which is not yet loaded
      //expires in 30 days
      setcookie('mysite_homepage_redirect', $current, time() + 86400 * 30);
      \Drupal::logger('mysite_homepage_redirect')->notice("saved redirect cookie: " . $current);
    }

    return $this->httpKernel->handle($request, $type, $catch);
  }
}

That seems to work as expected. The cookie seemed the simplest way to save the redirect. Any further thoughts welcome!


List all Nodes a user ever edited I want to do display a list with Views, which shows all Nodes the current user have ever edited.

The workbench Module includes a list like I need, 'workbench_edited', this view uses the Filter

(revision user) User: Current (Yes)

But the problem is that this View only checks if the user is the editor of the CURRENT REVISION, it does not check all revions of a node, just the current one.

Is there a way to list all Nodes a User ever edited? So that Views checks all revisions of a node?

The "content revision : content" relationship in that view needs to be based on the nid rather than the vid. Remove that existing relationship and add back the one that has the same name but uses the nid.

Then you'll need to fix the relationships that have been broken since a number of the fields, filters, and sort options relied on that relationship.  You can just step through each of the fields and filters, open their settings, then click "apply" to re-save them to fix the relationships.

In the settings for the title field you need to switch it to link to the revision rather than the node, in order to avoid an error.

And I also noticed that, for some reason, the exposed "published" filter got switched to having a default value of "no" after doing these steps.  I have no idea why that happened, but switch it back to "any".

Here's an export of the View you should end up with: http://pastebin.com/a9tXXCqP


how to change alphabetic order to descending order in drupal 7 I have a accordion menu in left side and the menu list come as alphabet order but i want newest come first. how can i change the sorting of that list.

Drupal menu items are manually ordered. You can drag and drop into the correct order here: /admin/structure/menu/manage/navigation


Migrating stories from Drupal 5 to Drupal 6 I am designing a Drupal 6 website from scratch, but I need to import about 5,000 story type nodes from a Drupal 5 website into the new one. What might be some of the ways to do that?

I would personally follow the steps described below:

1) Transfer my Drupal 5 site in a test machine (possibly a local VMWare Development Machine).

2) Convert the Drupal 5 site to Drupal 6 using the guide that you can find here.

3) Use a Node Export/Import module to transfer the nodes from the local site to the new/from-scratch-built website. (e.g. Node Export module)

Note: If you do not know how to transfer your live site to your local machine the steps that I usually follow are:

a) Download the live site's files locally

b) Export the live database through PHPmyAdmin and save it locally

c) Import the database in my local MySQL server

d) Most of the times the links don't work properly in the local machine. The most common reason for this is that the local server does not have the capability for clean URLs so I add this to the httpd.conf:

<Directory /var/www/yourDirName>
   RewriteEngine on
   RewriteBase /yourDirName
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

and restart the apache server (notice that you will have to replace the "yourDirName" part with whatever your dir name actually is)


In the Counter module the Visitors "This Year" count is decreasing. How can I get it to increase instead? The Visitors "This Year" count decreases in number in the D8 Counter module while the "Hits" and "Visits" increase as normal. For example, one afternoon the "This Year" count was 329,546. The next morning it was 328,149. The third day is was 327,138. The "Visits" and "Hits" only increase on the average of 150 per week. The "This Year" is decreasing more than a thousand by the day(????) What's going on? Any help would be appreciated.

I've checked the module and i can confirm that the behaviour of the module is like previously i explained in comments. So, it is not a problem related to a module. It's a problem related to marketing analysis. Probably the "Visits" and "Hits" are absolute values ( they are always increasing ). On the other hand, the "This Year" value is a calculated value for 365 last days.

At this time last year, you had lots of visitors.


How to display multiple fields in one line in drupal First of all I'm new to Drupal. I want to add 3 form fields inline as shown in the image. So I want to know what is the best method of doing it.

As mentioned in the comments, you need to use CSS to achieve this. Drupal makes it really easy by wrapping the elements nicely with divs and relevant classes. For example, if you are creating a new issue in Drupal.org, the form provides http://drupal.org/project/issues/linkedin?categories=All this kind of structure.

Using an inspector tool, you can find the target divs and apply a CSS in this way to your theme:

.views-exposed-form .views-exposed-widget {
    float: left;
    padding: 0.5em 1em 0 0;
}

Thats it. Don't forget to clear your cache to see the changes!


How to just show front page and message when search api search was queried with blank input How can I just show front page when no letters were printed in search input, but it was submitted?

And optionally maybe show message 'please enter the terms of the search'

I thought of doing this with Rules, but no rules considering searches are present(

Here is a solution:

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

  if($form_id == 'search_block_form' || $form_id == 'search_form') {
    array_unshift($form['#validate'], 'custom_search_validate');
  }
}

function custom_search_validate($form, &$form_state) {
  dpm($form_state);
  if(isset($form_state['values']['search_block_form']) && $form_state['values']['search_block_form'] == FALSE) {
    drupal_set_message('please enter the terms of the search', 'error');
    drupal_goto();
  }

  if(isset($form_state['values']['keys']) && $form_state['values']['keys']
    == FALSE) {
    drupal_set_message('please enter the terms of the search', 'error');
    drupal_goto();
  }
}


How do I populate report page using a controller? I'm following this tutorial on creating a report page for a custom plugin, but note that I'm using Drupal 9, and not Drupal 8 as per the tutorial.
I've created a report() method inside my implementation of ControllerBase:
<?php
/**
 * file
 * Contains \Drupal\rsvplist\Controller\ReportController
 */

namespace Drupal\rsvplist\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Database;
use Symfony\Component\HttpFoundation\Response;

/**
 * Controller for RSVP List Report
 */

class ReportController extends ControllerBase {

  /**
   * Gets all RSVPs for all nodes.
   *
   * @return array
   */
  protected function load() {
    $select = Database::getConnection()->select('rsvplist', 'r');

    // join the users table, so we can get the entry creator's username
    $select->join('users_field_data', 'u', 'r.uid = u.uid');

    // join the node table, so we can get the event's name
    $select->join('node_field_data', 'n', 'r.nid = n.nid');

    // Select the specific fields for the output
    $select->addField('u', 'name', 'username');
    $select->addField('n', 'title');
    $select->addField('r', 'mail');

    $entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);

    return $entries;
  }

  /*
   * Creates the report page
   *
   * @return array
   *   Render array for report output.
   */
  public function report() {
    $headers = [
      t('Name'),
      t('Event'),
      t('Email'),
    ];

    $rows = [];
    foreach ($this->load() as $entry) {
      // sanitise each entry
      $rows[] = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', $entry);
    }

    return [
      ['table'] => [
        '#type' => 'table',
        '#header' => $headers,
        '#rows' => $rows,
        '#empty' => t('No entries available'),
      ],
      ['message'] => [
        '#markup' => t('Below is a list of all Event RSVPs including username, email address and the name of the event they will be attending.'),
      ]];

  }
}

My routing file seems to be set up correctly since I see the link to the report page:

However, when I navigate to the report page, I just see a blank page;

I thought perhaps I'm supposed to return a HTTPFoundation\Response object, so I tried this;
$response = new Response();
$response->setMaxAge(0);
$response->setContent('hello world');

return $response

But that seemed to have the effect of completely nuking the HTML of my page and just printing "hello world" to the screen with all menu items gone, so clearly that's not correct either. What am I doing wrong here? Better yet, where should I go to learn about how to do this correctly?

A controller needs to return a render array for the page content. It is explained in Routing API and page controllers / Route controllers for simple routes.

The only requirement is that the method specified in your *.routing.yml file returns:

A render array (see the Theme and render topic for more information). This render array is then rendered in the requested format (HTML, dialog, modal, AJAX are supported by default). In the case of HTML, it will be surrounded by blocks by default: the Block module is enabled by default, and hence its Page Display Variant that surrounds the main content with blocks is also used by default.
A \Symfony\Component\HttpFoundation\Response object.

It's exactly what DbLogController::overview(), the controller method for the Recent log messages (/admin/reports/dblog) route, does.
  $build['dblog_table'] = [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => [
      'id' => 'admin-dblog',
      'class' => [
        'admin-dblog',
      ],
    ],
    '#empty' => $this->t('No log messages available.'),
    '#attached' => [
      'library' => [
        'dblog/drupal.dblog',
      ],
    ],
  ];
  $build['dblog_pager'] = [
    '#type' => 'pager',
  ];
  return $build;

(The Database Logging module also adds a pager, which is helpful when the rows to show could be too much, or they would make the rest of the page rendered too low in the page.)
What is wrong in your code is that it uses an array containing a string as array index, instead of a string. Any PHP version that supports the short array syntax would throw Fatal error: Illegal offset type. (The other versions would throw Parse error: syntax error, unexpected '[' since they don't support the short array syntax.)
The return instruction should be the following one.
    return [
      'table' => [
        '#type' => 'table',
        '#header' => $headers,
        '#rows' => $rows,
        '#empty' => t('No entries available'),
      ],
      'message' => [
        '#markup' => t('Below is a list of all Event RSVPs including username, email address and the name of the event they will be attending.'),
      ]
    ];


Let "Availability Calendars" start on monday I created this website http://peace-in-the-city.be/en/book-now and on that page you will see I used a Calendar to show the availability of the apartment. ( http://drupal.org/project/availability_calendars )

I tried to let the calendar start on Monday. I googled for the solutions and did change my regional settings local to start of the week to Monday. It worked after that for a couple days. But for some reasons it went back to Saturday. Changing the regional setting has no effect anymore now.

At this point, I'm clueless... Any tips, links and ofcourse working solutions are welcome.

PS. I did not change anything in the rAvailability Calenda module. I'm just install modules - enable/disable - or change configuration.

As a best practice whenever an issue like this arises - disable the module, uninstall, flush all cache, verify settings for regional locale is set to start on Monday.

Now re-enable the module. Flush all cache. Re-configure. And see if things are working as expected.

As an added additional option if you care to contribute to the community, on a fresh install of Drupal, attempt to recreate the issue that "potentially" caused this issue to arise by re-tracing any steps you may have taken (other contributed modules, other seemingly unrelated changes, etc.). If you're able to trace what caused the issue, then perhaps the potential bug can be fixed.

Of course, regardless if the uninstall, reinstall works and functionality doesn't again fail after a few days then you have solved your issue! This should be a fairly typical go-to strategy of troubleshooting for any module issue.


'File used may not be referenced' if form field submits same image twice I've built a custom module with a form that allows users to define custom site wide settings such as the icons that are meant to be used.

I'm able to upload and save images into the form using managed_file elements. However if I resubmit the form without changing what files are used I receive the message:

  The file used in the First Icon Image field may not be referenced.

First Icon Image was the name of my field in that case. Everytime I change the image used I don't receive the image. It's only when I submit the form again with the same values for the image fields.

I'm handling the image field with the following code:

public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('mymodule.settings');
    $form['icon1_file'] = [
                '#type'            => 'managed_file',
                '#name'            => 'icon1',
                '#title'           => t('First Icon Image'),
                '#default_value'   => $config->get('icon1_file'),
                '#upload_location' => 'public://',
    ];
}

public function submitForm(array&$form, FormStateInterface $form_state) {
    $imageid = $form_state->getValue('icon1_file');

    $file = file_load($imageid[0]);
    if (gettype($file) == 'object') {
        $file->status = FILE_STATUS_PERMANENT;
    }
    $filename = File::load($imageid[0])->getFilename();
    $this->config('mymodule.settings')
         ->set('icon1_file', $form_state->getValue('icon1_file'))
        ->save();
    $file->save();
    $this->config('mymodule.settings')
         ->set('icon1_filename', $filename)
         ->save();
}

After doing some research I saw that a possible solution might be using \Drupal::service('file.usage')->add however I'm not sure what I'd use for the entity_type and entity_id parameters if that, indeed, is the solution.

How would I prevent the "File used in the field may not be referenced" when occurs on the second time I submit the form with the same file?

UPDATE: I added

$file_usage = \Drupal::service('file.usage');

and

$file_usage->add($file, 'mymodule', 'managed_file', $imageid[0]);

to the code, but it did not resolve my issue.

Using the skumy's approach worked for me, but instead of putting 'managed_file' as the third parameter for $file_usage->add(), I put 'file'.

$fid = $config['image'][0];
$file = File::load($fid);
$file->status = FILE_STATUS_PERMANENT;
$file->save();
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'mymodule', 'file', $fid);

That's because putting 'managed_file' causes an error when I check the file usages, following the links in the "Used in" column in /admin/content/files, since in my installation does not exist any entity called 'managed_file'.

  The "managed_file" entity type does not exist

Using 'file' instead of 'managed_file' solves the problem.


How do I render the search form for a particular Apache SOLR search page on its own? I have the SOLR search module installed, and have set up a couple of different search pages.

I need to render the form for one of these pages on a separate page. I thought I could just piggy back off the default search_form(), but it doesn't work.

Using this code:

$build['search_form'] = drupal_get_form('search_form', 'directory/search', '', 'apachesolr_search');

The search form is displayed, and has the correct action property. But when the form is submitted, it just redirects to directory/search, without the keys in the URL (which are obviously required for the search).

What am I missing?

Well I'm not sure what the problem was, but after a bit of further digging into apachesolr_search I've come up with a work around which seems to do the trick:

$search_page = apachesolr_search_page_load('PAGE_ID');

module_load_include('inc', 'apachesolr_search', 'apachesolr_search.pages');
$build['search_form'] = drupal_get_form('apachesolr_search_custom_page_search_form', $search_page);

As kiamlaluno has noted in the comments it doesn't look like it's actually apachesolr_saerch causing this behaviour, but rather the core search module doing...something.

Hopefully this code will save someone the time in the future.


In Views, use group type's image in a field when a group content type is fitered I currently have a view that filters through a certain content type, which is a group content type. I am displaying fields such as title, body and last comment. I would also like to add an image field, which comes from the content type's group.

Is there a way to do this in Views?

I am using Drupal 7, and Views 3.

You will need to setup a relationship between the "Group Type" and "Group Content" content types. If the parent > child relationship is determined using Taxonomy you can use the "Taxonomy: Parent Term".

Then you can add the field for the image which comes from the parent (make sure you change the relationship to the parent tax) and have it on the same row the as children.


Two forms on one page break submit I have two forms on a node page (the comment one + a custom form). Ajax is not enabled for both of them but still, when submitting the custom form form_set_error or durpal_set_message are not displayed but displayed when you load a new page (if you submit the form again, if you reload a page or if you change the page). It's like I have a hidden ajax behavior messing the submit up.

function my_module_quote_request_form($form, &$form_state) {
  global $user;
  $account = user_load($user->uid);

  $user_phone_number = $account->field_user_address[LANGUAGE_NONE][0]['phone_number'] ? $account->field_user_address[LANGUAGE_NONE][0]['phone_number'] : '';

  $form = array();

  $form['phone_number'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone number'),
    '#default_value' => $user_phone_number,
    '#size' => 30,
    '#maxlength' => 10,
    '#required' => TRUE,
  );

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#title' => t('Submit'),
    '#type' => 'submit',
    '#value' => t('Request'),

  );
  $form['actions']['cancel'] = array(
    '#title' => t('Cancel'),
    '#markup' => l(t('Cancel'), '/market'),
  );

  return $form;
}

function my_module_quote_request_form_validate($form, &$form_state) {
  if (blabla) {
   form_set_error($phone_number, $message);
  }
}

If you trigger blabla, then the message is not displayed but displayed on page reload.

Any idea what it can due to?

I have finally found what was the issue. It's absolutely not related to the fact I have two forms but that I was implementing my theme variable in a node preprocess function.

Errors messages are prepared in upper function so the result is that you alter a variable after it's actually called. The result is the message is displayed on reload.

See here : form_set_error message delayed one page refresh


Programmatically enable another language I'm trying to programmatically enable/install another language? (Through install profile).. Any suggestions, please?

Assuming your environment is Drupal 7 (or 6 may be OK, too?), you can use locale_add_language() function (defined in locale in the core). For example, if you want to enable French, run locale_add_language("fr") and the job's done.

Then, you can check the result via language_list() to make sure.


Mailto link causes blank page I just attempted to add an e-mail address link to a drupal page putting

Contact us

on the page. I then preview it, and no content shows up but the title. I remove the link and all the text is back again. What is causing this and how can I fix it? The strange thing is I have pages made earlier that already have mailto links on them.

Edit: I've tried this with both filtered and full HTML. I also have Invisimail installed, which does some e-mail filtering.

(I also couldn't get filtered html to turn a e-mail address into a hyperlink, but then discovered it was because it was in a  block.)

If all else fails, you could try using the Bbcode module.  The advantage here is that you can turn Email address encoding on, so your address isn't spammed.  (If you want this feature without the Bbcode module, you could use the SpamSpan module.)

Sorry, I can't tell you how to fix your issue... but this may possibly be a workaround if all else fails?


Add different classes to the images that where uploaded with multi-upload I'm looking for the best solution to add different classes to images that where multi uploaded to one field.

So not a class to the field, but a possibility to add different classes to each single image...

So my client will be able to add for ex. the class 'right' that will let the image float to the right and be only 60% width. And then for a other image add the class 'left' for example...

So if you look at the image above, you see my client can add for each image a different alt and title. There should show up there a space where he can add for each image a different class.

Any tips, links or other sulotions to reach my goal are welcome!
Thanks in advance.

Go to admin/structure/file-types/manage/image/fields. Add a text field for the class.

Now the difficult part is how you are going to get the class as an attribute into the img tag, or into a wrapper div.

If you are using Views you can easily 'rewrite the output of this field' and do it in there.

If you want to render by view mode you can use Display Suite and a custom field template, or you can just forego Display Suite and implement your own custom template file for the file display : Displaying Media

And perhaps rethink your methodology. You can let your client use CKEditor and set the classes to the images right there where he has a proper preview of how it is going to display. You can add your own custom predefined styles that is selectable from a select list. It is also possible to right click on an image and set the classes on.


Programmatically append multiple paragraphs to entity reference field on node I have a paragraph type that contains a text field and a text format field.
I also have a content type that takes an unlimited number of paragraphs of this type.

The paragraph type is called 'questions_and_answers' and the two fields are 'field_question' and 'field_answer'. I'd like to be able to programmatically append 'questions_and_answers' paragraphs to a content type.

In the example below I'm grabbing the content from a 'double' field and importing them into the paragraph reference field.
Here's my code so far.

    $nids = \Drupal::entityQuery('node')
        ->condition('type', 'faq')
        ->execute();
    foreach ($nids as $nid) {
        $node      = \Drupal\node\Entity\NODE::load($nid);
        $questions = $node->field_questions_and_answers->getValue();
        foreach ($questions as $question) {
            $q         = $question['first'];
            $a         = $question['second'];
            $paragraph = Paragraph::create([
                    'title'          => $q,
                    'type'           => 'questions_and_answers',
                    'field_question' => $q,
                    'field_answer'   => $a,
                ]);
            $paragraph->save();
            $node->field_qs_and_as[] = $paragraph->id();
        }
        $node->save();
    }

However when I perform this action the node gets a number of question paragraphs added but they're completely empty and they can't even be deleted. What am I missing? How do you append multiple paragraphs you created to an entity reference field on a node?

When you add a paragraph you also need to pass the revision id:

  $node->field_qs_and_as[] = [
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ];


How do you make sortable tables with a pager with data from a custom table? For Drupal 6 you could do something like this:

$header = array(
  array('data' => t('Order id'), 'field' => 'order_id'),
  ...
  array('data' => t('Transaction time'), 'field' => 'payment_time', 'sort' => 'desc'),
);
$sql = "...";
$sql .= tablesort_sql($header);
$limit = 25;
$result = pager_query($sql, $limit);
...

I took a look and for drupal 7 and both pager_query and tablesort_sql is now gone. It seems that instead the PagerDefault class can be used to create a pager query using DBTNG. I wasn't able to find any clues on a simple API for attaching a sortable table to the query like it is done in Drupal 6.

So how do you create a sortable table with a pager pulling data from a custom table?

You use the so called extenders.  In your case, the code would be similar to the following one.

$header = array(
  array('data' => t('Order id'), 'field' => 'order_id'),
  // ...
  array('data' => t('Transaction time'), 'field' => 'payment_time', 'sort' => 'desc'),
);

// Initialize $query with db_select().
$query = db_select('your table name');

// Add the fields you need to query.
// ...

// Add the table sort extender.
$query = $query->extend('TableSort')->orderByHeader($header);

// Add the pager.
$query = $query->extend('PagerDefault')->limit(25);
$result = $query->execute();

See HowTo: Convert a module to DBTNG, Dynamic queries: Table sorting and Extenders.


How to print node's timestamp in computed field I want to save my node's submission timestamp in a computed field. I know that I should use date_format function, but idk how it works.

How can I do that? thanks.


Can you make a block appear only in a specific content-type The natural option is to filter blocks by node ID's. I am looking for a way to filter it by content-types (i.e the block "roses in special prices!" will appear only at the content type "Flowers").

Google search didn't help me very much in this subject. Thank you for your help.

In the block configuration page, select the content type like this picture:


url alias not working in block page restrictions I've create some blocks that I have set up to show on "Only the listed pages".

I had set up a taxonomy with a url alias and added this alias to the list of pages allowed. This was working few weeks ago. The client has come back saying that the blocks have disappeared from the pages and they have.

When I was looking at the block I took it's none aliased url and put that into the list of allowed urls and then the block reappeared.

Has anyone come across this before and if so was there a reason behind it?

Do I now have to go through the site and put the node/1 etc.. url into the block allowed lists?

Thanks in advance for your help.

Looks like this has to do with having multiple URL Alias set up for the same page. To fix the issue I had to remove all URL Alias' that were not being used. The blocks then reappeared on the page.

If some else has an answer to this please post and if it fits better than my conclusion I'll mark it as the answer instead of this.


How to manually delete a node from the database knowing its id Well, look my problem is weird, I have a view that lists content of a desired type, it is listing all the content of a type, I have deleted from the drupal admin UI a node of that type, but the view is still listing the node I have deleted. If I try to access to that node from the view, I get an entityMetadataWrapperException

Now I cannot see the node in the drupal content admin UI.

I know the nid of this node (its 22) I need to delete it manually from the database, how to achieve this, is necesary a custom module or something?

Thank you very much for your help.

You should use node_delete:

<?php
$nid='22'; // $node id , which you want to delete;
node_delete($nid);
?>

This function from the API does the necessary cleaning up when a node is deleted.

You can stick this in a custom module, or enable the PHP filter and just have it a node where you allow PHP code.

If you use the PHP Filter method, remember to disable it when done.  You don't want it permanently enabled on a production site.

You may also want to repair your database, just to make sure.  The screenshot below shows how to use phpMyAdmin to repair the {sessions} table.  You can also use to repair the {node} table


How do I add typekit fonts to a D8 theme? Having looked over the existing D8 documentation on adding JS to the <head> of a page, I'm still not sure how to go about it?

What is the correct way to achieve this on every page for my theme:

<script src="//use.typekit.net/abc0abc.js"></script>
<script>try{Typekit.load();}catch(e){}</script>

Regarding inline JS, from the latest D8 documentation:

  In the case of front-end/styling (e.g. hosted font services), the JS
  belongs in the theme. Put the JS directly in your html.html.twig file.
  In the case of fonts, this will also allow you to put it right in the
  place that gives you the best (and fastest) end user experience,
  because it allows you to prevent a FOUT (Flash Of Unstyled Text) while
  the font is still loading (fonts loaded through JS must be listed in
  the HTML  before the CSS)!

So, I guess the inline JS goes directly into html.html.twig, but what about the external file?

I have this in my theme files, but it's not adding the external file to any pages:

mytheme.info.yml

libraries:
  - mytheme/typekit

mytheme.libraries.yml

typekit:
  version: 1.x
  js:
    //use.typekit.net/abc1abc.js: { type: external }

For put the library to the header you must user header: true, then:

mytheme.info.yml

libraries:
  - mytheme/typekit

mytheme.libraries.yml:

typekit:
  version: 1.x
  header: true
  js:
    //use.typekit.net/abc1abc.js: { every_page: true }
    js/custom.js: { every_page: true }

js/custom.js:

try {
  Typekit.load();
}
catch(e) {
}


Use Google Analytics to Track Home Page Links Differently We use Google Analytics on our Drupal website. We are re-doing our current homepage and we would like to track the links on our homepage separately from the rest of the tracking. For instance, if you navigate to the "Contact Us" section from anywhere on the website except the homepage, it logs it as such. However, if you navigate there directly from the homepage, it notes that the person arrived there from the homepage and there is pretty much a separate statistic for this.

We would like to see where people are drawn to when they land on the homepage, so this is why we would like to implement this.

Alternatively, if Google Analytics can't do this, is there another potential solution?

You actually can see the Landing pages and their behavior flow in your Google Analytics account. Login your Google Analytics account and go to "Reporting > Behavior > Behavior Flow", and you will see all the landing pages and interaction. The home page should be the "/".


Drupal 8 alter existing field setting How to alter existing field type instead of creating new one to add new options with custom processing for insert and display of the field.

Use case : upgrade hijri taarikh  project that extends the default date field types allows to use Hijri calendar for both select list and popup letting the user add Hijri dates and display Hijri dates.

To alter how to insert content into the field, define your own field widget and then apply the new widget for the existing field in "manage form display" of the content type.

Field Widget

To alter how the field is displayed, define you own field formatter and apply it in "manage display" in the same way:

Field Formatter

When you start with a field widget or field formatter, the fastest way is to copy an existing one out of core and modify it or use drupal console to generate the scaffolding.

If you only want to modifiy an existing widget/formatter, then extend it, not write a complete new one. This is a good explanation, how to do this:

http://www.sitepoint.com/creating-custom-field-formatters-drupal-8/


Implementing custom entity forms In Making use of the admin UI, Step 3 - Implement the entity adding/editing form, it says that you need to implement "a" form with the  ENTITY_TYPE_form() signature for add/edit/clone operations...

However the wiki page is not specific in regards to whether you should implement one or two forms. I explain - the example creates two "entities": a "regular" entity, and a "bundle" entity. The example then implements ENTITY_TYPE_form() for the "bundle" kind of entity ONLY.

In attempt two answer the question: "Should I implement one or two forms?" I looked at the source code of both the Model and the Profile2 modules. The source of my confusion is that the Profile2 module implements only one form - like in the example - for the "bundle" kind of entity. But on the other hand the Model module implements two forms: one for the "regular" entity, and another one for the "bundle" entity. Why? What's the correct use case? What's the difference between the two implementations? What additional ability does implementing the "regular" entity form give us, if any?

You're essentially correct I think. You can write a hard-coded Entity or make something more flexible supporting bundles (hard coded bundles, or say user-defined bundles like the Profile2 module) .... it can get as complicated as you want! :D

Have you seen this sandbox released a few days ago showing the mimimum for 1 hardcoded entity using Drupal core API and then an Entity supporting bundles via the EntityAPI.

https://drupal.org/sandbox/AlexanderAllen/2062531

  This module aims to provide a developer friendly, ready to use,
  barebones implementation of a custom Entity.

  The master branch provides a single, hardcoded entity (bundles are not
  supported), lacks entity revisioning support, and the only CRUD
  operation supported is save(). At a total of 16 functions, 4 files,
  one class and one method - the mater branch is recommended for
  understanding what is the bare minimum needed to create a custom
  Entity by code - using the Drupal core Entity API only.

  The bundles branch adds bundle and automatic CRUD support with the
  help of the Entity API contributed module.

  This module was inspired by the Profile2 and Model modules. This
  module is simpler than Model in that it uses the default UI and Entity
  controllers. If you're already comfortable with Entities, you should
  refer to the Model module instead for help with creating custom UI and
  Entity controllers.


Convert timezone value from seconds to W3C hour format Doing an API integration that requires timezones to be handed off in W3C format, while Drupal opts to store timezones in seconds.

Wondering what the clean way to do this is, rather than stripping the +/- sign, dividing by 3600 and adding it back on. There has to be a date transformation right?

FYI... W3C looks like this: -08:00 and Drupal looks like this: -28800

Trying to avoid this code...

// $val = '-28800';
$sec = substr($val, 1);
$hours = intval(intval($sec) / 3600);
$minutes = intval(($sec / 60) % 60);
$w3cTZ = substr($val, 0, 1) .
  str_pad($hours, 2, "0", STR_PAD_LEFT) .":".
  str_pad($minutes, 2, "0", STR_PAD_LEFT);

Ended up this this function...

// Convert timezone from second in Drupal to WC3 standard
function timezoneConvert($val, $toSeconds = false) {
  if(!$toSeconds) {
    // Starts like: "-28800" and becomes: "-08:00"
    $sec = substr($val, 1);
    $hours = intval(intval($sec) / 3600);
    $minutes = intval(($sec / 60) % 60);
    $w3cTZ = substr($val, 0, 1) .
      str_pad($hours, 2, "0", STR_PAD_LEFT) .":".
      str_pad($minutes, 2, "0", STR_PAD_LEFT);
    return $w3cTZ;
  }
  else {
    $seconds = 0;
    $units = explode(':',$val,2);
    $seconds += $units[0] * 3600; // Hours
    $seconds += $units[1] * 60; // Minutes
    return $seconds;
  }
}


Pass variables through AJAX callback and update MySQL database I have a form where the users submit a text. Here is the code:

$form['reason'] = array(
            '#type' => 'textfield',
            '#title' => '',
            '#size' => '200',
            '#attributes' =>array('placeholder' => t('*Reason')),
            '#prefix' => '
'
          );

    $form['newsletter_unsubscribe_submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#attributes'=> array(
            'class' => ['btn', 'btn-primary']
        ),
        '#ajax' => array(
            'callback' => 'newsletter_unsubscribe_quiz_submit_driven_callback_share',
            'method' => 'replace',
            'effect' => 'fade',
        ),
        '#prefix' => '
',
        '#suffix' => '

');

    return $form;

I managed to get the input of the user on a variable using $_values = $form_state['values'];
Also, I have some other variables to read from the current path and get some values.

    $_path = $_SERVER['HTTP_HOST'] . request_uri();

    preg_match('~id=(.*?)&~', $_path, $id);

    $first = $id[1];
    $second = substr($_path, -5);

where the first is the user id and the second is another variable that is unique per user.
My only problem is that I can't pass the $first and $second variables through the callback, and have them along with $reason $_reason = filter_xss($_values['reason']);
So, in my callback I want to be able to get the variables $first,$second with the $reason I already have. Now I have the $_path variables above my form, in the same function.
Then I want to perform an update query on MySQL, something like

UPDATE users SET reason=$reason
WHERE first=$first AND second=$second

where the column users has only the columns first,second and reason . Is this possible? Thanks in advance!

EDIT
I actually managed to do the first part and get the variables. I created two form inputs and I give them default values, the two variables I want to get, and I will hide them afterwards.
I still haven't figured out how to update MySQL though, so all answers are welcome!

I actually managed to do it! For anyone that may have a similar problem this is what I did.
First of all, I took the url parameters using parse_url and did the following

$parts =  parse_url($_path);
parse_str($parts['query'], $query);
$first = $query['first'];
$second = $query['second'];

,then put those variables as form default values, that I will hide using css:

$form['user_id'] = array (
         '#type' => 'textfield',
         '#title' => t('User id'),
         '#description' => t('user id'),
         '#default_value' => $first,
);

Then, on my callback function I take those variables, for example:

$_first = filter_xss($_values['first']);

and then I used db_update:

$num_updated = db_update('unsubscribed_users')
    ->fields(array(
        'reason' => $_reason,
      ))
    ->condition('first', $_first , '=')
    ->condition('second', $_second , '=')
    ->execute();


Change the value of a field depending on the selection of another I need to change the value of a field based on the selection of another.   I also don't want the user to have the ability to change this value.  I tried using #disabled = true, but the values don't save, and the same with #access.

I'm not sure how to go about this?  #disabled seems to stop values from being saved - what alternatives are there?

This surely can't be unique, I know often date fields do this.

Converting the element to a value type might be easiest:

// In a form alter hook.
$form['field_foo'][LANGUAGE_NONE][0]['value']['#type'] = 'value';
$form['field_foo'][LANGUAGE_NONE][0]['value']['#value'] = 'some static value';


Drupal 7: fetchField(0) giving me half of the records! I am trying to get all the records from one table. I get from the count 18 record, but the actual given lines are 9.

$name = 'admin';
$result = db_query("SELECT name FROM {users} WHERE name <> :name", array(':name' => $name));
$rownum = $result->rowCount();
print "This is the total number: ";
print $rownum;
print "
";
foreach ($result as $record) {
  $value = $result->fetchField(0);
  print $value;
print '
';
}

Results:

  This is the total number: 18
  user1
  user2
  user3
  user4
  user5
  user6
  user7
  user8
  user9

Do you think is my loop?

Yes, the loop iterates through result, but additionally you do that kind of again in your line $value = $result->fetchField(0);.

This should be changed to $value = $record->name;.


how to limit view to just show each type one time? I have a content type what is news, the news has a field type that is List (text) to keep different types of news. for example I have Health, Sport, Economic and etc.

So now I am going to create a block and have each of these type in that as a hyperlink.

I can do it and I created a new view block but each news_type may showing more than one time according to published content.

How to set the view (for block) to just show news_types and show them just one time?

You can achieve this by following the steps given below:

Enable aggregation under Advanced Accordion of the view
Add Nid field & set aggregation type as Count Distinct
Exclude Nid field from display
Add news type field & set Aggregation type as Group results together, in Group Column select Value option from dropdown
Remove Publishing Date from sort criteria

Please check attached screenshot for reference

and for more information you can check this question


Help me with hook_views_data I create a simple module to test hook_views_data but may I get some errors
this is my code

in tungcan.module file

function test_views_api() {
  return array(
    'api' => '3'
  );
}

and in tungcan.views.inc file

function tungcan_views_data() {
  $data = array();
  $data['tungcan']['table']['group'] = t('TungCan');
  $data['tungcan']['table']['basic'] = array(
    'field' => 'tungid',
    'title' => t('Tungcan'),
    'weight' => -100,
    'defaults' => array(
      'field' => 'tungname',
    ),
  );

  $data['tungcan']['tungname'] = array(
    'title' => t('Tung Name'),
    'help' => t('Display name of Tung')
  );

  return $data;
}

but when I clear cache, in my Views (add new views or add new Field) doesn't change anything.

Can somebody point out what is wrong in my code?

If the module is tungcan.module, then the implementation of hook_views_api() (necessary to load the include files used from the module to integrate with the Views module) should be tungcan_views_api(), not test_views_api().

If, vice versa, the module is test.module, then tungcan_views_data() should be renamed to test_views_data().


How to automatically generate a table of contents for a list of nodes? I want to generate a table of contents made up of the titles of the nodes listed within a view, which will then be displayed at the top of that view. The nodes are of just one content type.

I've spent the last couple of days looking through the pre-existing modules, but thus far they all seem to generate TOCs only for one particular node.

Can anyone point me in the correct direction?

You can make use of the attachment display in Views.

Create your normal view
Add an attachment display to that view:

Set "Attach to" to your normal view display
Configure the attachment display to show titles of your content types nodes.


Auto resize iframe from different domain? I already post a question regarding this issue but I haven't got any solid answer(s). Since we are not allowed to communicate inside the iframe due to "Same Origin Policy", which I almost give up due to all responses that there is no way to re-size the height of an iframe coming from different domain.

Being eager to solve the problem I searched for solutions and I found this easyXDM which looks like a solution to my problem. Any of you guys have an idea about this. In addition to that I read this post also.

I also tried this one but it keep refreshing the page and keep looping to add height. Looking forward to hear from you guys.

I'd hate to say it, specially as the author of easyXDM, but http://consumer.easyxdm.net/current/example/resize_iframe.html is kinda the way to do it if you need cross-browser (and especially IE6) support. If you're fine with only supporting more modern browsers, then using postMessage directly is not that hard.


How can I output custom html inlcuding js files I'm trying to output a JS based frontend app through one controller action.

To achieve this I need this action to output a very specific html layout, inlcuding some js files.

As far as i know I can return a symfony response object to bypass drupals render stack, inlcuding themeing mechanism.
But how to deal with the js files that should be included? Right now they are located inside my module folder, and I definitly don't want to link to this location inside my custom html output.

If i understand u want to output custom HTML for module, for smoething like this best practice is to preprocess output with twig template, in twig u can generate custom HTML for your needs and of course attach js and css with libraries.
See: Theme system overview.


multiple submit handlers I have the following code:

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

  switch ($form_id) {
    case 'user_login_block':
    {
      unset($form['links']);

      $form['#action'] = '/user/login';
      $form['#submit'][] = 'custom_redirect';

      $form['actions']['submit2'] = array(
        '#type' => 'submit',
        '#value' => t('Sign Up')
      );

      //echo '<pre>';
      //print_r($form);
      //exit;

      break;
    }
  }

}

By all examples I have seen this should call a custom_redirect() in which I have tried echo'ing and exiting and using drupal_set_message('Form submitted'); to verify this callback is called.

It is not...I have refreshed the cache a dozen times...I had this working about 3 weeks ago and changed something...

Any ideas?

All you need is $form['#submit'][] = 'custom_redirect';, if you want your custom submit handler to be ADDED to the default submit handlers.it will run along with the other (user module submit handlers) this way.

If you need this function only as your submit handler, then

$form['#submit'] = 'custom_redirect'; (assignment not addition to the submit array)

No need to alter the $form action.

Just alter the original submit button title if its necessary, no need to add another.


How to disallow node authors to change node content if comments were submitted for that node? On my site we have enquiries (nodes) and price offers (comments). So if there's at least one price offered (a comment submitted) the enquiry details (node) shouldn't be changed. Is there any way to do that?

If coding this is an option, you should look at hook_node_prepare.
As mentioned there on the first line:

  Act on a node object about to be shown on the add/edit form.

A code snippet idea that could do this for you:

function SOME_MODULE_node_prepare($node) {
  if (isset($node->nid) && $node->type == 'YOUR_CONTENT_TYPE' && $node->comment_count> 0) {
    drupal_set_message('You cannot alter this node anymore', 'warning');
    drupal_goto('node/' . $node->nid);
  }
}

Good luck!


Create node from another node How do I create a node from an existing content type on front end? Let's say we have a article i need to associate tags with it in a fashion.
For example a book of tags which a user can view . Either we can create a book or we can add tags to an already existing book. Those books are binded to a user also.

Well if what I getting from you is right then you have to look into Taxonomy Vocabulary and terms.

So you can have a Vocabulary of Sports but under sports there are so many taxonomy terms - types of sports, like footbal,hockey,basketball etc

then for your content type you add a taxonomy field mapped to the sports vocabulary

now users can create content and add the various tags/terms to it.

if not then you may have to look at using books in drupal


Add user points to author for every up vote received to content using Rate module I saw the post Add user points for every upvote But that was for rewarding the voter, I want to reward the author like Reddit karma. Does anyone know how to do this with Rules? Vote integration for rules is installed of course

I recommend to go for a combination of these often used modules to add (or subtract) user points when some node is voted up (or down):

Voting API.
Rules.
Voting Rules (attention: alfa version only).
User Points.

It's also the approach used in the Answers module (disclosure: I'm a co-maintainer of it), i.e. within its submodule "Answers Userpoints". If you agree, read on ...

Required Rules

To handle all variations of voting, you need 4 rules (only!), which cover these 4 cases:

a node is upvoted.
an upvote for a node is canceled (= no longer upvoted).
a node is downvoted.
a downvote for a node is canceled (= no longer downvoted).

Below are the required rules, for each of these cases (use the Rules UI to import them in your own site, after you enabled the required modules mentioned above). These rules are enhanced versions of the rules included in the 7.x-4.0-rc2 version of Answers (and are expected to be committed to its dev version also). They use a content type with machine name answers_question (adapt this name to fit your own machine name).

Have a close look at how user points are added (or subtracted), and also who gains (or looses) those points. Obviously, then actual amounts of userpoints can be adapted in those rules to fit your own needs.

Upvote a node

The rule below will grant +5 user points for an upvote (to the author of the node):

{ "rules_voteup_question" : {
    "LABEL" : "voteup_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "5",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive upvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionUpvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Cancel the upvote a node

The rule below will grant -5 (= remove +5) user points for a cancelled upvote (to the author of the node):

{ "rules_voteup_question_cancel" : {
    "LABEL" : "voteup_question_cancel",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_delete_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-5",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Unupvote [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionUpvoteCancelled",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Downvote a node

The rule below will subtract -2 (grant -2) user points for a downvote (to the author of the node) ... AND also -1 user point for the voter:

{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Cancel the downvote a node

The rule below will grant +2 (= remove -2) user points for a cancelled downvote (to the author of the node) ... AND also +1 user point for the voter:

{ "rules_votedown_question_cancel" : {
    "LABEL" : "votedown_question_cancel",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_delete_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Cancel downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteCancelled",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Withdraw downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteWithdrawn",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}


How can I get user_save() to update the nid instead of creating a vid? I updated a node at hook_user_update() with this node object:

$node = new stdClass();
$node->nid = $f_node->nid;  // Updating
$node->title = 'TestT';
$node->type = 'employees';
$node->status = 1;        // Published?
$node->promote = 0;       // Display on front page?
$node->sticky = 0;        // Display top of page?
$node->field_employee_first_name['und'][0]['value'] = 'TestF';
$node->field_employee_last_name['und'][0]['value'] = 'TestL';
$node->field_employee_email['und'][0]['value'] = 'example@example.com';
node_save($node);

It executes without error but only my node_revisions (vid?) table is updated. The node table is untouched.

Am I missing something in the object that is keeping it from updating the node (nid) table?

Instead of creating a new object, you should simply update the node object you already seem to have (or load it first with node_load()), update it's properies and then save it.

Trying to save a node object that doesn't have all properties set will result in loosing those that aren't set and other issues like the one you're experiencing.


How to hide a block entirely if it's empty I've added a series of blocks to my template file for a specific content type. These blocks are built in Views and they show Downloads filtered by the specific content you are viewing. For example, on the Product A page, the Product Literature block shows all downloads categorised as Product Literature specifically associated with Product A.

There is a block for Product Literature, a block for Videos (set up in a similar way) and a block for Publications (again, set up in a similar way).

At the moment, if there aren't any videos for Product X, the heading Product X still displays for Video Gallery, is there a way I can detect if there is any content under the Video Gallery heading and if there isn't, choose not to display it?

Each block is printed as below:

$block = module_invoke('views', 'block_view', '712046d635e195e59dd93bd378e45423');
print "
Product Literature
";
print render($block);

If you create blocks from the views interface itself it will not print the block if there are no results. I would recommend this method since it saves time and complexity. If you need to change the template for the block being created by the view you can do so. There is a lot of documentation on how to do that. Here is an example: Create template file for views block

In the case of what you have written below you could do something like:

$block = module_invoke('views', 'block_view', '712046d635e195e59dd93bd378e45423');
if (isset($block)) {
print "
Product Literature
";
print render($block);
}

but I would highly recommend the approach above.


Find specific node to uninstall a module I want to uninstall a module but I'm getting the following message. The "Name of Module" field type is used in the following field: node.field_feature_interest. How can I find this node so I can remove their relationship between each other so that I can delete the module?

I figured out how to do it:

Go to content types
Features Article ->Manage Fields
Delete field


Remove all markup from user registration field I have been searching in vain for days trying to find the right hook or theme override to basically change a few fields I have defined in a custom registration form.

The default markup generated by Drupal is too verbose and the designer has requested that I not change the CSS -- I need to bend the markup to meet the CSS not the CSS to play nice with Drupal.

I have tried hook_field_widget_form_alter and have managed to wrap the existing markup in div's but I need to remove the default:

function tweakform_field_widget_form_alter(&$element, &$form_state, $context) {
  //$element['#prefix'] = '<dir style="background-color: red">';
  //$element['#suffix'] = '</div>';

}

Can someone please show me how this is done? I don't want to re-write the entire form.tpl.php as I only need to override a few fields markup -- then again it may be handy to override the whole thing. These fields are dynamic and controlled by designer and more may be added later or possibly removed.

Alex

function tweakform_field_widget_form_alter(&$element, &$form_state, $context) {
  $element['#theme_wrappers'] = '';
  $element['#prefix'] => '
';
  $element['#suffix'] => '
';
}


NL and other languages visible, but English site not visible and showing error after translating news item I get below error when try to reach my site (see screenshot):

The editor of the site made a news item and translated it to English. Now the English (default) site can't be reached. But the other languages are still working. For example the dutch version.

  Notice: Undefined offset: 5 in tb_megamenu_insert_tb_item() (line 347
  of
  /var/www/clients/client7/web17/web/sites/all/modules/tb_megamenu/tb_megamenu.functions.inc).
  Notice: Undefined index: href in include() (line 2 of
  /var/www/clients/client7/web17/web/sites/all/modules/tb_megamenu/templates/tb-megamenu-item.tpl.php).
  Notice: Undefined index: href in include() (line 2 of
  /var/www/clients/client7/web17/web/sites/all/modules/tb_megamenu/templates/tb-megamenu-item.tpl.php).
  Notice: Undefined index: options in include() (line 2 of
  /var/www/clients/client7/web17/web/sites/all/modules/tb_megamenu/templates/tb-megamenu-item.tpl.php).
  Recoverable fatal error: Argument 2 passed to url() must be of the
  type array, null given, called in
  /var/www/clients/client7/web17/web/sites/all/modules/tb_megamenu/templates/tb-megamenu-item.tpl.php
  on line 2 and defined in url() (line 2220 of
  /var/www/clients/client7/web17/web/includes/common.inc).

From the error msgs shown, it seems that you're using the TB Mega Menu module. So think of a way to get that module disabled (eg using the Dutch admin screens to disable a module, or using Drush if you have it available). That might possibly help to get rid of those errors again.

If you then also unpublish (or delete?) that news item where your problems started from, you may have a stable situation again. And from there continue your investigation to find the real cause (root) of your issue.

Doei!


How can i remove title requirement for content type For example i have content type article i need to remove requirement for title, right now its a Node module element and i can not edit it. I found module title but when i installed id and tried to change title, my site crashed.

Is there any solution to achieve this?

Should i remove title on content type edit page and replace it with editable field?

UPDATE:

Some of you maybe do not understand me right). So i have content type Answer and this c.type has two fields title and body. When someone want to answer atm he needs to fill title field every time he wants to answer, but i need to give user a choice to just fill only body field OR body and title if user want to fill the title. The title field should be displayed on node edit every time!

So only way i see viable is to create new field and  hide title with automatic-node-title module...

I dont' think you can entirely remove the title from the nodes but you may hide it and automatically populate it, as is below:

Auto node titles and Title override

I have used the first one before.


Print node title in custom block module twig file I want to send node title and description into twig file. See my code

public function build() {

return [
'#theme' => 'block--maincontentlatestnews',
'#latest_news' => $this->read_latest_news(),
'#sample' => 'sample_txt',
'#attributes' => [],
];
}

function read_latest_news(){

$nids = \Drupal::entityQuery('node')->condition('type','article')->execute();
$nodes = entity_load_multiple('node', $nids);

return $nodes ;

}

return array_map(function($node) {
  return $node->label();
}, $nodes);

or if you want links:

return array_map(function($node) {
  return $node->toLink()->toString();
}, $nodes);


Can two nodes have same URL using Pathauto? I know that Drupal allows same url for multiple nodes.
But I've a scenario: a registered user creates and submits an article as an unpublished node and assigned an URL by pathauto based on its title.
At the same time another user creates an article with same title in unpublished form. Will it too have same url?

I'll not "publish" those nodes anytime. I'll (as an admin) simply create a new node and copy paste contents.

a registered user creates and submits an article as an unpublished node and assigned an URL by pathauto based on its title. At the same time another user creates an article with same title in unpublished form. Will it too have same url?

No. pathauto by default will append a number to the end of the URL to differentiate between them.


Site migrated to the new server with PHP 7.2 and I can't log in We're preparing to get our Drupal infrastructure moved from PHP 5.6 to PHP 7.2. In order to start testing, I migrated a Drupal 7.67 multi-site from our current production server to a test server running PHP 7.2 and got one of the sites configured. So far, everything about the web site appears to work fine (visual, navigation, etc). Except that I can't log in!

When I navigate to /user/login, type my username and password, and click submit, there's evidence in the database that the login appears successful (users.login timestamp updates), and I'm redirected to /users/myusername, but it says "Access Denied" and doesn't show the top bar to change config, content, etc.

Drush appears to work fine for changing my password (upwd), creating one-time login links (uli), etc, but the login link doesn't work, instead showing "Access Denied" again.

I've checked just about everything you're supposed to check when issues like this come up:

Verified mod_rewrite is enabled
Tried with and without Base URL setting enabled in settings.php
Tried with and without RewriteBase setting in .htaccess
Tried with and without cookie_domain setting in settings.php
Cleared caches and truncated tables like cache*, flood, semaphore, sessions, watchdog
Made sure no database updates are pending
Restarted Apache periodically
Checked Apache error logs, nothing of note there
Tried multiple browsers from multiple computers, with and without Incognito modes

I have no idea what else to try, and sadly I'm not even sure if this is simply related to migrating the site from one server to another or whether it's because we moved from PHP 5.6 to PHP 7.2. Where do I begin troubleshooting this? Thank you in advance for your help!

We found the problem. The site was using HTTPS on the production server and HTTP on the test server, and we had set php_flag session.cookie_secure On in our Apache config. HTTPS wasn't in use, so no cookies were sent, so no logins would work properly. Setting this to Off worked wonders. Thanks for pointing me in the right direction, folks!