Set default text format for a content type At "Home » Administration » Configuration » Content authoring"
I added a custom text format (news).

Now when I trie to enable this for a certain content type "Newsmessage"
"Home » Administration » Structure » Content types » Newsmessage » Manage fields"

I only see  "Plain text" or "Filtered text (user selects text format)" as options.
How do I set the "news" text format as a default for my "newsmessage" content type?

If the field is Wysiwyg, so you might want to configure the "Wysiwyg" profile settings, then it will be available in the Structure » Content types » contentType name  » Manage fields.


Drupal 8 Display True/False instead 0/1 on checkbox value in ConfigFormBase By default the boolean fields' value displayed as 0/1 when user filled the checkbox field under custom configuration form. Need to render True/False instead of 0/1.

$form['newfield'][$id]['required'] = array(
  '#type' => 'checkbox',
  '#default_value' => ($config[$id]['required'] ? $config[$id]['required'] : $field['required_disabled']),
  '#disabled' => $field['required_disabled'],
);

public function submitForm(array & $form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $config = $this - > config($this - > configId);
    $fields = static::getFields();
    $values = $form_state - > getValues();
    $values = $values['newfield'];
    foreach($values as $key => $field) {
        $config_values[$key] = array('visible' => $field['visible'], 'required' => $field['required'], );
    }
}

In drupal8, you can easily handle this from "Manage Display" of your content type.

  Go to /admin/structure/types/manage/article/display
  Select your "view_mode". Ex- Default.

  Go to the boolean field and click on its settings icon which is placed at atmost right side of the field.
  Change the output format to "True/False".

Hope, this works for you.


check mark disappear after moving to new ip address I moved my web server to another ip address. But "Advanced CSS/JS Aggregation" still refer the images from the old ip address. All the checkmark in my dashboard are disappeared, no matter for radio or checkbox.

Here is an example:

Update:
I checked the console and found an error message: "Failed to load resource: net::ERR_CONNECTION_TIMED_OUT".
Here is a screenshot for error from console:

What do I need to do??? How can I update the css and js file? Does anyone have any idea?Thank you for all helping.

Thank you for all your help.
I found out the reason for a long time searching. Cause I moved an existing complicated website to a new ip address. The Advanced CSS/JS Aggregation module does affect images, css and js.

Here are some solutions that I found might be useful:

Check $base_url in setting.php file (might be set as old url/ domain name/ ip address)
Uncommend "#RewriteBase /" in .htaccess file then flushing the cache (Do not try this unless you know what you are doing)
Unable Advanced CSS/JS Aggregation Module (It will compass your js/css, this might cause some problem. Just unable it, use your
original css file) -- This works for me.

Here are some references I used here:

Need help changing domain/url on existing drupal site...
images not showing / displaying after moving to localhost (Wamp
Server)


Cannot block access to nodes with hook_node_access_records I have written a module which adds a node access record. The workflow module is also installed which adds two other records to the node_access table.

Here Author says that:

  Drupal is a “deny-based” access control system. In other words, if
  anybody denies access to a node, then the node is blocked.

But when I deny access to a node in my module, it is still accessible for all users.(workflow module grants access for both anonymous and registered users)

A solution would be setting the record priority higher than workflow's access records, but I don't want to change the priorities.

/**
 * Implements hook_node_access_records()
 */
function mymodule_node_access_records($node) {

   $user = field_get_items('node', $node, 'field_recipient');
   $uid = $user[0]['uid'];

   if ($node->type == 'contact') {
      $grants[] = array(
         'realm' => 'contact',
         'gid' => $uid,
         'grant_view' => 1,
         'grant_update' => 0,
         'grant_delete' => 0,
         'priority' => 0,
      );
   }
   return $grants;
}

/**
 * Implements hook_node_grants()
 */
function mymodule_node_grants($account, $op) {
   $grants['contact'] = array(1234); //1234 is for test and doesn't exists in node_access table
   return $grants;
}

Is anything wrong?

Blog post needs to be updated. I remember having discussion with him about it.

hook_node_access is a deny access; grants are if a user has any matching grant, they have access.

you can use the alter hook to remove undesirable grants, but doing custom access requires a lot of testing and thinking. Also, read the https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_access/7 node_access documentation/code


How do I create a local menu action to node/add/page? Here is the code in mymodule.links.action.yml to add a local action in a custom page (generated by the Views module).

amidori_utils.add_content:
  route_name: 'node.add_page'
  title: 'Add Content'
  appears_on:
    - view.admin_blogs.page_1

The above page will create a local action menu, which will take you to node/add page which will again list links to various content that you can create.

What I want is to create a link to node/add/blog as a local action. How can I do it?

After watching to the content of the node.routing.yml file, I understand I need to use node.add as route, but I can't figure out how to pass blog as parameter to the end of the route.

Basing on this comment found on Local action links now provided by plugins using YAML discovery and implementing LocalActionInterface, this is the action declaration you should use.

amidori_utils.add_content:
  route_name: 'node.add'
  title: 'Add content'
  route_parameters:
    node_type: 'blog'
  appears_on:
      - view.admin_blogs.page_1

I take that, in your case, node_type should be simply blog, if that is the machine name for the content type you want to let users create.


Where to declare an API key? I'm confused about the following:

I'm working on a module that creates a interactive Google Maps background, I've added the Javascript to my module ( which is run at hook_init), but when I try to load the page, the maps background doesn't show up.

Before I decided to create a module, I used the same Javascript code which was called on page load through the header-section (through script>src) in my page.tpl.php file, and everything worked as it was supposed to.

So I'm suspecting that, because I call the module with hook_init, my Javascript cannot show up because the API key hasn't yet been validated/declared by the page.

What's the best way to tackle this problem? Can I declare the API key in my .module file? or even my module.js file? Or should I change the hooks to something else, in that case, is there a hook that lets me call the module.js file after the head of my page is loaded?

<?php function maps_markers_init() {
$markerAantal = 0;
$latitudes = db_query('SELECT field_latitude_value FROM {field_data_field_latitude}')->fetchCol();
$longitudes = db_query('SELECT field_longitude_value FROM {field_data_field_longitude}')->fetchCol();

json_encode($latitudes);
echo "<br>";
json_encode($longitudes);
};

And to load the Javascript:

function maps_markers_page_build(){
drupal_add_js(drupal_get_path('module', 'maps_markers') .'/maps_markers.js');
};

Eventually things got fixed, learned that you can just add a .js file into your module with the HOOK_init() since they get stored to use at a later stage.

What obviously was causing the problem, was the wrong declaration of the API key, this was fixed by adding the line:

drupal_add_js("https://maps.googleapis.com/maps/api/js?key=[MY API KEY]", "external");

to the document.
After that, I could call the .JS file with:

drupal_add_js(drupal_get_path('module', 'maps_markers') .'/maps_markers.js');

More information on how everything was fixed can be found here:
Module conflicting with JQuery


How do I print a twig variable inside a JavaScript in a twig file I have a twig file of a custom module. It has a <script></script> section and I need to print a twig variable inside that section. How do I do this?

{{ set twigVariable = '123456' }}

<script>
    function myFunc() {
        var myJsVar = {{ twigVariable }};
    }
</script>

The variable does not print when I write like above.

I'll spare to tell that it's a bad practice to add custom script blocks to templates, and just point out the error(s):

(1) To set the variable content, you have to wrap set into a {% %} block, not {{ }}.

(2) You most probably want the value as JavaScript string, so don't forget to wrap it in " ".

This sums up to

{% set twigVariable = '123456' %}

<script>
  function myFunc() {
    var myJsVar = "{{ twigVariable }}";
  }
</script>

Which should be working just fine.


Display Suite Token Fields in Custom Block Types I want to add a Display Suite token field to my Custom Block Type.

I have a custom block type.
I created a token field with Display Suite
Entities: Block Content
Limit field *|* or link_card|* where link_card is the machine name of my custom block type

I expect to be able to go to Manage display of my custom block type and see the token field I created, but it's not there. I have successfully made token fields and added them to Content Types.

What am I missing?

--

UPDATE: Whatever this was, it resolved itself. Shrug!

Does it work when you don't limit?

And just to be double sure.... you have got to Structure > Block Layout > Types > (actual type) > Manage Display.  And once there, in the bottom area where it says "Layout for basic in default", you selected a "Select a layout" of something other than "-None-".  Because the fields won't show until you select a Display Suite layout.


Find current location of logged in user How can I find out the current location of the logged in user?
When a user is logged in I just want to search the current location of user and save the lat and long in the database . How can I do that? Please help.

You a use a geo IP database/service to lookup a lat/long based on the user's IP address. There are many PHP API's out there to do this. The most popular Drupal module based solution is Smart IP.

  Smart IP identify visitor's geographical location
  (longitude/latitude), country, region, city and postal code based on
  the IP address of the user. These information will be stored at
  session variable ($_SESSION) with array key 'smart_ip' and Drupal
  $user->data object with array key 'geoip_location' of the user but
  optionally it can be disabled (by role) at Smart IP admin page. Other
  modules can use the function smart_ip_get_location($ip_address) that
  returns an array containing the visitor's ISO 3166 2-character country
  code, longitude, latitude, region (FIPS), city and postal code. It
  provides a feature for you to perform your own IP lookup and admin
  spoofing of an arbitrary IP for testing purposes.


Alter an existing form We just starting out with Drupal 8 and very quickly we ran into our first problem.

How should I alter an existing form in Drupal 8?

We need to alter the save method for the node form to do a redirect to an other page. We want to alter the node form to become something like a multistep form. After the user creates new content they get redirected to a new form (we created) to get some more information.

We solved our problem implementing hook_entity_type_alter().

function mymodule_entity_type_alter(&$entity_info) {
  $handlers = $entity_info['node']->get('handlers');
  $handlers['form']['default'] =    'Drupal\mymodule\Form\MyExtendedNodeForm';
  $handlers['form']['edit'] = 'Drupal\mymodule\Form\MyExtendedNodeForm';
  $entity_info['node']->set('handlers', $handlers);
}

