How do I pass parameters as JSON format to the HTTP client request? How can I pass parameters to the http client get request in json format:

$clientFactory = \Drupal::service('http_client_factory');
$client = $clientFactory->fromOptions(['verify' => FALSE]);

$params = '{"data1":"",
"data2":"mydata"
"data3":"mydata",
"data3":"mydata",
"data5":"mydata"}';

$url = 'https://myendpointurl';
try {
  $response = $client->get($url, array(
      'headers' => array('Accept' => 'text/plain'),
    )
  );
  $data = json_decode($response->getBody());
}
catch (RequestException $e) {
  watchdog_exception('my_module', $e->getMessage());
}

Where I need to put $params variable in my code?

You can add it to the request like so:

use Drupal\Component\Serialization\Json;
...
$response = $client->get($url, [
    'headers' => ['Accept' => 'text/plain'],
    'json' => Json::decode($params),
]);


Loop in Rules not picking up VBO data I have a Views of users (friends of the current user) and I have added a VBO field to it. The objective is that when an event is created by the current user, their friends receive an email about it.

I created a Rule, and using VBO (release 7.x-3.3), I try to send an email to people. Right now, the loop is not picking up any data, even if the View is working properly. Am I missing something?

PS: The rule first shows a message to confirm that it has been triggered, and I am testing the loop with a status message.

{ "rules_test_loop_triggeredvbo" : {
"LABEL" : "test_loop_triggeredVBO",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "views_bulk_operations" ],
"ON" : { "node_insert--event" : { "bundle" : "event" } },
"DO" : [
  { "drupal_message" : { "message" : "Rule when event is created is TRIGGERED" } },
  { "views_bulk_operations_action_load_list" : {
      "USING" : {
        "view" : "clone_of_profile_friends|page",
        "args" : "[site:current-user]"
      },
      "PROVIDE" : { "entity_list" : { "entity_list" : "A list of entities" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-list" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "drupal_message" : { "message" : "User has friend:  [list-item:name]" } }
      ]
    }
  }
]
  }
}

Have a look at these VBO issues:

views_bulk_operations_action_load_list not working.
Load a list of entity from a VBO View doesn't work (AJAX error).

Since you're using the 7.x-3.3 release of VBO, I recommend you retry your scenario with at least the 7.x-3.4 release. However, as per this comment you might only get it to work using the latest DEV version of VBO.


Autocomplete field search start character limitation? How can I limit the number of characters on when the search starts send a request to the server?

What happens if I do for example always call my own API (in the sense of using the autocomplete_path attribute)? Is the minimum still 3 characters?

Will you explain the search that you are using (ex.solr, default).
Basic limitation of characters is 3. if you want to increase this go to admin/config/search/settings and change the length of Minimum word length to index to your-limit and re-index the site. If you type minimum word length then only your search send a request to server.


Lost all JS and CSS on updating the module? I had added JS and CSS in the views module using the .info method. Made JS and CSS file in the views module file (as sites/all/modules/views/jsfile.js & sites/all/modules/views/cssfile.css) and attached it through views.info file. It was working fine. But today got an update notification of views module and updated the views and those all customized css & js things gone. Code was small so I made it again. But what is the right way to do this? So on update it will not go away? I believe adding css & js by .info method also a one of standard method.

That is why you should never do any modification to a module. The proper way to do this is to add the js and css to your custom theme using the same method you have done for views.
It is strongly discouraged to modify module or add anythings to the module otherwise on update all the changes will be lost.


Print field content as div attribute in views template Using Drupal 8

I have a view:

Unformatted List
Two fields, Title and an Image with Image URL formatter via the module Image Url Formatter

I need to print out that URL such that:

The problem lies in the fact that I have TWIG DEBUGGING enabled , so the output of the field also includes all the debug mumbo-jumbo that I don't need. I don't want to have to be turning on/off debugging to make sure this works, I want a way to print the content without that mumbo jumbo.

I thought this post would help. It explains that field.content contains the rendered field, and what I am looking for is the field data from the database.

When trying this out with views-view-fields.html.twig , the code row._entity.field_art_image.value works great but it returns the information about the image itself (alt, title, width, height..) but not its URL.

Is there a way for me to access either the image url that points to the Image Style applied to the filed? (For example /sites/default/files/styles/large/public/2016-11/feature-javelin-throw.jpg?itok=UJugCoqn .

Trying file_url(row._entity.field_art_image.entity.uri.value) works, but it returns the URL to the uploaded image, not the one that results from the Image Style applied.

The code you linked is for normal data fields like text or number.

{{ row._entity.field_field_text.value }}

An image is a reference field, which has no value property, but a target entity. This has it's own set of fields. In case of an image the target is a file entity with the field uri, from which you can get the url with file_url().

{{ file_url(row._entity.field_image.entity.uri.value) }}

Or use Twig Tweak to generate an image style url:

{{ row._entity.field_image.entity.uri.value | image_style('thumbnail') }}


drupal 7 remove logon & password for anonymouse users I have a username and password for my site for development purposes and now want to take the site live and remove the username and password for anonymous users.  How do I do that?

Go to admin/structure/block and look for the user login block set Region dropdown to none. If you are using the default Drupal theme, it would be under sidebar first category

UPDATE

but users can still create new accounts from /user page. To disable this, go to

configuration -> people -> account settings -> registration and cancellation and set "Who can register accounts?" -> "Administrators only".


The User registration form in drupal 7 site The User registration form in drupal 7 site has only one country under the country dropdown. How to add the entire list from country module?

gbctest.com/drupal7

change the "Country status" of the user's field for country to "both" or enable all country you want


Problem with flexslider I have been searching everywhere for an answer to this. I created a views slide show, in Drupal 7, then found out it wasn't working with my responsive theme, so I followed a guide on how to install and use flexslide show modular. Everything worked great, in the preview it shows how it should look but once saved and viewed on website it is showing the nav arrows at the bottom together, not on side of slide show.

I have cleared cache, tried to edit using a css file, tried to move block to another region, tried to adjust size of images through styles, choose both styles and flex style in image format everything I have tried nothing works.

I can change the effects of the arrows, but I can not move them to where they should be. I have searched everywhere, but can not find anything on this problem or how to move them. I have included 2 screen shots of the preview in views and live site. Also, the address of the site i'm working on.

If someone could point me in right direction why this is happening would be great. Thanks!

prntscr.com/dhmdn4 screen shot in views
prntscr.com/dhmde7 screen show of live site

I know that the views shows arrows cropped or missing the top and my pager buttons not center, I can fix that with .css file I created to override my theme I am working on. I just can't figure out why the nav arrows are showing like that.

remove the

/* position: absolute; */
/* bottom: 0; */
/* right: 0; */

from .flex-direction-nav


Profile picture with a border color depending of the role Is there any way to set a border color to every profile picture displayed all over the website depending on the role of the user?

I was trying to do it at least on the user profile image and on the User picture block module image following this instructions Custom node color from role but I ended in nothing.

Note: I display the profile pictures in a user search view, in the forums and in a block that display the latest forum comments.

Try hook_preprocess_user_picture() in your template.php

function MYTHEME_preprocess_user_picture(&$vars) {
    $account = user_load($vars['account']->uid);

    foreach ($account->roles as $role) {
        $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
    }
}

Each user picture should then have the role-rolename classes added to it.
It is similar to Clive's answer you mentioned, but different hook.


Kint breaks in template and doesn't allow me to view anything In my template I am trying to view the contents of Childen in a form template.
<form{{ attributes }}>
  {{ kint(children) }}
</form>

However, the result I get is a useless broken kint message, that doesn't allow me to expand any of the fields or view any other information.

Any ideas?

Deactivate the BigPipe module, it causes some errors in Google Chrome when the user is logged in.

There's no error in Chrome if you aren't logged in. Firefox and Safari will still work with Kint and BigPipe enabled.


Page template suggestion based on content types but not for node/edit or node/delete I have a template for a page content type that works perfect. But when I try to edit or delete the node of that content type it blocks the standard template.

So node/130/edit? or node/130/delete? are not working because I don't get the right page.

I tried strpos($_SERVER['REQUEST_URI']) versions but it doesn't work or like the one below only gives me the "original" Drupal template  when the path is node/130/edit? so the second variable gets through.

function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
      // Add content type suggestions.
      if (($node = \Drupal::request()->attributes->get('node')) &&
      (strpos($_SERVER['REQUEST_URI'], "delete") || strpos($_SERVER['REQUEST_URI'], "edit") === false)
      ) {
        array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
      }
    }

The array_splice hint comes from
https://www.drupal.org/forum/support/theme-development/2015-07-02/how-to-add-in-drupal-8-a-custom-suggestion-page-template#comment-10684366

Any help?

A slightly different approach: Add a custom theme suggestion for the canonical route of your node type(s).

This way, you neither have to meddle with path arguments whose position might change, e.g. when using subpath aliases in a later stage of your site's development cycle, nor have to extend your checks for additional routes added by third party modules, as e.g. node/{nid}/translate, node/{nid}/revisions, node/{nid}/devel, and so on.

I didn't test it though, but you could do something like this:

/**
 * Implements hook_theme_suggestions_HOOK_alter() for page.html.twig.
 */
function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if (
    $route_name = \Drupal::routeMatch()->getRouteName()
    && $route_name == 'entity.node.canonical'
    && $node = \Drupal::request()->attributes->get('node')
  ) {
    $suggestions[] = 'page__node__' . $node->getType() . '__canonical';
  }
}

Then you could rename your page template to page--node--my-type--canonical.html.twig and it should be picked up only for your node type my_type at its canonical (view) route.


After moving document root, pages can't be found Drupal 8 installed on shared hosting.  To access the site from the web during development, I installed D8 in /www/d7/d8.

Then I moved d8, which contains the D8 install, to /www/d8 and then set my document root in Cpanel to d8.

The theme and blocks load, and I can fill out the form at /user/login, but after that, every time I try to access a page, I get an "access denied" message and the link is pointing at mysite.com/d8/page instead of mysite.com/page.

I looked in settings.php and .htaccess but I couldn't find any references to a base directory.

