Module and Custom Content Type I am trying to create a module (Drupal 7) which will have the following workflow:
 1. User enters data via form  (frontend)
 2. The data is validated and get stored in database (custom content type e.g. Reservations )
 3. User will receive confirmation e-mail
 4. User will be redirected to another page
 5. Data will be manipulated by Admin (CRUD functionality)

Ideally, I would create custom content type via GUI e.g. Reservations. And when use the Views module to manipulate the data.
Could anyone suggest any tutorial or explanation about how should I proceed
Pls. Note that already played with Webform module and found that I prefer to do it via custom module and Form API

Thank you in advance

You can do it via drupal's form API, First create your content type

1.Create a module (http://drupal.org/node/361112)

2.Create menu callback

function form_example_menu() {
  $items = array();
  $items['examples/form_example/tutorial'] = array(
    'title' => 'Form Tutorial',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_example_tutorial_1'),
    'access callback' => TRUE,
    'description' => 'A set of ten tutorials',
    'type' => MENU_NORMAL_ITEM,
  );
}

3.Use form api create form with necessary fields

function form_example_tutorial_1($form, &$form_state) {
  //your fields goes here
   $form['name']['first'] = array(
     '#type' => 'textfield',
     '#title' => t('First name'),
     '#required' => TRUE,
     '#default_value' => "First name",
     '#description' => "Please enter your first name.",
     '#size' => 20,
     '#maxlength' => 20,
   );

 }

4.Add necessary validation

function form_example_tutorial_1_validate($form, &$form_state) {
  //your validation goes here
}

5.Add form submission codes

function form_example_tutorial_1_submit($form, &$form_state) {
  //here you can process your data, in your case you want save it to a content type. so you can use node_save here
  $node = new stdClass();
  $node->title = $new_node['title'];
  $node->body['und'][0]['value'] = $new_node['body'];
  $node->type = 'article';
  //include all necessary fields
  node_save($node);

  //after success full save you can  write code for confirmation e-mail and redirection page
 }

6.As you have saved data to a content type, You can create a view with all required details, with edit delete functionality

If you have any doubt in module development and implementing form api you can get examples on this page http://drupal.org/project/examples

hope this may helps you


Why does the Google Analytics module restrict uid? When I try to insert the [current-user:uid] token for a custom dimension in the Google Analytics module, it gives me an error that this is a forbidden item.

However, reading through the GA Terms of Service, I can only find a vague statement saying only "non-personally identifiable information" is allowed.

The GA module is the only documentation I have found that explicitly states the uid is forbidden.

Wouldn't an id be allowed because Google has no way of retrieving the Drupal user's information?

Does anyone have a reference to where in the GA policy they disallow uid?

There is nothing specific in the GA documentation that forbids it. There is actually a section in the GA Help which explains how to use user ids: Benefits of using the User ID feature, so using user ids is not forbidden by GA at all.

Why it doesn't work in the GA Drupal module is because of this paragraph, as stated by one of its developers (found here):

  If you upload any data that allows Google to personally identify an individual, your Google Analytics account can be terminated, and you may lose your Google Analytics data.


Correct way to import an RSS feed and display it in a view? I have an rss feed (facebook) (can also be output as a json). I want to import the RSS feed and have it display using a view.

I already have the Feeds module installed and the Feeds: Facebook Parser installed. I think I have everything I need but I can't figure out how put it together. Seems like this is a common need just not sure how to put the pieces together to make it happen.

The proper way to import an RSS feed and have its data displayed in a view is by creating nodes from the feed data. This is what the Feeds module accomplishes.

You will need to define two content types: one to be used by the feed importer (ex. "Facebook Feed Importer") and one for the feed items themselves (ex. "Facebook Feed Item"). In the feeds importer:

Under Basic settings, attach the feed to the Facebook Feed Importer content type.
Set the node processor bundle to Facebook Feed Item.
Map the fields.

See this tutorial for more details in setting up the importer. If you have troubles using the Feeds: Facebook Parser, give the Feeds JSONPath Parser a try.

Once you have everything configured correctly, make a new Facebook Feed Importer node, enter in the feed URL, and save the node. View this node and click import. The RSS data should be imported as Facebook Feed Item nodes. If you get errors, or 0 nodes created, you probably have an issue with your mappings or importer configuration.

By importing the feed data into your website as nodes you have more flexibility in how you can display this information to the user. Instead of having one large string of data for a feed item, you have a node containing fields for each part of the feed item which can then be customized in your views or anywhere else on your site however is required.


Commerce hook attributes refresh alter Commerce 1.x (D7) has a hook _commerce_cart_attributes_refresh_alter(&$commands, $form, $form_state) that allows modules to add arbitrary AJAX commands to the array returned from the Add to Cart form attributes refresh. Is there anyway to have something similar in Commerce 2.x (D8)?. I would like to add my custom commands.

Drupal 8/9 modules often use events to take the place of alter hooks like this one found in Commerce 1.x on Drupal 7. You have to do a little digging to find the place in the code that executes it, but you can look it up with the following info:

An Add to Cart form in Commerce 2.x is an order item add form governed by the "Add to Cart" form mode (a new concept in Drupal 8).
Looking at the configuration for the default order item type, you can see that the "Purchased entity" reference field uses a field widget called "Product variation attributes."
You can find that widget's definition in the ProductVariationAttributesWidget.php plugin contained in the product module, and its formElement() function shows you that it invokes an ajaxRefresh() function on the object to process the Ajax response when attributes are updated.
That class extends ProductVariationWidgetBase where the ajaxRefresh() function is located. You can see that it builds a response array using an Ajax renderer and gives other modules the opportunity to add commands to the response array via the PRODUCT_VARIATION_AJAX_CHANGE event (using a constant defined in the ProductEvents.php class).

If you're still following, the solution then is to create your own event subscriber that subscribes to that event and appends your own commands to the event's $response array. I've created an example module showing how to do this: https://github.com/rszrama/commerce_example3


How to get the node ids of answers for a question in Drupal Services (REST)? I have a Drupal setup that is currently having a question and answers module.

I am able to read the question and answers by accessing http://mysite.tld/rest_endpoint/node/{nodeid} . However when I access a question, I am not able to get the nodeIds of all the answers to that question.

So I am looking to get the Node Ids for all the answers for a specific question.

What params/filters do I need to use in the Drupal Services GET call? I have services module.
Can I achieve this by doing a database query? I am not able to find a link between questions and answers in the DB too!

Any suggestions?

I didn't know what are question and answers modules that you used. My assumption is your answer and your question has a content type and they linked together. So if my assumption is correct here is the way that you can use for solving your problems:

Create a views will list all the answers of specific question(your question nid).
using Views Services to get the views that you created before and use your question (question nid) for the views parameter.

In case my assumption is wrong. Your have to create custom resource by your own to get the list of answers. In this way you must create your SQL sentences too. The reference for creating custom resource here


How can I create a view which includes all parent terms of a taxonomy term? I am creating a view which takes a tid as an argument. I then want to generate the full list of tids which includes the one directly referenced plus all those above it in its taxonomy.

How could I do this?

I guess you can't do it directly in views. You can use "Contextual filter: Taxonomy term: Term ID" and write small php code by selecting "Provide default value".

Here is the code you can use:

$parent_terms_string = '';
$current_tid = 3; //The term ID of whose all parents you want to fetch.
$parent_terms_tid_array = array();
$parent_terms_array = taxonomy_get_parents_all($current_tid);
foreach($parent_terms_array as $term){
  if($current_tid != $term->tid){
    $parent_terms_tid_array[] = $term->tid;
  }
}
$parent_terms_string = implode('+',  $parent_terms_tid_array);
return $parent_terms_string;


How can I insert PHP code in Views? I tried the views_php but I have no luck. Any link to its documentation?

I want to add some custom field with PHP code inside it but the one I did return nothing. Please see the attached picture.

Yes you can add php code using views_php

Add field in views global

Then add code you need is in Output code sector. I thing here is the problem for you. you add php code to 'Value code'.

Then look at the preview. it's done!!!!!!


How can I create a "related content" view but display it as a page with an url alias? I have created a "related content" view but display it as a page instead of what would more traditionally be a block.

Let's say I have three content types, event, photo and speaker. Each photo and speaker node have an entity reference to an event node.

Photo ----> EVENT <---- Speaker

When I view an event node, I would like to have a link to a page that displays all of the photos that reference that event and a similar link/page to display all speakers that reference the event. I have created a view page for each of the subordinate content types (photo/speaker) that takes an event nid as an argument and displays all the nodes that reference that parent node, but there are a number of issues related to the url of these view pages which follow the structure /node/%/photos.

Aesthetically these url's are not ideal. I would prefer to have the url contain the url alias of the event node. For example /event1/photos and event2/photos etc. would all be pointing to the same view but passing the bid of the event as the argument to the view.

I am also open to the possibility that I am going about this in the wrong way so any advice would be appreciated.

You could create two new views for this. For example:

Create a new page view and name it something like Event_Photos.
Set the path to be something like `event/photos/%'.
Add an argument of type Content:nid.
Setup a relationship using the field that references the photos from the event content-type.
Add a filter using the above relationship of type Content:Type = photo.
You will also need to use the relationship for all your fields.
In your first view, rewrite the output for the photo link to event/photos/nid.
Create a second view for your other content type and follow the above steps.

It would also be possible to use a url in the form your-event-title/photos. Then you would have to change the path to %/photos and use a argument like Content:Title instead.


adding extra tab to user's profile using hook I am trying to add a Send email tab to all user's profile using hook_menu(). However, it's not working. My custom module name is page_callback_test and here's the code in it.

function page_callback_test_menu() {
$items['/user/%user/email_user'] = array(
    'title' => t('Send email'),
    'page callback' => '_send_email_touser',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    );

return $items;

}

function _send_email_touser(){
    return t("let's send email to this user");
}

Your code works - just remove the first forward-slash from the URL you are passing to hook_menu().

Correct: $items['user/%user/email_user'] = array(
Not correct: $items['/user/%user/email_user'] = array(

Be sure to clean cache after you update this.


Made a local copy of live-site: all paths generate error 404 Drupal version: 6

I've made a local copy of a site that is live, has loads of content and is configured to run in the Kurdish language.

Steps I did to accomplish this:
- Made a tarball of the Drupal installation and extracted it on my localhost
- Dumped the live-database and imported it locally
- Modified settings.php to reflect local database settings

When browsing to the local installation, the front-page seems to work fine (except for a few pictures not showing up, as well as the facebook like box generating a 404 error). Except: when clicking on any url, of any node-type, a 404 error is generated.

I tried to fix it with this proposed solution: http://www.paulmarc.org/learn/drupal/rebuilding-site-urls, but to no avail. It seems to me I have to rebuild the site, however: even invoking that path does not work and generates a 404 and is thus inaccessible.

Fixed. It appeared that I installed the mod rewrite module, but didn't activate it in my default site profile (as per these instructions: http://www.seangw.com/wordpress/2012/01/how-to-enable-mod_rewrite-in-apache2-ubuntu/). Did that and everything works fine now. Woops, feel kind of stupid now.


Send parameter to another page I want to build a page that will be my player.
That page.tpl.php will include code like the following one:

<object bla bla ... idmedia="**the parameter that i want to get**"></object>.

I want to call this page with various parameters that play other videos.
I can I do it?

you can your page with a GET variable appended in the url, something like

www.mysite.com/node/1?videoId=123

then inside your template you use a GET variable like this

$videoId = $_GET['VideoId'];

then you could do this

<object bla bla ... idmedia=" $videoId "></object>.


Alter validation when using inline entity form Is it possible to alter the validation function when using inline_entity_form ?

Here is an example module that I'm using where I use devel to validate if I can hook into drupals and IEF validate functions (as pointed out by Shawn Conn).

function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state)
{
  $entity_form['#element_validate'] = array('mymodule_inline_entity_form_entity_form_validate');
}

function mymodule_inline_entity_form_entity_form_validate(&$entity_form, &$form_state)
{
  // No effect
  form_set_error('field_price', '!Validate');
  form_set_error('field_bucket_list', '!Validate');
}

I have one content type which has a title and a decimal field called field_price and a second type which has the IEF field (called field_bucket_list).

At last I got it to work. Here is the final code where the error was that I did not fully understand how to use form_set_error to point at the field I wanted to validate.

function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state)
{
  $entity_form['#element_validate'] = array('mymodule_inline_entity_form_entity_form_validate');
}

function mymodule_inline_entity_form_entity_form_validate(&$entity_form, &$form_state)
{
  form_set_error('field_bucket_list][und][form][field_price', '!Validate');
  inline_entity_form_entity_form_validate($entity_form, $form_state);
}

The field I wanted to validate is field_price and is located as values->field_bucket_list->und->form->field_price in $form_state, which I got from using Devel.


Request a page - as admin - via command line to build up cache Folks:

I have a pretty hefty view page which has been overridden with template files to produce a custom gantt chart for a long list of users. For each row of gantt data - the outputted html is cached to speed things up..

I've written a function which I call via drush that deletes the cached key:values from my custom cache table.

drush eval 'custom_tweaks_clear_cache_codes()'

The plan is to 1) flush the cache every morning via cron using this drush command. Then, 2) 'warm the cache' essentially request this page via command line to build the cache table up again.

The issue is, I could leave it and let the first user who views the page, take the hit so the cache gets built - but I can't allow this, the user needs to be an admin..

Essentially: I need a way to hit the page but as admin - which doesn't involve me loading the page every morning manually before the day starts.

Has anyone got any ideas?

Load the page via the cron (maybe 5 mins after deleting the cache) using wget. You'll need to set this up on the server as opposed to through the Drupal UI.

This won't hit the page as admin but I'm not sure what value that adds. You just need the caches to be built so hitting as an anonymous user will do this.

Also checkout hook_drush_command() for creating your own Drush functions (good tutorial here).


Properly building array and using with drupal_json_encode()? I am trying to pass data from my database to a javascript variable, however I'm not sure if I'm correctly using drupal_json_encode(), or correctly building my 2D array.

When I check my console, the javascript variable only displays [], so the data is not being passed.

I know this isn't the very best way of doing this, but I am only trying to make a functioning prototype, and not a finished product

Here is a portion of my php code that is making the sql query, as well as the 2D array, and is located in my page--front.tpl.php:

<?php
$server = 'db.*****';$user = '*****';$database = '*****';$password = '*****';
$db = mysqli_connect($server, $user, $password, $database);

  if (isset($_GET['routeselected']))
  {
  $result = mysqli_query($db, "SELECT * FROM STOP INNER JOIN RouteStop ON Stop.Stop_ID = RouteStop.Stop_ID WHERE RouteStop.Route_ID = " . (int)$_GET['routeselected'] . " AND RouteStop.Company_ID = " . (int)$_GET['companyselected']);
  $items = array();
  while (($row = mysqli_fetch_array($result))){
      $markers[$row['title']] = array($row['Stop_ID']);
      $markers[$row['lat']] = array($row['Latitude']);
      $markers[$row['lng']] = array($row['Longitude']);
      $markers[$row['description']] = array($row['StopName']);
      }
    drupal_json_encode($markers);
    drupal_add_js(array('markers' => drupal_json_encode($markers)), 'setting');
  }
  ?>
];

and here is my google map javascript that is in my js folder and is being implemented to the front page via drupal_add_js:

var map = null;
var infowindow = new google.maps.InfoWindow();
var markers = [Drupal.settings.markers];

window.onload = function () {

var mapOptions = {
    center: new google.maps.LatLng(
        parseFloat(markers[0].lat),
        parseFloat(markers[0].lng)),
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var path = new google.maps.MVCArray();
var service = new google.maps.DirectionsService();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var poly = new google.maps.Polyline({map: map, strokeColor: '#F3443C'});

var lat_lng = new Array();
           for (i = 0; i < markers.length; i++) {
           var data = markers[i]
           var myLatlng = new google.maps.LatLng(data.lat, data.lng);
           lat_lng.push(myLatlng);
           var marker = new google.maps.Marker({
               position: myLatlng,
               map: map,
               title: data.title
           });
           (function (marker, data) {
               google.maps.event.addListener(marker, "click", function (e) {
                   infoWindow.setContent(data.description);
                   infoWindow.open(map, marker);
               });
           })(marker, data);
       }
for (var i = 0; i < markers.length; i++) {
    if ((i + 1) < markers.length) {
        var src = new google.maps.LatLng(parseFloat(markers[i].lat),
                                         parseFloat(markers[i].lng));
        var des = new google.maps.LatLng(parseFloat(markers[i+1].lat),
                                         parseFloat(markers[i+1].lng));
        service.route({
            origin: src,
            destination: des,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        }, function (result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                    path.push(result.routes[0].overview_path[i]);
                }
                poly.setPath(path);
            }
        });
    }
}
}

Does anyone possibly know a solution to my issue? Thank you for all and any help!

drupal_add_js(array('markers' => drupal_json_encode($markers)), 'setting');

Should be

drupal_add_js(array('markers' => $markers), 'setting');

See https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7. You will probably want to remove the drupal_json_encode($markers); as well.

Also noted that you should use db_query instead of mysqli_connect/mysqli_query https://stackoverflow.com/questions/11369447/drupal-7-db-query


How do I set up both a landing page and front page? Here's the behavior I'm trying to achieve.

If a user types in our domain name www.mysite.com, I want them to go to one page, describing our site.  It can be called www.mysite.com/landing.

But if they hit the logo or the home button anywhere in the site, I want them to go a different page, the one defined in Configuration->Site Information.  It is called www.mysite.com/phront.

Ideas?

It’s as simple as sheena_d already commented on your answer. Define /landing as your home page and link your logo and home button to /phront. Done!


Multiple formatters for a field collection - best approach? I'm building a site with a "function" content type, to manage a list of functions and their arguments. Because arguments can be zero or more, and have multiple properties (name, required, usage notes) it seems best to handle them as a field collection, using field collection table as the input widget. Therefore, on the node edit form for the "function" content type, the input widget would look something like this:

On the display side, I need to display the argument data in at least two ways: (1) in a table formatter provided by field collection table and (2) in an arbitrary "syntax" format, where only the arguments are output, but with some kind of visual indication of which arguments are required. So, something like this:

My questions:

What's the best way to add a custom formatter for the field collection (i.e. in code, in a field template of some kind, using the custom formatters module, etc.)?
What's the best way to output two instances of the field collection field, each in a different format?

I do have Display Suite installed on this site, if that helps. Also interested in any general advice if there's a better way to handle this use case.

This sounds like it would be best output as two separate views.  The first view would be set in your first format and the second in the other format.  Probably using a view template of some sort.  The issue is that the field collections attached to the node are actually referenced separately and you only know they belong to the same node because the field collection entity has a reference to the NID.

The view would reference by nid in the contextual filters.

The other option is to programmatically load the fields via the node.tpl.php file (assuming you are loading them on the node page). in which you simply gather the data via the $node object and display it as you need.

https://drupal.org/project/field_collection_views

https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7

http://www.youtube.com/watch?v=_GlfYhsk3X0


Update user fields programatically resets password When trying to update user (custom) fields programatically in drupal 7, I get the weird problem that whenever I do, my password is reset, my user is logged out, and I have to reset password to be able to log-in again.

I have tried a few different things, none seem to work, here's my code.

global $user;
global $language;
$fullUser = user_load($user->uid);

$updateUserParams = array();

$updateUserParams['language'] = $language->language;
$updateUserParams['field_first_name'][LANGUAGE_NONE][0]['value'] = $form_state['values']['firstName'];
$updateUserParams['field_surname'][LANGUAGE_NONE][0]['value'] = $form_state['values']['lastName'];

$year = $form_state['values']['birthdate']['year'];
$month = $form_state['values']['birthdate']['month'];
$day = $form_state['values']['birthdate']['day'];

$birthdate = date( "Y-m-d", strtotime($year.'-'.$month.'-'.$day));

$updateUserParams['field_birthdate'][LANGUAGE_NONE][0]['value'] = $birthdate;
$updateUserParams['gender'][LANGUAGE_NONE][0]['value'] = $form_state['values']['gender'];
$updateUserParams['field_address']['en'][0]['thoroughfare'] = $form_state['values']['street'];
$updateUserParams['field_address']['en'][0]['postal_code'] = $form_state['values']['postalCode'];
$updateUserParams['field_address']['en'][0]['locality'] = $form_state['values']['city'];
$updateUserParams['field_phone'][LANGUAGE_NONE][0]['value'] = $form_state['values']['phone'];

user_save($user, $updateUserParams);

What am I doing wrong?

If you look user_save there special code at the top, that prevent updating password if pass not provided on $updateUserParams. So please check your other modules or Rules, that possibly resetting password each time, then user_save called.


Have followed instructions to disable cache for development but it's still caching I have followed all the instructions here https://www.drupal.org/node/2598914

I'm developing a module with a block, and when I went to the Block Layout page and clicked "Place Block", the list of blocks did not come up due to an error in my code. I edited the code and was sure it was correct, yet it still didn't work. So I tried doing "drush cr" just in case the cache wasn't really disabled ... and that made it work.

So it seems to me that the cache has not been disabled by following those instructions. Is there something missing?

Edit: This has happened again when I have made new changes, even after the plugin has successfully loaded. It happens when when I make any changes to src/Plugin/Derivative/Foo.php (inside my module). Those changes aren't picked up until I manually cache rebuild

You've disabled the render, dynamic_page_cache, and page cache bins; plugin discovery is stored in a different bin (discovery). You probably don't want to disable that bin, as it's likely to slow the site down appreciably (the project will be scanned for plugins on every request).

If you just keep in mind that you need to rebuild caches manually when you add a plugin, implement a hook, or add/change a .yml file in the module's root, you'll be able to work a lot faster.


Module for comment validation I'm learning how to create a new module for the first time, so please bare with me. I'm trying to add a validation on the comment form from scratch; it's just not validating at all, meaning that my form successfully submits when I intentionally don't fill out the subject field.
Here is my code:

/*
 *  Implementation of hook_form_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == "comment_form") {
    $form['#validate'][] =  'my_module_comment_validate';
  }
}

/**
  * Validate routine to prevent keywords from being used within comments.
  */
function my_module_comment_validate($form, &$form_state){

if ($form_state['values']['subject'] == '') {
 form_set_error('', t('Error!'));
 }
}

In your form_set_error() call, you haven't set a specific field name on which to set an error. It's possible that without a form_set_error() call identifying a real form element no error is happening.

form_set_error('subject', t('Error!'));

Also, check to make sure your validation function is being called with a drupal_set_message()


Problem with db_select not returning records sometimes Works:

$rows = db_select('notification_queue', 'nq')
    fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method','latest_time', 'earliest_time'))
    ->groupBy('uid')
    ->groupBy('notification_type')
    ->groupBy('delivery_method')
    ->addExpression('COUNT(*)', 'count')
    ->execute();

Does not work:

$rows = db_select('notification_queue', 'nq');
$rows->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'));
$rows->groupBy('uid');
$rows->groupBy('notification_type');
$rows->groupBy('delivery_method');
$rows->execute();

I'm testing that something is returned with a simple foreach loop:

foreach($rows as $row) {
    msg($row); //msg is a simple wrapper for drupal set message
}

The reason I need to do things the second way is that I have to use addExpression and it won't work if try and use it in the first way.

I've tried this:

$rows = db_select('notification_queue', 'nq');
$rows->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'));
$rows->groupBy('uid');
$rows->groupBy('notification_type');
$rows->groupBy('delivery_method');
$rows->addExpression('COUNT(*)', 'count');
$rows->execute();

And I've checked that the resulting query is correct (it is, I've tried using it with MySQL directly and it does exactly what I want). However, I can't get access to the rows using Drupal.

What am I doing wrong?

Turns out addExpression does not return the object, just the alias of the expression. Solution:

$query = db_select('notification_queue', 'nq')
    ->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'))
    ->groupBy('uid')
    ->groupBy('notification_type')
    ->groupBy('delivery_method');

$query->addExpression('COUNT(*)', 'num');
$rows = $query->execute();


Ajax callback not working with 'language_select' in drupal 8 forms I'm trying to implement an ajax callback whenever language gets changed. Following code I have used:

public function buildForm(array $form, FormStateInterface $form_state) {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$langcode = $from_database->lid;
$form['langcode'] = array(
           '#title' => $this->t('Language'),
           '#type' => 'language_select',
           '#default_value' => !empty($langcode) ? $langcode : $language,
           '#languages' => Language::STATE_ALL,
           '#ajax' => array(
        'callback' => ::ajax_example_autocheckboxes_callback',
        'wrapper' => 'checkboxes-div',

       ) ,
       );

$form['checkboxes_fieldset'] = array(
  '#title' => t("Generated Checkboxes"),
  // The prefix/suffix provide the div that we're replacing, named by
  // #ajax['wrapper'] above.
  '#prefix' => '
',
  '#suffix' => '
',
  '#type' => 'fieldset',
  '#description' => t('This is where we get automatically generated    checkboxes'),
 );
}

function ajax_example_autocheckboxes_callback($form, $form_state) {
  return $form['checkboxes_fieldset'];
}

But ajax callback is not working. Suggest a way to implement ajax on language select.

Try adding a container. It works for me:

public function buildForm(array $form, FormStateInterface $form_state){
    $current_user = \Drupal::currentUser();
    $user_preferred_langcode = $current_user->getPreferredLangcode();

    // The status messages that will contain any form errors.
    $form['status_messages'] = [
     '#type' => 'status_messages',
     '#weight' => -10,
    ];

    $form['title'] = [
      '#type' => 'html_tag',
      '#tag' => 'h2',
      '#value' => t('Change Language'),
    ];

    $form['preferred_langcode'] = [
      '#type' => 'language_select',
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
      '#default_value' => $user_preferred_langcode,
      '#ajax' => [
        'callback' => [$this, 'languageCallback'],
        'event' => 'change',
        'wrapper' => 'language-wrapper',
      ],
    ];

    $form['language_wrapper'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'language-wrapper'],
    ];

    $preferred_langcode = $form_state->getValue('preferred_langcode');

   if(empty($preferred_langcode) || $user_preferred_langcode ==
$preferred_langcode) {
      $form['language_wrapper']['default_language'] = [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this->t('Your Current Language'),
      ];
    }

    $form_state->setCached(FALSE);

    return $form;
  }

  public function languageCallback(array $form, FormStateInterface $form_state) {
    return $form['language_wrapper'];
  }


Useability of the user registration workflow When you want to create an account on a drupal7 page, you have to click very often to create the account finaly.

Go on user/register
Click on one time login link
Open the one time login page and click an login
Change password
Now your done

Are there any approaches to modify the registration process without loosing the email verification? There so many Websites doing it better. Is there a Drupal way?

Use https://www.drupal.org/project/logintoboggan to allow users to login immediately and assign them a "not verified" role. Once they use the verification link they will become authenticated users.

Enjoy.


Is it possible to insert blocks into content using the paragraphs module? I have a node (basic page type) with a lot of text (several paragraphs <p> of text).

Within two <p> tags I have to insert a block (generated with views oder other modules like Nodeblock).

How can I insert the existing block directly between the text of my node? Is it possible to do this with the "Paragraphs" module?

If not, why not?

If not, which other modules allow me inserting blocks directly into the node text?

you can install the Viewfield module, create a view, then create a Paragraph with a field of type Viewfield which allows you to insert the view as content of the field.


User Module modifications I need to add about 64 custom fields to the user object. These fields will be filled when the user is created and updated from a 3rd-party database when the user logs in.

How would I go about making these modifications? Would I subclass the user or just make a new module to do this?

Clive's answer is right for Drupal 6.

For Drupal 7, you'd implement a Field. This field would provide the 64-field form to fill out, the way to display the info, and know how to query the external database. (Obviously there's some room for design improvement here.. I'm chunking all the different pieces into one meta-field, but you could split it out however you want.)

Then you go to admin/config/people/accounts/fields and add your field to the user account profile. When you add it, there will be an initial configuration page for that field instance, and you'd check 'Display on user registration form.'

Easy as pie, right? :-)

There's a generic field implementation example in the Examples project.


Why is webform submit handler not working in form alter? webform submit handler not calling in form alter. I have tried solutions like
   use Drupal\Core\Form\FormStateInterface;

function MODULENAME_form_alter(&$form,$form_state, $form_id) {
  if ($form_id == 'FORMID') {
    $form['actions']['submit']['#submit'][] = 'MODULENAME_form_submit';
  }
}

function MODULENAME_form_submit($form, FormStateInterface $form_state) {
  print_r($form_state);
}

But this one is not working. Any help?

Maybe you can try this :

  function MODULENAME_form_alter(&$form,$form_state, $form_id) {
    if ($form_id == 'FORMID') {
      foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = 'MODULENAME_form_submit';
        }
      }
    }
  }

  function MODULENAME_form_submit($form, FormStateInterface $form_state) {
    kint($form_state);
  }


Create tab for related content types How do I link 2 content types (business, photo) together and able to display as a tab? is there a module for this?

Most simple way (i.e., without coding) would be to use Panels module, and create a node type view page override for the first content type.  Then use a nodereference field to make the first content type reference a node of the second type.  Lastly, use Panels' context system to generate a new context of that referenced node, and display it in whatever means you want on the overridden node view page.


How to find machine module name for `drush dl`? Long time Drupal front-end dev but doing more site building lately and have been using Drush much more. One of the biggest limitations I've found with downloading (dl) command is that you have to know the machine name of the module, which is not a big issue for say Views or Context. But who knows the machine name of stuff like node reference or simple google maps?

I guess and get it right sometimes, or I have to hit d.o to figure it out. Is there a list function I havent uncovered? The other answers to this on Stack Overflow and Drupal Answers are pretty bad.

drush dl module-name-here

According to my experience, I know machine names of some commonly used modules,
but basically when it is for new module or when I have doubt in machine name,
I google it the module name, it should provide you with link for drupal project page,

the url will be in the format   https://drupal.org/project/[project-machine-name]

drush dl [project-machine-name]

for multiple module you can do like this

drush dl [project-machine-name1] [project-machine-name2][project-machine-name2] ..


Trouble with Form API and #states I have a form built and need a fieldset to collapse/expand based on the value of another checkbox field.

The checkbox code is:

$form[$serving_key] = array(
        '#type' => 'checkbox',
        '#title' => t($serve_size)
);

The fieldset is:

$form[$fieldset_key] = array(
        '#type' => 'fieldset',
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#states' => array(
            'expanded' => array(
                ':input[name="' . $serving_key . '"]' => array('checked' => TRUE)
            )
        )
);

These are in a foreach loop, and $serving_key at any point is 'serving_large', 'serving_small', etc.  The corresponding $fieldset_key is 'fieldset_large', 'fieldset_small', etc.

This looks like it should work in the form_example_states_form example code.  What am I missing?

You forgot about unique keys in your form elements. Here is a working example:

function test_form($form, &$form_state) {

  // your size options
  $options = array('small', 'medium', 'big');

  $form['checkboxes'] = array(
    '#type' => 'fieldset',
  );

  foreach ($options as $size) {

    $form['checkboxes'][$size . '_checkbox'] = array(
      '#type' => 'checkbox',
      '#title' => t($size . ' size'),
    );

    $form[$size . '_field'] = array(
      '#type' => 'fieldset',
      '#title' => t($size . ' size'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#states' => array(
        'expanded' => array(
          ':input[name="' . $size. '_checkbox"]' => array('checked' => TRUE),
        ),
      ),
    );

    $form[$size . '_field']['some_info'] = array(
      '#type' => 'textarea',
      '#title' => t($size . ' size textarea'),
    );
  }
  return $form;
}

Result:


increase users to display in who is new block I need to display more than 10 users in who is new block, i see the dropdown list has at max 10.

So, how can I increase it?

You have two options I see:

Recreate this block with Views - changes like that are the very sense of their existence.
Create custom module with hook_form_alter() and add numbers up to some arbitrary max you prefer. Note that it might be a performance hit that way, if block in question loads full user objects. To much and you'll eat your memory.


How to send an automatic reply using webform? I'd like to send an automatic reply to every user who fills the form
"Thank you for registration"+ link to a restricted webpage on my website -available only to registered users who filled that form.

Is it doable?

Yes you can do that in the following way:

Add an email field in webform. Set that field to get the users email by clicking "User email as default" option in the field's edit page.
Configure your forms to send emails by going at node/%nid/webform/emails and choosing "Component value", then choose your component.
After you add this "rule" you can then configure the actual email send to the user.

PS if you are not sure what the capabilities of a module are you can try it out at https://simplytest.me/.


What is the difference between path and theme path in theme registry? I'm trying to alter the theme registry:

function comment_simplify_theme_registry_alter(&$theme_registry) {
  $module_path = drupal_get_path('module', 'comment_simplify') . '/tpl';
  $theme_registry['comment']['template'] = $module_path . '/comment';
  $theme_registry['comment']['theme path'] = $module_path;
  $theme_registry['comment_wrapper']['template'] = $module_path . '/comment-wrapper';
  $theme_registry['comment_wrapper']['theme path'] = $module_path;
}

Now this is what I have in theme registry:

comment_wrapper
  template: sites/all/modules/comment_simplify/tpl/comment-...
  path: themes/bartik/templates
  type: theme_engine
  theme path: sites/all/modules/comment_simplify/tpl
  render element: content

I want to know what the difference between path and theme path is.

From the hook_theme() docs:

path: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.
theme path: (automatically derived) The directory path of the theme or module, so that it doesn't need to be looked up.


How can I attach multiple pdfs to drupal_mail() function? Was doing something like this

        global $base_url;
        $uri = $base_url . '/sites/default/files/test.pdf';
        if(!empty($mail_content)) {
            /*send mail */
            $to =$mail_content['to'];       //gets the current user's mail address
            $from = variable_get('site_mail', '');    //admin's mail address
            $body = $mail_content['body'];

            $filemime = $mail_content['mime'];
            $filename = $mail_content['filename'];
            //$filepath =
            //$filealtname  = drupal_basename($filearray['uri'], $suffix = NULL);

                $attachment = array(
                'filecontent' => 'http://localhost/cando/sites/default/files/test.pdf',
                'filename' => $filename,
                'filemime' => $filemime,
            );

            $mail_content['params']['attachments'][] = $attachment;
            $params = array(
                'subject' => $mail_content['subject'],
                'body' => $body,
                'attachment'=>$attachment,
            );

             // print_r($attachment);print_r($params);exit;
        //  print_r(file_get_contents(DRUPAL_ROOT));die;
            $message = drupal_mail('cando_custom', $mail_content['mkey'], $to, language_default(),$params,$from);

            return 'Mail Sent ... ';

        }
    }

You forgot to add headers to the params array.

I did something like :

$attachment = array(
      'filecontent' => $filepathname,
      'filename' => $namefile,
      'filemime' => 'application/pdf'
      );
//where $filepathname should contain the path to the file and $filename should contain the name of the file.

$params = array(
  'headers' => array('Content-Type' => 'text/html'),
  'key' => 'test',
  'to' => 'test@example.com',
  'from' => 'test@example.com',
  'subject' => 'Test email',
  'body' => 'test',
  'attachment' => $attachment
);

drupal_mail($module, $key, $to, $language, $params, $from, $send);

which worked for me.

In your case:

Check the value of $filemime variable.
Add headers to the code.


How to add a new permission in "node_list_permissions"? Is there a way to  add a new item in node_list_permissions function in node module from a custom module. Let me explain my problem.

I have a module say "audit" which will track node history, I have a new tab say history and user whoever have access to see the node history should be allowed to see the history of that node. Is that possible?

A more experienced user should check the below.. I've only added permissions to contrib modules.

From https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_permission/7
This will add the permission to the people page.

function YOURMODULENAME_permission() {
  return array(
    'see history' => array(
      'title' => t('See History'),
      'description' => t('Blah Blah.'),
    ),
  );
}

From
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7
This should check for the permission when viewing that url. I might have gotten the % wrong.

function YOURMODULENAME_menu() {
  $items = array();

  $items['user/%/history'] = array(
    blah
    'access arguments' => array('see history'),
    blah
  );


Register form breaks after changing submit button value with jQuery I need to change the submit button value (text) based on the selection made in a certain register form field. I accomplished this by using jQuery:

(function ($) {
$(function() {
$("#edit-field-registrierung-als-und").change(function() {
if ( this.value == "2") {
$("#registersubmit").val("Kostenpflichtig registrieren");
}
else {
$("#registersubmit").val("Jetzt registrieren");
}
});
});
}(jQuery));

The submit button value changes as expected. But the form is not sent anymore after submitting. The page refreshes and the entered data is still in there. I don't get any error in the console or error log.
I think drupal expects the very term and is 'confused' to get a different one. Does somebody know how to resolve this?

This is my register page: https://my-business-location.com/registrierung
The first field on the page influences the submit button value (option 2).

Based on what Clive said and your response regarding the Ajax stuff, I edited your code. I am assuming you only want to change the text of the button for display purposes.

(function ($) {
  $(function() {

    // Create a copy of the button
    $('#registersubmit').after('<input id="new-submit" class="form-submit" value="Jetzt registrieren">');
    // Hide original
    $('#registersubmit').hide();
    // When copy  is clicked, "click" the original
    $('#new-submit').click(function(){
      $('#registersubmit').click();
    });
    // Your code with changed IDs
    $("#edit-field-registrierung-als-und").change(function() {
      if ( this.value == "2") {
        $("#new-submit").val("Kostenpflichtig registrieren");
      }
      else {
        $("#new-submit").val("Jetzt registrieren");
      }
    });
  });
}(jQuery));

Can't test it as you appear to have the code active right now, but it should work fine in this scenario.


"The value in Date is not a valid date" error I am editing an existing node of content type event, and am trying to update the Date using the date pop up. However, no matter what date I select I get the The value in

  "Date is not a valid date"

error.

The same issue appears when I try and add a new node with the same content type...

Any suggestions?

The latest dev version of clientside validation contains a fix to support more formats, so you can give it a try


Get pre-processed data from nested Paragraphs I am new to Drupal and building a theme with Drupal 8 + PatternLab. Instead of printing the actual paragraphs, I just extract the data from the fields and pass it to the front-end twig modules. For example, I have a "Hero" paragraph with a nested "Video" paragraph. The "Hero" paragraph has a "Title" field and the "Video" paragraph has a "Video URL" field. The "Video URL" field is of type "Media", which would be a reference to an entity. Here is the template for the paragraph:

// paragraph--hero.html.twig
{%
  include '@organisms/o-hero.twig'
  with {
    title: data.title,
    video_url: ???
  }
%}

Here is the THEME.theme:

function THEME_preprocess_paragraph(&$variables) {
  foreach ($variables['content'] as $field => $fieldData) {
    if (isset($fieldData['#field_type'])) {
      $newField = preg_replace('/^field_/', '', $field);

      // text
      if (in_array($fieldData['#field_type'], ['string', 'string_long', 'text', 'text_long'])) {
        if ($fieldData['#is_multiple']) {
          $variables['data'][$newField] = array_map(function ($item) {
            return $item['value'];
          }, $fieldData['#items']->getValue());
        } else {
          $variables['data'][$newField] = $fieldData['#items']->getValue()[0]['value'];
        }
      }

      // link
      if (in_array($fieldData['#field_type'], ['link'])) {
        $link = $fieldData[0];
        $title = $link['#title'];
        $url = $link['#url']->toString();
        $target = $link['#options']['attributes']['target'] ?? null;
        // echo '<pre>'; var_dump($link); exit;
        if (!$fieldData['#is_multiple']) {
          $variables['data'][$newField] = [
            'title' => $title ? $title : null,
            'href' => $url ? $url : null,
            'target' => $target ? $target : null
          ];
        }
      }

      // image
      if (in_array($fieldData['#field_type'], ['entity_reference'])) {
        if (!$fieldData['#is_multiple']) {
          if (isset($fieldData[0]['#media']->field_media_image)) {
            $image = $fieldData[0]['#media']->field_media_image;

            $imageUri = $image->entity->uri->value;
            $imageUrl = file_create_url($imageUri);

            $variables['data'][$newField] = [
              'alt' => $image->alt,
              'sizes' => [
                'default' => $imageUrl
              ]
            ];
          }
        }
      }
    }
  }
}

This way I get the data variable with only the data I need in the front-end. But the problem is that when using a nested Paragraph, it won't go through the pre-process functions since it's not actually being rendered, only its data are being extracted. Now, I can access the "Video URL" media inside the "Video" paragraph, but it only gives back the Entity ID value, and it doesn't get populated with the actual Entity values so I can extract the video thumbnail / title / url.

I am not sure if I could explain this correctly, but I want to be able to access content.field_video_paragraph fields same way I access the main paragraph field content.field_title.

I'd advice not to loop through the render array content, but go directly for the entity object, in your case $paragraphObject = $variables['paragraph']

Once you have the object, you can always query any data you want, to drill through a referenced/nested entity, use ->entity:
$paragaph->hostfield->first()->entity->field_whatever->value

For paragraphs, you can also query upwards:
$parentEntity = $paragraph->getParentEntity()

The example above works similar for almost all entity templates like node.html.twig or paragraph.html.twig and actually wouldn't need any preprocessing at all, since the entity object is passed to Twig:

Most of the time you can use
entity.fieldname.index.value

E.g. for a simple plain text field:
{{ paragraph.field_whatever.0.value }}

For nested paragraphs or referenced entities you can use:
{{ paragraph.hostfield.0.target_id }} /* only numeric ID of ref.ent. */
{% paragraph.hostfield.0.entity %} /* referenced entity object, can be queried again */
{{ paragraph.hostfield.0.entity.field_whatever.0.value }} /* field value of a nested paragraph */

For your hero paragraph you could do something like

{% include 'hero.twig' with { title: paragraph.field_title.0.value } %}


Drupal 7 db_insert() execute() error when table contains unique keys I have a database (mysql) table that contains a unique key in barcode column.

What I intend is this:

I have a form that has a barcode field.
When user submits the form and the barcode entered already exists in the database table, I should just give an error message.
Currently, it gives me PDOException: ... Duplicate entry and the page contents does not load.

This is how I did the insert:

$insert = db_insert('mymodule_mytable')->fields($fieldarray)->execute();

At that line, Drupal 7 returns PDO error so I cannot execute the lines after it. Thus, I cannot also check the return value in $insert.

Is there workaround to avoid the PDO error? I need to do something like:

if($insert === FALSE) {
  drupal_set_message(t('Error'), 'error');
}

PHP has exception handling in the form of try...catch blocks:

try {
  $insert = db_insert('mymodule_mytable')->fields($fieldarray)->execute();
}
catch (PDOException $e) {
  drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}

So rather than ignore the error completely, you can actually respond to different types of exception and react accordingly.


Can we output individual form items within a Layout? We are using Layouts (via mytheme.layouts.yml) to create regions for our Node Edit forms.  This looks something like...

edit_nodelayout:
  label: 'Edit Node Layout'
  category: edit
  path: templates/panels
  template: edit-nodelayout
  default_region: toplayout
  regions:
    toplayout:
      label: 'Top'
    details:
      label: 'Details'
    other:
      label: 'Other'

We have placed each field for the content-type into the appropriate region via the admin UI.  At least one of our fields is a reference field to a Paragraph entity-type.

In our template, which is defined in the yml as /templates/panels/edit-nodelayout.html.yml, we are currently outputting all content as full regions.

{# some html here #}
{{ content.toplayout }}

{# some html here #}
{{ content.details }}

{# some html here #}
{{ content.other }}

How would we access individual items within a region?  For example, if within the content.details region, we have placed a field called "Foo", how do we output that individually?  We have tried this...

Please enter everything you know about Foo

{{ content.details.foo }}

This becomes interesting when the field called "Foo" is a reference to a Paragraph entity-type.  How would we then output individual fields within "Foo" entity?

Output the "bar" field within the "foo" Paragraph type

{{ content.details.foo.bar }}

Any help, pointers to documentation appreciated.

That is not how you're supposed to use layout templates as those should be for for placing content, just like normal Drupal regions, and then modify the output using field and node templates. The general idea being to be able to reuse the templates in other places and as such reducing the number of templates needed.

Of course you can output content directly in the layout template. I would recommend you install the Twig Tweak module. You can then use {{ dd() }} to see what is available to you. As an example you can display a field value like this:

{{ node.field_myfield.value }}

It depends on what you want to display, but that's the general idea, very similar to the node template.


How can I evaluate the security of a contrib module? Are there security standards for each stage of a module on Drupal.org?

  Create sandbox project > full project with dev version only > official release

What is the process for the security of contrib modules? Do audits happen?

Historically, I have functionality rather than security on my mind when selecting a contrib module. Partly because I don't know how to easily evaluate security (that is, without studying the entire code). How can I evaluate how secure a contrib module is?

Currently there is no correlation between project status and presumed security of code. From The Security Team Handbook page

  in general the team does not review core nor contributed code

The Drupal security team works to resolve vulnerabilities that others find. Any review that happens to sandbox modules would be part of normal project review (no guarantees). When code is explicitly reviewed for security, it is most likely because someone was hired to review it.

In general, you can use the Writing Secure Code guide as a starting point. Also checkout presentations from Cons and Camps.


Node and revision id I am working with a company setting up a drupal website. I am responsible for entering our product information into the drupal tables. I am having difficulty getting a straight answer/an answer that makes sense as to what the values for nid and vid should be in the drupal_node and drupal_node_revision tables should be. I am being told by our vendor that the values for nid and vid need to be the same (ie 27 and 27) but that doesn't make sense to me. Shouldn't the vid just start at 0 or 1 and increment up from there. Isn't it simply what the node table uses to read the current version from the revision table.

I know very little about drupal so I may be wrong but their answers aren't making sense to me. And as the nid is automatically incremented in the table, I have no way of knowing what the nid value is until after the insert. So I would have to read the value and run an update statement, which seems really sloppy.

If you begin to add nodes and never edit them, like you would do when migrating data to a new Drupal installation, then the nid and vid would increment at the same pace, and would happen to be the same. After first edit though, assuming you have revisioning on, the new vid would be what ever is the next available number for all revisions.


how do I specify a render cache context as universal? I want to a render array in my page to be cached, and I know that it's the same for every user in every circumstance.
How do I specify that its cache context is universal, rather than anything else?

There is no universal cache context. This is the default for a render array if you don't specify any cache context.
Render contexts are merged upstream. Additionally you can configure required cache contexts which are added to all render arrays before they are rendered.
Out of the box Drupal requires these three contexts:
core.services.yml
parameters:
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

You can override the parameter in /sites/default/services.yml (use default.services.yml as template).


Replace Ubercart radio button with image? I have a product with three radio button options, and I want to replace those radio buttons with clickable images. This is how those radio buttons appear in the code:

     <input type="radio" class="form-radio" value="136" name="attributes[51]" id="edit-attributes-51-136">Red, +$3.00

     <input type="radio" class="form-radio" value="135" name="attributes[51]" id="edit-attributes-51-135">Green, +$5.00

     <input type="radio" class="form-radio" value="137" name="attributes[51]" id="edit-attributes-51-137">Blue, +$10.00

Instead of the radio button and label, I'd like to simply display a image color swatch. How can I accomplish this? I assume I'd need to somehow reference the "for" value in the "label", but I'm not sure how to do so. I'd prefer not to go the "nth child" route, but I can if I need to.

Thanks!

You can use CSS like so to target the labels:

label[for*="edit-attributes-51-"]{
   /* ADD YOUR IMAGE HERE */
}

or target the individual ones (135,136,xxx):

label[for="edit-attributes-51-135"]{
   /* ADD YOUR IMAGE HERE */
}


How to retrieve value of start date with format end date? I D8 installed the module Optional End Date in order to add an optional end date within a date field.

When I had a single date field value I could get the value by using:

 $datum_deelname = $node->get('field_normaldate')->value;

If I change this in the new field name:

 $datum_deelname = $node->get('field_optional_enddate')->value;

I get back NULL.

How should I get this value?

Try using:

 $datum_deelname = $node->get('field_optional_enddate')->end_value;

This will give the optional end date.

If you want to get the normal date as you mentioned you can use as:

 $datum_deelname = $node->get('field_optional_enddate')->value;


Is it possible to have 2 sources for migration? I have a tid (taxonomy ID) and a csv file (which is  a  list of terms to remove during migration with columns : tid, name, delete ).  The tid and CSV file are my sources for the migration.
How can I access (and process) values from both sources in my migration?
The tid is giving me the terms used as tags and the CSV file  is to verify if the terms are listed on the CSV as term to be ignored (not added) during migration on the newly created node.

Something like :

process:
#create temporary field to call plugin that gets the taxonomy
  _prepare_TaxonomyIssues:
    plugin: sub_process
    source: field_issues_ref
    process:
      target_id:
        -
         plugin: mm_taxonomy_tag_issues_plugin
         source: #tid
           - tid
           - plugin: csv
           path: public://allTagsDec6CleanedUpdated.csv
           header_row_count: 1
           keys:
             - tid
             - name
             - delete
           column_names:
             -
               tid: tid
             -
               name: name
             -
               delete: delete

I am getting an error:

TypeError: Argument 2 passed to Drupal\Component\Utility\NestedArray::getValue() must be of the type array, null given, called in /var/www/mm/docroot/core/modules/migrate/src/Row.php on line 158 in /var/www/mm/docroot/core/lib/Drupal/Component/Utility/NestedArray.php on line 69 #0 /var/www/mm/docroot/core/modules/migrate/src/Row.php(158): Drupal\Component\Utility\NestedArray::getValue(Array, NULL, NULL)

Is it possible to have 2 different sources?
Is there another way to do it?

You can't use two sources in the same migration. But if you can split your import into two separate migrations (e.g. taxonomies first, then nodes), you can use either migrate_lookup (if your 2nd source provides the same primary key as a previous master) or entity_lookup (if your 2nd source needs to look up the referenced entity by something else than the primary migration key).

Entity lookup is part of Migrate Plus.


How can I print a views exposed form into a custom block? I have a page view with exposed filters and would like to print said filters into a custom block in order to add extra html markup above the actual form.  This block will be used on other pages using Context.

I know I can create a block by setting 'exposed filters in block' to yes, however that's not the solution I am looking for.

Hours and hours of searching and nothing was working.  Several minutes after posting this question, I figured it out.  The following code can be used in template files or blocks.

<?php
  $block = module_invoke('views', 'block_view', '-exp-VIEW_NAME-DISPLAY_NAME');
  print render($block['content']);
?>


Show a summary calculated from webform submitted values on the submission preview page only (not on form) and re-use in e-mail handler We need to display a computed summary of submitted information on both the submission preview page and in e-mails that are sent out.
I'd expect this is a common usecase and wanted to check if i'm missing something obvious before cobbling something together (and documenting that and leading others astray!)— like figuring out if computed twig elements can be excluded from the original form, and if the same computed twig elements can be pulled into the email handler easily.
Thanks for any assistance!
(Edited body and title: clarified that this need is for the submission preview page, not the Webform 'confirmation' page)

It's not the way i'd prefer to do it, but as far as putting customization on the preview page, there is at least an alternate template available for that:
 FILE NAME SUGGESTIONS:
   * webform-submission-data--preview.html.twig
   * webform-submission-data--webform-10152--preview.html.twig
   * webform-submission-data--webform-10152.html.twig
   x webform-submission-data.html.twig

Rather than use the overall template above, we decided to do most of the work in a preprocess function for a key element on the webform.  This only affects the preview page, as it's about the HTML display not the form element.
function example_preprocess_webform_element_base_html__example_element__specific_instance(&$vars) {
  $rows = example_summary($vars['webform_submission']);
  $vars['table_summary'] = [
   '#type' => 'table',
   '#rows' => $rows,
  ];
}

We can take the {{ table_summary }} variable we added there and include it in the custom template for that element, webform-element-base-html--example-element--specific-instance.html.twig.


Set default "Quantity" dropdown select in product. Commerce Kickstart Using the Commerce Kickstart distribution I have a shop site listing products.
The product page shows a Quantity widget to allow the buyer to choose the product quantity to be added to the cart. (look my capture)

I need to change this widget to the standar select list html element. (look the capture)

Update: I found the library which generate this "spinner", is located at: profiles/commerce_kickstart/libraries/jquery_ui_spinner I don't see any module related to this. Maybe in theme?

I know its already a year ago, but if someone bump in this question here's one of the solution, I don't know if there's a module that already existing changing the widget type of quantity in add to cart form but you can achieve this using
hook_form_commerce_cart_add_to_cart_form_alter like this

Example:

function example_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  // Change widget type of quantity to select list
  $form['quantity'] = array(
    '#title' => t('Quantity'),
    '#type' => 'select',
    '#datatype' => 'integer', // <-- I added this one to fix Notice: Undefined index: #datatype in commerce_cart_add_to_cart_form_validate() when you click add to cart button
    '#options' => array(
      1 => '1',
      2 => '2',
      3 => '3',
      4 => '4',
      5 => '5'
    )
  );
}


How to use RefreshView event properly? I'm editing views rows via ajax request. After request I expected refresh of this view.

I've added custom ajax command:

  Drupal.ajax.prototype.commands.refresh_view = function(ajax, response, status) {
        var selector = Drupal.settings.my_module.refresh_selector;
        $(selector).triggerHandler('RefreshView');
    };

but nothing happends. I'm debugging this and have sure that selector is ok.
Maybe this issue is because that Drupal.views.instances is empty?

What am I missing?

Solution is dead simple. 'Use Ajax' option in View settings must be enabled.


What operator is equivalent to "Is not greater than or equal to"? I have a view showing a list of events. The events are sorted by a date field, which a user can use to input the event starting date/time. However, I want the events removed from the list once the current time is 1 hour past the start date/time of the event. When I add the event date to the view filters, I get the following operators.

However, none of these operators give me the desired result. What I really want is a "Is not greater than or equal to" operator. All of this said, is there a workaround that I could easily implement to get my desired result?

You must use "Is less than" with an offset - just like the screenshot.


How to get a count of number of nodes created per month in views I have created a view using aggregation which counts the number of nodes created of a certain content type.  I want to be able to group these by month i.e. Jan - 10, Feb - 15, Mar, 20 and so on.  At present it is just a count of all nodes created.

How do I do this with views?  I've looked around and cant seem to find any information how to do this.  Any help would be appreciated. thanks

I just figured it out:

Create a view for all nodes (filtered by type or status if
necessary).
I use a table layout, enabled aggreation, added field
"nid" with "Count distinct".
I then add a sort by "post date" with    "monthly" granularity.
Then I added a "post date" field with custom    format "M-Y". I
select "min" instead of "group results together. That's important, otherwise it will not group the results by month


Feed import of 20,000 nodes. How to batch up 1000 at a time? I setup my Drupal 7 feed importer to import from a csv file with 20,000 nodes. I'm able to get it working with 20 nodes just to test to make sure everything is working. But is there a setting to be able to process X amount of nodes at once? My csv file is 12MB and I'd like to just do 300 at a time, but I don't see an option for this anywhere.

How would I make it process a set amount?

Which version of Drupal are you using? I haven't checked on Feeds for Drupal 8, but Feeds for Drupal 7 (unless it's changed in the last few years) has a hard-coded item limit of 50. If you're importing from a CSV, your node architecture is probably pretty simple. You could try the Feed Import module instead of Feeds, in my experience it's better suited for very large imports.


Why do I get "Access Denied" on every page? I've been trying out Drupal 8 on localhost which has been great, and I've now transferred it to a server, but every page gives me Access Denied. I can't even access the front page, or the user login page.

I have tried truncating the session and cache tables, and deleting cookies, but don't know what else to try. I've also installed drush, cleared the cache, and tried user-login drush command - still no access.

What things should I check? How do I fix this?

Don't edit core code as suggested by Flounders answer. If you're not using HTTP auth then simply disable the Basic Auth module via the UI or Drush:

drush pmu basic_auth -y

Drupal has different authentication providers. The defaults are: basic_auth and cookie, basic_auth has a higher priority but is not enabled by default.


Create a separate view for each primary menu based on URL aliases in drupal 7 I have created a taxonomy menu in drupal 7. Let say the main menu has technology and market data.

Let say Technology has sub menu as security and security has test1 and hello as sub menus and so on.

-Technology       URl: http://localhost/drupal/taxonomy/term/1
     -- Security    URL: http://localhost/drupal/taxonomy/term/2
         --Test     URL: http://localhost/drupal/taxonomy/term/3
         --Hello    URL: http://localhost/drupal/taxonomy/term/4

Market data also has the same hierarchy.
These are the values I have set while creating the view

    Format:

      Unformatted list | Settings

      Show:Content | Teaser

    FILTER CRITERIA
      Content: Published (Yes)

      Content: Type (= Article)

      Content: Has taxonomy terms (with depth) (or Technology, ...) | Settings

    PAGE SETTINGS

      Path:/taxonomy/term/%

      Menu:No menu

      Access:Permission | View published content

    CONTEXTUAL FILTERS
      Content: Has taxonomy term ID (with depth)

After creating this view I am able to see the view in all pages (Technology,Security,test1,Hello) I am able to display article as mention in point 1.

Now I replaced the url with automaic url aliases and the url it generate the following URL.

        -Technology       URl: http://localhost/drupal/technology
             -- Security    URL: http://localhost/drupal/technology/security
                  --Test     URL: http://localhost/drupal/security/test
                  --Hello    URL: http://localhost/drupal/security/Hello

Now I replaced the view with following settings

     Format:

   Unformatted list | Settings

   Show:Content | Teaser

FILTER CRITERIA
   Content: Published (Yes)

   Content: Type (= Article)

   Content: Has taxonomy terms (with depth) (or Technology, ...) | Settings

 PAGE SETTINGS

   Path:/technology/%

   Menu:No menu

   Access:Permission | View published content

 CONTEXTUAL FILTERS
   Content: Has taxonomy term ID (with depth)

Within  Has taxonomy term ID (with depth) has the following settings:

     WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED
       Override title:    %1
     Specify validation criteria

      Validator

         Taxonomy Term

      Vocabularies

         Home Page Main Menu

      Filter value type

         Term name converted into ID

   I have selected the Transform dashes in URL to spaces in term name filter values also.

But the problem is I am not able to overwrite the taxonomy pages.

Can anyone help me what I have missed while creating the view.

The reason for this problem has to do with how path aliases are handled. When the url is set to a page alias, Drupal translates the url into its actual url taxonomy/term/tid before it seeks the content that is to be displayed, such as your view definition whose path is still an alias.  Since the view path doesn't match the URL, it is not selected to generate content.  If you want a descriptive URL to work with the view path, you cannot use the path aliases.

I have a similar problem where I have converted hundreds of hierarchical taxonomy terms into a menu system with aliases using taxonomy menu. The aliases show up fine when I select a menu item, and set the View definition to Taxonomy/term/% but the views, of course, display the base URL instead of the alias.  I have not explored a work-around yet.  If you find anything, please post it here on your question.


How to add a new CSS class to a Link Badge if the value is 0? I'm using the small module Link Badges to display a badge with the amount of flagged nodes next to a link to the View in question. It works great and I've styled the badge to my needs. This is the current HTML code:

  My View

    0

Now, I'd like to display the badge a little bit differently (other colors etc.) when the value is 0. I thought about doing this by adding a new CSS class link-badge-zero to the value.

  My View

    0

How can I achieve this?

Thanks to @Ramis Wachtler at Stack Overflow, I got the following JQuery code:

if($(".link-badge").text() == "0"){
    $(".link-badge").addClass("link-badge-zero");
}

Possible easier solutions are always welcome.


Dropdown whose options are dependent on a choice made in a previous dropdown I have two taxonomies (class type and level). I load one in drop-down (class type) and another depended on result of choice (level).

I handle lot of cases (when choice class type load level ) && (if level have data and class type load it when first load) but when I choice empty class type load default data of level :(

function ria_form_alter(&$form, &$form_state, $form_id) {
        $classTypeSelected = false;
        // load class type fron taxonamy
        $classTypes = Utilities::LoadTaxonamy ( 'class_type' );
        $form ['field_level'] ['und'] ['#prefix'] = '
';
        $form ['field_level'] ['und'] ['#suffix'] = '
';
//dpm($form_state ['values'] ['field_class_type'] ['und'] [0] ['tid']);
        if ( isset($form_state ['values'] ['field_class_type'] ['und'] [0] ['tid'] )) {
            $classTypeSelected = $form_state ['values'] ['field_class_type'] ['und'] [0] ['tid'];
        }  else {
            $classTypeSelected = false;
        }

        $form ['field_level'] ['und'] ['#options'] = load_level ( $classTypeSelected );
        $form ['field_level'] ['und'] ['#default_value'] = isset ( $form_state ['field_level'] ['und'] ['#default_value'] [0] ) ? $form_state ['field_level'] ['und'] ['#default_value'] [0] : '';
        $form ['field_class_type'] ['und'] ['#ajax'] = array (
                'callback' => 'ajax_example_dependent_dropdown_callback',
                'wrapper' => 'dropdown-second-replace'
        );

    }

function ajax_example_dependent_dropdown_callback($form, $form_state) {
    return $form ['field_level'] ['und'];
}

function load_level($class_type) {
    $levels = array ();
    if ($class_type && $class_type != '_none') {
        $levels = Utilities::DataFromTaxonamy ( $class_type );
    }
    return $levels;
}

Maybe you should consider using thee Reference field option limit module to implement what you're trying to do. Here is a quote from its project page:

... allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.

Here is an example of how to use this module (also from its project page):

Suppose you want to label articles (or products, or businesses, etc) by both city and country so both can be used for filtering and searching. You could use a hierarchical taxonomy with city terms as children of country terms, but that doesn't make sense when you come to set up Views filters.
With this module, create two separate taxonomies for country and city (or content types, or whatever entity you want to use). Then add a reference field so that each city points to its country: eg, the term 'Paris' has a reference to 'France'.
Then when editing an article, selecting 'France' in the country field will cause the city field to update to show only cities in France.


How to create "Custom Forms" that trigger own business-logic / do not create any Content I'm new to Drupal, so sorry for this maybe simple question.

I'd like to create some kind of content-type, which a user can "create" and fill the forms, but instead of just saving the content to the database, i want Drupal to pass the values to a 3rd party software (which can be accessed by socket-communication), wich renders PDF's from the text the user entered.

The PDF should be displayed to the user after Form submission.

I know, i can use Drupal to render PDFs, but i want to connect to our legacy 3rd Party software.

So the question is: How and where can i hook-in to write my custom 3rd-Party socket-communication-phpcode and display the result to the user (or save it to drupal db, or, or, )?!

Thanks in advance!

Create your form by using the drupa FAPI.
Set-up a path to your form using hook_menu.
Call your custom communicatin code from your FAPI submit handler.


How to launch a Rule when X nodes were created in X days time? I'm currently awarding medals to the users on my website by using the Goals and Rules modules: a medal awarding Rule fires when a Goal is completed. However, I'd like to get rid of the Goals module, because it is no longer maintained at the time of writing and it doesn't fully provide the functionalities that I need.

The Goals module has a nice feature, though: it is possible to record tasks that were completed within a certain period. I would like to keep this functionality, because some of my medals are granted to users who created X nodes in X days time.

Therefore, I had the idea to add a condition to my medal awarding Rules that checks whether the user created, say, 5 nodes in 10 days time. Is it possible to do this?

I don't think rules by itself has the capability to do that - unless you get very deeply embedded into components, and by then it's almost the same as programming.

You probably need to write a custom module with a cron hook that checks how many nodes were created in the last 10 days. Do you want to know how many nodes were created at all, or just by a particular user? Either way that seems the best way to do it.


I need get the MID for specific Entity Drupal 8 I am using the message module, so I have an entity of type 'message', as for the children I can get the machine name or the Uuid.

The problem I have is that by means of a 'hook_update_n' I need to update a field. The code I am using is:

function hook_update_8001() {

  //Change content in text field for 'caregiver_referral_incomplete'.
  $field_value = array(array('value' => 'Hello My formatted text', 'format' => 'basic_html'));

  entity_load('message', 2166)->getTemplate()->set('text', $field_value)->save();
}

With this structure, I need the Mid, but I only have the machine name or the Uuid, some way to find it with that data?

If you want to load by uuid, you can use this:

\Drupal::service('entity.repository')->loadEntityByUuid($entity_type_id, $uuid);


Taxonomy: Show select options as a dropdown, not multiple I am trying to display a dropdown where users can divide their article in a certain category. I have created a vocabulary called "category" and added s few fields to them.

I have added this to the content structure where the articles are defined. This works perfectly, however, the categories are not displayed as I desire:

When I inspect this element, there is a property used:

<select multiple="multiple">
    <option>...</option>
</select>

I don't want these options to be displayed together. I need a dropdown to let users select one of the categories.

I tried debugging and look for which html.twig file is being called, and tried to edit the select.html.twig but this did not solve the problem.

See select.html.twig

  How can I get these options to show as a dropdown?

To get a taxonomy entity reference to show as a dropdown, there are two things you need to do.

Go to the "manage form display" (admin/structure/types/manage/MY_CONTENT_TYPE/form-display) for your content type and make sure the Widget for the term field is set to Select list.
Go to the "manage fields" for your content type and click "edit" for the entity reference for your terms.  Go to the "Field settings" tab and make sure the Allowed number of values is 1.  If this is set to 2 or more, Drupal will give you a multiple select, not a dropdown.


drupalSettings cached in page I have a module that adds functionality to the front-end. The feature can be turned on or off via the configuration page of the module.

I pass the settings to the frontend in the HTML preprocess function using #attached. Simplified, the code looks like this:

function my_module_preprocess_html(&$variables) {
  $config = \Drupal::config('my_module.settings');
  $settings = ['enabled' => $config->get('enabled')];
  $variables['#attached']['drupalSettings']['my_module'] = $settings;
}

This approach is suggested here:

https://docs.acquia.com/tutorials/fast-track-drupal-8-coding/add-custom-variable-drupalsettings/

It works fine when logged in, but for anonymous users changing the setting from the module's configuration page does nothing until I clear caches (as, I assume, the drupalSettings variable is defined within the HTML that makes up the page)

So, my question:

Is there a way to ensure the settings are fresh with each page load (without disabling the entire page cache, of course), or
Should I refresh the cache whenever the module's configuration form is submitted? If so, what's the most efficient way to do that? (I've noticed a full cache clear is far slower on D8 than it was in D7)

Okay, I found the answer. It was as simple as adding this to $variables:

$variables['#cache']['tags'] = $config->getCacheTags();

My question is basically a duplicate of this:

How do I avoid having to clear the cache when changing a module configuration parameter?


What theme function outputs the administrative overlay in D7? What theming function generates the output for the admin overlay in d7?

To output the overlay, Drupal uses a template file, overlay.tpl.php. To use that template file, the Overlay module implements hook_page_alter(), which contains the following code:

  $mode = overlay_get_mode();
  if ($mode == 'child') {
    // Add the overlay wrapper before the html wrapper.
    array_unshift($page['#theme_wrappers'], 'overlay');
  }

The Overlay module has also a preprocess function for that template file: template_preprocess_overlay().


Set conditonal default value of a field I have a custom form with a field...

function mh_integration_connect_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => $params['cat'],
  );
}

as $param is not set before the form is submitted, so it show error for "Notice: Undefined index: cat".
I am wondering if we can set this default_value conditionally,

if(isset($params['cat'])) {
    '#default_value' => $params['cat'],
}

Here is how you can do it:

  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
  );

  if(isset($params['cat'])) {
    $form['cat']['#default_value'] = $params['cat'];
  }


jQuery ui isn't loading I'm simply trying to implement the tabs widget on a particular page.

I have both jquery_update and jquery_plugins modules enabled.
If I go to Administration > Reports > Status report Under jQuery Update, I see jQuery 1.10.2 and jQuery UI 1.10.2 are both green and showing as loaded.
If I type jQuery.fn.jquery into the console I see "1.10.2"

But the bad news is

If I try to use jQuery("#tabs").tabs();  I get an Uncaught TypeError: undefined is not a function error
If I enter any of the following "jQuery.fn.ui","jQuery.ui", "$.fn.ui", "$.ui" into the console:  I get undefined
Having this in my template.php:

:

 function my_theme_preprocess_page(&$vars){
   drupal_add_library('jquery_plugin', 'tabs.min.js');
 }

does nothing.

And finally, checking the heading of the rendered page, I see a call to Google CDN to the minified version of jQuery 1.10.2, but don't see any similar call to grab the jQuery UI library.

Working with Drupal and jQuery is such a nightmare, what else can I check, do, change, to get this working?

In your theme_preprocess_page function use this

drupal_add_library('system', 'ui.tabs');

Here is a list of all the libraries for 'system' https://api.drupal.org/api/drupal/modules%21system%21system.module/function/system_library/7


Webform validation are working but they some error When I login and page redirects to home page, it shows this notice:

  Notice: Undefined index: submitted in web_alter_form_validate() at line 19

Here is my code:

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

    if($form_id) //Change webform id according to you webformid
      {
        $form['#validate'][]='web_alter_form_validate';
        return $form;
      }

}

function web_alter_form_validate($form,&$form_state){

    if($form_state['values']['submitted']['title']){

      $val_title = $form_state['values']['submitted']['title'];
      if(preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $val_title) !== 0){
        form_set_error('title', 'Special character are not allowed in form title.');
      }
    }
    // Then use regular expression to validate it.
    // In above example i have check if phonefield is empty or not.
}

I have set validations on webform title.

This line:

if($form_id)

is doing nothing. Form ID is never something that will be considered FALSE. PHP Manual says:

  When converting to boolean, the following values are considered FALSE:

  the boolean FALSE itself
  the integer 0 (zero)
  the float 0.0 (zero)
  the empty string, and the string "0"
  an array with zero elements
  an object with zero member variables (PHP 4 only)
  the special type NULL (including unset variables)
  SimpleXML objects created from empty tags

Form ID is a string, name of a function really, and as such can never be empty or "0".

This means your function always enters the code block under if, and appends your validator to all forms. Most forms does not have submitted index defined, hence warning.

You probably wanted something like

if($form_id == 'some_form_ID_you_know_and_I_do_not')

and in validator something like

if( isset($form_state['values']['submitted']) and !empty($form_state['values']['submitted']['title']) ){


Drupal behaviour function not getting executed I defined a simple block on my module, using the following code.

function visita_virtual_block_view($delta = '') {
  switch ($delta) {
    case 'mapa':
      $path = drupal_get_path('module','visita_virtual');
      drupal_add_js('https://maps.google.com/maps/api/js?sensor=false','external');
      drupal_add_js($path.'/visitavirtual.js');
      $block['subject'] = t('google maps');
      $block['content'] = visita_virtual_mapa_content();
      return $block;
  }
}

That returns a simple div with an specific id, wich will allow me to alter it later through the usage of the google maps api.
For that I defined my 'visitavirtual.js' file, and inside of it I declared the Drupal behavior. That function is supposed to get executed when the whole page is loaded, since it'as a wrapper of the JQuery ready function.

(function($){
  Drupal.behaviours.visita_virtual = {
    attach: function(context,settings) {
      alert('Entered the init function');
      var latlng = new google.maps.LatLng(-34.397, 150.644);
      var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    }
  };
})(JQuery);

However, that code is not executed; I can't even see the alert window. What am I doing wrong?

Lol, it was a silly typo, Sorry. First it's behaviors not behaviours and then the namespace is jQuery not JQuery. Hard to find them on the IDE since it's valid javascript after all.


Change the add content look and feel for an specific content type? So, I would like to change how the Add Content form looks like. Right now the user sees it like this (everything's in spanish, sorry)

But I would like to change it to something like this (all text in spanish again, sorry)

The text in grey would be the latest saved node, the button on the right ("Agregar Siguiente") acts like the "save" button, but it comes back immediately to this same page.

I know I would have to develop a Module to do this, could you direct me in the right direction to do something like this? Thanks in advance.

You will want to create a theme override template for that content type for the edit mode. Then you can style it how you want. See this link for more information about how to do this:
https://www.drupal.org/node/1142800#comment-4433994


Front page works; the rest returns "URL not found" I have been trying to migrate a Drupal site to do some development locally. After moving the code, restoring the DB and doing some settings, I got the front page of the site to show up (minus some images). However, when I click on any of the menu links, I get the following error:

  Not Found

  The requested URL was not found on this server.

Now, I made sure that my base_url is set properly in settings.php. No trailing slash and all that. Currently it is of the type: http://example.com/drupal_directory, where drupal_directory is the directory with the site within Apache's /html folder.

What can I do to fix this? Is there some kind of a setting I am missing? There are no errors in PHP error log.

Note: This answer tells you how I fixed it in Ubuntu. I don't know about other operating systems, but you might wanna look up if
  mod_rewrite exits there too. If yes, you probably need to enable it
  there too.

I had that happen to me. I fixed it by enabling mod_rewrite.

In your terminal, type:

sudo a2enmod rewrite

sudo service apache2 restart


"Twig_Error_Syntax: The block 'content' has already been defined line" I have a block template in Drupal 8. I want to wrap a section element around the block when it is in the right region.

Twig gives me this error.

  Twig_Error_Syntax: The block 'content' has already been defined line

I understand the error, but I don't know how to fix it. Can anyone show me how to fix the code?

   {% set block_region_var = block_region %}
   {% if block_region_var == 'footer' %}
     <div{{ attributes.addClass(classes) }}>
       {% block content %}
         {{ content.body }}
       {% endblock %}
     </div>
   {% else %}
     <section id="{{ section_custom_id }}">
       <div{{ attributes.addClass(classes,'container') }}>
         {{ title_suffix }}
         {% block content %}
           {{ content.body }}
         {% endblock %}
       </div>
     </section>
   {% endif %}

You can remove all twig blocks from the template; that is, remove all of these lines:

{% block content %}
{% endblock %}

This defines a Twig Block, which could be used to extend this template, but this doesn't make sense anymore after you have implemented the condition.


Import CSV/XLS data to Webform? Is there a way to import records into webform database from user uploaded CSV/XLS?

This worked well for us: Webform Import

  Allows delimited data files to be imported as submission (results) into webforms.

  This is useful for importing submissions from other systems in to Webform. Can also be used to Edit submissions via Export / Import as long as the CSV has the SID column filled.


Why is my .htaccess not working when uploaded to a Pantheon server? My drupal site has a .htaccess file on which I am redirecting the page without changing the URL.

It's working fine on local server & other servers but when I upload the files & databases to pantheon server It will not redirect the page saying 404 not found. I placed .htaccess at the root of code folder, I tried placing it in server root folder, sites/ folder & themes/ folder but nothing works for me.

Does anybody know what is the correct placement of .htaccess in a Drupal site on Pantheon? And why my .htaccess is not working on Pantheon?

Because Pantheon servers use Nginx, and they don't enable .htaccess support.

You should contact them directly to discuss your options (if you're lucky and/or have a high enough subscription they'll probably add some custom rules to the nginx conf for you).


Adding “Unblock the user” option in Views Bulk Operations field I have created a user based view and I used the Views Bulk Operations module, but I don't see Unblock user or something like that. I also want to show tree-based roles in the bulk operation options list.

How can I achieve this?

In drupal 7-

We need a Rules module, after enable Rules module and Rules UI go to

1- Configuration -> Workflow-> Rules-> Component-> Add Component

In Component plugin dropdown-> select Action Set
then add next page
Fill the mandatory field Name as (Ex: Unblock user)

2- Select Data type from list User ---Label Unblock user ---machine name unblock_user -- usage parameter

3- In setting option you can set Permission roles wise.

then click on continue button
then click on Add Action Link

4- then Select the action to add User ->Unblock User

5- Select Data Selector -> unblock-user and Save

6- Now go to- Views Page add field Bulk operations there will be present Unblock user option

for reference - Add Unblock user option by rules in views and set permission


How to extend ArgumentPluginBase and have it recognized by Views? I'm wanting to create a Views argument plugin that extends ArgumentPluginBase in order to overrides one of the form elements in the buildOptionsForm(). I've pasted my plugin below. However, it doesn't seem to be recognized by Views. How do I make Views aware of this plugin and to make use of it?

<?php

namespace Drupal\my_custom_taxonomy_validation\Plugin\views\argument;

use Drupal\views\Plugin\views\argument\ArgumentPluginBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Resize the override text field.
 *
 * @ingroup views_argument_handlers
 *
 * @ViewsArgument("my_custom_taxonomy_validation_argument")
 *
 */
class MyCustomTaxonomyValidationArgument extends ArgumentPluginBase {

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['title'] = [
      '#maxlength' => 355,
    ];

   }

}

register it with hook_views_data_alter() in mymodule.views.inc

Something like this:

/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(&$data) {

  $data['node_field_data']['my_custom_taxonomy_validation_argument'] = [
    'help' => t('Hello world'),
    'real field' => 'title',
    'argument' => [
      'title' => t('Hello world'),
      'id' => 'my_custom_taxonomy_validation_argument',
      'accept depth modifier' => TRUE,
    ],
    'filter' => [
      'title' => t('title'),
      'id' => 'my_custom_taxonomy_validation_argument',
    ],
  ];

}


How do I add attributes to CSS in theme.info? I'm try to add a stylesheet switcher.  This requires the following CSS files to be included on the site.
<link rel="stylesheet" type="text/css" href="styles1.css" title="styles1" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="styles2.css" title="styles2" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="styles3.css" title="styles3" media="screen" />

theme.info reference some CSS files. How can I a rel and title attributes?
stylesheets[all][] = common/css/small.css
stylesheets[all][] = common/css/medium.css
stylesheets[all][] = common/css/large.css

Since Drupal will use CSS aggregation (and doesn't have support for adding extra attributes via the info file or drupal_add_css), you will have to print out the style sheets yourself. This can be done with theme functions or by creating the markup in the html.tpl.php


Errormessage with reference module When I want to add a link between two content types I got the following error:

  Notice: Undefined index: args in _node_reference_view_settings_validate() (line 161 of /var/www/vhosts/nielsjansen.be/httpdocs/drupal/sites/all/modules/references/node_reference/node_reference.module).

Settings were saved but with this error. Is this a problem?

You should report this in the module's issue queue.

Notice type errors are most of the time harmless and caused by sloppy programming or some edge case the developer didn't think of.