We then created a new form class that extends the node form and alter the save method.

class MyExtendedNodeForm extends NodeForm {

    public function save(array $form, FormStateInterface $form_state) {
      parent::save($form, $form_state);
      $node = $this->entity;
      $form_state->setRedirect('entity.regions.add_form', ['nid' => $node->id()]);
  }

}

This works perfectly, but is it good? If another module does the same, our code does not get executed anymore.

I had to do the exact same thing yesterday, and I am still looking for a more Drupal 8 way to do this, but haven't found it. I ended up doing it this way:

<?php

/**
 * @file
 * This is my module.
 */

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Implements hook_form_alter().
 */
function MODULE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_form') {
    $form['actions']['submit']['#submit'][] = '_MODULE_goto';
  }
}

/**
 * Make the form go to route.id.
 */
function _MODULE_goto($form, FormStateInterface $form_state) {
  $form_state->setRedirect('route.id');
}

I am still very interested in doing it a different way, my module looked so clean without the .module file :).


Views: add (link to file field) to image field In D7, I have an event content type containing an image field ("Featured image") and a file field ("Document"). I have a view of events containing documents, and would like to wrap a link around the image, leading to the document. Here's a sample link.

How can I rewrite the image (or use another technique) to get the desired link around the image? Looking at available tokens (I did add a second, hidden Document field above the image to define tokens), nothing seems suitable. Thanks for your help.

First add the "Content:File" field
Check "Exclude from display" (hidden)
Under "Formatter" select "URL to file"
Then add your Image field and uncheck "Link this field to the original piece of content" or something similar
Click on "Rewrite Results" and check "Output this field as a link"
In the "Link path" textbox add "Replacement Pattern" from the file field ([field_file] == Content: File, for example)


Alphabetical view sorting in multilingual site not working for translated content I have created a view that alphabetically lists all nodes of type "glossary entry". A glossary with many terms. Besides German I need the glossary in English, too. The translation has worked great using Entity Translation module. I only have the problem that the alphabetical order of the English version is not correct. The English glossary has the same sort order than the German (original) version:

  German version:

  Adler (German word for eagle)
  Hund (German word for dog)
  Kuh (German word for cow)

  English version:

  Eagle
  Dog
  Cow

I crawled many forums but couldn't find a solution for my problem. I already added the relationship "Entity Translation" in my view but the additional filter and sorts don't help me here.

What I need is a sort "title (English Translation)". Does somebody has a clue how to get this work?!!

Please find here the view's query

I solved that by adding this field as a relationship to the view and so name:field became accessible as sort criteria, which I then chose instead of content:field.


Restrict blocks to specific pages I am using someone else's theme on a very small site.

Specifically, I want to display blocks on specific pages. I am able to display blocks on  only and on all pages except .

My understanding is that I should be able to display a block only on page "what-we-do" putting what-we-do where I put .

Alternatively I code put node/7 (this page being node/7).

The result is that the block is displayed persistently on the front page and on no others.

This is clearly nonsensical and either I am doing something very silly or I need to start reading through the code.

My question, precisely: has anyone encountered this problem before and can they suggest a way forward?

Sumit Madan was spot on.  Several blocks were hard coded as front page only in the page.tpl in the contributed theme.

For other newbies caught out by hard coding, the cues are:

The visibility settings for a block behave erratically, i.e., in a pattern not consistent with your expectations
When you inspect the regions (/Structure/Blocks - at the top), some of the regions do not appear. Yet, you can put a block into them and the show up when you inspect under Firebug. Now I understand the problem, a quirk that had puzzled me is fully explained.

To find the hard coding in page.tpl, look for ($is_front) and change that to ($page != 0).

page=0 refers to pages like lists of taxonomies. So this edit means the relevant blocks will be available to all pages including the front page and can be managed using the block visibility as usual.

Thanks everyone.


I backed-up my site and now my views are broken My site recently got deleted by a possible hack. I backed up the database and the folders, but now my views are not working; everything else works.

The fields are showing this in admin/build/views/edit/nameofview:

  Broken/missing handler: node_data_field_guru_photo > field_guru_photo_fid
      Broken/missing handler: node > title
      Broken/missing handler: views > nothing
      Broken/missing handler: node_revisions > body
      Broken/missing handler: node_data_field_guru_link > field_guru_link_url

It looks like it is looking for fields that do no longer exists?
Have you changed anything in your content types maybe?


Problem with date_timezone_set() I've managed to get my webform fields to display in views via this tutorial. The tutorial uses the Webform My SQL views and data modules.

Webmform My SQL views: 7.x -1.0
Data: 7.x-1.0 alpha

System:
Plesk 10.3
CentOS 5.8
Apache 2.2.3
Php 5.1.6

I can successfully create my view that allows me to choose the webform fields I want to display, however, when i try to add the "Webform views request time off 272: Submitted" date field, I get this:

  Warning: date_timezone_set() expects parameter 1 to be DateTime, boolean given in format_date() (line 1909 of /var/www/vhosts/mydomain.com/intranet/includes/common.inc).

  Warning: date_format() expects parameter 1 to be DateTime, boolean given in format_date() (line 1919 of /var/www/vhosts/mydomain.com/intranet/includes/common.inc).

As a result, this field displays no values.

I've done a search on that issue and while I did find some topics, I'm not sure how they apply to my situation. Unfortunately, this site is for our intranet so I cannot post a link.

The goal in this view is to show the submission fields and include a filter control that I can expose to the user that uses the submission date as the criteria for a date range.

I had the "Date" module activated, then deactivated which didn't resolve the issue.

Any help would be greatly appreciated.

I ran into the very same 2 errors but in the context of of sub-theme preprocess function when using the format_date() function as follows.

$vars['timestamp'] = format_date($dc_file_items[0]['timestamp'], 'custom', 'd M, Y');

After searching in many directions (including installing the Date module - not required), I came to realize that $dc_file_items[0]['timestamp'] was returning a string and not an integer. Adding intval() around it made the errors disappear. In the end, the code above should look like this.

$vars['timestamp'] = format_date(intval($dc_file_items[0]['timestamp']), 'custom', 'd M, Y');

Hope this helps.


how to a translatable string in drupal theme? I want to put a string as a signature in drupal theme I am working on. the website is multilingual and the string should be translated based on the current language of the website. I don't know how to do it.

my drupal version is 6.

Would you help me?

The first step to translate a string used from a module, or a theme is using t() for every string that needs to be translated. Remember that the first argument given to the function is a literal string containing a phrase in English. This means that the following calls to t() are not correct.

// The string is a concatenation of literal strings.
$error = t('This example, ' . "doesn't work.");

// Also in this case there is a concatenation of literal strings.
$errno = 15;
$error = t("Error number $errno received while translating a string.");

// This could work, provided that another function calls t() using a
// literal string that is equal to the string returned from the function.
$error = t(mymodule_get_error());

The second step is providing the translation of the string passed to t(). If the theme is hosted on Drupal.org, then the translation will be provided from translators on http://localize.drupal.org.
Otherwise, you need to translate the string on admin/build/translate/search.

You can look for the string to translate searching for untranslated strings, or entering a string.


How to do a db api join on "has no value"? I've got two tables, Foo and Bar.  Foo and Bar can be joined by matching Foo's "nid" column to  Bar's "col" column.  In use, some rows in Foo will have a corresponding entry in Bar, but some won't.  I now want to get all the rows in Foo that do NOT have a related entry in Bar.

I'm trying something like this:

$the_query = db_select('foo', 'f');
$the_query->fields('f', array('nid', 'val'));
$the_query->join('bar', 'b', 'f.nid = b.col');
$the_query->isNull('b.col');
$the_query->execute()...

but it's not returning anything; my method of testing for null-ness is almost certainly wrong.  I've never been good at these kinds of queries, let alone being able to figure out how to do it within the context of the DB api.  Any clues out there?  Thanks!

If I am reading this right, I think you need to use a left join and then test the nullness.

$the_query = db_select('foo', 'f');
  ->fields('f', array('nid', 'val'))

$the_query->leftJoin('bar', 'b', 'f.nid = b.col');

$results = $the_query->isNull('b.col');
  ->execute()
  ->fetchAll();

Very often, though, I will break down and do this with two queries.  The first will get a list of nids, the second will use a NOT IN condition.


Adding event listener on an AJAX button I've tried to add a loading animation to the website in case if the user clicks on buttons or input submit buttons. It work, except on those buttons which using AJAX. For some reason those buttons are processed, but my event listener looks like it was detached... Anybody know the reason or how can I fix it?

Code for the loading (it will create an overlay with a spinner and text):

(function ($, Drupal) {
  Drupal.behaviors.myModuleLoading = {
    attach: function attach(context) {
      $('button, .btn, input[type=submit]').not('.close').once('loading').on('click', function (event) {
        // Create the loading DOM.
        var background = $('<div>', document);
        background.addClass('loading-background');
        var logo = $('<div>', document);
        logo.addClass('loading-container').append(
          $('<div>', document).addClass('loading-container-inner').append(
            $('<div>', document).addClass('loading-icon')
              .append($('<div>', document)).append($('<div>', document))
              .append($('<div>', document)).append($('<div>', document))
              .append($('<div>', document)).append($('<div>', document))
              .append($('<div>', document)).append($('<div>', document))
          ).append(
            $('<div>', document).addClass('loading-text').text('Processing...')
          )
        );

        // Add to the body the created DOM.
        $('body').append(background).append(logo);
      });

      // Remove any remaining loading if user close a modal.
      $('.close').on('click', function () {
        $('.loading-background, .loading-container').remove();
      });

      // If it was an AJAX call this will be called.
      $('.loading-background, .loading-container').remove();
    }
  };
}(jQuery, Drupal));