How can I get my D8 site working after moving the directory and changing the document root?

Browser cache was the issue.  Resetting the cache made everything go back to normal.


How to make a CCK field appear as single-value on one Node Type, and multi-value on another Node Type? I have a CCK field (text, options widget, predefined value list) I'm using on two Node Types.  On one Node Type, I'd like to allow an unlimited number of selections.  On the other Node Type, I'd like to restrict the user to a single selection.

Currently, I've configured the CCK field to allow unlimited values, and am using this hook_form_alter() code:

/*
 * Implementation of hook_form_FORM_ID_alter().
 */
function custom_form_custom_node_form_alter(&$form, &$form_state) {
  // http://drupal.org/node/726282
  $form['#after_build'][] = 'custom_after_build';
}
function custom_after_build($form, &$form_state) {
  $form['field_custom' ]['value']['#multiple'] = false;
  return $form;
}

So far, so good: the field shows up as single-value on one Node Type, and multi-value on the other.

But when I click Save, the data doesn't end up in the node — I presume this is because the single-value and multi-value fields store data differently, and CCK's submit handler is expecting the data in a different format.

What do I need to do to get the single-value field data into a format CCK will understand for a multi-value field?

So far I've tried:

implementing a #validate handler to alter the $form_state array to match the $form_state array produced by submitting a multi-value field — no effect
implementing hook_nodeapi() $op==='validate' to alter the field values in the $node object — no effect

You need to implement the hook_nodeapi and use the operation "presave"

Presave will have all the data submitted from the form and you can then alter it here just before it goes into the database.

If you have the devel module do a dpm($node); to see what data you are getting.

the important thing is that the field for multi values will be expecting an array so it may be as simple as grabbing the data from the form and adjusting it to pass it as an array.

EDIT

Aah ok validation....

I would probably turn off validation for that item by using the: '#element_validate' property, this way you can target validation for that specific element see the fapi docs on drupal.
http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/6#element_validate


How to prevent actions using Flag (or similar) module? The Goal: I'm trying to setup functionality similar to a library with downloadable files. Only one user can download a file at a time.

The Solution: Use the Flag module.

Open to suggestions but through my research it seems like people are using the Flag module for this type of functionality. My question is how do I actually get this to work? I'm using a file field to add a file to a node. An admin comes along, wants to "checkout" that file, and they click the checkout flag, and then download the file. Now no other admin can download that file.

Once the original admin comes back, they can just click the flag again, setting it to open. (I know, they aren't really returning a digital file.) They just need to simulate returning it by basically just telling the system someone else can get this file.

Anyone set up something similar to this or just have an idea of how I would do this? Thanks for any suggestions and help.

I haven't done this, but if you want a library check in/check out system this is the approach I would try.  Create a flag (here I'll call it Check out) that allows users to "check out" files.  Make sure this is a global flag.  Name the unflag link "Check in" or something similar.  (You could also automatically have files checked back in after a certain interval with Rules Scheduler.)

Then, I would create views so that users cannot see the nodes that are checked out.  To actually enforce security, I would also add a rule that automatically redirects users away from the page of any node that they did not flag that has been flagged (this probably will cause a performance hit and may not be the most secure way but will probably work for general cases).


Send Billing Information from Address Field to PayPal site using WPS Referring to the solution here posted by Fnik, I'm trying to implement it on my own custom module.  But I thing our two sites are configured differently, and since I'm not too familiar with php, I don't get how to adapt his code for my project.

I use Address Field module for customers billing and shipping address.  This doc page explains how it stores its subfields.  So I need to access these subfields with the hook Fnik pointed.

My code doesn't do it correctly on checkout. Although syntax seems ok, I get errors (specified bellow) when the function is called.  Here is my code:

function my_module_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
$profile = user_load($order->uid);
$data['first_name'] = $profile->field_commerce_customer_shipping->commerce_customer_address->first_name['und'][0]['value'];
$data['last_name'] = $profile->field_commerce_customer_shipping->commerce_customer_address->last_name['und'][0]['value'];
$data['address1'] = $profile->field_commerce_customer_shipping->commerce_customer_address->thoroughfare['und'][0]['value'];
}

Some context:

commerce_paypal_wps_order_form_data_alter is a hook from commerce_paypal_wps.module
field_commerce_customer_shipping is a Customer profile reference in Order type order entity.

commerce_customer_address is a Postal address field type in Shipping information Profile type entity.

Erros, 3 different errors for each $data line:

Undefined property: stdClass::$field_commerce_customer_shipping in my_module_commerce_paypal_wps_order_form_data_alter() (line 27 of ...)
Trying to get property of non-object in my_module_commerce_paypal_wps_order_form_data_alter() (line 27 of ...)
Trying to get property of non-object in my_module_commerce_paypal_wps_order_form_data_alter() (line 27 of ...)

Is is the $profile variable declaration that is wrong right in the beginning, or is it the way to refer to fields and subfields?

Thanks in advanced.

The user profile may not have the data saved to it yet, if it is a new user or if you allow anonymous checkout somehow, so it is better to retrieve this data directly from the order. To do that, we have to do some fancy footwork using the entity API - this also avoids any snafus related to database changes or translation arrays. I created a simple function that uses this API to extract an array of address fields:

/**
 * Helper to retrieve the profile from an order
 *
 * @param order
 *   The order object
 * @param type
 *   Either shipping or billing
 * @return
 *   The requested data
 */
function _my_module_address_from_order($order, $type="billing") {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $type = "commerce_customer_".$type;
  return $wrapper->$type->commerce_customer_address->value();
}

Then I call it thusly in the actual hook:

/**
 * Send default billing address to paypal
 */
function my_module_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $address = _my_module_address_from_order($order);
  $data['address1'] = $address['thoroughfare'];
  $data['address2'] = $address['premise'];
  $data['first_name'] = $address['first_name'];
  $data['last_name'] = $address['last_name'];
  $data['city'] = $address['locality'];
  $data['state'] = $address['administrative_area'];
  $data['zip'] = $address['postal_code'];
  $data['email'] = $order->mail;
}

Note that paypal will not display a billing address unless it gets all of the values address1, city, state and zip as well as first_name and last_name!

Much of this solution was arrived at from consulting http://www.drupalcommerce.org/discussions/756/load-address-order


Date form to unix timestamp I'm using Drupal 7.8, and am trying to get the user to specify a date using the drupal date form. I want to take this date, and save it to a database as a unix timestamp. The trouble is, I think the data given by the date form is based on the user's current timezone. Does drupal provide anyway to convert the form data back to unix time? Is there an easier way to handle dates?

I'm pretty sure the values stored using the date attribute are unaltered and just passed on in an array. So the question would be if the user submits the date for UTC or his/her timezone. I would say the latter ;-)

I'm no expert on date settings and timezones, but had seen this question before on stackoverflow, so taking that into account I assume you can do this:

global $user;
$datefields = $form_state['values']['submitted_date'];
$submittedDate = "{$datefields['year']}-{$datefields['month']}-{$datefields['day']}";
$timezone = $user->timezone;
$newdate = new DateTime($submittedDate, new DateTimeZone($timezone));
$unixts = $newdate->getTimestamp();

This would require the user to have set his/her timezone accurately in the account settings.


Can admins create new accounts without passwords? When an admin creates a new account (admin/people/create), they're prompted to enter a password for the account. My client wants it to be that when an account is created in the back end, the admin doesn't have to enter a password, but the user is sent a notification message with a one-time log-in link and can then set a password after logging in using that. What's the best way to achieve something like this?

I've thought of maybe altering the form to set the #default_value of the password fields to a random password and then setting '#access' => FALSE, but I'm not sure if that's the best way to go about it.

There is a module that does this.

Check out Generate Password.

It introduces this additional setting in Configuration » People » Account settings:

  Users may enter a password on registration. If left empty, a random password will be generated. This always applies when an administrator is creating the account.

Then, when creating the account, leave the password field empty, but make sure you also check this checkbox on the "Add user" page:

  Notify user of new account

The result of these two settings is that the module generates a random password when the administrator creates an account, and the user is sent an email with a notification about the account and prompted to set a password in the one-time login link that is included in the notification.

If you want to learn how it is done, read the source code.


Implementing callback function in hook_menu() In the link given below ,
https://drupal.org/node/224333
So as given in below statement you do not have to declare the callback path* what does this mean?
I have hook_menu() in d6 which is as follows :

$items['ort/add/ion'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'ort_add_ion',
    'access arguments' => array('access content'),
    'file' => 'ort.tion.inc',
  );

Does the link say that for d7 you do not need page callback or something different?

In Drupal 7, you do not have to declare the callback path in hook_menu(), and the callback function is far simpler.

Drupal 6:

<?php
// This function must be pointed to in hook_menu() in D6.
function my_callback_function() {
  // ... Much work to build the form ....

  drupal_process_form($form_id, $form, $form_state);
  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);

  $output = drupal_render($form);

  // Final rendering callback.
  print drupal_json(array('status' => TRUE, 'data' => $output));
  exit();
}
?>

Drupal 7:

<?php
// No path needs be set up to point to the function, and $form and $form_state are provided.
function my_callback_function($form, &$form_state) {
  // Often you would select a portion of the form to match #ajax['wrapper']
  // rather than processing the whole form.
  return $form;  // Either HTML or a render array may be returned.
}
?>

The simple answer is it is for ajax items. In drupal 6 you had to declare a path and direct your ahah to it with ['#ahah']['path']. In drupal 7 it is handled automatically and you now use ['#ajax']['callback'] to call the function without having to declare a path.


"The website encountered an unexpected error" right after login in So I recently bought a very cheap host just to run a not-important website on it. but when I login to admin, it shows

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

message, since its a shared host I checked into my cpanel for error logs, there were just two errors regarding my .htaccess files (in root and also sites/default/files) regarding FollowSymLinks not being available here, so I commented out those lines and all error logs now are gone. but still I get the error message after I try to login.

I contacted the webmaster regarding FollowSymLinks and he said we are using SymLinksIfOwnerMatch .

however with or withought FollowSymLinks I still get the error message while my error logs in cpanel is empty.