Keep in mind, it works on those buttons, which doesn't use AJAX at all. With those buttons which using AJAX, it doesn't work from the beginning, but the loading-processed class is visible, which is added by the once('loading') code. I guessing there's a magic somewhere in Drupal which prevents to call other event listeners? (In chrome there's a way to stop the script and debugging if a click event happened, in AJAX buttons it doesn't stop, in normal buttons it stops, both are input[type=submit] type buttons.)

I'm not sure, based on your code, how you are adding buttons to your form(s)/pages, however, I would venture to guess the AJAX controlled buttons are not working because they are calling the built-in loading/submit callbacks within the Drupal 7 AJAX API (example.)

You may find the following example useful:

/**
* Implementation of hook_menu().
*/
function myModule_ajax_menu() {
  $items['get/ajax/Simple Drupal AJAX load with jQuery and delivery callback'] = array(
  'page callback' => 'myModule_ajax_get_ajax', // Render HTML
  'type' => MENU_CALLBACK,
  'page arguments' => array(2),
  'access arguments' => array('access content'),
  'delivery callback' => 'myModule_ajax_callback',  // Magic goes here
 );
 return $items;
}


jQuery dependency on a custom theme is not adding jQuery? I know that this question has been asked previously many times but any of the solutions are not working in my case so please, I request if anyone can help me with this situation please provide me assistance.
I have added dependency of the core jQuery(along with other core libraries) in my theme.libraries.yml but only core jQuery is not loading in my drupal frontend and the console is showing the error of jQuery is not defined.
Also other drupal core libraries as working fine only jQuery is not loading.
My code of various files is as follows
theme.libraries.yml
global-styling:
  version: 1.x
  css:
    theme:
      css/bootstrap.css: {}
      css/custom.css: {}
      css/owl.carousel.min.css: {}
      css/owl.theme.default.min.css: {}
      css/responsive.css: {}
      css/style.css: {}
      fonts/fonts.css: {}
  js:
    js/bootstrap.js: {}
    js/owl.carousel.min.js: {}
    js/popper.js: {}
    js/scripts.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal

theme.info.yml
name: wcsb
type: theme
description: 'Another outstanding WebCube Theme'
package: Core
version: '0.1.2'
core: '8.x'
base theme: classy

libraries:
  - wcsb/global-styling

regions:
  header_bar_1: 'Header Bar 1'
  header_bar_2: 'Header Bar 2'
  header_bar_3: 'Header Bar 3'
  header_bar_4: 'Header Bar 4'
  mobile_header_1: 'Mobile Header 1'
  mobile_header_2: 'Mobile Header 2'
  slider_images: 'Slider Images'
  breadcrumb: Breadcrumb
  featured_top: 'Featured top'
  above_content: 'Above Content'
  content: Content
  below_content: 'Below Content'
  sidebar_first: 'Sidebar first'
  sidebar_second: 'Sidebar second'
  featured_bottom_first: 'Featured bottom first'
  featured_bottom_second: 'Featured bottom second'
  featured_bottom_third: 'Featured bottom third'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'
  footer_fourth: 'Footer fourth'
  footer_fifth: 'Footer fifth'

list of scripts loading
<body class="path-frontpage page-node-type-page" data-new-gr-c-s-check-loaded="14.1002.0" data-gr-ext-installed=""
cz-shortcut-listen="true">

<script type="application/json" data-drupal-selector="drupal-settings-json">
    {
        "path": {
            "baseUrl": "\/",
            "scriptPath": null,
            "pathPrefix": "",
            "currentPath": "node\/1",
            "currentPathIsAdmin": false,
            "isFront": true,
            "currentLanguage": "en"
        },
        "pluralDelimiter": "\u0003",
        "suppressDeprecationErrors": true,
        "ajaxTrustedUrl": {
            "form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM": true
        },
        "user": {
            "uid": 0,
            "permissionsHash": "508c848d9cf616f3b3735479b8cad945e128b7dbb0a534206170c7d3643afe05"
        }
    }
</script>
<script src="/core/assets/vendor/jquery-once/jquery.once.min.js?v=2.2.3"></script>
<script src="/core/misc/drupalSettingsLoader.js?v=8.9.13"></script>
<script src="/core/misc/drupal.js?v=8.9.13"></script>
<script src="/core/misc/drupal.init.js?v=8.9.13"></script>
<script src="/themes/custom/wcsb/js/bootstrap.js?v=8.9.13"></script>
<script src="/themes/custom/wcsb/js/owl.carousel.min.js?v=8.9.13"></script>
<script src="/themes/custom/wcsb/js/popper.js?v=8.9.13"></script>
<script src="/themes/custom/wcsb/js/scripts.js?v=8.9.13"></script>
<script src="/modules/contrib/commerce/modules/cart/js/commerce_cart.js?v=8.9.13"></script>

console errors

Solved The problem was in my .theme file where it was unsetting the core jQuery library.
The problem code:
function theme_js_alter(&$javascript, \Drupal\Core\Asset\AttachedAssetsInterface $assets)
{
    unset($javascript['core/assets/vendor/jquery/jquery.min.js']);
}

Thanks to @AlfredArmstrong for providing the suggestion of reviewing the php files


How to restrict a specific user to an IP range he can login from? I want to create a subscription service where the user can only login with the IP address the user registered with and all Class C & D's of that IP range. How can this be done?

Would also be great if I can restrict the user to logging in from withing that state if possible.

Have a look at IP Ranges module.

  IP Ranges is a module that let's you completely ban both single IP-addresses as well as
  full ranges from your site. The ban is triggered already at the early bootstrap phase, so you
  can get rid of unwanted visitors as early as possible without wasting server resources.

  You can also define whitelists that override blacklists, both single and ranged.
  The UI is similar to core ip-ban, so you will feel like home immediately.


template_preprocess_HOOK: what do I put for HOOK? My objective: get and change the breadcrumb within a custom module.

So it's possible that template_preprocess_HOOK is not even the best tool to be using for this, please mention that.

My question, though, is what HOOK to use? Should it be called template_preprocess_mymodule or template_preprocess_mytheme?

The HOOK corresponds to the theme function or template you are preprocessing.

If you wanted to alter page.tpl.php, you would use function MYTHEME_preprocess_page(&$variables).

If you wanted to alter theme_item_list(), you would use function MYTHEME_preprocess_item_list(&$variables).

A note, any dashes should be converted to underscores.

So views-view.tpl.php would be altered by function MYTHEME_preprocess_views_view(&$variables).


Programmatically insert field collection of Phone fields I have a profile2 profile type. In profile type i have created the collection for storing the information of form fields.

I have used the phone module to create the phone number fields.
This collection contains the two phone number fields, one for office and one for mobile.

So my scenario is give below

--Profile type

--- Field collection to store the phone numbers

---- Two fields to store  phone numbers
    1. field_office_phone
    2. field_office_mobile

Now i want to save the data of the field programmatically.
I have used below snippet from here to create and save the field collection programmatically.
In the given below code company is my profile2 profile bundle.

module_load_include('inc', 'field_collection', 'field_collection.pages');
  // Load the profile we're adding the field to
  $profile_entity = profile2_load_by_user($account, 'company');

  // Define the values of the new field
  $values = array();
  $values['field_name'] = 'field_contact_number'; // field collection name
  $values['field_office_phone'][LANGUAGE_NONE][0]['#value']['number'] = 1234;
  $values['field_office_mobile'][LANGUAGE_NONE][0]['#value']['number'] = 12374;

  // Create the field collection entry and associate it with the profile
  $field_entity = entity_create('field_collection_item', $values);
  $field_entity->setHostEntity('profile2', $profile_entity);
  $field_entity->save();

The above code snippet only creates field but it is not storign the values in the field.
I am not getting the reason why it is not setting the values.

This code works fine for user entities under Drupal 7:

  $values['field_office_phone'][LANGUAGE_NONE][0]['number'] = '0412345678';
  $values['field_office_phone'][LANGUAGE_NONE][0]['country_codes'] = 'au';

Adapt countrycode to your user's country.
I don't think I'm using Profile2 and there are multiple different modules that implement phone number fields. My server has cck_phone-7.x-1.x-dev installed.


Ajax callback return 500 Internal Server Error file mymodule.inc :

        $items['ajax/channel/%/get-program'] = array(
        'title' => t('get channel program by ID'),
        'type' => MENU_CALLBACK,
        'page callback' => 'get_channel_program',
        'page arguments' => array(2),
        'access arguments' => array('access content'),
      );

      return $items;
//channel program
function get_channel_program($channel_id){
  $channel_id = (isset($_POST['channel_id']) ? $_POST['channel_id'] : '');
  if (!is_numeric($channel_id)) :
    drupal_not_found();
  else :
    drupal_json_output($channel_id);
  endif;
}

file mudule.js :

Drupal.behaviors.ajaxProgram = {
        attach: function (context, settings) {

            // CSS Selector for the button which will trigger the AJAX call

            $('.channel-tv-tabs .tab .tabset .single-prog', context).click(function () {

                var channel_id = $(this).data('channel-id');

                $.ajax({
                    url: '/'+Drupal.settings.pathPrefix + 'ajax/channel/'+channel_id+'/get-program', // This is the AjAX URL set by the custom Module
                    type: "POST",
                    data: { channel_id : channel_id }, // Set the number of Li items requested
                    dataType: "json",          // Type of the content we're expecting in the response
                    success: function(data) {
                        var parsed_data = $.parseJSON(data);
                        console.log(parsed_data);  // Place AJAX content inside the ajax wrapper div
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        console.log(errorThrown);
                    }

                });

            });

        }
    };

Pls help me and tell what i do wrong?
When I try go to link http://hostname/ru/ajax/channel/25/get-program I recive page not found

Change the callback into this:

function get_channel_program($channel_id){
  if (!is_numeric($channel_id)) :
    drupal_not_found();
  else :
    drupal_json_output($channel_id);
  endif;
}

Change the jQuery into this:

$('.channel-tv-tabs .tab .tabset .single-prog', context).click(function () {
     ...
     $.get('/ajax/channel/'+channel_id+'/get-program', function(data) {
     alert("got "+ data);
   });
});

This uses HTTP GET verb.

  According to the design of the HTTP specification, GET (along with
  HEAD) requests are used only to read data and not change it

instead of POST

  The POST verb is most-often utilized to create new resources.


Drupal show breadcrumbs on certain nodes I've been using the path by bread crumbs module (https://drupal.org/project/path_breadcrumbs), which allows me to create bread crumbs based on nodes. However the page the crumb is on, shows the title of the crumb.

Example: Home>>Node_Title

I want the Home crumb, but not the Node_Title (I'ts a long title as well).

This is what I want:

Node 36 URL= TitleExample

Breadcrumb example for Node 36: Home>> (no node URL)

Does this make sense?

When using the path breadcrumbs module it doesn't append the title to the end unless you add it yourself when configuring the breadcrumbs.

It is quite possible that what is adding the title is your theme.

For example the zen theme has an option to show the page title at the end of the breadcrumbs, as do lots of other themes.

To get to these settings, on your site go to admin/appearance and then click the settings link for whichever is your theme.


How can I get newly created node of a certain type? I understand I could use hook_nodeapi('insert') in Drupal 6 (Drupal hook fired after node created), but this seems to have changed in Drupal 7. What would the equivalent of that in Drupal 7?

The equivalent of hook_nodeapi('insert') in Drupal 7 is hook_node_insert().

function hook_node_insert($node) {
  db_insert('mytable')
    ->fields(array(
    'nid' => $node->nid,
    'extra' => $node->extra,
  ))
    ->execute();
}


is there a module for instagram like YouTube Field? I need a module that permit to my editor user to choice photo from instagram and linked them in a field of a content type.

I have found https://www.drupal.org/project/instagram_feeds but I don't want to create feeds for every node.

Edit: and if possible a youtube module too. ("Youtube" module permit to write video's url, but not a graphical choise).
Thanks.

Firstly user will have to authenticate to their Instagram account. Then the user can access his personal photos via the end-point /users/self/media/recent. You will have to write some code to achieve this. The authentication part can be achieved using the HybridAuth module. Then you'll have to implement your own interface to search content.

This is if you want the user to first see a list of photos and then choose from it. If you just want to embed from url, you can use this module  along with the media module.

Its also important to note that Instagram API no longer permits public scope, and you can only search your own images.

With respect to youtube, Media module along with Media: Youtubemodule allows you to add youtube video from a link. You can then set the video player or thumbnail settings from the display settings. However, by default, there is not out of the box solution to search for youtube video graphically and then add it to Drupal.

However, adding this on top of Media Youtube field won't be very hard. Quick js around this form could solve the issue. See to quick js based youtube search below:

https://codepen.io/timivey/pen/jEXxZY
https://www.w3tweaks.com/youtube/search-youtube-videos-using-youtube-v3-api-using-jquery-ajax-call.html (Click on Demo)

You can use the Drupal Form Alter and Form attached options to add the necessary JS and CSS to the form.


Is there a module that displays a field only when a condition is met? I am looking a module that will only display some fields if a condition is met. Basically only administrators or editors should be able to see those fields in the display. In editing mode it should be alright as only editors have the right to view those fields.

I have checked the documenation for  Conditional Fields module and Field Conditional States which enable this but they do it based on field contents, but I want run if a PHP condition is met. Are there any other similar modules which implement this?

Have a look at the Field permissions module. It allows for role-based conditional display.


Why might form values not be passed from input to values? Somewhere between buildForm and validateForm the $form_state's 'input' becomes the 'values'.  The values are listed as 'null'.  For some reason, some sort of validation from core seems to be preventing only SOME of my values to be left behind, and there's no reason I can come up with, because the data is identical.  Both are textfields representing URLs.  My form is kind of complicated, so I can't post it unfortunately.

I have a feeling the problem is involving ajax somehow.  The fields which are failing are fields which are added to the form by ajax.  Sometimes the values turn to null, and other times the values turn to an empty string.

Where should I look in core to figure out what validation might be getting mad at my fields?  Do you know of any typical thing that might prevent a user's input from passing to values?

EDIT: Here are the contents of my buildForm:

$items['redirect']['old'] = [
  '#type' => 'textfield',
  '#title' => t('Old'),
  '#default_value' => '',
  '#size' => 40,
  '#maxlength' => 502,
  '#description' => t('Old URL.'),
  '#required' => TRUE,
];

$items['redirect']['new'] = [
  '#type' => 'textfield',
  '#title' => t('New'),
  '#default_value' => '',
  '#size' => 40,
  '#maxlength' => 502,
  '#description' => t('Redirect URL.'),
  '#required' => TRUE,
];

$defs = $this->grabDefaultValues();

FormHelper::elementClone($form, $form_state, $items['redirect'], ['old'=>$defs['olds'],'new'=>$defs['news']]);

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

return $form;

The FormHelper part is just some reusable code for cloning the two elements together, so I get old1, old2, old3, etc.  old1 always works, but old2 and old3 mess up sometimes.  The thing is, I have used this code before, and it worked, so I don't know what's happening in this case.

Apparently, around line 1162 of FormBuilder.php, Drupal checks to see if there is a #name element to the field element you're using.  If there's not, it uses the parent's name, which seems to be the previous form element's name.

The clone function wasn't setting unique #name's.  I could have sworn it worked before, but maybe not.


How to map ubercart attributes to CCK fields? The reason I am trying to map ubercart attributes to CCK fields because I can then use these CCK fields to display price list using views for many use cases.

Is there any fields references module which can do this?

If you really want fields and do not want to use your price in your views (though Ubercart is really compatible with views), you can use Rules to fill the value of a "hidden" (I recommend you use field permission for that) CCK numeric field.

Once you've created the field for your product content type, set the rule like this :

Event : Content is created
Condition : Is of type your product content type
Condition : Entity has field your numeric hidden field
Action : Add a variable : get your price value
Action : Convert data type : make it numeric
Action : Set a data value : set your hidden field value.

(Maybe this 3 last actions can be done in only 1 with "set a data value", it's worth trying it)


Optimize performance of custom pre-built option list to webform I am looking to add a pre-built options list, based on a query. I crafted the function nicely with the below code

function mitacan_webform_select_options_info() {
    $items = [];
    if (function_exists('basliklariAl')) {
        $items['addresses'] = array(
            'title' => 'Stok Kodları',
            'options callback' => 'basliklariAl'
        );
    }
    return $items;
}

function basliklariAl($component, $flat, $arguments) {
    $nodes = [];
    $select = db_select('node','n')
        ->fields('n',[
            'nid',
            'title'
        ])
        ->condition('type','urun')
        ->execute()
        ->fetchAll();
    foreach($select as $n) {
        $nodes[$n->nid] = $n->title;
    }
    return $nodes;
}

This is very slow, mostly because there are about 10k records. What can I do to optimise the process?

You can always cache the results as seen in the official documentation

  if ($cache = cache_get('my_module_cache') && REQUEST_TIME < $cache->expire) {
    $data = $cache->data;
  }
  else {
    $data = 'xxxxxxx'; //do all your time taking complex calculations here
    cache_set('my_module_cache', $data, 'cache',  REQUEST_TIME  + (3600 * 24 * 30 * 6)); //stores in cache table and expires after 6 months
  }

More about cache_set and cache_get


Why Can't I Call Drupal Function From .inc File? I have an inc file which I am including in my module using module_load_include. It contains the following function:

function _get_vid($vocabulary_name) {
    $vocabs = taxonomy_get_vocabularies();
    foreach ($vocabs as $vocab_object) {
        if ($vocab_object->name == $vocabulary_name) {
           return $vocab_object->vid;
        }
    }
    return NULL;
}

But PHP keeps complaining that taxonomy_get_vocabularies is an undefined function. Why? I know I've used Drupal functions in .inc files before with no issues.

I think your module must have weight higher than the taxonomy module so that I can call any functions that are defined in taxonomy.

You can make sure your module is the heaviest one in order to run last by implementing hook_install().
You would create a file yourmodule.install in your module folder which may contain the following code:

/**
 * Implementation of hook_install()
 */
function yourmodule_install(){
    # Fetch max module weight from "system" table.
    $max_weight = db_query("SELECT MAX(weight) FROM {system} WHERE type = 'module'")->fetchField();
    # Make sure this module is the heaviest one in order to run last
    db_update('system')
        ->fields(array('weight' => $max_weight+1))
        ->condition('name', 'yourmodule')
        ->execute();
}

/**
 * Implementation of hook_uninstall()
 */
function yourmodule_uninstall(){
    db_delete('system')
        ->condition('name', 'yourmodule')
        ->execute();
}


Delete from Multiple Tables using db_delete() How can we delete fields from multiple tables using db_delete() and INNER JOIN in Drupal 7?

You can't I'm afraid.

db_delete() takes a single string parameter to define which table the query is to be run against. There's no scope to provide more than one table at a time.

You can run any SQL statement you like, though, with db_query(), eg.

// Deletes all nodes and related author users...please don't actually run this!!
$sql = 'DELETE u, n FROM {node} n INNER JOIN {users} u ON u.uid = n.uid';
db_query($sql);


How do I address the checkout button? I need to add a custom function to the Confirm Order button on a Commerce Checkout form. I can't figure out how to call it. The button ID is #edit-continue and its displayed text is Confirm Order. I thought this would show up in the $form[submit] array, but that array is empty. So I checked $form['buttons']['continue']['#submit'], which  seems to be where Drupal Commerce stores the submit functions.
I created a module and two functions.
function MYMODULE_form_commerce_checkout_form_checkout_alter($form, $form_state, $form_id){
   drupal_set_message('ALTERING CHECKING OUT! THIS WORKS' . $form_id);
   $form['buttons']['continue']['#value'] = 'Send Me A Quote!';
   $form['buttons']['continue']['#submit'][] = 'MYMODULE_submit';

function MYMODULE_submit_function($form, &$form_state) {
  die('Triggered submit');
}

drupal_set_message() shows the message, but the submit function isn't invoked, and the text in the button is not altered. So clearly, the problem is that I am not targeting the button properly. How do I "address" that button?
To make it clearer, I need to overload that button, not replace the commerce checkout functionality.
PS: I have no access to the console or Devel. So I'm limited to debugging with var_dump().

Your changes to $form here are lost because you are passing by value.  Pass by reference using &$form instead:

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


Add bootstrap button to rewrite output views I have a view with a table, the last column is a link but should be a button.
So in the last field i enable rewrite output and add this code

<button type="button" class="btn btn-default">
      [clone_node]
</button>

I am using the bootstrap theme. But views is filtering out the button code.
What is the fasted way to change the link into a button?

It might not be what you need, but in Bootstrap you can create buttons using the <a> anchor, which will not be filtered out by Views.

  <a class="btn btn-default" href="#">
        [clone_node]
  </a>


how to react on file save using rules module How is it possible to react on newly uploaded file with rules? Is there any trigger like file upload or file update? Thank you.

You can use Entity Rules I believe for this.
From the module page:

Entity Rules provides a page for selecting and creating Rules components that will be executed when different operations happen to an Entity of a particular bundle. This provides an alternative method of triggering Rules. Instead of adding entity related events to Reaction Rules you are able to select which Rules will fire from the bundle management page.
Currently the operations supported are create, update, delete, validation and form access. You are also able to pass different arguments to the Rules per bundle.

In Drupal 7 the de facto module is typically file_entity used alongside the media module so if you are using those then the above should work but if you are not you may at least need the file_entity module.
I also noticed an issue in the Entity Rules issues page that listed a bug with file_entity but has been fixed in dev, so if the normal version does not work I would try the dev version to see if that works.
Hope that helps!


How to create a checkbox to turn-off/on email notifications each time when a node is published or updated? How can I make a checkbox for turn-off/on sending e-mail notifications to users each time when I publish or change a node (in Drupal 7)? I mean, I don't need to send notifications each time I changed a node (or published it).

I used an editor interface in Drupal 6 (maybe earlier) and it included a similar checkbox: I could turn-off/on sending email notification to users. Here is a picture of it (last checkbox):

Unless you want to re-invent the wheel, you should have a look at the Message Stack, which does exactly what you are asking for (and much more ...). The Message Stack consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium.
If you want to have a closer look at the Message Stack and see it at work in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions (= nodes of content type "Question"), and so that they receive notifications (using the Message Stack) when Questions receive Answers (= nodes of content type "Answer").


Query returns 0 rows on JQGrid filter due to translated rows I have a JQGrid table that can be displayed in different languages. The data for this table is stored as English text and translated when output. The JQGrid table can be filtered by text.

The issue I have, is that when the JQGrid table is filtered, the query will run against the English text. E.g.

Original table:
Yes
No

Translated table:
Oui
Non

User is French and tries to filter for 'Oui':
Database query will return zero results because 'Oui' does not exist in the database table. If the French user queries for 'Yes' then Oui will show because it matches the database and is translated on output.

This is using custom integration with JQGrid.

Since all string translation is cached and as far as I know there are no database tables available to join on, how can I get translated filtering to work?

Any ideas on the best way to handle this?

Ok. I've solved this in what I believe is a reasonable way but it won't really scale:

As I build up the data for the table and translate each cell, I store that into an array with the foreign language string as the key and the untranslated string as the value. (This could work either way round).

$strings[t($my_string)] = $my_string;

I save that array after I've done everything with the last snippet. This array is read at the beginning of loading the table data:

$strings = $saved_strings = variable_get('my_translated_strings_' . $language->language, array());

If the array has changed then I will save it:

if ($strings != $saved_strings) {
  variable_set('my_translated_strings_' . $language->language, $strings);
}

I can then manipulate the filter rules to filter on the original untranslated strings instead of the user's language.


How to display different page content to Anonymous user and to Authenticated User in drupal 7.x? Am don't have much knowledge on drupal. Just starting my first drupal site. I created a "content" under a menu named "information". The menu "information" is given permission for both "anonymous user" and for "authenticated user" as well. As i click the menu "information" (as in anonymous user), the content i set was "please login as authenticated user, if you unable to login, please contact the administrator".

Then, i login as the "Authenticated user" and i click the menu "information", am getting the same content message as *"please login as authenticated user, if you unable to login, please contact the administrator."*Please, i don't need this content message, under "information" menu if i login as the "authenticated user".

I needs to "DISPLAY DIFFERENT PAGE CONTENT TO ANONYMOUS AND TO AUTHENTICATED USER"?
I don't know how to proceed this ? Can anybody please help me out the step by step procedure to do this task ?  Please help me out . Thanks in advance...

The "content" and "information" part of your question doesn't make sense to me. I'm posting a general guide to displaying different content on a per role basis, and you can update your question/comment if you need any part clarified.

I would use Panels. You can use it on either a custom page such as "example.com/information" or on a per conent basis to display different content or parts of the content, on a per role basis. Example below if for "content"/"nodes".

Install the Chaos tool suite (ctools) module, and Panels.
Enable the Page Manager and Panels modules.
Enable the node template.
Create a variant of type "Panel", call it "Authenticated user view".
Pick a suitable layout.
Go to the "Selection rules" settings and add a "User:role" setting to limit viewing to a certain role, such as authenticated user.
Go to the content tab, and add your "Node: Content" to a suitable region so that your content shows up.
Repeat steps 4-6 but call the variant "Anonymous user view". Make sure it's below the first variant in the list.
Add whatever you want your anonymous users to see to the second variant.
Save

That should be all. Using Panels requires a bit of understanding of the tools it provides, and I probably introduced a great deal of new Drupal terms to you in this answer. I recommend you start by viewing these videos here.


Panels + Recaptcha : how to add a (re)Captcha in my panels view? I've just installed Panels 3.1 on my D7 website.

There is no options to add a Recaptcha form on my Panels view.

Where should I find that ?

Thank you,

You don't usually add a recaptcha directly to Panels; you'll want to add it to the appropriate form(s) (comment, registration, etc.)  When you do so, adding the appropriate form in Panels should automatically pull in the recaptcha as well.


Update existing nodes via cron I need to update my nodes created from my own module. The data is extract from my database external.

Now, I want to update this nodes via hook_cron.. My question is: What is the function that update nodes? Or the steps for do this?

I think your looking for node_save. You can node_load your node and make changes to the object and then use node_save to save the changes.


Getting node in theme_preprocess_node I have this code:

function material_base_preprocess_node(&$variables){
    $node = $variables['node'];
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $variables['username'] = $node->getOwner()->getTranslation($language)->field_name->value;
    $variables['mediums1'] = $node->getTranslation($language)->field_mediums->value;
}

this line works fine:

 $variables['username'] = $node->getOwner()->getTranslation($language)->field_name->value;

but this

 $variables['mediums1'] = $node->getTranslation($language)->field_mediums->value;

gets error:

The website encountered an unexpected error. Please try again later.

InvalidArgumentException: Invalid translation language (en) specified. in Drupal\Core\Entity\ContentEntityBase-&gt;getTranslation() (line 789 of core/lib/Drupal/Core/Entity/ContentEntityBase.php).

Why this code works for user, but not for node and how to fix that?

this one works

$node->get('field_mediums')->entity->getTranslation($language)->name->value;

As the exception message says, there is no english translation for that node.

The node is already in the translation that Drupal determined is the best available translation for this page.

If you do want to get a specific translation, you need to check with hasTranslation() first or use \Drupal::service('entity.repository')->getTranslationFromContext($entity, $langcode);


Creating a form where users can edit their own submissions I'm beginning with Drupal. I've got to set up a multistep form which allows users to add content. I want them to be able to edit their own submissions too.

I began to code a custom module in drupal/php but I'm not sure it's the easiest way. I've heard a lot about Drupal native forms or content types that could do it as well as a custom module.

My question is : what kind of modules do I need to build a multistep form with own submissions edition ?

In the
Home » Administration » Structure
and in the content type
add new content type and create your forms as you need

You can edit every content type i.e. node and
for editing own submissions you can set appropriate permissions like 'edit own content' in the
Home » Administration » People  under permissions tab

For multistep forms
you can in the hook_form_alter() create

$form['redirect'] = 'your_next_form_path';

By using redirect as soon as the form is submitted you will be redirected to other form (only thing is proper path for node or form needs to be mentioned).


.htaccess problem for Drupal I decided to ask about this issue, because I found this problem is a common problem for many Drupal designers.

It seems to be a common problem for many drupal designers to face with the Server Error 500 after moving their site to the production server.

There are mainly two lines in the default .htaccess, which are:

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

So, for some hosts these lines should be removed.

What is your solution, after removing these lines from the .htaccess file? How should the directory listing be prevented?

This is a known issue, see:
https://www.drupal.org/node/1269780 regarding a longterm resolution.

In general it looks like going forward +FollowSymLinks should be replaced with +SymLinksIfOwnerMatch, but refer to the issue queue item above for a definitive answer.

Typically per host, and definitely with Shared Hosting plans it's up to your webhosts documentation as to what Apache Overrides are allowed by your (system) user account. There is a certain amount of trial and error is seeing if -Indexes for example is allowed on your webserver.

This is why when you upgrade Drupal they recommend backups of your projects .htaccess and robots.txt file as per webhost and project these files are highly likely to be modified.


Auto assign organic group to a content type I'm trying to assign the group audience to a content type at creation instant. The first thing I have done is to disable the group audience field. So I have implemented the hook_form_alter and done this:

$form['og_group_ref']['#access']= false;

Then, I have implemented the hook_node_insert and here is where I have tried to assign the group. In my use case, users can only have one group. That's my code:

/**
 * Implements hook_node_insert
 */
function og_autoassign_node_insert($node){
  //Get the type
  $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type);

  if ($type == 'content_type1' || $type == 'content_type2'){
    // Get the user
    $user = user_load($node->uid);

    // Load the current user's group
    //$groups = og_get_entity_groups('user', $user);
    $groups = og_get_groups_by_user($user);

    // Load the GID
    $group_id;
    foreach(array_keys($groups['node']) as $id){
        $group_id = $id;
    }

    $values = array(
        'entity_type' => 'node',
        'entity' => $node,
        'field_name' => 'og_group_ref',
        'state' => OG_STATE_ACTIVE
    );
    og_group('node', $group_id, $values);

    dpm($node);
  }
}

When I print the node with dpm, I can not see the organic group associated. What I'm doing wrong? Can anyone help me?

Thanks a lot

UPDATE (I can't answer myself because I have less than 10 in reputation)

Well, I found one solution. Instead of implementing the hook_node_insert, I did that in my hook_form_alter:

function my_module_form_alter(&$form, &$form_state, $form_id){
...
// Load the current user's group
$groups = og_get_groups_by_user();

$form['og_group_ref']['und'][0]['default']['#default_value'] = $groups['node'];
}

And that set the field "Audience Group" with the user's group.

I just ran into this problem with hooks. It's being saved but you won't see this in node_insert due to the caching system of nodes in Drupal. Add this before your dpm code and you'll see the results immediately.

entity_get_controller('node')->resetCache(array($node->nid));

I'm so happy I can stop someone else from banging their head on the wall like I did. Ha.


How to define a non-database relationship for the Views module Basically, I have an array of nids (node ids) stored in a $_SESSION variable, which is updated according to user actions (it holds a history of visited node pages).
Now, I would like to create a view which displays a list of nodes, filtered by nids given in a $_SESSION variable.

For example:
if $_SESSION['my_nids'] == [1,5,6]
=> I want to display nodes 1,5,6 in the view.

Storing the nids in a db table is not an option due to performance reasons.

Can someone point me how to create such a non-database relationship views handler?

You can use the views php module. And you can get the $_SESSION['my_nids'] with in view. Actually you can do anything there that can be done with PHP.

Please note that this will again have a performance hit if the code is large. for simple things you go this route.


views with different content types case studies For my first Drupal site ever I was thinking of filling the frontpage with a view that has different content types. I'm even mixing page content type with a custom event content type so now I have problems with styling the view because of different content fields in different view items.

Does anybody know of case studies where people have succesfully mixed custom with stock content types because this is becoming a nightmare.

Views gives you enough power to maintain your custom styling. Please check for Views for theme information.

You can theme your different fields, rows, general theme.

You can style your node.tpl.php for general and for specific type node-[type].tpl.php


How to get value from URL in a view block using contextual filter? I want to show related nodes of an open article in a block, but how do I access Node IDs from url in block view.

Assume your article is located at node/nid (with nid the id of the node of the article), then configure your contextual filter like so:

  When the filter value is not available: Provide a default value with Type = "Content ID from URL" (that value should correspond to the nid of your article).


Batch Enable alt text for image fields I'm updating a site in which I need to ensure that the alt (and possibly title) attribute are enabled for any field of time file (widget image).

There are tonnes of content types and I don't want to have to go through every field in every content type to check and enable it each.

I've had a search for modules but have been unsuccessful in my search. Is there a way I can enable them in as a bulk operation in the database?

I've looked but couldn't find exactly where the setting for each field was

For example, the table content_type_source_homepage has the following fields

field_shp_image_fid     int(11)                         Yes NULL
field_shp_image_list    tinyint(4)                      Yes NULL
field_shp_image_data    text        utf8_general_ci     Yes NULL

These obviously store a reference to the image but does not indicate whether or not the user is allowed to edit the alt attribute for that image, and what the default alt attribute might be.

Furthermore, fields which allow multiple images have a separate table such as content_field_title_image which again has similar fields without indication as to whether or not the alt attribute is editable.

Each content type will have a form associated with the content type. Using hook_form_alter, you can change these items and set them in batch.

Here is a great video that teaches how to do what you are asking, but using the author check box.  Using a technique like this you could set everything to 'on' (1).

http://mustardseedmedia.com/podcast/episode53

How many is 'Tonnes' - do you have 50 content types or 500? Remember you would have to write custom code to do this, so you would need to be familiar with PHP and how modules are written.  If that is not your forte and there is not a module, it may be best just to dedicate a few hours and a beer to it :)


How to use user_load() for user on $_GET[] request in Drupal way? I'm trying to get UID of users on $_GET[] request, following is my module code:

my_module.module

function hover_card_init() {
  $module_path = drupal_get_path('module', 'hover_card');
  drupal_add_js($module_path . '/javascripts/hover_card.js');
  drupal_add_js(array('hover_card' => array('module_path' => $module_path)), array('type' => 'setting', 'scope' => JS_DEFAULT));
}

function hover_card_menu() {
  $items['hover-card'] = array(
    'title' => 'Hover Card',
    'page callback' => 'hover_card',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function hover_card() {
  $id = $_GET['id']; // Get UID using JS, not a Drupal way!
  $user_fields = user_load($id);

  if (isset($user_fields->name) && !empty($user_fields->name)) {
    $name = $user_fields->name;
  }

  $array = array(
    'name' => $name,
  );

  return theme('hover_card_template', array('details' => $array));
}

my_module.js

(function ($) {
  Drupal.behaviors.hover_card = {
    attach: function (context, settings) {
      var module_path = Drupal.settings.hover_card.module_path;
      var hoverUserDetails = '

';
      $("a.username").hovercard({
        detailsHTML: hoverUserDetails,
        width: 250,
        onHoverIn: function () {
          var user_id = $(this).find("a").attr("href").split("/");
          var hover_details = $(".hover-details");
          $.ajax({
            url: Drupal.settings.basePath + "hover-card",
            type: 'GET',
            data: {
              id: user_id[3] // What should I do here? As this is not a clean and Drupal way :-(
            },
            beforeSend: function () {
              hover_details.empty();
              hover_details.prepend('Loading...');
            },
            success: function (data) {
              hover_details.html(data);
            },
            complete: function () {
              $('.loading-text').remove();
            }
          });
        }
      });
    }
  };
})(jQuery);

As said in the comment for the question, you should use placeholders in your menu definition.

function hover_card_menu() {
  $items['hover-card/%user'] = array(
    'title' => 'Hover Card',
    'page callback' => 'hover_card',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

Then you can pass the user ID for the currently logged-in user to the JavaScript code, instead of passed the module path, which is irrelevant.

function hover_card_init() {
  $module_path = drupal_get_path('module', 'hover_card');
  drupal_add_js($module_path . '/javascripts/hover_card.js');
  drupal_add_js(array('hover_card' => array('user_id' => $GLOBALS['user']->uid)), array('type' => 'setting', 'scope' => JS_DEFAULT));
}

The JavaScript code doesn't need to know the module path, since it will make an AJAX call to hover-card/%user which is not related to the module path in any way.


Rewrite photo field URLs Every time I download a new copy of the live database to my local site I also have to download the photos (several GB).
Is there an easy way to write the URL for one "photo" field (type image) to always use the live site urls?

I'm using S3 but haven't found a good way to batch move images and image styles to S3.

theme_image() by default looks like this:

function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

so, if you are storing the images in this field in an identifiable place, eg, you can look at $variables['path'] and figure out they are the ones you want to always look for on a specific host, you should be able to do something like this in your theme:

function MOTOTHEME_image($variables) {
  $attributes = $variables['attributes'];

  if (dirname($variables['path'])==WHEREIKEEPTHISFIELDSIMAGES) { // on d7 this might be a uri so you might need to get fancier than dirname() :)
    $attributes['src'] = // http://.....
  } else {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}


Anonymous users getting same product items in cart I am using drupal commerce module, i have an issue with anonymous users, when users click on add to cart button, cart is showing extra items which are added by other anonymous users.

I am using custom code for add to cart using ajax. following is the code.

    // Add a product to cart on ajax call.
    function mymodule_custom_add_to_cart($product_id,$uid){
        $line_item = commerce_product_line_item_new(commerce_product_load($product_id));
        commerce_cart_product_add($uid, $line_item);
        $order = commerce_cart_order_load($uid);
        commerce_cart_order_refresh($order);
        // loads data array from order object
        $data = mymoudle_custom_cart_load_all_variables($order->order_id);
        $jsonencoded = json_encode($data);
        print $jsonencoded;
    }

I dont know why all anonymous users are getting same products in there cart.

Please help me to find out the issue.

UPDATE 1:

I have changed the code for anonymous user as following, then i am getting an error: EntityMetadataWrapperException: Unable to get the data property data as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 451 of /entity.wrapper.inc

CHANGED CODE

    // Add a product to cart on ajax call.
    function mymodule_custom_add_to_cart($product_id,$uid){
        if($uid == 0){

            $order_id = commerce_cart_order_id($uid);
            if($order_id == false){
             $order = commerce_cart_order_new(0, 'checkout_checkout');
            } else {
             $order = commerce_order_load($order_id);
            }

            // Load whatever product represents the item the customer will be
            // paying for and create a line item for it.
            $product = commerce_product_load($product_id);
            $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
            commerce_line_item_save($line_item);

            // Add the line item to the order using fago's rockin' wrapper.
            $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
            $order_wrapper->commerce_line_items[] = $line_item;

            // Save the order again to update its line item reference field.
            commerce_order_save($order);

            // loads data array from order object
            $data = mymoudle_custom_cart_load_all_variables($order->order_id);
            $jsonencoded = json_encode($data);
            print $jsonencoded;
        }else{
            $line_item = commerce_product_line_item_new(commerce_product_load($product_id));
            commerce_cart_product_add($uid, $line_item);
            $order = commerce_cart_order_load($uid);
            commerce_cart_order_refresh($order);
            // loads data array from order object
            $data = mymoudle_custom_cart_load_all_variables($order->order_id);
            $jsonencoded = json_encode($data);
            print $jsonencoded;
        }
    }

UPDATE 2: ISSUE RESOLVED.

Site is crawling by googlebot, which is clicking addtocart link and its adding an product to anonymous user account automatically, so i removed link for addtocart button and used commerce addtocart form.

I would guess it has to do with:

$order = commerce_cart_order_load($uid);

Since all anonymous users are assigned uid:0, it could be drawing from all products currently associated with that uid (which would be all anonymous users), rather then the products from the current user's session


Render a full entire html page from custom module I've searched/asked around without success.

I'm creating a custom Drupal 7 module, and I would like to render the code in an empty full template (not a page/node.tpl.php); by full template I mean a template containing the <html> tag.

Since now, I've used the following code but the template is rendered in page.tpl.php (render($page['content'])).

function mymodule_theme() {
  return array(
    'adm_xyz' => array (
      'render element' => 'render',
      'template' => 'adm_xyz', //  template *.tpl.php
    ),
  );
}

Your callback in hook_menu() will by default call drupal_deliver_html_page() which in turn calls drupal_render_page() where the page.tpl.php comes from.

It is possible to implement your own "delivery callback" method, which will be called by drupal_deliver_page() this is how the ajax is delivered in D7


Admin to Create User type Foo that can then Create User type Bar I'm looking to build the following user structure in Drupal 8

Admin: They can create users of type Foo and Bar.

Foo: They can only create user type Bar.

Bar: They can only create content of a particular content type.

Is this achievable with any current module release? Here are some that I found that could help contribute to a solution:

I've seen profiles, but it has not got an official release yet.. and the feature set doesn't take care of my problem.

Rules, again not a full release but it can trigger events depending on a saved node/ submitted form etc..

Administer users by roles, sounds perfect, not tried and tested.. but noticed again the no official release.

Organic Groups. I don't need to entwine users and nodes (associating content with groups). Which is what I gathered when installing this module

The other option would be to create some custom code that is fired on the submission of a form to add a user via official drupal code... the only problem with this is making sure the code is correct and updated as new release of drupal is released for example. Would this be a good / stable approach?

Can anyone help point me in the direction of a solid solution?

Thanks in advance.

@cwiggo Drupal doesn't really have a concept of a user 'type', just roles that a user can participate in, which I presume you know. You can of course layer 'types' on top of the provided structures using additional fields and tables. You've obviously looked at some of the candidates for helping with this, but have you considered Organic Groups, which might be closer?

As for using projects before stable release: my best suggestion is to dive in and help get a project over the line, perhaps by contacting the module maintainers and offering to help directly. There are however a lot of sites based on 'dev' modules; the maintainers just have to evaluate the code, the issue queue, and the overall risks/benefits and make a decision.


Add a local task tab for a content type only Someone can help me ? I want to display a tab only when the content type is 'test'.

Here's my files.

mymodule.routing.yml :

mymodule.check_test:
  path: '/checktest/{node}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CheckTestController::content'
  requirements:
    _access: 'TRUE'

mymodule.links.task.yml :

mymodule.check_test:
    title: Display tests
    route_name: mymodule.check_test
    base_route: entity.node.canonical

My tab is displayed for every content, i don't know how to filter with my content type...

Thanks :).

Edit :
From mradcliffe's answer,

I've add a mymodule.services.yml :

services:
  access_check.test:
    class: Drupal\mymodule\Access\MyModuleTestAccess
    tags:
      - { name: access_check, applies_to: _access_test }

and a MyModuleTestAccess class with :

public function access(NodeInterface $node)
{
    return AccessResult::allowedIf($node->bundle() === 'test');
}

My edited mymodule.routing.yml :

mymodule.check_test:
  path: '/checktest/{node}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CheckTestController::content'
  requirements:
    _access_test: ''

You can use an access check to hide a route.

If the user that will view the tab has the same permission for adding a node of a given type, then simply adding _node_add_access: 'node:MYNODETYPEHERE' would be sufficient. However this is probably not the case.

Instead you can add _custom_access to the route requirements as a method on the controller class.

mymodule.check_test:
  path: '/checktest/{node}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CheckTestController::content'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\CheckTestController::checkAccess'
    # It is highly-recommended to always use the default entity access check for
    # an Entity as pointed out by @pwolanin below. Not doing so may lead to
    # undesirable results and potential information disclosure or access bypass
    # vulnerability.
    _entity_access: node.view

And then a corresponding method on the controller (see Access checking on routes for more details). Something like this might work for you (untested).

public function checkAccess($node) {
  return AccessResult::allowedif($node->bundle() === 'my_node_type');
}

Update 2019.08.30: Incorporated @pwolanin's answer into this one in case anyone misses and doesn't read its importance.


User profile image update from a popup window Is there a way to make the user profile image updated using overlay window from different page other than /user/edit

Profile Pic Changer Module Provides a modal dialog box to change user pictures

  Allow users to change their profile picture through a modal form
  directly on their profile page, without having to go to the profile
  edit form.


Set a condition in views to remove title link Currently I have a custom view that lists a series of nodes. One of my fields is "Content:Title" and I have checked "Link this field to the original piece of content". Everything works.

Question: For my list of nodes I would like to selectively "unlink" some of them and have the text remain. So in a way, it would be a preview of what's to come. Then when I am ready to link them I will "reactivate" the link.

Example:

Title 1
Title 2
Title 3
Title 4
Title 5

Add a boolean field to your node to determine if the link is shown or not. Let's suppose it's called Show Link
In Views add the Title field and then check 'Exclude from display'. Don't check 'Link this field to the original piece of content' here.
Add a Field that you can use to build your link, e.g. Content: Path. (You could also use Content: Nid.) Check 'Exclude from display' so this does not show.
Add the Show Link field and select the formatter type to be Key - this is important! it won't work without it
Rewrite the output of the Show Link as, e.g. [Title]. Check the box to 'Output this field as link'. And then fill in the path box with, e.g. [path] or if you've gone the Nid route node\[nid]
Now edit the No results section of the Show Link field. In this case you want to output the Title without the link, e.g. [title]. Check the 'Count the number 0 as empty' In my testing I also have 'Hide if empty' and 'Hide rewriting if empty' checked.

Make sure you order the fields so that the ones providing the tokens for the rewrites come before the Show Link field.


drupal jquery mobile datepicker cannot select year I'm using drupal 7 with jquery.mobile-1.4.5.

I had created a form with date field, using Inline Datepicker

  $form['body']['dob'] = array(
    '#type' => 'textfield',
    '#title' => 'Date of Birth',
    '#attributes' => array('data-role'=>'date', 'id'=>'dob'),
  );

The Inline Datepicker is showing exactly like the demo in http://demos.jquerymobile.com/1.4.1/datepicker/

However, I would like to have a inline datepicker, with a dropdown menu for user to select year in calendar.
Eg: https://jqueryui.com/datepicker/#dropdown-month-year

I had tried adding in below function but it doesn't work.

$(function() {
    $( "#dob" ).datepicker({
      changeMonth: true,
      changeYear: true
    });
  });

Is there any way I can allow user select year in the inline datepicker?

You can use Date module which has several options regarding to your requirement. You can use date functionalities in your custom form.

For example,

$form['body']['dob'] = array(
  '#type' => 'date',
  '#title' => 'Date of Birth',
);

will have options to select date, month and year.

If #type => 'date_popup', it  will popup with calendar which allows user to select date.

Check this link for more info date example


Programatically change autocomplete views exposed filter by a select list I have a view which has a filter by users that created de nodes. This filter is exposed, in order to select an user and filter the results by this user. I would like to change the default autocomplete filter by a select list of user, and in this list I want to show only some users.
I followed this tutorial but without success. Although I change "uid" form field, It does anything.
How could I do it? Thanks

UPDATE: my code.

function my_module_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {

$pos = stripos($form['#id'], 'views-exposed-form-my-form');
if ($pos !== false) {

    $opcusuarios = array();
    $query = \Drupal::entityQuery('user');
    ... some conditions ...
    $entity_ids = $query->execute();
    $usuarios = \Drupal::entityTypeManager()->getStorage('user')->loadMultiple($entity_ids);
    foreach($usuarios as $user) {
        $opcusuarios[$user->id()] = $user->getAccountName();
    }

    // Change the input
    $form['uid']['#type'] = 'select';
    $form['uid']['#multiple'] = FALSE;

    // Add the $options from above to our select list
    $form['uid']['#options'] = $opcusuarios;
    unset($form['uid']['#size']);
}

}

It won't work because validateExposed function from core/modules/user/src/Plugin/views/filter/Name.php expect the values to be something like :

array:1 [▼
   0 => array:1 [▼
     "target_id" => "1"
   ]
 ]

So if you just modified the autocomplete to select you will send the value of uid like 1 for example:

Suggested solution

Add Validation function before validateExposed and refactor the value of input uid.
Here is code snippet:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // If not the view we are looking, move on
  if (stripos($form['#id'], 'views-exposed-form-my-form')) {
    return FALSE;
  }
  //- query
  $query = \Drupal::entityQuery('user');
  /**
   * @TODO: Add your conditions.
   */
  $options = [];
  //- get user ids
  $entity_ids = $query->execute();
  //- Get Users List
  $users_list = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->loadMultiple($entity_ids);
 //- Prepare the list options.
  foreach ($users_list as $user) {
    $options[$user->id()] = $user->getAccountName();
  }
  if (isset($form['uid'])) {
    //- alter the Uid field.
    $form['uid'] = [
      '#type'         => 'select',
      '#options'      => $options,
      '#empty_option' => t('-- Select User --'),
      '#multiple'     => FALSE,
    ];
    unset($form['uid']['#size']);
    //- Add Validate in the beginning To be before validateExposed
    array_unshift($form['#validate'], 'validateUserExposedFilter');
  }
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function validateUserExposedFilter(&$form, FormStateInterface $form_state) {
//- Get the input value
  $input = $form_state->getValue('uid');
  //- Prepare value to be like the expected
  if ($input) {
    $value = [
      0 => [
        "target_id" => $input,
      ],
    ];
    //- Set the new value
    $form['uid']['#value'] = $value;
    //- Update the form state
    $form_state->setValue('uid', $value);
  }
}


Paid Registration with Paypal I have visited related questions here but i need more specific answer.

I have hooked into the user registration form and i have added a custom submit handler for user registration before the user drupal core registration function.

I want to implement paid registration. I have visited Paypal IPN documentation but they said the require a return url.

Actually i am confused in the whole process. I want to know actual steps to implement payment api of paypal then if the user has paid the drupal core submit function should run otherwise i'll die the script.

Thanks

If this is an activity that you'll be repeating, like hosting events on a regular basis, I would step it up a notch and add CiviCRM to the Drupal installation. It will increase the complexity of your site by adding a new administrative area where you would manage the CRM components (at this point events and Payment Processors) but that additional complexity will simplify managing them.

Out of the box it's set for managing events with PayPal; During setup you're prompted to go through a checklist. One of those items is Payment Processor. Set it to PayPal, follow the prompts and it just pretty much works.


What hook can access every field label at once and change the label of one? I am trying to change the display label of one field on a node (not the form), depending on the value set in another field in Drupal 7. I don't want to change the label in the database, just on the final node page when you view it, if another field is set to a certain value.

I tried a few different hooks with no luck. Some can access every field, but only the value and not the label. Some can access the label on a per field basis which I can get half working (Set a flag in another function if the field is set correctly) but that only worked if the fields are checked in the right order.

So which painfully obvious hook will allow me to check a field setting and then edit the display of a label on another only on the node page? My perusing of the hook documentation and Google have not helped.

Thanks!

A guaranteed solution for all fields is hard. It depends on:

The field formatters you have chosen
the template files used

For a general approach try:

/**
 * Implements hook_preprocess_HOOK().
 */
function YOUR_MODULE_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'YOUR_DEPENDENT_FIELD' && !empty($variables['element']['#object']->YOUR_DEPENDENCY_FIELD)) {
    // YOUR LOGIC IN RELATION TO YOUR_DEPENDENCY_FIELD
    $new_value = 'something';
    $variables['label'] = $new_value;
  }
}

Notes:

This will change the label display everywhere, not only on a
node display. Since you don't mention anything about view modes, I
guess the given solution is good enough.
Make sure you sanitize $new_value if you are showing user input.


How to avoid submitting a form when creating a new content, depending on some criteria? Let's suppose I have a content type Person, and I don't want the field Name to contain the text AAA.

What would be the best way of avoid submitting the form if that happens?

For example:
- Hiding the Save button
- Submitting it, but return to the same page with that field marked as red, or just show a message...

This is just an example. I'm asking it because sometimes I need to do a query to the database and see if some records exist, or something like that...

Edit:
I have edited the template.php file under the theme folder I'm using, and I have added the functions:

theme_theme()
theme_formId($form)

In the 2nd function, I've modified the form to see Drupal is calling this function, and yes, it works...

Then I did the following in the 2nd function:

$form['#validate'] = array('my_validate_function');

and under my_validate_function($form, &$form_state) I just wrote form_set_error('', t('Testing...')); and nothing seems to be happening: I can still create a new content without problems :(

What am I missing here?

You can add validation callbacks to any form in Drupal using the Form API. Specifically, you can use hook_form_alter to add a validation callback to the $form['#validate'] element.


Views: pass link to referenced node to image field I have a content type "slideshow" with three fields:
1. title
2. image
3. entity reference to nodes of a specific content type.

Then I created a view which I want to display as a slideshow on the frontpage. Its filter is set to the content type "slideshow" and I have three fields there:
1. the entity reference to the nodes (hidden)
2. image
3. title

What I want to achieve is, pass the referenced node from the entity field as a link to the image field so that the image in the slideshow has a link to the node from the entity reference field.

I tried the following:

In 2. image field settings: I checked: Output this field as a link and in the link path I put: [field__slideshow_link_gallery] which I got from the replacement patterns below.

The problem is that the image actually has a link but the link is the name of the referenced node rather than the link to the referenced node. I would need the link not the name.

In the 1. entity reference field in the view I have only three formatters (label, entity id and rendered entity). I used label as a formatter and checked "Link label to the referenced entity. Unfortunately only the name is passed to the image not the link. Any ideas would be greatly appreciated.

You can select the entity I'd formatter and set the image link to 'node/'[your_token_here]
Use the views image field template (see the views theme information) to wrap it with the link


Use HTML tags inside rows of a table in a render array I'm creating a table within a render array.
I can easily create rows within the table like so

$rows = [
    'test 1',
    'test 2',
    'test 3',
];
$header = [
    'header 1',
    'header 2',
    'header 3',
];
$render['table'] = [
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

However when I attempt to include html tags within the row like so:

$rows = [
    'test 1',
    'test 2',
    'test 3',
];

it spits it out with the tags written out. It shows

test 1test 2test 3

instead of showing

test 1 test 2 test 3

Is there a way to use html tags inside rows of a table element in a render array?

UPDATE:
I've also tried

'#rows'    => [
                        'test 1'  => [
                            '#type'  => 'html_tag',
                            '#tag'   => 'h1',
                            '#value' => 'Test 1',
                        ],
                        'test 2'  => [
                            '#type'  => 'html_tag',
                            '#tag'   => 'h1',
                            '#value' => 'Test 2',
                        ],
                        'test 3'  => [
                            '#type'  => 'html_tag',
                            '#tag'   => 'h1',
                            '#value' => 'Test 3',
                        ],
                    ],

But that returns a table with 3 rows and 3 columns that say

'html_tag' 'h1' 'Test 1'

'html_tag' 'h1' 'Test 2'

'html_tag' 'h1' 'Test 3'

Instead of actually producing an html tag.

Try creating the links using function Drupal::l,

For example,

$url = Url::fromUri('http://example.com/');
$link1 = \Drupal::l(t('Link1'), $url);
$url = Url::fromUri('http://example.com/');
$link2 = \Drupal::l(t('Link2'), $url);
$url = Url::fromUri('http://example.com/');
$link3 = \Drupal::l(t('Link3'), $url);
$rows = [
  array(
    $link1,
    $link2,
    $link3,
  ),
];
$header = [
    'header 1',
    'header 2',
    'header 3',
];
$render['table'] = [
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

To add other html tags to table , you can use Drupal markup element and renderer service,

$element['#markup'] = 'Example Span Tag';
$span_tag = \Drupal::service('renderer')->render($element);


Performance and Field Collection I have a use case where I want to add multiple fields grouped together to an entity, field collection is perfect for this and I have it working well now this way.

Field collection stores all field collection entities in one table in field_collection_item, so if I had another field collection that had a huge number of rows would it effect performance? If so then I would like to store these other fields groups somewhere else, maybe an entity reference so these fields are in their own table. How would I convert my field collection to entity reference.

Can I duplicate the functionality of field collection with entity reference? As essentially an entity reference and field collection are the same. But if I had an entity reference it would be in it's own table that is less crowded.

Not exactly. Field Collection main purpose is to make a field that holds other fields so the data can be logically grouped. So, no, you can't really "convert" it to an entity reference field - they store different data. An entity reference points at another entity; so you'd need an entity to be a container for that data. You can either achieve this via Entity API, or use ECK. I suppose you could write a migration/batch script to port over the data, but I really don't see the point unless the entities were going to be viewed on their own page.

You shouldn't have any issue with the number of rows in the database, the issue will arise when it comes to operating with that data. If you have an entity that has 1500 field collection items, and you load them for display, yes, you will have very severe performance issues. Think of it like calling entity_load 1500 times.

This usually rears its ugly head when you try to make some Views to display field collection items. Pro tip there - disable automatic preview in the Views config.

Here are some resources that may help:

https://drupal.stackexchange.com/a/105397/57
https://www.computerminds.co.uk/drupal-code/you-should-use-entity-cache
https://blog.openlucius.com/en/blog/drupal-field-collection-vs-drupal-compound-fields

This thread also has some good history on a group of people looking for performance improvements with Field Collections: https://www.drupal.org/node/1268620

Edit:

Forgot to link to Entity Cache, which you can bolt on to Field Collection.

In the past, I had came up with two solutions to solve performance bottlenecks revolving around Field Collection.

In one case, I would prime the cache with a nightly cron run, render the field collection field into a variable and cache that variable. If the cache item exists, I pass that as the template variable. This bypasses loading and rendering the field and rendering the data (entity_load) for every user requesting the page.

This works, until your cache item grows to over 1MB in which case it can still cause MySQL to slow down. You may also want to look into adding Memcache or Redis on top as the caching backend to alleviate that. Ultimately, MySQL will be your bottleneck - so you should try to offset that work and cache as much as possible in a caching backend.

In another case, I wound up storing the data in Solr. When the node was preprocessed, I would query Solr for that item. I was also storing the rendered result in Solr, so that my result already contained the rendered HTML. This was the fastest solution for end users, but came with a bit of work to keep it up to date. This is also beneficial if you also have to search through that data elsewhere, since you'd already (read: should) be working with Solr in that case.


The node from one content type doesn't appears in Nodequeue I'm using Drupal 7 and nodequeue module with Royalslider.All other content types are working fine but only one content type which is named as Real Estate Listing doesn't show it properly.

Here's even it's available in queue list:

and here's how it's displaying in slider:

All of other content type nodes it displays all queues as:

But for Real Estate content type node it displays only 2 queues as:

What can be wrong?

Thanks in Advance!

Go to admin/structure/nodequeue/
Click 'edit' for the nodequeue in question.
Check 'Real estate' under 'types'.
Save.


Turn form builder response into HTML I have a node type called "competition". I can get a form for it like so:

$values = array('type' => 'competition');
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($values);

$form = \Drupal::entityTypeManager()
  ->getFormObject('node', 'default')
  ->setEntity($node);
$form = \Drupal::formBuilder()->getForm($form);

In a controller it's easy enough to return $form and it will be rendered. But I want to do other things with this form so I need it back as HTML. How can I turn $form into fully rendered html?

I managed to use:

$html = drupal_render($form);

Just like you would do in Drupal 7. Not great, but solves my problem.