Any Ideas or hints?

If you are not able to login then you can try checking the logged error directly looking into your database watchdog table.

In your case:As per our chat you were missing watchdog table so importing the database back helped you.


Views Arguments formatted nicely for the title I know that you can get the arguments in the view's title and format it so that it makes sense so that an argument like "search-for-something" can be output as "Search For Something".

I have an argument passed like "argument-here" and I need to search in the database for that exact phrase.

The problem is that in order to get it to format nicely in the title as "Argument Here", this also removes the dash in the SQL query - resulting in nothing for my view to return.

Is there a way that I can format the result for the title without messing up the actual argument for the SQL query?

Restore your view so that the query works. Then, make sure the PHP Filter module is enabled and that you have permissions to use it.

In the view, add this header:

<?php
$view = views_get_current_view();
$my_title = ucwords(str_replace("-", " ", $view->args[0]));
drupal_set_title($my_title);
?>

Make sure the input format for the header is PHP.

The view's preview will show the wrong title. That's ok. When you navigate to the page, you'll see that the title is as you want it.


Programmatically setting video_embed_field URL I am trying to populate nodes programmatically from a feed (migrating earlier site to Drupal 9). So far I have managed to get everything else to move, but I can't figure out, how to set video_embed_field or rather the URL-value of the video. I found an example, but it caters just youtube, but there are also other video providers used.
I have tried the following ideas:
$node->set("field_video", $videourl);

$node->field_video = ['input' => $videourl];

$node->field_video = ['value' => $videourl];

but so far nothing works.
Could anyone hint me to the right direction?

Actually, the last try in my choices seems to work after all.
 $node->field_video = ["value" => $item["video"]];

I must have done something dumb with my editor like not saving the changes...
Well, maybe someone else finds the info here...


Passing taxonomy term through drupal_html_class() and use it as row class name In a view I would like to use a excluded term reference field as source for the the row classname. But the values need to be sanitized by putting the term names through drupal_html_class(), otherwise the resulting classnames are not valid in every case.

How can I sanitize the values using a preprocess function?

I got it working by using this preprocess function:

function mytheme_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'field_category') {
      $tid = $variables['row']->_entity->field_category->target_id;
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
      $name = $term->getName();
      $variables['output'] = \Drupal\Component\Utility\Html::cleanCssIdentifier($name);
    }
  }
}

An alternative would be using mytheme_views_pre_render.


How to use value passed to views_embed_view as a filter? I want to embed a View in a node template. I understand that I can use views_embed view to do that, and pass values to it.

$my_arg = $node->nid; //the nid of the node that I want to use as filter
print views_embed_view('my_test_view', 'block_2', $my_arg);

How can I use that value as a filter ? I want that view to list nodes that have a field with the same value as the passed to the function

The value you pass as last argument to views_embed_view is not passed to the Views' filters, but to the view's contextual filters  (also known as arguments). Contextual Filters are like filters, expect they take external input (from the URL when viewed as a page or from the arguments passed to functions such as views_embed_view). You can learn more about contextual filters here: http://drupal.org/node/1578558


How To Remove Menu Tabs From Custom User Dashboard I'm working on creating some custom user dashboards but cannot seem to find how to remove certain menu items. I intend to use a combination primarily of Panels with Context and Views (but I haven't ruled out simply using Homebox) but at this early stage learning D7 I've created a custom Variant in the system Panels template, created a rule set in the Variant which will set each user dashboard to load based on their subscription (Ubercart Role). Because of the nature of the Roles, different DBs are required.
As you can see in the attached screenshot, the menu tabs are showing left to right (View, Affiliate Center, Bookmarks etc), I've tried going through all the backend and cannot for the life of me find what controls them to show, could somebody please tell me what causes them to show, so I can either 'hack it' or delete it.

I know it maybe a theme influence and for my current testing I'm using Bartik, but I intend to use an HTML5 theme based on either AT Theme or Boilerplate, but haven't got to that stage as yet (or that maybe my next 'hack' learning lesson today!). Ultimately, I intend to use a Less framework, but for now I merely want to get the functionality working BEFORE I do CSS.

So, what's influencing the menus in my basic User DB as shown here?

https://dl.dropbox.com/u/55172207/screen_shot_cp.png

Thanks in advance to anyone for the help.

You can do that from your theme's template.php file by implementing the theme_menu_local_task().

Using this function you can also rename specific tabs.

Code for both actions is below.
It is taken from this file of our Ultima theme.

<?php

/**
 * @file
 * Theme local task function.
 *
 * Created by: Topsitemakers
 * http://www.topsitemakers.com/
 */

/**
 * Implements theme_menu_local_task().
 */
function YOURTHEME_menu_local_task(&$vars) {

  $link = $vars['element']['#link'];

  // List of tab names to be excluded; t() function will ensure that the
  // tab name will be matched and excluded on multilingual sites as well.
  // This is useful in case you have many modules installed on the site and
  // large number of tabs break the layout of the theme.
  $excluded_links = array(
    t('View'),
  );
  if (in_array($link['title'], $excluded_links)) {
    // Skip all further processing.
    return;
  }

  // Uncomment code below to rename the "View" tab for certain node types
  /*
  // Check if the link title is "View"
  if ($link['title'] == t('View')) {
    // Make sure we are on single node page
    if (arg(0) == 'node' && arg(1)) {
      $node = node_load(arg(1));
      // Do this for specific content types
      if ($node->type == 'page') {
        $link['title'] = t('View full page');
      }
    }
  }
  */

  // Continue building the local task link
  $link_text = $link['title'];

  if (!empty($vars['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '' . t('(active tab)') . '';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  return '
' . l($link_text, $link['href'], $link['localized_options']) . "
\n";

}


How to allow arbitrary query string with url alias? Using Google Custom Search and as part of it's configuration I specify a callback url on my site (e.g., www.example.com/search).  I setup my page www.example.com/search as a Basic Page.

When someone searches for something they are taken to the url I specify and arbitrary query string parameters are appended (e.g., www.example.com/search?cx=partner&ie=UTF-8&q=dom&sa=Search&siteurl=www.example.com/search).

However this results in a page not found because Drupal appears to treat the entire request path as a url alias which it can't find.

How can I allow arbitrary query strings?

Drupal doesn't treat the query string as part of the URL alias, the problem is that your URL has the q parameter as part of it (q=dom).

Google obviously uses that for some purpose, but Drupal uses $_GET['q'] to determine the path of the page that should be shown. So when you visit a URL with q=dom in the query string, Drupal will try to find a page with the path dom...which obviously doesn't exist on your server.

Short of some crazy hacking of Drupal core (and probably dozens of contrib modules) I think the only way you're going to solve this is by somehow changing the original query string and removing the q parameter from it.


How To Create a Remote Views Search Form - D7 I have overridden the default Drupal /search page with a panel view that is listing users. In this view, users can be filtered by gender, age, location, etc - and it's working quite well! I have paired Contextual Filters and exposed Filter Criteria enabled to allow GET variables to be passed to the view while still allowing for a Filter Criteria fallback. Achieving this took a few experimental patches.

Now I need to place a search form on the home page that has a few of these filter options. This form needs to direct users to the /search page and take with it whatever the user enters. I've tried using the Exposed Filters Block but doing so removes the filters from the /search page entirely and negates the view header and footer which are unfortunately essential to the view.

Creating a basic HTML GET action form that sends users to the /search page works well, but that's a nasty long URL and I would prefer to keep this within Drupal. It seems that changing this form to use POST instead of GET does not work.

Is there some way to create a stripped-down form that leads into this search view? Using the Forms API would be nice but I'm open to any other solutions presented.

I would suggest writing your own form in a block which you can place on the home page. I don't see anything wrong with writing the form in HTML - though if you generate your form the Drupal way using the Form API then you'll ensure you get consistent themeing across your site, you'll be protected against XSS attacks and so on. How to use the Form API is beyond the scope of a single question ;
There is a module that allows you to use POST queries with views exposed filters : http://drupal.org/project/views_expost - hopefully this should deal with your long URL problem.


Order receipt email content I have a Drupal 8.6.7 site with Commerce 8.x-2.11 installed. I would like to include slightly more information in the emails sent out when customers complete the checkout process. I would like to reference both the equipment category field and a more general category field present in both the product and product variations.

At the moment I just see the Title, Unit Price and Quantity if I look at the list of orders (all tests right now) at /Administration/Commerce/Orders.

Is there a way of adding these fields through the web admin GUI so that they end up in an order receipt email? I also have 'MIME Mail' and 'Mail System' modules installed if that helps.

This is not really an answer but closer to one than I've been before; even though I cannot go any further.

In /core/themes/bartik/templates I've placed a copy of commerce-order-receipt.html.twig. I can change the wording in this template, refresh the cache and I can see that come through in new emails. I see there's a mention of an 'order_entity' which I do not know how to reference so it appears in an email receipt.

If you can see the screenshot I've uploaded, it may become clear where I'm at or where I'm going wrong.

I thought I might be able to change one of the columns in the order item (as the current four columns are exactly those that appear in receipt emails) and then try and reference it through {{ order_entity.getSomething }} in commerce-order-receipt.html.twig (after clearing the cache).

If I can get the fields in 'Purchased Entity' into the receipt email, I can then complete my business case for my Drupal site as everything else works a treat.

Thanks again.


How can I filter which entities are available in the admin form for an Entity Reference Field? I've got a Field which is called "Primary Article" which is an Entity Reference Field. I've configured this field setting the "Reference Type" to be "article", so that only articles show up in the Form when editing this field.
I would want to add two customizations to the current autocomplete field:
)
1) only return some articles based on some logic ( like I only want to return articles which are not selected as primary articles for another taxonomy )
2) change the text of the autocomplete field, so in this case, instead of "Primary Article" I would want to return "Primary article - XYZ" where XYZ is a custom field

1.) You can create the limited list of Articles with Views, then use that Views in the Entity reference Field settings as the source.

2.) This should have probably gone into a separate question. Try researching into modules related to autocomplete, like: Search Autocomplete, Autocomplete Search Suggestions.


cant reach content in block--views I am new to Drupal8.
How can i get the content ?
I call a view in page.html.twig like:

  {{ page.content.views_block__serviceboxen_block_1 }}

and created a template with name:

  block--views-block--serviceboxen-block-1.html.twig

How can i access to the content from my view in this template ?
I have no idea when i use

{% for row in rows %}

and

{% for item in items %}

thanks a lot.

solution: you can access the fields with 'content'

e.g. content.body or content.your_field_name.value

in a iteration it looks like:

  {% for item in content['#view'].result %}
      {% set topic = item._entity %} {# just for shorter writing #}

{{ topic.title.value }}
 {# or topic.yourFieldName.value #}

  {% endfor %}

Hope it'll help


How to make twig rules based on paths? I want to make some rules in twig based on current page path. To be precise I want to make the page template look a little different when node is in edit form, revision history page and translation overview.

I want to do something like this, but doesn't seem like working;

{% if path('<current>') is path('entity.node.edit_form') %}

I want to make rules for all these paths;

entity.node.edit_form
entity.node.version_history
entity.node.revision
entity.node.content_translation_overview
entity.node.content_translation_add
entity.node.content_translation_edit

Are all available at any page template where a node will be rendered?

Put the route name in a variable in preprocess

mytheme.theme

function mytheme_preprocess_page(&$variables) {
  $variables['route_name'] = \Drupal::service('current_route_match')->getRouteName();
}

and use it in twig:

page.html.twig

{% if route_name == 'entity.node.edit_form' %}
  This is a node edit form.
{% endif %}


Add Bootstrap Carousel to Region I am creating a custom front page (using a template page--front.tpl.php).

I've defined a few regions to be used on my front page. In one of these regions I would like to embed a Bootstrap Carousel (that was created with the Bootstrap Carousel module). Can this be done? It appears only blocks can be added. A Carousel appears to be of type content. Perhaps this can be done using Views or a similar module?

The reason for me going this route is for simplicity of updating the carousel. Another maintainer of this website does not have PHP/HTML/CSS skills, so I would like for them to simple update the carousel using the Drupal admin interface, as opposed to updating page--front.tpl.php itself.

I did something similar and used the Views Bootstrap Module. I am not sure if you are using also a Bootstrap Subtheme, but  here is what i did:

Installed the Bootstrap Theme and created a Subtheme.
Installed JQuery Update. (Most recent Bootstrap need JQuery 1.9)
Installed Views Bootstrap.
Created a Views Block for my Slides. I did it with articles which have an imagegallery field.
Added a contextual filter, so for each article a carousel of images can be added in form of a block.
In the Views Block under Format i choosed Bootstrap Carousel.

Then i had a Carousel Block to put in any region i want. You can configure your view to serve your personal needs.


How do I remove the commits in git? I am using git to track my commits in a Drupal 7 site. I was involved in a project which uses git to move between production and development server. I made some changes in features and pushed it to the production server. I now notice the following error:

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

I am sure this is because of some feature errors, but at the same time I am not sure what feature caused this to happen.

I want to know is there a possible way to remove the commits by date. Like remove commits from 25th may? or Set header before 25th may?

To revert a very simple commit, this is enough:

git revert ba24a3fdeae4a3a034691308171d798d2ddbf93e

here that long string of characters is the ID of the commit you are reverting.

To get the ID of the commit see the git log.


Drush 8.1.2 is not working on Windows I have installed Drush 8.1.2 on Windows 7, but it doesn't work. Few command are working, but few are not working.

drush uli 1 works
drush dl <project name> works
drush en <project name> doesn't work
drush cc all doesn't work

Running drush en "module name", I get the following:

  Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
  The drush command 'en fieldupdate' could not be executed.
  Drush was not able to start (bootstrap) the Drupal database.
  Hint: This may occur when Drush is trying to:

  bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See drush topic docs-aliases for details.
  connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

  Drush was attempting to connect to:
   Drupal version         :  7.34
   Site URI               :  http://default
   Database driver        :  mysql
   Database hostname      :  localhost
   Database port          :
   Database username      :  root
   Database name          :  staticpages
   PHP configuration      :  C:\xampp\php\php.ini
   PHP OS                 :  WINNT
   Drush script           :  C:\Users\ins237\AppData\Roaming\Composer
                             \vendor\drush\drush\drush
   Drush version          :  8.1.2
   Drush temp directory   :  C:/Users/ins237/AppData/Local/Temp
   Drush configuration    :
   Drush alias files      :
   Drupal root            :  C:\xampp\htdocs\cms-staticpages
   Drupal Settings File   :  sites/default/settings.php
   Site path              :  sites/default

Looks like your database cannot be contaced, run drush status to make sure of that. If that's the issue, then you should update your settings.php files with the correct ip, I guess 127.0.0.1 for your xampp stack.

Not an answer to your question, but running PHP/Drupal on Windows is just asking for problems. You should look into Vagrant or Docker to run your Drupal sites on Windows, that will save you a lot of pain in the long run AND will make it easier to deploy your sites later on.


How to change the entity view display configuration programmatically? In a hook_install implementation, I need to change the entity view display configuration of certain bundle / view mode combinations. For instance, I would like to change the 'teaser' view  mode of the 'article' bundle and hide 'field_image'.

When you export the configuration, you'll see those settings stored in core.entity_view_display.node.article.teaser.yml. I know it's possible to load the configuration like this:

$view_mode_config = \Drupal::configFactory()->getEditable('core.entity_view_display.node.article.default');

This would allow you to change and save the config object, but I suppose that is not the correct way to do it. I'm guessing there must be some kind of view mode manager class I should use to do this, but I haven't been able to find it.

So how do I change the entity view display configuration programmatically?

Bonus question: When you find yourself in a situation like this, what are your strategies to explore the code and find the classes you need?

There are two configuration types. Simple configuration and configuration entities. In this case this is a configuration entity. The class name is in camelCase:

EntityViewDisplay.php

class EntityViewDisplay extends EntityDisplayBase implements EntityViewDisplayInterface

If you have a config entity for the configuration, you can load the config entity,

$storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
$view_display = $storage->load('node.article.default');

modify it and save it:

$view_display->save();

Why you want to use config entities?

You can get the array of the configuration:

$config = $view_display->toArray();

This is not different from what you get in the yml file or config api.

The advantage is, that config entities usually have method for special configuration tasks. With displays this is for example to add or remove components:

$view_display->setComponent('body', [
     'type' => 'text_summary_or_trimmed',
     'settings' => ['trim_length' => '200'],
     'weight' => 1,
   ])
   ->removeComponent('field_image')
   ->save();

That is much easier than to do this in the configuration array.


Themng the grouping fields in Views I have a view which lists dishes by category. Category is a tag ("main", "soup", etc). I use grouping fields, and what i wanted is to make a kind of anchor menu for this view. Is it possible to style the grouping fields?
Right now, grouping fields are in h3 headers, just before the relevant views rows.
Is it possible to rewrite them,or alter their structure?

You have to override the view template.

In your views UI click on 'Theme:information'. This will open up a dialog with views templates and suggestions. As your view is using grouping, you need to override the 'Style output' theme template as it is the one that contains the h3 tag you want to alter. When you click on the blue 'Style output' link it will open up a dialog with the code you can copy and alter. That code needs to go into a file placed within the template's folder of your theme. The file name must be selected from the list of suggestions in the same line next to the blue 'Style output' link. First in the list is:

views-view-list.tpl.php

If you override that template it will override it for all views of HTML List format, so you now have to select a more targeted suggestion. Going down the list you will see how different template suggestions target different contexts.

Have a look at this question for more information: Commerce Product Collection View Block: What Determines CSS For Each Header Link?


How to apply the attribute "rel=nofollow" to links in the comments? I configured the Text Format "Plain text" (admin/config/content/formats) to "Convert URLs into links" so I would like to add the attribute rel="nofollow" to all the links in the comments.

This way I would minimize the effects of spammy links in the comments.

Is there an easier way than using regular expressions to insert the attribute?

Go to Configuration -> Content authoring -> Text formats -> Plain text (your format), then tick the Limit allowed HTML tags option.

In the filter settings at the bottom of the page is the Add rel="nofollow" to all links checkbox. Tick that... Since this is plain text, you will probably want to remove the contents of the Allowed HTML Tags field, too.


Displaying image from referenced entity in a view I am trying to create an image albums with the biblio content. These are the steps I have taken:

On the Biblio content type, I added a new field called Image of type Image
Created a new content called Album. Added one field of type Entity reference; and referenced, to the Biblio content, with multiple selection
This is where I'm stuck, creating a view for the albums. I'm not able to display the image content of the biblio entity reference. I have added a relationship to the entity reference: referencing the biblio entity. And added the field Content:Image with a relationship to the biblio entity.

I'm at loss, I know I have a big mistake in the view, but I'm not getting the big picture on how to relate.

I think you want to display the content of "Album" with the contents reference to "Biblio", first in views follow these steps:

Select the content type of "Album"
Create a relation ship with reference to "Biblio"
Then again select an image in fields and enable the relationship with the same (which you have selected in relationship).


Search Nodes by Username Is there any way to find node content (e.g., articles, pages, etc.) by username using Drupal's (version 7.x) core site search (i.e., the search end users can use)?

The installation that I'm working on currently indexes usernames only if they occur within the body of the node content; however, the users' respective articles will not show up.

I've attempted to write a small module to update the index to use the username (modifying this example for 7.x). I had no luck with this.

I've also attempted to write a small module that hooks into the search; however, it seems to be only accessible to the core node and user modules, which implement the hooks already.

For the time being, I have edited the core search module (in search.pages.inc) to call my small module. Then I grab the search keywords and see if they resembles an author name. If so, I grab some recent articles.

It works for now, but it's obviously not a good idea to edit the core.

Anyway, thanks for any help!

Here's my Core Drupal search based solution for the same. The code below would be responsible for indexing the node author in a custom module badly named My custom module ('my_module.module'). Most of the code is heavily inspired by the core search module's search.api.php.

Once the module is in place ensure that its name (again My custom module) is checked in Active search modules.

/**
 * Implements hook_search_info().
 * This ensures that the Search Content by author tab is present in your Search result
 * and available in the path site/byauthor/<searchterm>
 */
function my_module_search_info() {
  return array(
    'title' => 'Search Content by author',
    'path' => 'byauthor',
    'conditions callback' => 'callback_search_conditions',
  );
}

Following this click and confirm re-index content and run cron for the actual indexing
The hook_update_index is written such that for each node the author name is retrieved and stored in the search index as a type 'nodebyauthor'.

/**
 * Implements hook_update_index().
 *
 * To actually index the nodes based on the uid
 * "Inspired" by search.api.php from drupal core search
 */
function my_module_update_index() {
  watchdog('my_module', 'entered my module update index');
  $limit = (int)variable_get('search_cron_limit', 100);
  $result = db_query_range("SELECT n.nid FROM {node} n
            LEFT JOIN {search_dataset} d ON d.type = 'nodebyauthor'
            AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0
            ORDER BY d.reindex ASC, n.nid ASC", 0, $limit);
  foreach ($result as $node) {
    // simple query seemed a better option than loading the node and author object
    $author = db_query("SELECT `uid` FROM {node} WHERE `nid` = :nid",
              array(':nid' => $node->nid))->fetchField();
    watchdog("my_moduleupdateidx", "Node is {$node->nid} and uid is {$author}");
    if ($author !== FALSE) {
      $author_name = db_query("SELECT `name` FROM {users}
                     WHERE `uid` = :uid",
                     array(':uid' => $author))->fetchField();
      search_index($node->nid, 'nodebyauthor', $author_name);
    }
  }
}

A helper hook hook_search_reset to mark content for reindexing when re-index option is triggered

/**
 * Implements hook_search_reset().
 *
 * Reset the indexed item timestamp for being reindexed on subsequent cron runs.
 */
function my_module_search_reset() {
  db_update('search_dataset')
    ->fields(array('reindex' => REQUEST_TIME))
    ->condition('type', 'nodebyauthor')
    ->execute();
}

The hook_search_execute is where the actual newly indexed content (after enabling our custom module and running cron) will provide results based on the user when a search is triggered:

/**
 * Implements hook_search_execute().
 *
 * To provide matching node results based on the node author when searched, again blatantly copied from search.api.php
 */
function my_module_search_execute($keys = NULL, $conditions = NULL) {
  $query = db_select('search_index', 'i',
           array('target' => 'slave'))
           ->extend('SearchQuery')
           ->extend('PagerDefault');
  $query->join('node', 'n', 'n.nid = i.sid');
  $query
    ->condition('n.status', 1)
    ->addTag('node_access')
    ->searchExpression($keys, 'nodebyauthor');

  // Insert special keywords.
  $query->setOption('type', 'n.type');
  $query->setOption('language', 'n.language');
  if ($query->setOption('term', 'ti.tid')) {
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  }
  // Only continue if the first pass query matches.
  if (!$query->executeFirstPass()) {
    return array();
  }

  // Add the ranking expressions.
  _node_rankings($query);
  /*drupal_set_message((string) $query);
  drupal_set_message(var_dump($query->arguments()));
  drupal_set_message((string)$query->countQuery());*/
  // Load results.
  $find = $query
    ->limit(10)
    ->execute();
  $results = array();

  foreach ($find as $item) {
    // Build the node body.
    $node = node_load($item->sid);
    node_build_content($node, 'search_result');
    $node->body = drupal_render($node->content);

    // Fetch comments for snippet.
    $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
    // Fetch terms for snippet.
    $node->rendered .= ' ' . module_invoke('taxonomy', 'node_update_index', $node);

    $extra = module_invoke_all('node_search_result', $node);

    $results[] = array(
      'link' => url('node/' . $item->sid, array('absolute' => TRUE)),
      'type' => check_plain(node_type_get_name($node)),
      'title' => $node->title,
      'user' => theme('username', array('account' => $node)),
      'date' => $node->changed,
      'node' => $node,
      'extra' => $extra,
      'score' => $item->calculated_score,
      'snippet' => search_excerpt($keys, $node->body),
    );
  }
  return $results;
}

Despite being huge even with some additional search hooks missing I believe anything is better an option than hacking core. Hope this helps.


'og:url' meta property displaying wrong path, messing up posting on external sites I'm trying to post a link to a landing page on my Drupal site, like http://me.mysite.com/aboutme. When I post it to Facebook, the link that pops up is to http://me.mysite.com/node/xyz. node/xyz is an actual node on my site, and content from it appears in a panel that's on http://me.mysite.com/node/xyz but it's only like 1/16 of the content of the page, and I have a lot of other panels on that page too. Why is it picking this one? How do I get it to link to the actual page I'm giving the URL for?

Here's a screenshot of my meta tags config:

Assuming your permissions are correct, you can override the settings for anything.

In your case, override Content, and expand the Open Graph section.  Then, you can pick the proper token.  I use [current-page:url:absolute]


drupal get node revision by timestamp I'm building a module that gets the value of a custom field based on a timestamp that a user clicked on it in the past.

To not make it too specific and complex I simplified my question so other users can use this as well.

Basically I'm selecting from the pop_links_stats ( has the timestamp ), node, node_revision, and field_revision_field_custom tables:

$query2 = db_select('pop_links_stats', 'p');
$query2->join('node', 'n', 'n.nid = p.nid');
$query2->join('node_revision', 'nr', 'nr.nid = n.nid');
$query2->join('field_revision_field_custom', 'f', 'nr.vid = f.revision_id');

I already have the $nid so I set the condition to that $nid

$query2->condition('n.nid', $node->nid);

grouping by so it will only select one 'click' per day, per node, per ip ( added the following for the completeness. I need this but it is somewhat unrelated to my question so ignore the groupBy if this is not causing any problems. )

$query2->groupBy('DATE(FROM_UNIXTIME(p.timestamp))')->groupBy('n.nid')->groupBy('p.hostname');

selecting the fields I need ( for now just the revision id) :

$query2->fields('nr', array('vid'));

So my guess is to join the node_revision table and selecting the max vid where nr.timestamp <= p.timestamp and n.nid = nr.nid
OR 'selecting' the max nr.timestamp where nr.timestamp <= p.timestamp

But I'm having trouble implementing that in the drupal DB API

EDIT:

Here's a query I've used in mySQL which gives me the result I want:

SELECT p.cid, FROM_UNIXTIME(p.timestamp), FROM_UNIXTIME(nrev.timestamp), n.nid, nrev.vid FROM pop_links_stats p
JOIN node n ON n.nid = p.nid
JOIN node_revision nrev ON nrev.vid = (SELECT max(vid) FROM node_revision nr WHERE nr.nid = p.nid AND nr.timestamp <= p.timestamp )
GROUP BY DATE(FROM_UNIXTIME(p.timestamp)), p.nid, p.hostname

So what I'm looking for is how to make the join in:

JOIN node_revision nrev ON nrev.vid = (SELECT max(vid) FROM node_revision nr WHERE nr.nid = p.nid AND nr.timestamp <= p.timestamp )

There doesn't seem to be a structured way to shoehorn an advanced join like that into an API query...so you'll probably just have to go manually:

$query = db_select('pop_links_stats', 'p')
  ->fields('p', array('cid'))
  ->fields('n', array('nid'))
  ->fields('nrev', array('vid'))
  ->groupBy('DATE(FROM_UNIXTIME(p.timestamp))')
  ->groupBy('p.nid')
  ->groupBy('p.hostname');

$query->addExpression('FROM_UNIXTIME(p.timestamp)', 'p_timestamp');
$query->addExpression('FROM_UNIXTIME(nrev.timestamp)', 'nrev_timestamp');

$query->join('node', 'n', 'n.nid = p.nid');
$query->join('node_revision', 'nrev', 'nrev.vid = (SELECT max(vid) FROM {node_revision} nr WHERE nr.nid = p.nid AND nr.timestamp <= p.timestamp )');

That produces:

SELECT p.cid AS cid, n.nid AS nid, nrev.vid AS vid, FROM_UNIXTIME(p.timestamp) AS p_timestamp, FROM_UNIXTIME(nrev.timestamp) AS nrev_timestamp
FROM
{pop_links_stats} p
INNER JOIN {node} n ON n.nid = p.nid
INNER JOIN {node_revision} nrev ON nrev.vid = (SELECT max(vid) FROM node_revision nr WHERE nr.nid = p.nid AND nr.timestamp <= p.timestamp )
GROUP BY DATE(FROM_UNIXTIME(p.timestamp)), p.nid, p.hostname


SQL query the Drupal way, complex SELECT, conditional aggregate I'm starting to invest time in learning custom Drupal entities like the ones explained here and I want to make sure that I am going to be able to do something in the future.

I am working with Drupal 7 with MySQL and have the entities API. Being tied to MySQL is okay.

Is it possible to perform a query like the one listed below in Drupal? If not, can I access a MySQL database view?

 select
        `listProducts`.`productId` AS `productId`,

        group_concat(if((`listProducts`.`className` = 'manufacturer'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `manufacturer`,

        group_concat(if((`listProducts`.`className` = 'model'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `model`,

        group_concat(if((`listProducts`.`className` = 'sub model'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `sub model`,

         group_concat(if((`listProducts`.`className` = 'year'),
                `listProducts`.`optionValue`,
                '')
            separator '') AS `year`
    from
        `hqr`.`listProducts`
    group by `listProducts`.`productId`

It's sort of an intense select statement. The data I'm working with is in the form

productId  className      optionValue
---------------------------------------
1          manufacturer   abcCompany
1          model          aModel
2          manufacturer   xyzCompany
2          year           2005

and should come out like

productId  manufacturer  model  sub model  year
-------------------------------------------------
1          abcCompany    aModel    -        -
2          xyzCompany      -       -       2005

Is doing this possible using the Drupal tools? If so, knowing how would be a big bonus too. Somewhere in my travels I saw a Drupal patch to enable group_concat in Drupal views (if that changes anything).

Drupal does not provide database transposition, unfortunately. It's database access system is pretty good at filtering, joining and reordering the data, but not at restructuring them.

There are many patches and hacks for specific task, but none was general enough and needed enough to be accepted into core or views so far.

Your safest bet is to define a view, and then access it just like any other table. Drupal sees no difference as long as you don't write (and if you want to play, you could make MySQL to accept writes, too).


Im using entityforms to make events on a Calendar. How can i prevent duplicated dates? I am developing a Booking System and I am having a issue i.e. How can I prevent duplicate events to be registered ?

Right now I am using:
Calendar and Date for the event management and Entity Form for the booking system.

Users book a date and a time (for example: 09 / 10 / 2014, 14:30 and this is done with the Date field)

The problem I am facing that I don't want to let the users book a date and hour that is already selected. How can I prevent that?

For example: If an user books 09 / 10 / 2014, 14:30, no other user can book for the same date and time. How can i achieve this? Entity Forms has the option to set rules (via the rules module) but my knowledge on rules is not that good. Hope someone could give me a hint. Thanks in advance.

You could do this with Entity Rules, VBO, and Entityform if you are using 2.x(if not should upgrade).

It actually would an advanced Rule but here are the general steps.

Make a VBO View that has date time contextual filter. You would want to return any Entityform Submission that matched.
Make an Entity Rules Validation Rules.
Within Rule check the Number of results of the View from step #1 when you send it the date value of the current Entityform Submission.
If any results are returned then you have found a Entityform Submission that is for the existing date.

You would have to learn how to use Rules, Entity Rules, and VBO.


New site appearing in folder structure after first hit on homepage? This one has me scratching my head.  I'm new to Drupal and am trying to restore a backup of a Drupal 7 site to a 3rd party hosting provider (hostgator as it happens.)

I purchased a business account and domain name to experiment with, and via their interface installed Drupal 7 in the public_html/myaccount subfolder.

I then restored the backup to that same folder.  Beneath myaccount is the typical drupal file structure-- includes, scripts, sites etc.

Beneath the sites folder were subfolders all and default, exactly as restored from the backup and a typical Drupal structure.  But that has changed.

When I browse to www.myhostedsite.com/myaccount I get an unstyled version of my site along with messages on the page that say things like:
Undefined index: highlighted in include() (line 126 of /home4/xyz/public_html/myaccount/modules/system/page.tpl.php).

...and to my surprise, under the sites folder there's now a new folder with the name of the old site, with js and css subfolders beneath it.

How did that appear, and would anyone know what I may be doing wrong?  I've noodled with .htaccess and settings.php values but am not sure I know what to look for in either location (though I did set the database connection correctly in settings.php, I'm pretty sure.)

It would be good if you ask HostGator support guys to assist you through your problem. Got to Support and create a support ticket.


How to alter a form element's properties before rendering? Here's a simple task.

For accessibility reasons, from a custom module I need to perform alterations on textfield based form elements (such as email, textfield, etc ...) on custom forms displayed to front users.

These forms extends the Drupal\Core\Form\FormBase class.

The alterations I need to perform would be for exemple to automatically and programmatically copy the value of the field's placeholder text and put it in the field's title attribute (not the field's label, I'm talking about the HTML title attribute).

So the field's markup would look something like this :

<input type="email" placeholder="Email" title="Email" />

I want to check all custom forms for the entire website.

I tried different methods :

hook_field_widget_form_alter : doesn't fire for fields on custom
forms because they are not widgets.
hook_preprocess_form_element : It's too late to perform these changes. The values just won't take effect on the field.
hook_form_alter : Well it's just too general, I find it a bit dodgy to parse the entire Render Array, check for fields, etc ... but may be it is the only way..

I looked into the Form API, Render API, Plugins API, I looked into services, nothing seems to offer any solution, unless of course I missing something, and I probably do.

Has anyone any idea on how to achieve this in the best Drupal 8 way?

In hook_template_preprocess_form_element the (input-)tags is already rendered.
You can use

function hook/template_preprocess_input(&$variables) {
  $variables['attributes']['title'] = 'my-title';
  $variables['attributes']['placeholder'] = 'my-placeholder';
}

to alter the input tag. use the same method for all other desired tags.
Here's a nice tutorial.

  You could make use of hook/template_preprocess to go a more generic
  way.


High performance DB Cluster with Drupal I am looking for a system where I can cluster MySQL. I saw an article which guided me to custom Drupal schema for NDBCluster engine for MySQL clustering, Btw. I am using Drupal 7 with Varnish, memcache etc.

Drupal MySQL NDBCluster High availability

And I also saw another solution for clustering MySQL using Galera Cluster

(MarinaDB and Percona also uses this for Clustering)
Scaling Drupal stack with Galera

The reason why I need a cluster is because my fields are over 8 kilobytes
There will be a minimum of  15.000 Users visiting the site at the same time.

what is the performance expectations? and what would be the ideal DB to choose?

Galera Replication for Drupal

Things you need to watch out for:

Caching
Sounds like you are using memcached, that good because drupal caching needs to be disabled because if one drupal node modifies the cache stored in the db and that change
replicates the other drupal nodes don't know about it creating conditions in which the drupal cache can serve stale content. Most people use memcached for caching to get around this.
Deadlocks
On websites that are high writes you can incur deadlocks when two drupal nodes try to update the same row at the same time. In this case you would want your app to retry the action but Drupal doesn't always do that. In the Galera settings you can set up some settings in my.cnf (wsrep_retry_autocommit=n) to enable retries at the Galera layer to prevent deadlocks being sent to drupal. Although for a website with low writes and mostly reads you may never encounter the issue.

Other than perf testing a realistic workload I don't know of a formula for performance expectation.

For Galera I've used both MariaDB and Percona. Percona does have additional information it can expose for performance and troubleshooting. Not a lot of difference in how they use Galera replication. I've moved innodb databases between percona and maria and had no issues.

I've found a Percona whitepaper on galera performance and best practices for drupal. It seems to cover all the issues I've encountered plus some additional info: http://www.percona.com/files/presentations/percona-live/nyc-2012/PLNY12-galera-cluster-best-practices.pdf

At this time I would use Percona Galera or Maria Galera. I don't touch mysql from Oracle anymore.

hope that helps


Cannot save any modules Whenever I want to enable/disable modules I am given different errors like the one below. These error messages change every time disable/enable a module.

"Fatal error: Out of memory (allocated 31981568) (tried to allocate 311296 bytes) in /homepages/4/d364988985/htdocs/sites/all/modules/views/modules/node.views_default.inc on line 278"

I have already done the following steps:

created a php.ini file with the following line:

memory_limit = 512M

put it into the Drupal root folder

This fixed the major problem of the whole site showing an error.

The host that I am using is 1and1. Is there a way that this can be fixed?

If you are getting that error is because you are probably using a shared host instance at 1and1, and these instances are mostly better for simple static HTML sites of the kind you would create by hand in Dreamwweaver, for example.

If you are hosting a small Drupal site with a few modules, a small database, and a few visitors, then perhaps 1and1's cheapest (shared host) package will suffice. But as your sites grow bigger, shared host packages tend to not cut it (regardless if they are hosted at 1and1, godaddy, dreamhost, etc).


Taxonomy terms from multiple vocabs on a single line I migrated from Drupal 6 to Drupal 7 and used the same theme, now the "post tags" (taxonomy terms from multiple vocabularies) aren't displayed on the same line as shown below.

How to get these into a single line.

This change in my style.css did the trick :

.node .taxonomy,
.node .field-type-taxonomy-term-reference {
  font-size: 0.8em;
  line-height: 100%;
  display: inline;
  /* padding-left: 1.5em; */
}


Simplenews is not Activated Automatically for Users I'm using Simplenews module for newsletters. My newsletter is set to subscribe users automatically on account creation. However the status remains inactivated after creation.

How can subscriptions be automatically activated?

If you're using the silent option for new accounts, this only automatically activates if you've disabled email verification for new account registration or an admin activates the account (if requiring administrative approval).


Show special roles on user profile I have a little issue on drupal 7. I want a little object/field on the userprofile. This object/field shoud show special roles of the user (special = "admin, moderator ...").
And is it possible that this object comes directly after the username ?

(I am very sorry for my bad english. I hope you understand my question)

So I found a solution that works for me.

Modules used:

Display Suit
Display Suit Extra
PHP filter
(I hope I didn´t forget one)

Here is how I did it ...

1.Go to a Profil

2.Click on "Edit"

3.Switch to the tab "Manage display" (right upper corner of the overlay)

4.scroll down to "custom fields" and click it

5.click "Add a code field"

6.check "User" on "Entities" and change the Text format in the "Field code" to "PHP code"

7.Now type the following in the "Field code" (Add/Change the Roles You have)

<?php $account = user_load(arg(1));?>

        <?php foreach($account->roles as $role): ?>
            <?php if($role != "authenticated user"): ?>
<?php //--------------HERE YOU NEED TO ADD/CHANGE THE ROLES YOU HAVE------------------- ?>
                    <li class="user-role- <?php
                    if($role == '[Your Role]'){ echo 'user-role-[your role]'; }
                    elseif($role == '[Your Role]'){ echo 'user-role-[your role]'; }
                    elseif($role == '[Your Role]'){ echo 'user-role-[your role]'; }?>">
<?php //------------------------------------------------------------------------------- ?>
                    <?php print $role; ?>

            <?php endif; ?>
        <?php endforeach; ?>

Press "Save"

That´s it. I hope it works for You too.

(Again I apologize for my bad English. It can gladly edit for correcting my grammar)


Add more fieldset with remove option custom module I'm developing custom module and there's one fieldset that can be added multiple times and can be removed any particular entry also. Can anyone please suggest to achieve this? Here is my code:

function hook_form($form,&$form_state){
$form_state['storage']['emails'] =
isset($form_state['storage']['emails']) ? $form_state['storage']['emails'] : 0;

$form['emails'] = array(
    '#type' => 'container',
    '#tree' => TRUE,
    '#prefix' => '
',
    '#suffix' => '
',

);
if(empty($form_state['storage']['emails'])) {
    $form_state['storage']['emails'] = 0;
}
for ($j = 0; $j <= $form_state['storage']['emails']; $j++) {
    $form['emails'][$j]['candidate_email'] = array(
        '#title' => 'Email',
        '#type' => 'textfield',
        '#size' => '30',
        '#required' => FALSE,
    );
}
$form['emails']['add_email'] = array(
    '#type' => 'button',
    '#value' => t('Add Email'),
    '#href' => '',
    '#ajax' => array(
        'callback' => 'hook_ajax_add_emails',
        'wrapper' => 'emails',
    ),
);
$form_state['storage']['emails']++;

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

function hook_ajax_add_emails($form, $form_state) {
    return $form['emails'];
}

I got solution by this way. Here is solution code:

$form['emails'] = array(
    '#title' => 'Education Information',
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    //'#size' => '30',
    '#required' => FALSE,
    '#prefix' => '
',
    '#suffix' => '
',
);
if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
}
for ($i = 0; $i < $form_state['num_names']; $i++) {
$form['emails'][$i]['candidate_email'] = array(
    '#title' => 'Email',
    '#type' => 'textfield',
    '#size' => '30',
    '#required' => FALSE,
);
}

$form['emails']['add_name'] = array(
'#type' => 'submit',
'#value' => t('Add one more'),
'#submit' => array('hook_add_more_add_one'),
// See the examples in ajax_example.module for more details on the
// properties of #ajax.
'#ajax' => array(
  'callback' => 'hook_add_more_callback',
  'wrapper' => 'names-fieldset-wrapper',
),
);

if ($form_state['num_names'] > 1) {
$form['emails']['remove_name'] = array(
  '#type' => 'submit',
  '#value' => t('Remove one'),
  '#submit' => array('hook_add_more_remove_one'),
  '#ajax' => array(
    'callback' => 'hook_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper',
  ),
);
}


What is the ideal way to restore a previous version of a site with Backup & Migrate files? So I've been backing up my sites with backup and migrate and I always found weird that the backup&migrate .mysql files are smaller than the "drush sql-dump" sql files. Does anyone know why?

Also what is the quickest way to do a restore using backup&migrate? I usually unzip the gz files that gets saved to my server and just do a mysql drop database and then recreate it again and just fill it in with the sql files. I'm not sure if im doing it the long way or not.

You can restore using backup & migrate itself.

If you've backup and downloaded the file, then you can use Restore tab (/admin/config/system/backup_migrate/restore) to upload the zipped file and restore.

If you've backed up to the Manual Backups Directory, then you can restore from the directory listing (/admin/config/system/backup_migrate/destination/list/files/manual).

There are Drush commands for the above as well, see drush help after you enabled backup & migrate module.


How can I position a logo I absolutely love the Andromeda theme for the site that I am developing, however I have to make use of two logos. The site logo in a standard position (upper left) and a logo for a parent site which needs to be positioned at the bottom right of the footer. How can I do this?

First of all, if you're going to change the theme, it is recommended to make a subtheme first so that updates don't clobber your changes. See Creating a sub-theme for more details.

As one option, the theme will have a page.tpl.php which is used to construct all the pages on your site. You could add your second image here.

Another way would be to add a block and place it in the footer if you really didn't want to modify the theme directly.


Two different views with common URL I want to have an URL which calls a View, for instance:

www.example.com/products

This will be the URL for a View called products_list

If I want to filter the products by category, I could clone the View page, add a Contextual filter based on Taxonomy, and with a URL indicated as /products/% I could use

www.example.com/products/Brand-1

to filter the products of brand "Brand 1".

But what if I want to use a completely different View, with a layout different from the above, for just the special case of some brands, i. e.,

www.example.com/products/Special-Brand

I want the above URL to use a completely different View. How can I manage to do that in the simplest possible way?

Exactly, that is the point. I need just 2 Views, which one shows some
completely different data than the other, and for different kind of
brands. But all of these brands can be grouped in 2 big groups. Now I
solve it by using views_embed_view in template.tpl.php, and using a
View or other in the function via database logics, but I was not sure
if there was an ideal way of doing without "hard code", via Rules,
Context or something.

Here is an alternative.
Create taxonomy terms.
go to   /admin/structure/taxonomy

Add Vocabulary, call it Products
Then click on list terms (/admin/structure/taxonomy/products) and add terms

Brand A with url alias /products/brandA
Brand B with url alias /products/brandB

Then on your actual products content type (lets pretend it's Articles) add a term reference field of Bundle Type: Products.
Then edit your Article and select A or B for that node.
Create 2 block views (one for each type)

under advance, add relationship of terms on node

Then Add a contextual filter of Taxonomy Term Name

Provide Default Value

Fixed Value

Brand A

Then go to blocks, and find your 2 view blocks and configure them.

I only showed A here, repeat steps for B.


How to assign drupal webform to drupal node/block? i am using drupal 6.0 and webform modules to create webforms but i have no idea about asigning webforms to drupal node/block. so please help me and give some ideas and suggestion about this.

I suggest using the Webform Block module. It is stable and compatible with Drupal 6.

  Allows embedding a webform node into a block which can be positioned in any block region (theme space permitting).

  Handles redirecting back to the current page on validation errors.

  A good use for this is to add a site wide contact form inline on your pages, such as in the footer or sidebar.


Menu link to block or div Is it possibile to link menu links to the div or block on the certain subpage? If yes what is the method to do this?

This is not completely straight forward. If you try to create and save a menu link like book/page#anchor-id, Drupal will give this error

  The path 'book/page' is either invalid or you do not have access
  to it.

You will need the node ID. Drupal wants the link to look like this: node/55#block-you-want.

The easiest way to do this is

Save the menu link without the anchor id. ex: /book/page
Drupal will create the menu link like this: node/55
Edit your menu link to: node/55#anchor-id. Save again.


How to map fields from content type to user Profile I am using a content type named application

There are some fields I like to map to the users profile to use them with panels.

For example there are fields called:

name -->textfield
nickman-->textfield
birthday--> date
about-->text with summery
etc

Now I would like to map the content of these fields to the same fields used in the users profile to display the information the users had entered in their applications.

How could I do that? Where to start to find more about field mappings?

Thank you guys and gals!

If you want the content of the fields in application to be saved in the user entity, I can think of a couple of approaches:

Use Rules module to copy the values to the user entity when the application content is saved.
Write a custom module and use hook_node_update() to add the values to the user entity.


How to exclude certain variable from the Feature code? In my Feature I wanted to add the multilingual path_breadcrumbs_home_link_title for en and de, but when generating the feature by including the realm_variables there is the site_name and site_slogan in the en array included too.

The site_name is a mandatory field, so I can not just leave it empty.

The generate file looks like this:

<?php

/**
 * Implements hook_variable_realm_default_variables().
 */
function foo_variable_realm_default_variables() {
  $realm_variables = array();
  $realm_variables['language']['de'] = array(
    'path_breadcrumbs_delimiter' => '»',
    'path_breadcrumbs_home_link_title' => 'Startseite',
  );
  $realm_variables['language']['en'] = array(
    'path_breadcrumbs_delimiter' => '»',
    'path_breadcrumbs_home_link_title' => 'Home',
    'site_name' => 'Demo Site',
    'site_slogan' => '',
  );
  return $realm_variables;
}

The site name would overwrite all the site names of any already deployed Drupal site.

I don't understand why it doesn't appear in the de array even while site name is set there too.

How can I get rid of this?

Any workarounds?

The hook_features_export_alter would allow you to alter the final array of Component names to be exported, just prior to the rendering of defaults.

This allows feature modules a final say in whether or not certain Components are exported.

However the Components' actual data cannot be altered by this hook, so I'm not sure if that actually helps.

Example:

function hook_features_export_alter(&$export, $module_name) {
  // Example: do not allow the page content type to be exported, ever.
  if (!empty($export['features']['node']['page'])) {
    unset($export['features']['node']['page']);
  }
}


How renderable array for an image with style should look like? I have a custom module that outputs some images. Now, I would like to render them properly.

Currently, I use theme() function, kinda similarly to the way shown here1 and here1:

echo theme('image_style', array(
  'path' => $image['uri'],
  'style_name' => 'product_page_thumbnail',
  'attributes' => array(
    'alt' => $image['ImageAlt'],
    'title' => $image['ImageTitle'],
  )
));

Now, the theme() docs says:

  Avoid calling this function directly. It is preferable to replace direct calls to the theme() function with calls to drupal_render() by passing a render array with a #theme key to drupal_render(), which in turn calls theme().

So how would I do that?

I know renderable array for links, it's as simple as:

$link = array(
  '#type'    => 'link',
  '#title'   => $title,
  '#href'    => 'http://example.com',
  '#options' => array('html' => TRUE, 'title' => 'link'),
);

So I want the same, but for images. Somehow I can't find any documented example of it.

1Internal Stack Exchange links, just for reference.

There's nothing specific for images, but there is for any theme function. Your old code using theme() would be equivalent to:

$build = array(
  '#theme' => 'image_style',
  '#path' => $image['uri'],
  '#style_name' => 'product_page_thumbnail',
  '#alt' => $image['ImageAlt'],
  '#title' => $image['ImageTitle'],
);

Basically you pass the named variables for the theme function as #-prefixed properties, and the render system will do the rest.


How can we discover the machine name of $conf keys? This is part of an interview questions and I am not sure. How can we discover the machine name of $conf keys from standard administrative settings forms by inspecting the DOM? (Assume it is in drupal 7)

By literally looking at the DOM.

For a random example, take the aggregate CSS checkbox on the Performance page:

<div class="form-item form-type-checkbox form-item-preprocess-css">
 <input type="checkbox" id="edit-preprocess-css" name="preprocess_css" value="1" class="form-checkbox">
 <label class="option" for="edit-preprocess-css">Aggregate and compress CSS files. </label>
</div>

You'll find the machine name for the variable in the name attribute of the associated <input> element. In this case, preprocess_css.


How to push form values to database in Drupal I am building a drupal site in which I would like the admin to have the ability to input goals into a table on the drupal database that can then be output to other users to be completed.

The form for the input and the table get created, however the values are not added into the table when submit is pressed and I'm not sure why.

I have the following code from the module that I am hooking into my site. I think the problem occurs at the top where I am creating the fields, or at the bottom when I submit the values. I'm really not sure.

Can anyone tell me where I went wrong and how to fix it?

function achievementList_init() {
if(!(db_table_exists('achievements'))) {
    $achvmnt_list_schema = array(
        'description' => 'Achievement Fields',
        'fields' => array (
            'achvmntID' => array('type' => 'int', 'unsigned' => TRUE, 'AUTO_INCREMENT' => TRUE, 'not null' => TRUE),

            'achvmntName' => array('type' => 'varchar', 'length' => 256, 'not null' => TRUE, 'default' => ''),

            'achvmntDesc' => array('type' => 'varchar', 'length' => 256, 'not null' => TRUE, 'default' => ''),

            'achvmntPts' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE),

    ));
    db_create_table('achievements', $achvmnt_list_schema);
}
}

function achievementList_menu($form, &$form_state) {
$items = array();
$items['achievementList/addAchievement'] = array(
    'title' => 'Achievement Input',
    'description' => 'Input Achievement info to add achievement to database',
    'page callback' =>'drupal_get_form',
    'page arguments' => array('achievementList_form'),
    'access callback' => TRUE
);
return $items;
}

function achievementList_form($form, &$form_state) {
$form['name'] = array (
    '#type' => 'textfield',
    '#title' => 'Achievement Name',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['description'] = array(
    '#type' => 'textfield',
    '#title' => 'Achievement Description',
    '#size' => 50,
    '#maxLength' => 400,
    '#required' => TRUE

);
$form['points'] = array(
    '#type' => 'textfield',
    '#title' => 'Point Award',
    '#size' => '20',
    '#maxlength' => '20',
    '#required' => TRUE
);
$form['add_button'] = array(
    '#type' => 'submit',
    '#value' => t('Add Achievement')
);
return $form;
    }

function achievementList_validate($form, &$form_state) {
$name = $form_state['values']['name'];

if($form_state['values']['name'] = '') {
    form_set_error('name', t('Achievement must have a name!'));
}
if($form_state['values']['description'] = '') {
    form_set_error('name', t('Please describe the achievement!'));
}
if(!($form_state['values']['points'] > 0)) {
    form_set_error('name', t('Achievement must be worth points!'));
}
}

function achievementList_submit($form, &$form_state) {
db_insert('achievements')
->fields(array(
'achvmntName' => $form_state['values']['name'],
'achvmntDesc' => $form_state['values']['description'],
'achvmntPts' => $form_state['values']['points'],
))
->execute();
}

You're not far off, a couple of things:

Creating a table like that in an init hook is definitely not recommended; Drupal provides hook_schema() so you can describe tables to the system. Uninstall and install your module again after implementing it and you'll see the table appear.
The reason your insert is failing is because you have a NOT NULL integer field which you're not providing (achvmntID). Drupal has the serial field type rather than an AUTO_INCREMENT key to get a serial field:

'achvmntID' => array(
  'type' => 'serial',
  'unsigned' => TRUE,
  'not null' => TRUE,
),


Member for - how Drupal 7 calculaties and formats duration? Drupal 7 has ability to show since how long someone is member, like this:

  Member for 2 months 21 hours

What date field it uses to save the registration date/time?
How it calculates and displays this duration? And can't we use same module / method to calculate duration from our date (in node) and display in our views?

I am really in need of this functionality of calculating of duration, I am using views Calc and subtracting end-date from start-date and dividing it with number of seconds in day to get number of days between two days. but not satisfy besides don't know why can't subtract now() from a given date field in views calculations.

$account->content['summary']['member_for'] = array(
  '#type' => 'user_profile_item',
  '#title' => t('Member for'),
  '#markup' => format_interval(REQUEST_TIME - $account->created),
);

It's in function user_user_view($account). And yes, of course you can use format_interval($interval) function in other places.


Views contextual filter not working for Pathauto path Im using Pathauto so set aliases for taxonomy terms.

So this:
/taxonomy/term/1

Is the same as this:
/custom-term-url

Im using Drupals default Taxonomy term View to control the layout of the term page. This works fine for both of the paths.

Ive created an additional page in this view with a path of /taxonomy/term/%/something and an additional filter so show different results.

When I go to this page everything works perfectly:
/taxonomy/term/1/something

However this returns a page not found:
/custom-term-url/something

How can I get my View working with the Pathauto URL?

Install Global Redirect module, this module create a unique form of all of the aliases. I am not able to test this solution of your problem But I guess it may solve the problem.


Override breadcrumbs is not present? In Drupal 7, in the views with an argument, is easy to override both title and breadcrumbs.

Now in Drupal 8 I can't find the option.

Did I miss something? or isn't possible? In this case what is the workaround?

I had came to this thread as we also require this feature. Could not find a satisfactory solution anywhere. Prepared a patch for views module and submitted at https://www.drupal.org/project/drupal/issues/3156711#comment-13732219
Posting here as somebody might find it useful.


Spam users on drupal7 site being created automatically I need some urgent suggestion. In my live site a lot of spam users are being created every few minutes. I will install captcha and MOLLOM but I need to delete the spam users. How can I identify them and how do I prevent this from happening again?

Please advice

How to prevent it from happening you already know:

Anti-spam tools like Mollom
Captcha

For mass deletion, use Views to list them:

Create a new users view (add new view, show: "Users"),
add relationships you feel will be helpful to identify spammers, like "User: Content authored".
add filters based on these relationships, like

Created unreasonably high amount of content or no content at all,
only users with account younger than the spam wave,
et cetera;

use VBO to actually delete unwanted ones - just check them, or use select all and uncheck good guys. Of course good filters will reduce number of good gu


Node Teaser Acting like Full Node I have got a problem.  I have been upgrading my site from Drupal 6 to 7 and I've reached about 75% of the way.  I have updated all my 3rd party modules and custom modules and while I was configuring some setting for my 3rd party modules, like Taxonomy Image, I noticed that in my front page the teasers where displaying a view that I wanted to embed only in the full node view.

I looked at my node.tpl.php, which is where I was adding the view and the if/else for the view looks good, but for some reason, when I debugged it, the if ($teaser) is not the one that it is going to when I load the front page, it is actually going to the else.

This is the code in my node.tpl:

    <?php if (!empty($content['links'])): ?>

<?php print render($content['links']); ?>

    <?php endif; ?>
        <?php if($teaser): ?>
            <?php print render($content['comments']); ?>
        <?php else: ?>

                <?php print render($content['comments']); ?>
                <?php $related_by_term_block = block_load('views', 'related_by_term-block_1');
                    $block_content = _block_render_blocks(array($related_by_term_block));
                    $build = _block_get_renderable_array($block_content);
                ?>

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

        <?php endif; ?>

I have no idea if any of the 3rd party modules I have are getting in the way.  This is the list of my 3rd party modules:

FLAG
DATE
CAPTCHA
MOLLOM
ADVANCED HELP
BETTER FORMATS
FLAT COMMENTS
FORWARD
SEARCH CONFIGURATION
SHARED EMAIL
VOTING API
WYSIWIG
AUTHOR PANE
PUBLISH CONTENT
WORKFLOW
THEMEKEY
CHAOS TOOL SUITE (CTOOLS)
VIEWS
ENTITY API
VIEWS BULK OPERATIONS (VBO)
VIEWS ATTACH (EVA)
SIMILAR BY TERMS
ADVANCED FORUM
RULES
LIBRARIES API
GRAMMAR PARSER
GRAMMAR PARSER LIBRARY
HTML PURIFIER
TOKEN
INVITE
FIVESTAR

Any input would be greatly appreciated.  Thanks.

It is the Advanced Forum module that is causing the problem.  Once I disabled it, it displayed as a teaser.  Now, I need to figure out just why.  Thanks for your help, Alex, really appreciate it.


Creating facets for custom contents added by CCK in apache Solr module I was unable to create Facet for a CCK field, in the sense that for a specific CCK content type i was unable to group.

This could be summarised as my problem statement

Ex. CCK Field - Article Author

Actual Result :
No Group (No of Search Records)
Expected:

Author 1 (2)
Author 2 (5)

etc....

This is my primary concern, I need to create facet for the custom content types.

Please let me know if any of you have previous experiences with implementing Apache Solr for Drupal. Also let me know your kind suggestions and feedback.

My drupal version is 6.22.

Note: Based on my googling experiment i set the CCK field type in question as text and not string but still didn't help me much.

I was finally able to get this done with good assistance from one of the module's maintainer.. This is the issue list query comprising further details and some sample code. Hope this servers of some help to anyone using solr search.

Cheers!!


How to get field values in node template in Twig I have an image field named Gallery. You can add multiple images in this field. It’s in a content type named Gallery with Captions.

I have a twig template named field--node--field-gallery--gallery-with-captions.html.twig. Within that, I have the following, so that I can use the title and alt fields as content:

{% for item in items %}

 {{ item.content }}
{{ item.content['#item'].title }}

{{ item.content['#item'].alt }}

{% endfor %}

This all works great! Except when I want to use a different Display for this where it’s related to another entity type. There are two template hints I can use there:

node--gallery-with-captions--teaser-complementary.html.twig

field--node--field-gallery--gallery-with-captions.html.twig

I don’t want to use the latter, because I've already configured that for the full gallery/node page and in this case a) I only want to output the first image as a thumbnail to link to the gallery and b) I don’t want the title or alt. The node template has the right display type, but I’m struggling with digging into a) the first image in the gallery and b) the fields I want.

Any suggestions on zeroing in on the first image in this field displaying it as just the image linked to the entry? The template debug suggestions aren't suggesting a field template by display type, which is where this would ideally reside.

A teaser image linked to the content is the standard configuration for the teaser view mode. You only need to limit it to one image. This is a feature request for core, see this issue https://www.drupal.org/node/1234624. Until then you can use this sandbox project: https://www.drupal.org/node/1234624#comment-11868691.

If you want to do this in a node twig you can get the first field item with the delta 0:

{{ content.field_image.0 }}

and then remove the field from the main content to avoid double content:

{{ content|without('field_image') }}