Drupal 7 + Solr - Importing feeds after website restore leads to 1062 Error I’m developing on localhost, using Drupal 7 with the Search API with Solr module. After performing a restore from backup, I needed to reimport several items from a feed. I set up my feed importers, using the Node ID as the unique target. However, after conducting the import, it always returns failure. The error report is a long list of:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '62911-1' for key 'PRIMARY'

(The Duplicate entry number is different for each line.)

There are no nodes or actual content on the site, which leads me to believe that it is something in the database. Could be wrong, though.

I have done the following things to try and rectify this problem, with no luck:

Changed “Do not replace existing nodes” to “Update existing nodes” in
the Node Processor settings.
Changed “Update existing nodes” to “Replace existing nodes” in the
Node Processor settings.
One search made me realize that my Solr server wasn’t automatically
starting, so I did that and then ran the import; no luck.
Rebuilt user node access permissions.
Installed “Delete All” module and deleted all content, resetting the
node id counter from 1.
Cleared the Solr index from within Drupal.
Deleted all items from within the Solr core itself (although the
Index status page at
admin/config/search/search_api/index/default_node_index still has
“172/60857 indexed” under the status bar. This was the only partial
success, as it managed to import 172 items, but the rest still
received the error.)

Not sure where the problem is. I suppose I could just try and use GUID as the unique target, but I don’t know if that will work. (I’d also like to keep using the Node ID if possible.) I could also try to completely remove the Solr module from Drupal 7 and trying again, which I think will be my next step. However, I am really looking for any thoughts on this. Have any of you encountered this problem before? What have you done to fix this?

It turned out it was the Solr module itself. I'm not sure why it wasn't clearly it's index completely, but after disabling and actually removing the module, then reimporting, everything worked.

So if you're having this kind of trouble importing content, and you have the Search API Solr module active, first disable and then remove it so that you have a clean slate on that end. Then you can reimport the content, then later re-add the Solr module and reindex your content.


Adding validator to a number of fields I have a number of fields added to multiple content types. Using the Field validation module takes much time, so I decided to validate them programmatically. Which hook should I use to validate fields?

You'll need to add a hook_form_alter(), check the form ID matches one of those that you're interested in, then add a validation handler to the form. The validation handler will perform your validation against the form fields. Something like

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form_ids = array(
    'article_node_form',
    'page_node_form'
  );

  if (in_array($form_id, $form_ids)) {
    $form['#validate'][] = 'MYMODULE_field_validate_callback';
  }
}

function MYMODULE_field_validate_callback($form, &$form_state) {
  if (empty($form_state['values']['field_x'][LANGUAGE_NONE][0]['value'])) {
    form_set_error('', 'Field X cannot be empty.');
  }
}

I don't know of another way to do this as hook_field_validate() is only called for the module that implements the field type.


remote DB for remote servers with Aegir I am working to install Aegir on an AWS EC2 instance (Amazon AMI) using an RDS mysql database. So basically a virtual box with a remote DB server.
I am using the manual procedure and am running into problems at the hostmaster-install phase.
The remote mysql server is correctly identified and the logon is accepted but the install fails.
Here is the command I am running:

drush hostmaster-install --aegir_db_user="root" --aegir_db_host="the_FQDN_of_the_remote_DB_server"

Install starts great but the starts giving warnings and errors which obviously have to do with problems running MySQL commands. Here is a small excerpt:

MySQL server has gone away                                                                                [warning]
query: SELECT filename FROM system WHERE name = 'jquery_ui' AND type = 'module' database.mysqli.inc:134

MySQL server has gone away                                                                                [warning]
query: CREATE TABLE variable (
name VARCHAR(128) NOT NULL DEFAULT '',
value LONGTEXT NOT NULL,
PRIMARY KEY (name)
) /*!40100 DEFAULT CHARACTER SET utf8 */ database.mysqli.inc:134

I noticed that the database was not created, so any table attempts will also fail.
The question is why is the database not created? I am not getting any clear output indicating this. I ran the command with the --debug option, but did not get any additional information to point out why it is failing.

Amazon Web Services (AWS) RDS service does put some limitations on the "root" user. For instance it does not have the "SUPER" privilege and also does not have the "CREATE TABLE SPACE" privilege. Could these be a reason fro the failure?

Where can I see what exact SQL commands are being run? I would like to try and run them manually to debug this issue.

Of course if anyone out there has successfully installed directly on to AWS with RDS as a remote DB, I'd love to know how.

Thanks, Eric

You're getting the error "MySQL server has gone away". Usually when this happens during Drupal installation, it's related to MySQL's max_allowed_packet setting. I'd recommend bumping that value up to 32MB. The process for changing that value on Amazon RDS is detailed here: https://survivalguides.wordpress.com/2012/02/02/change-the-max_allowed_packet-amazon-rds/


Remove link from active page in menu I need the active page in my menu not to be a link.

So let's say I'm on the services page, I need my menu structure to look like this:

home

services

portfolio

contact

How can I do that?

You need to override the theme_link function.
In your template.php file add this. (changing THEME to the name of your theme).

function THEME_link($variables) {
  if ((isset($variables['path']) && ($variables['path'] == $_GET['q'] || ($variables['path'] == '<front>' && drupal_is_front_page())))) {
    // Return text instead of link if current menu item active
    return ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text']));
  } else {
    return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
  }
}


Drupal 6 import/export book I'm looking for a module to export/migrate a books (with all child pages) from a Drupal ( 6.x) Installation to another.

Thank you in advance for your kind replies

The module Migrate is the most versatile Drupal tool for database migration.

However, book module migration is still not trivial.  Books are nodes, so they can inherit most of their migration from a common class.  But to preserve book node hierarchy that is stored within menu links, you need to use special code  to migrate the hierarchy.  Here is a sketch of the required workflow:

Migrate nodes as normal.
Get hierarchy from the source database book table, and weights from the menu_links table.
Place a public function complete() in your Migration class to call _book_update_outline() to migrate the hierarchy.

A more detailed receipe, with a special code example, is at Drupal.org: Book node migration.


How Change the Style of views based on user option I have a set of products into grid view. I need to create a two tabs one for grid view and list view(swipe view). How to create like this using views in drupal 7?

Sounds like this will need to be done programmatically.

Use hook_views_pre_render() to be able to change the settings of a view based on certain conditions.

https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7

Then using the global $user definition to lookup the logged in user, use that to create a condition and alter the settings of the actual view.


How do I programmatically add a field to a Transaction in Drupal Commerce? I am attempting to add a field to the entity commerce_payment_transaction.  However, when I check the database after installation which should create the field, there is no field_data_ created, nor is there any field on the entity commerce_payment_transaction.  I have successfully used code similar to the following to create field on the Commerce Order.  Do I have the bundle wrong for the instance?

Here is my code.

During the install, I create the field and its instance.

function commerce_stripe_connect_c_install_install() {

$field_info = field_info_field('tr_vendor_user_reference');

$field = array(
        'field_name' => 'tr_vendor_user_reference',
        'type' => 'user_reference',
        'cardinality' => 1,
        'entity_types' => array('commerce_payment_transaction'),
        'translatable' => FALSE,
        'settings' => array(
                //must have the referenceable_status defined or the user reference won't work
                'referenceable_status' => array(
                        0 => 0,
                        1 => '1',
                ),
        ),

);

if (empty($field_info)) {
    field_create_field($field);
}

$instance = field_info_instance('commerce_payment_transaction', 'tr_vendor_user_reference', 'payment_method');

//I check if the vendor_user_reference has already been created on the commerce_product
if (empty($instance)) {
    $new_instance = array(
            'field_name' => 'tr_vendor_user_reference',
            'entity_type' => 'commerce_payment_transaction',
            'bundle' => 'payment_method',

            'label' => t('Transaction Vendor User Reference'),
            'required' => TRUE,
            'settings' => array(
                    //This is required so that vendors will be available for programmatically selecting
                    //for a product
                    'referenceable_status' => array(
                            0 => 0,
                            1 => '1',
                    ),

                    'view' => array(
                            'args' => array(),
                            'display_name' => '',
                            'view_name' => '',
                    ),

            ),
            //The widget will not show up because it is hidden later on, but this is needed so that
            //a default value can be chosen
            'widget' => array(
                    'active' => 1,
                    'module' => 'options',
                    'settings' => array(
                            'apply_chosen' => '',
                    ),
                    'type' => 'options_select',
                    'weight' => '40',
            ),

            'display' => array(),
    );
    field_create_instance($new_instance);
}

The payment transaction entity type isn't field-able (see commerce_payment_entity_info()).

But you can change that with hook_entity_info_alter():

function MYMODULE_entity_info_alter(&$info) {
  $info['commerce_payment_transaction']['fieldable'] = TRUE;
}


On feeds, how to access ORGANIZER source I'm importing an iCal feed using iCal Parser. I've actually tried a few other parsers including Date API iCal parser, iCalCreator parser, but every one seems to have the same set of sources. How can I access all the other fields in the feed, specifically, the ORGANIZER: ORGANIZER;CN=name@email.com:mailto:name@email.com?

I've tried to hook into hook_feeds_parser_sources_alter, and setting up a new callback function. Like this:

/**
* Implements hook_feeds_parser_sources_alter().
*/
function my_hook_feeds_parser_sources_alter(&$sources, $content_type) {
$sources['field_importer_reference'] = array(
'name' => t('Organizer'),
'description' => t('The name of the organizer.'),
'callback' => 'my_hook_get_organizer',
);
}
function my_hook_get_organizer(FeedsSource $source) {
dpm($source->CN);// this doesn't do anything...
return $source->CN;
}

I get this message when I try to import: Date iCal does not recognize the "Organizer" Mapping Source, and must skip it.

In writing the question I came across the answer and want to share. I was using the wrong hook. Instead I used:

function my_hook_date_ical_mapping_sources_alter(&$sources) {
// Add the "ORGANIZER" iCal property to the mapping sources.
$sources['ORGANIZER'] = array(
'name' => t('Organizer'),
'description' => t('The ORGANIZER property.'),
'date_ical_parse_handler' => 'parseTextProperty',
);
// Add "ORGANIZER:CN" parameter to the mapping sources.
$sources['ORGANIZER:CN'] = array(
'name' => t('Organizer: CN'),
'description' => t("The CN parameter of the ORGANIZER property: the organizer's Common Name."),
'date_ical_parse_handler' => 'parsePropertyParameter',
);
}

Note that I'm pulling both the Contact's Name and the mailto field.

This is a hook provided by the date_ical module. I basically copied the example found there.


Commerce Discount Module : Free Products : n+x Is someone using commerce discount module and customized free products quantity field for buy x and get y functionality ? If i set buy 1 get 1(free product qty) its not multiplying while user updating quantity on cart.for ex-

I added 1 product = 1 qty.if user increase product qty with 2,its remaining same.like 2 = 1

Buy X Get Y offers (or "Per quantity" offers) are supported out of the box in the Commerce Discount Extra module, which we'd like to merge into Commerce Discount eventually:

https://www.drupal.org/project/commerce_discount_extra


Update a cck field value of a node I have a cck field in a node. I bring this value out in some other form and alter its value, But i am unable to save it back to DB. How should i write it back to table such that node changed date also gets changed. please show some code for this.

You can use node_save() to do this; CCK will automatically hook into it and update the field values in the database for you:

// Load a node
$node = node_load(1);

// Update the field value
$node->field_field_name = array(0 => array('value' => 'A value'));

// Save the node. Field values are also saved, and the node modified time is updated.
node_save($node);


How can I programatically add the default AJAX throbber to a form submit? I'm trying to add the AJAX throbber in core to a form submit button, specifically the Private Message module new message page.

Here is my code:

function MYMODULE_form_privatemsg_new_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#ajax'] = array(
'callback' => 'MYMODULE_submit_throbber_callback',
  );
}

function MYMODULE_submit_throbber_callback($form, $form_state) {
  return;
}

Here's what I have done so far.

First, I looked at the Page Throbber module for ideas, but this does everything in hook_init(), and it doesn't use the throbber included in core.  If possible, I want to avoid replicating what is already in core for a single form.

Next, I looked in the Examples module, specifically the AJAX example that includes an AJAX submit example.  However, this is for adding a callback to do something else, but all I want to do is get the pager, which appears to happen automatically if you add any kind of callback.

So I added a dummy callback that just returns.  This gives me a throbber, but it breaks the submit functionality of the form.  How do I get the throbber without breaking the form submit?

It should be easily done like this:

$form['submit']['#ajax'] = [
  'callback' => 'MYMODULE_submit_throbber_callback',
  'progress' => [
    'type' => 'throbber',
    'message' => NULL,
  ],
];

And then return $form in the callback;


How to get view name and display ID in template_preprocess_node function I'm having some trouble in order to get a view's name and the display ID in a template_preprocess_node function.
I have a custom content type and a view with two different displays.
My idea is to define a variable in the preprocess function related to the content type (using theme_preprocess__content_type_name function), in order to use this variable in the Twig template to switch between the displays, according to the number of results.

I understand that in order to use a variable in the preprocess function, it has to be defined somehow in the template (correct me if I got this wrong).
So my question is: how can I call the view and the display in the node preprocess function?

EDIT 1:
Using Hudri suggestion:

function theme_name_preprocess_node__content_type(&$variables) {

    $route = \Drupal::routeMatch()->getRouteObject();
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    if($view_id == 'view_name' && $display_id == 'display_name'){
        $counter = count($view_id->result);
        $variables['count'] = $counter;
    }
}

Can the variable count be used in the Twig template in an if clause?

I'm assuming you're using a view page to display your content type:

$route = \Drupal::routeMatch()->getRouteObject();
$view_id = $route->getDefault('view_id');
$display_id = $route->getDefault('display_id');


Custom module with its own menu block I am trying to create a module that supplies a custom menu block, that changes based on what organic group you are looking at. I'm confused by the documentation, so I thought I'd ask here. I saw an answer for Drupal 7, but I'm using Drupal 6.

og_menu doesn't work for me because I don't want group admins to change it. I just want the default to be dynamic based on some logic of my own.

Specifically, should I supply a custom block from my module? If so, how do I render the list of links I create, or should be supplying a custom menu? What hook do I use?

Sounds like you'd really want to supply a hook_block, whose $content will call a custom PHP function that will construct your array of links to other organic groups, based on your criteria.


Need a list of third party video services that i can offload the conversion and serving up of my private videos? Can anyone help me to narrow down a list of third party video services that i can offload the conversion and serving up of my private videos?

Requirements are:

Already have a Drupal 6 module that integrates the api (Also has a D7 future)
Must allow the video to only be viewed on my Drupal site. Not on their site (e.g. not viewable on YouTube)
HTML 5/Flash fall back (would be nice, but not necessary.

Try these:

ZenCoder
Bits on the Run
Kaltura

with Video module


Cannot Login After Drupal 7 migration Sorry, unrecognized username or password. Have you forgotten your password?

The error above shows even though I have inputted correct credentials in my site(192.168.5.141/doc_monitor). Below are the steps I have tried to solve my problem.

Reset my password in Drupal users table using md5 hash.
Verify mod_rewrite is enabled. mod_rewrite module is loaded as I can view it in phpinfo()
Verify RewriteBase rule in my .htaccess

RewriteBase /doc_monitor
Repair/Truncate sesssions table.
Set (doc_monitor)drupal files to 777 permission.
Run update.php
Clear browser cache and drupal table cache;
Truncate flood table.

I always restarted my Apache in every changes I made. Anymore suggestions? I dont know what to do anymore.

First thing to do to see if the login is functioning is use drush uli, which will create a login link for user 1. If that works, after logging in, set your password to test123. Logout, then try to log in with that.

You can also set the password with drush, trying to edit the md5 hash etc is not reliable.

https://drushcommands.com/drush-8x/user/user-password/

This doesn't have anything to do with the files directory.

Another thing to do is check your settings file just to ensure you are talking to the right database. Also check the database to see if the user you are logging in as is not blocked (status).

If you had previously set cookie domain in the settings file, verify that the value is correct.


How to limit the number of comment a user can post? I have a content type where users can post reviews or comments.
I want to achieve this with the comment module and not by creating another content type and using node reference.

So I want to limit the number of comment a user can post per node for a specific type of content type.

Again I also have other content types where I have given the users the option of commenting on article, and that can have multiple comments and replies.

Can anyone suggest me how to achieve this?

Can I do it through rules(I haven't tried yet)?

You could add a validate handler to the comment form

e.g, something like:

/**
 * hook_form_FORM_ID_alter
 */
function MODULE_form_comment_form_alter(&$form, &$form_state, &$form_id) {
  $form['#validate'][] = 'MODULE_comment_form_validate';
}

/**
 * Validate comment form submission
 */
function MODULE_comment_form_validate($form, &$form_state){
  $node = node_load($form_state['values']['nid']);
  if(isset($node->type) && $node->type = 'targetted_type'){
    $account = user_load_by_name($form_state['values']['name']);
    if(!empty($account->uid)){
      // Get comment count for this node type
      $query = db_select('comment', 'c');
      $query->join('node', 'n', 'n.nid = c.nid');
      $query->condition('c.uid', $account->uid);
      $query->condition('n.type', 'targetted_type');
      $query->countQuery();
      $comments = $query->execute()->fetchField();
      if($comments > variable_get('max_comments_targetted_type', 3)){
        form_set_error('name',
          t('You are only allowed to post %max comments on this type of content.', array('%max' => variable_get('max_comments_targetted_type', 3))));
      }
    }
  }
}


Theming forms on alter with Drupal 7 I'm having issues customizing a radio button for a specific form using hook_theme.  Below is the piece of code I have on my module; see my comments elaborating the issue I encounter:

// Implementation of hook_form_alter().
function mymodule_form_alter(&$form, $form_state, $form_id){
  // e.g form id: commerce_cart_add_to_cart_form_u6onPJSgS7pOgw0Tlo7zHy42LTQzbV913taANkYQKTo
  if (strpos($form_id, 'commerce_cart_add_to_cart_form') !== FALSE) {
    // Alter add to cart form
    mymodule_commerce_cart_add_to_cart_form_alter($form, $form_state, $form_id);
  }
}

function mymodule_commerce_cart_add_to_cart_form_alter(&$form, $form_state, $form_id) {
  // Change the field type to radios.
  $form['attributes']['field_artwork_ref']['#type'] = 'radios';
  // Apply my custom theme for radios.
  $form['attributes']['field_artwork_ref']['#theme'] = array('custom_radios');
}

// Implementation of hook_theme().
function mymodule_theme() {
  return array(
    'custom_radios' => array(
      'variables' => array('element' => NULL),
    ),
  );
}

function theme_custom_radios($variables) {
  // Custom theme should go here.
  // However, $variables are empty, print_r gives me "Array ( [element] => )."
  // I am at least expecting to see my radio element here.
  print_r($variables);
}

I found this answer for Theming forms on alter with Drupal 7 on Stack Overflow:

  Themes for Drupal 7 form elements need to use the new render array key instead of variables in the theme definition:

function mymodule_theme() {
  return array(
    'custom_radios' => array(
      'render element' => 'element',
    ),
  );
}

  Once you've made the change, clear Drupal's caches and your code should work (I've just tested the above and it works fine).


How to display a node in overlay popup effect? I have a content type 'students' with fields name, description and a photo. I have created a view(Block) to display only the images of the students. When the teacher/user clicks the photo of the student, It must show up the name, description and the photo of the student in a overlay/lightbox effect.

I have tried using Lightbox2 and colorbox node module to achieve as per my needs, But needed up in failure. Any help is widely appreciated.

Thanks.

Let me answer my own question. Based on j2r's comments and http://drupal.org/node/1378438 question from this node I was able to solve my issue.

Create href as node/nid/lightbox and rel as lightframe. This will result in displaying the whole page in the lightbox. To avoid this U need to create a page--contenttype.tpl.php (In my case) http://www.digett.com/blog/01/11/2012/overriding-page-templates-content-type-drupal-7 and then remove the header, footer and other unwanted regions in the page.

Once this is done I am sure u will get as what I got.


How to show warning and list of related content I'm working with Drupal and I wanted to show users that the included URL in post has already been submitted when they click preview

Use the Unique field module:

  This module performs additional validation when a node is created or
  updated by a user to require that a node's title, author, language,
  and CCK fields are unique within a given context.


After upgrade from OG6 to OG7 directly to ver. 2.x: Is there any possibility to use OG migrate (available only in OG 1.5)? I´ve realised that OG Migrate is only in 7.x-1.5 but NOT in OG 2.x.

I´ve accidentally updated my site from D6 to D7 directely to OG 2.x.

Is there anything I could do to use OG migrate?

For OG 7.x-2.2, the migrate functionality is now coming with the OG module itself. No additional module is needed. Documentation can be found here:

Migrate: Contributed module support: Organic Groups

Which means the functionality is no longer in migrate_og (where it was for OG 6.x-1.x) and also no longer in migrate_extras (where it was, I think, for OG 7.x-1.x).


Gmap Views - Proximity filter for user locations based off of a specific node location I am trying to build a view that shows the location of any users that are within a certain radius of a node's location. I can get a specific node's location to show up using its nid as the argument, and I can get the users' locations to show up (content profile location), but I can't get BOTH to display on the same map.

I'm thinking the problem is that I only have one option for the datatype that views uses to generate the markers. I've also tried displaying the node's marker through a gmap macro, but when view is displayed, the marker information from the macro is gone, and only the locations rendered by the view's fields are displayed.

This is really a Views question. You can specify a Relationship and a Contextual Filter under the Advanced tab in Views.

I don't know the specifics for Gmap Views, but the principle is the same: You'd make a view of users, with a contextual filter of content:NID. Then you'd create a relationship to nodes based on the location. Gmap Views might give you a way to say 'within x miles of'... This is Views' way of creating a JOIN query.

Then on your content you'd add a Viewfield and tell it to pass the NID to the view. This will attach the view to your node and generate the view of users nearby.

Helpful tutorial about relationships here. Start at about 1:00 if you're impatient. :-)


Help with a db_select() not returning results when it *should* I'm having trouble figuring out why the db_select() is not returning any results.  Long story short, if I pass the results of $results->execute() through a foreach ($results as $result), I don't get any results.  If I take the generated SQL and go directly to command line or phpMyAdmin (substituting manually for the placeholders) I get the expected result.  I feel like I have to just be overlooking something - I'm hoping fresh eyes can point it out for me.

Here is the select:

$results = db_select('product_charges_override', 'pc');
$results->join('products', 'p', 'p.product_id = pc.product_id');
$results->fields('pc', array('uid', 'product_id', 'override_count', 'redemption_count', 'coupon_code'))
  ->fields('p', array('human_name'))
  ->condition('pc.coupon_code', $coupon_code);
$results->execute();

Here is the result of dpq($results):

SELECT pc.uid AS uid, pc.product_id AS product_id, pc.override_count AS override_count, pc.redemption_count AS redemption_count, pc.coupon_code AS coupon_code, p.human_name AS human_name FROM {product_charges_override} pc INNER JOIN {products} p ON p.product_id = pc.product_id WHERE (pc.coupon_code = :db_condition_placeholder_0)

Here is the relevant Where statement from just var_dump($results):

protected 'where' =>
  object(DatabaseCondition)[136]
    protected 'conditions' =>
      array
        '#conjunction' => string 'AND' (length=3)
        0 =>
          array
            'field' => string 'pc.coupon_code' (length=14)
            'value' => string 'ugd2pl8z92j9' (length=12)
            'operator' => string '=' (length=1)
    protected 'arguments' =>
      array
        ':db_condition_placeholder_0' => string 'ugd2pl8z92j9' (length=12)
    protected 'changed' => boolean false
    protected 'queryPlaceholderIdentifier' => string '52e7fdf78bbd25.63959182' (length=23)
    public 'stringVersion' => string ' (pc.coupon_code = :db_condition_placeholder_0) ' (length=48)

And, finally, the query as I run it from the command line (notice the '{' and '}' have been removed, as well as the placeholder replaced with the value from the 'where' object). Those are the only things I replaced from the results of dpq().

SELECT pc.uid AS uid, pc.product_id AS product_id, pc.override_count AS override_count, pc.redemption_count AS redemption_count, p.human_name AS human_name FROM product_charges_override pc INNER JOIN products p ON p.product_id = pc.product_id WHERE (pc.coupon_code = 'ugd2pl8z92j9')

And an export from phpMyAdmin of the query results:

/**
 * Export to PHP Array plugin for PHPMyAdmin
 * @author Geoffray Warnants
 * @version 0.2b
 */

 //
 // Database "mats_theme"
 //

 // mats_theme.product_charges_override
 $product_charges_override = array(
       array('uid'=>null,'product_id'=>7,'override_count'=>5,'redemption_count'=>0,'human_name'=>'Fleet Forum Registration')
);

I'm not assigning $results->execute() to anything - that's why I can't iterate over the results.  Answer was provided by a local mailing list that I sent this link to.

So, solution is $results = $results->execute().  Of course, the query should be renamed to something like, $query;


Creating menu items for views during installation of a custom install profile fails I have created a custom installation profile in which I enable some default features and modules. In the profile I added an extra task at the end in witch I enable a custom deployment module.

That deployment module I then use to enable all project specific stuff. I do this using update_N functions and a script that runs through all the updates on installation of the deployment module.

One of the last updates contains the activation of some features that have a view with a page in code, each with a path but no menu item. I need those menu items but I don't put them in the view to prevent that the view is marked overridden when a user decides to change the menu title of a menu item.

That's why I run another script in a following step that creates default menu items for each view using the menu_link_save function.

The problem is that I can trace the creation of a menu item during installation (I get an mlid back) but when installation is done there are no menu items for the views.

As I understood from another Drupal Question (Drupal installation profile: menu_link_save() doesn't work for "import" path) the problem is that the path's of the views are not defined yet at that moment.

Any suggestions on how to create menu items on installation within an update of that deployment module or is this never going to work?

Thanks in advance!
Hatznie.

I've found it!
Adding "'customized' => 1" to the options of each menu item did the trick.


Drupal multisite manager module I am currently working on an internal project that would host a Drupal multisite platform.

For this, I am in the process of creating a site_manager module that will be running in the "main" Drupal instance, within the multisite setup.

Now, I want to be able to run a lot of functions in the context of a specific subsite.

For example: I want to run a cache_clear_all() or a module_enable() in a subsite.

When I call these functions, it will always run the functions in the current site's context (the "main" Drupal instance).

I have tried to use db_set_active() to resolve this, but no luck.
It will always run it in the current "main" site.

To resolve the problem I started implementing a custom class that holds methods for the actions I want to perform, that fire custom db_query() implementations...

It works, but that cannot be the cleanest way to do this...
Clearing the cache tables manually via db_query does not seem like the best way to do this, especially when you know that just calling cache_clear_all() should do the trick, when ran in the correct context.

Some research brought me here:
Programmatically create user in another Drupal site
But I don't really see how this would work, because I want the platform to be extendible,so that I can add functions later.

I could try to setup some kind of "client" module that listens for calls from the main site or something like this?

EDIT

After doing some additional research, I am looking into the possibilities of XML-RPC or some kind of webservice (json) that might do the trick as well.

It might be good to note that I would like to find a sustainable solution when looking forward to D8...

Anyway, did any of you try something like this?

Thanks in advance!

Normally, you would execute these commands on particular sites with Drush and site aliases (drush sa lists the aliases). I do it all the time.


Programatic output of views block breaks jquery I am using the following code to load a views slideshow block:

  <?php
            $view       =   'pagetopimage';
            $block_id   =   'block_1';
            $args       =   array(32);
            print views_embed_view( $view, $block_id, $args );
        ?>

The block is produced just fine but the javascript that makes the slideshow work is abscent.

 Can you enlighten me about a way to programmatically load the block whilst maintaining the javascript functionality, please?

I would assume you are just missing the jQuery Cycle plugin.  You might try adding

drupal_add_js(drupal_get_path('module', 'views_slideshow') . '/js/jquery.cycle.all.min.js');
drupal_add_js(drupal_get_path('module', 'views_slideshow') . '/contrib/views_slideshow_singleframe/views_slideshow.js');

before outputting the view and see if that works.


What settings from a zen sub theme are not saved as files? Im duplicating a zen sub theme so that I can later modify the styling. Ive duplicated the theme folder and changed its name. Ive changed the .info file name, and ive changed the theme name for theme overrides in my template.php and theme-settings.php.

When I enable the new theme its very much like the old one but there are still some differences. Ive looked at the theme settings pages in drupal and applied the settings from the original theme to the new one, but there are still some differences.

What other settings to do with the theme would not have been copied across with the files and also arn't visible on this page?

The only module that Ive found that I think could be affecting the layout is Panels which controls a couple of pages. Ive changed the selection criteria from themeA to themeB so I dont think its this module causing the difference.

There are two major locations for theme configuration - be it a sub theme or a primary theme:

http://example.com/admin/appearance/settings/yourtheme

For a zen sub-theme, this page lets you configure display of logo, site-name, slogan, and more, including a couple of menus. Also the favicon (shortcut icon), breadcrumb settings, and more can be found here.

http://example.com/admin/structure/block

You need to configure each block's "Region Settings" (click "configure"  on the right), to assign or adjust a region for the block to your new theme. The region settings provide a pull-down menu with available regions for each enabled theme.

If you want to duplicate settings from one sub-theme to another sub-theme, make sure you adjust all files in the theme folder (theme.info, template.php, theme-settings.php). If you do extensive theme pre- or post processing, and change themes frequently, you might want to roll these into their own custom modules (see How to modify module output via another module - whois module? for an example of the same functionality as theme pre-processing or custom module).

There might be additional settings in contributed modules - you mentioned panels.


Can't understand how to invoke my own theme() function i have made formexample.module, from Drupal 7 Pro Development

function formexample_menu() {
    $items['formexample'] = array(
        'title' => 'View the sample form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('formexample_nameform'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

function formexample_nameform() {
    $form['name'] = array(
        '#title' => t('Your name'),
        '#type' => 'fieldset',
        '#description' => t('what people call you'),
    );

    $form['name']['user_name'] = array(
        '#title' => t('Your name'),
        '#type' => 'textfield',
        '#description' => t('please enter name'),
    );

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

and a theme function and preprocess function

function formexample_theme() {
    return array(
        'formexmaple_nameform' => array(
            'render element' => 'form',
            'template' => 'formexample-nameform',
        ),
    );
}

function template_preprocess_formexample_nameform(&$variables) {
    $variables['name'] = $variables['form']['name'];
    $variables['submit'] = $variables['form']['submit'];
}

this is template file for this theme() - formexample-nameform.tpl.php

<div id="formexample_nameform">
<?php
    print render($name);
    print render($submit);
?>
</div>

my question is: how and where to invoke this theme('formexample_nameform') , i thought i should insert function template_preprocess_formexample_nameform to my template.php file(with template rename to my theme name) but its not working for me

You just need to set it on the $form element inside your form function:

function formexample_nameform($form, &$form_state) {
  $form['#theme'] = 'formexmaple_nameform';
  // ...

When you use render element with a theme the variable on which you set #theme is the one that's passed through to the theme/preprocess functions.

Don't forget to add drupal_render_children() at the bottom of your template file or the form won't render correctly:

echo drupal_render_children($form);


MySQL Error: Duplicate Entry on indexing taxonomy structure with Search API Problem

I have a search index. I use a views page with this to create a search page and results for users.

I was forced to re-create my search index. I deleted the old one and I'm getting the following error when I attempt to index the new one after re-creating it.

(Technically I get 49 errors, one for each piece of content i'm trying to re-index)

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '632' for key 'PRIMARY'

I only get this error if I attempt to index the hierarchy of a particular taxonomy field.

It sounds like it's trying to re-generate the ID for my set of items, but even uninstalling and re-installing the module and re-creating everything doesn't clear the error.

Any ideas about what might be causing it? Or what I should look for in MySQL as I dig through tables?

I raised an issue in the Search API queue which then got patched. Forgot to post about it here. My bad.

https://www.drupal.org/node/2174163


More link not displaying in content pane I've got a Content Pane View which I display multiple times on one page (it shows a grid of Employees and takes a Department as a parameter, so I show the View 4 times on a page, sending each one a different Department parameter).

Each view on this page shows only a subset of the results (it only shows 6 Employees from each Department). I want to add a More link at the bottom of each view that links to a page that shows all results for that Department.

However, in the View configuration (Content Pane variant) I enable the More link to show, but it doesn't show.

Any ideas why the More link wouldn't show? I've definitely got enough content and I've even tried setting the configuration so that it'll show the More link even if there isn't more data.

Are More links disabled when displaying the view in a content pane?

I had the same problem.

I solved it by creating a page view as well as an original block view.

Hope this helps


Template file not recognized when moved to module theme folder I have a template file in my custom module folder which I am using to theme a form. Everything works fine when the template file is in the root of my custom module folder. However, I would like to move this template file to another sub-folder in my custom module folder, so that I can basically put all the template files in one folder. My directory structure is such that in the root of the my custom module folder I have (/sites/all/modules/mycustommodule):

mycustommodule.module
mycustommodule.info
mycustommodule.install
mycustommodule_admin.inc

In /sites/all/modules/mycustommodule/mycustomthemes:
mycustommodule-example-form.tpl.php
mycustommodule-example2-form-tpl.php

This is my hook_theme:

'mycustommodule_example_form' => array(
  'template' => 'mycustommodule-example-form',
  'file' => 'mycustommodule_admin.inc',
  'render element' => 'form',
),

I would like to know what I would need to do to make the path clear to Drupal that the template file is in that sub-folder. Thanks.

Try using 'template' => 'subfolder/mycustommodule-example-form'.


How do you configure a Drupal linux dev system for sending email? My current dev system is a multi-site dual-boot windows/linux box with Apache 2.4/PHP 5.4.

In windows mode with a fresh install of D6 or D7, a verification email is properly sent when registering a new user. No contributed modules are required.

In linux mode (Ubuntu 12.04 LTS) the email does not work. I have tried using the ubuntu default (sendmail dummy?), sendmail, ssmtp, and postfix email packages with assorted configuration settings.

Most of the email packages seemed to have work from the command line.

With default or sendmail, a Create new account request causes the "wait" mouse-pointer to appear and remain like that for 30 secs or longer. The "email has been sent" message eventually appears but no email is ever received. With the postfix or ssmtp package installed, the same message appears within a second or two but no email is received.

I have searched for an answer on how to configure a Drupal linux system for email without much success.

The D6/D7 SMPT Authentication Support module solves this problem but it is a dependency that should not be necessary.

I don't have these problems running in Windows mode; never have in 3 years. I now have a shared NTFS partition so both modes use exactly the same code base.

Here is another attempt to answer the now questionable question...

Drupal core uses the php mail() function by default. See /modules/system/system.mail.inc

Context

Do you have a Linux based Drupal dev system? Does a fresh install of Drupal (6,7 or 8) appear to work? If an anonymous user attempts to create a new account, does it appear that an email is sent but NEVER received? Yes to all of the above?

A brief history. It was in the Fall of 2010 that I downloaded and installed this thing called Drupal (version 6). After creating a new account the system sent an email with a keyed link to set the new member password. I was impressed.

I was using a Windows XP laptop at the time.  Mail systems are not my speciality but I had managed to get websites to send emails. The sum total of my expertise at the time was this -- I was using some kind of SMTP thingy.

In the Spring of 2013 I switched to Ubuntu 12 for Drupal development. I recently discovered that the linux configuration did not send a new user email. The Win system (Windows 7) works like it always has since the XP days - it just works.

Most of us use email systems managed by our ISP, employer, or internet offerings such as Hotmail or Goggle's gmail.

I have since discovered I configured an smtp relay. A Drupal call to mail() will relay the message (with authentication if necessary) to my preferred mail server.

Windows install

On a windows (WAMP) system, there is a "window only" section in the php.ini file that allows the setting of a mail server.

Linux install

A search for 'mail' using the Synaptic package manager revealed that the default lsb-invalid-mta package was installed (Linux Standard Base sendmail dummy).

Linux has many mail systems available, sendmail, ssmtp, postfix, qmail  exim or nullmailer, to name a few.  They can get complicated. Most everybody with any experience prefers something other than sendmail.

Postfix

The postfix package seems to be the most popular. The trick here is to configure postfix as an SMTP relay. This means a call to mail() will relay the request to the mail server of your choice.

Here is a suggestion on how to configure your Drupal development system using postfix as an SMTP relay:

Step 1 - Prepare system

Uninstall and remove each mail package that you have tried but have failed to get working:

sudo apt-get remove --purge [mail package that did not work]

Rinse and repeat as necessary. I have read somewhere that this is a good idea. If all goes well, sendmail for dummies (lsb-invalid-mta) will be left.

Step 2 - Install postfix (again if necessary)

sudo apt-get update
sudo apt-get install postfix

Step 3 - Configure postfix

Cut and paste the following code into your editor. Replace every occurrence of mailserver:port with something that works. Modify username and password accordingly.

Note the 'myorigin' setting does not include a port number.

You may then cut and paste these commands onto the command line. It is recommended that it be done in steps, one line at a time, just to see how things go.

# Open up a sudo session so you don't have to preface every
# command with 'sudo' - remember to exit when done!
sudo -s

The following commands work as s when logged in as 'root':

# postconf is a program that can modify the postfix config file /etc/postfix/main.cf
postconf -e 'relayhost = mailserver:587'
postconf -e 'myorigin = mailserver'

postconf -e 'smtp_sasl_auth_enable = yes'
postconf -e 'smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd'
postconf -e 'smtp_sasl_security_options ='

# Authentication -- Substitute mailserver, username and password here:
echo "mailserver:587   username:password" > /etc/postfix/sasl_passwd

# Protect this password file
chown root:root /etc/postfix/sasl_passwd
chmod 600 /etc/postfix/sasl_passwd

# update the sasl_password.db file using the new password file
postmap /etc/postfix/sasl_passwd

# Restart
service postfix restart

# and exit the sudo session
exit

Step 4 - Test

If everything goes well, a variation of this command:

mail name@whatever.com

should work. You should be prompted for a Subject. After entering the subject line, follow with the body of the text (i.e. "Hello world!"). There is no prompt for "Body". I am not sure why.

Use Ctrl-D to complete the command.

Now check the email address for the message.

Acknowledgements

Maybe I should acknowledge Google because I used it to find these links, but the search was exhausting. Here are some of the pages I bookmarked. Some of them are quite old.

http://developernote.com/2012/07/how-i-configured-sendmail-for-php-on-ubuntu-server-12-04/#comment-27377

http://www.howtoforge.com/postfix_relaying_through_another_mailserver

http://www.howtoforge.com/how-to-relay-email-on-a-postfix-server

http://lenss.nl/2009/01/making-php-mail-work-on-ubuntu-through-postfix/


Create a node using the REST API I am trying to create a node from a different server via REST API, utilizing the Drupal 8 REST API and the Poster plugin for the browser.
I posted the request as shown below, and I got the following output.

{
    "message": ""
}

I already enabled the service end_point to create, retrieve, update, and delete the content in the REST API configuration.

What is happening? Is it the right way of doing it?

Okay, I am going to Explain you in a very simple way using a Postman Software.
 1. Enable the restui Module.
 2. Add the basic_auth authentication.
 3. Get the X-CSRF-Token from /rest/session/token.
 4. Follow things by this image:

 5. Add the following text into your Body.

And hit the Send Button Its Done!


How do I hide field in node.tpl.php? I would like to hide this field if it is empty. No clue where to start with my limited PHP/Drupal knowledge. The Else would be "Nothing to see here."

<?php

  $my_field_value = $content['product:field_course_no_']['#object']->field_pd_number['und'][0]['safe_value'];

echo "<input type=\"button\" value=\"Danh's Cart\" id=\"Adding PDC course\" onclick=\"setCookie('class','$my_field_value" . "r_000000000000');document.cartform.submit();\" style=\"float:none;\" /><input type=\"hidden\" name=\"id\" value=\"$my_field_value\" />";

?>

Here you go:

    if(isset($content['product:field_course_no_']['#object']->field_pd_number['und'][0]['safe_value'])){
     $my_field_value =  $content['product:field_course_no_']['#object']->field_pd_number['und'][0]['safe_value'];
} else {
        $my_field_value = '';
}


Add HTML code outside content area on every page load I am trying to add HTML code outside the content area on every page load with the use of:

function us_page_build(&$page) {
  $page['content'][] = array(
    '#markup' => '

Here is my div content!!

',
  );
}

However, in this way I am placing the element within the content attribute. Is there a way to set it outside, having as parent only the html element?
I am aware I can paste code into the template files, but then if I switch to another template(which I will) I will need to re-enter it.

Content is a region in your theme. Site content goes into regions. So, typically you can only put things in defined regions such as Header, Footer, Left Sidebar, Content.

You have slight flexibility with #prefix and #suffix render array attributes. You either have to edit the html.tpl.php file, or define your own region within a theme. Or you can supply your own hook_theme() implementation to hint when using your own html.tpl.php template file.


Bringing CKeditor, embedded content (e.g. iframe) and responsive design together I like to bring together the usage of CKeditor with embedded content (for expamle youtube / issuu) in a responsive website.

I have so far:

CKeditor with Media module integration and Media-Youtube to simply embed youtube-content via the media-library. Making the videos responsive works like a charm with fitvids.

Main question: i'm interested to either generalize these components or find another solution to make this work. Do i have to write something similar to fitvids and media-youtube for every embed-type i want to use or is there a solution out there that i overlooked?

Other suggestions highly appreciated. I'm kinda stumped at the moment... Thanks!

Edit:
For example i'd like to integrate issuu (http://issuu.com/) elements in the same manner like youtube-clips: the editor just adds a link inside the media library and submits it to the field. Right now, issuu only offers embeds with fixed dimensions, so they don't scale according to screen width.

You can override youtube videos using CSS and media queries. Infact, most videos from Youtube, Vimeo etc are all available in an iframe. In projects in the past, I allow clients to just copy and paste an embed field into a ckeditor field wherever they like, at any dimension they please.

But, once the screen width is reduced to mobile, my CSS takes over, and resizes the video to fit the mobile template, to reduce overlapping, and fix any issue with video height.

E.g.

@media only screen and (max-width: 767px) {

.field-name-body iframe     {width:100%;height:200px;}

}

Is that what you mean, or I have I not understood the question?


Why does Drupal run slow on localhost wamp? I'm using an i3 8GB RAM computer and Drupal is as slow as like using some cheap hosting provider.

So what could it be? I am using a freshly installed version of D7 and just browsing through site, going to Reports takes some time and I am not even talking about clearing cache or running cron.

Also using Drush via Git Bash also runs commands slow, like simply 'drush dl libraries' and then enabling it takes like 10 seconds and I am on 100MBit line.

I did some changes to php.ini file like memory_limit = 2G and etc. but it's as slow as if it was 128M.

Installed Acquia Dev Desktop, runs smooth ant fast. Wamp is not production system.


Modify create content flow I want to do the following:

filling content (create new content)
after pressing the save button (submit) will display the contents of the data has been filled,and other additional information required
select save to submit the content, or cancel it

How do I show data that has been filled as a confirmation before the data saved?

I have tried using the Form API to change the flow of the process (_form_alter) but no success. And i can't find the examples to altering the content type.

Provide the roles to user to make any content and after save the content it will show with restriction.
Or
you can make custom module for that.


Alter a view so it adds a custom field ->textbox I have a bit specific question.

I have a content type->TESTS
it has the more or less the normal fields.

There is a view that displays all of the tests. So far,so good.

But the requirement is to add a specific textbox-> SCORE of TEST for every instance.

And it should be different for all the logged in users.

For example. All users see the tests and can insert a result.
This result is recorded in the database.

What should be the best approach doing so ?

Maybe:
1.Create the field "ScoreOfTest"
2.Alter the view in a custom module

Thanks in advance

When you create the content type does it reference who test scores they are? Without any reference's to who's score it is this would be hard. You could use entities I believe as you can create relationships you need then you could use views to display it.

http://drupal.org/node/1261744


Checking for custom view mode inside twig template! I am using {% if teaser %} .... {% endif %} To change structure of content type according to its view mode.

But it looks like I cannot check for custom view modes created using Drupal 8, Such as:

{% if medium_teaser %}

     {{ content.field_image }}
     Buy now

{% endif %}

Is there a way to check for custom view modes in twig templates?

Assuming that's the node template, you have a view_mode variable available:

{% if view_mode == 'foo' %}

{% endif %}


How do I enable editing the body of a block? I have a block (in Drupal 7) with information in the body of it.

I want a specific user to be able to edit that information.

After assigning that user Administer blocks and Contextual links permissions the user can edit everything except the body and the following message shows:

Is there any way to enable the field for that user?

You are facing this issue because you probably created the block as a user who has access to a text format like Full HTML but the other user doesn't have that permission :( Here's what you can do:

Sign in as the root user (uid 1) who created the block;
Change the text format to Basic HTML or Restricted HTML.
Go to Admin > People > Permissions page and make sure the other non-admin user has the permissions to use the text format you applied.
Depending on your requirements, you can ignore point 2 and give Full HTML permissions to the concerned user.


How to create a task which run at cron time and send emails to users? Is there a module (based on cron) which can be used to check a date value form a field and to send email to users 2 days before the date?

If there is not, how can I implement this to work with cron?

Here is how I did without using any custom modules.

I implemented hook_cron like that:

function HOOK_cron() {
    // search for expiration date interval
    $result = db_query("SELECT my_date, uid, company_name, nid
            FROM my_table
            LEFT JOIN ...
            LEFT JOIN ...
            LEFT JOIN ...
            LEFT JOIN ...
            WHERE my_date BETWEEN DATE(NOW( ) + INTERVAL 6 DAY ) AND DATE( NOW( ) + INTERVAL 20 DAY)")->fetchAll(PDO::FETCH_ASSOC);

    foreach ($result as $product) {
        $module = 'MY_MODULE';
        $key = 'MY_KEY';

        $from = 'my_email@test.com';

        $user_account = user_load($product['uid']);
        $product_detail = node_load($product['nid']);

        $to_user_mail = $user_account->mail;

        // build the email
        $message = drupal_mail($module, $key, $to_user_mail, LANGUAGE_NONE, array(), $from, FALSE);

        //$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
        $message['headers']['Cc'] = 'cc_email@test.com';
        $message['headers']['Reply-To'] = 'reply_to_email@test.com';

        $message['subject'] = 'THE SUBJECT';

        $message['body'] = array();
        $message['body'][] = 'Dear ' . $user_account->name;
        $message['body'][] = '...';
        $message['body'][] = 'Regards,';
        $message['body'][] = 'YOUR NAME';

        // retrieve the responsible implementation for this message.
        $system = drupal_mail_system($module, $key);

        // format the message body.
        $message = $system->format($message);

        // send e-mail
        $message['result'] = $system->mail($message);
    }
}


How to allow users to add images to an existing node? How to allow users to add images to an existing node without giving them access to the whole node edit page. In Drupal 7 i used the Block Upload Module but it's buggy in the drupal 8 version. Do you have any approaches to get this functionality?

In D8 you can use a form mode for this to assign a reduced node edit page to a specific user role.

See https://www.drupal.org/project/form_mode_control


Cron function set to run once per month not completing I have a cron function that is being triggered but not completing. The function is supposed to run only once on the first of every month. The function runs but, I think, gets as far as comparing the $summary_sent variable and then stops. Cron is running once every 3 hours.

By changing the $day_of_month_to_run to the current day and resetting the $summary_sent variable I can successfully run the full function using cron but, when left to run automatically on the first of the month it fails.

variable_set('summary_email_recipients', 'me@example.com');

function appointments_cron() {
    send_monthly_summary();
}

function send_monthly_summary() {
    $recipients = variable_get(summary_email_recipients);
    // run on first of the month
    $day_of_month_to_run = 01;
    $date_string = date('Y-m-'.$day_of_month_to_run);
    // only run on the correct day of the month
    if ( date('Y-m-d') == $date_string ) {
        // check if the process was last run today
        // prevents process being run multiple times on the same day
        $summary_sent = variable_get( 'appointment_summary_sent' );
        if ($summary_sent != $date_string) {
            // do stuff
            // set a record of this process
            variable_set( 'appointment_summary_sent', $date_string );
        }
    }
}

Why isn't this running once on the 1st of every month as expected?

I always struggled to get cron jobs running at the right time until I found Elysia Cron. Inside the configuration screen of Elysia Cron you can specify which cron hooks run when, so the standard hooks can be set to run each hour, others each day, each week, each month, etc. and you don't need to worry about coding the date as you've done.

EDIT: I just ran the following code:

$day_of_month_to_run = 01;
$date_string = date('Y-m-'.$day_of_month_to_run);
dpm($date_string);
dpm(date('Y-m-d'));

The results were 2015-04-1 & 2015-04-15 your 01 is being collapsed to 1, you need to change it to '01'


How to add a result count in exposed filters? For theming purposes, I need to display the views results in the exposed form.  Right now, through the UI, it's easy to add "Global: Result summary" to the views header, section.  But how would one display it within the exposed form?

There's no use trying to use hook_form_alter, as you need to wait until the view is rendered.  You can do this in hook_preprocess_views_view__VIEWNAME like this:

function examplemodule_preprocess_views_view__exampleview(&$variables) {
  $result = $variables['header']['result'];
  unset($variables['header']['result']);
  $variables['exposed']['result'] = $result;
}


Media html not rendering in blocks I'm experiencing an issue on multiple sites where (image) media aren’t appearing in blocks despite working fine in node fields.
I first thought it only happened to me when using the linkicon module, but since then i created a custom block type for image blocks (using entity reference media fields) and the same thing happens, ie. the html renders nothing:

There's no problem rendering the fields in nodes on the same sites using the exact same display settings.
I've checked both the media, block and block_content logs and they show no errors.
My setup:

Drupal 8.9.7
Barrio 5.1.3
Local environment running on ddev
Remote environment running on cloudways

Any ideas what the issue might be?

This turned out to be a conflict with the songkick module. I'm a maintainer  so I'll make sure the issue is handled and post further updates in the issue cue on Drupal.org here.


Scanner module triggers call to node.admin.inc (require_once(), trying wrong path) All of a sudden, for no reason (favorite kind of problem) Scanner stopped working. I can access the configuration at /admin/config/search/settings but trying load the scanner at admin/content/scanner fatal errors:

Fatal error: require_once() [function.require]:
Failed opening required '/public_html/sites/all/modules/scanner/node.admin.inc'
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/moondev/public_html/includes/menu.inc on line 514

Notice the path is wrong where it's trying to load node.admin.inc

Scanner used to work as expected so I suppose either an update changed something or a conflict with another module (or it's settings) is happening.

Anybody experience something similar before, where a core include is trying to be loaded from the wrong path?

Turns out to be a conflict with Administration Views (7.x-1.0-alpha1).

Disable admin views & functionality is restored. Not sure where the blame is yet because I haven't pinpointed the conflict. But it does make sense at face value because admin views replaces the /admin/content and scanner is located at admin/content/scanner


How to avoid clearing of the form state? I want to add form field based on data provided in submit handler. I am using $form_state for the job. I have done similar in the past but now it's just not work

Form code:

function module_form($form_state) {
 if (isset($form_state['module']['data'])) {
   //add field
 }
}

function module_form_submit($form, &$form_state) {
  $form_state['no_redirect'] = TRUE;
  $form_state['rebuild'] = TRUE;
  unset($form_state['redirect']);
  $form_state['module']['data'] = module_get_data($some_value);
}

Inside module_form $form_state is always empty...

This:

function module_form($form_state) {

needs to be changed to this:

function module_form($form, &$form_state) {

The function sig for forms changed in Drupal 7 to the second example above.


How to add dependency to a custom module with drupal-composer? I have a problem with dependencies in my custom module.

I'm using drupal-composer and I'm able to install my own module with the composer.json. My module comes from custom Git repository.

At this moment, though, I'm unaware of any working way to get my custom modules dependencies installed at all. I can add them one by one to the composer.json, though they do not appear into right namespaces after that, but let's just disregard that because I would really like to be able to specify them into my custom module and get them installed automatically. This is because I will be having multiple modules with multiple dependencies. Also, some of these dependencies will be from my own repositories, but that should not make any difference. And to be specific, at this point I'm trying to add a custom git repository containing some PHP source files that I need for the services exposed from my modules.

I have also tried installing modules from Drupal packagist and their dependencies are all nicely downloaded.

So is there any way to specify these dependencies into my own module and how to get them working? I have added them to my modules composer.json, but that does not seem to have any effect. They also need to be there when I run my PHPUnit tests.

Also I'm aware of the composer-manager plugin for Drush, but at this point, (due to other requirements) it is not an option.

Ok, seems to me that I almost got it.

This was due to my repository list in the Drupal root composer.json. I had this kind of thing there:

{
  "type": "package",
  "package" : {
    "name": "blaah",
    "version" : "xxx",
    "type":"drupal-module",
    "source": {
      "url": "gitblaag",
      "type": "git"
    }
}

That some how seems to override what ever is in the modules composer.json. I do not really know why but something along the lines that the entry defines the whole package and no more info will be read from the composer.json in the module.

So I adding "require" there does the magic. Also probably removing some of those lines and making it just a repository, not a package, would result into composer reading the individual modules composer.json.

But now everything seems to be right and module is installed and it will install my other files under vendor but PHP still goes to "class not found" in my service when I try to use my class from the other library.


Endless redirect on paths containing question marks A similar question was posted here: EventSubscriber endless redirect

But I haven't quite been able to implement a workable solution.

On Drupal 8.73: Basically we have a custom module that is redirecting to clean urls (so that /node/42 doesn't get indexed by google). I didn't write the module and I'm a little fuzzy on what it's doing and why. The module works fine except that urls with ? in them endlessly redirect and get caught in a redirect loop. The browser eventually returns an error that the page is redirecting and will never load properly. Here is the module:

<?php

/**
 * @file
 * Contains \Drupal\mymodule\EventSubscriber\MyModuleSubscriber.
 */

namespace Drupal\sjwc_tweaks\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Event subscriptions for events dispatched by SimpleFbConnect.
 */
class TweaksSubscriber implements EventSubscriberInterface {

  public function onRequest(GetResponseEvent $event) {
    $baseUrl = $event->getRequest()->getBaseUrl();
    $attr = $event->getRequest()->attributes;
    if (null !== $attr && null !== $attr->get('node') && $attr->get('_controller') == '\Drupal\node\Controller\NodeViewController::view') {
      $node = $attr->get('node');
      $nid = $node->id();
      $current_uri = \Drupal::request()->getRequestUri();
      if (\Drupal::service('path.matcher')->isFrontPage()) {
        $redirect_uri = '/';
      } else {
        $url = Url::fromRoute('entity.node.canonical', ['node' => $nid]);
        $redirect_uri = $url->toString();
      }
      if ($redirect_uri != $current_uri) {
        $event->setResponse(new RedirectResponse($redirect_uri));
      }
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['onRequest'];
    return $events;
  }

}

I believe this line is the issue:

$event->setResponse(new RedirectResponse($redirect_uri));

At the issue linked above, a kind user suggested a solution that I do not quite understand, they said:

  The problem is, you should never send a response inside of a StackPHP
  application. Drupal continues to build its own response (the real
  frontpage) and stores this in the cache. Set the response in the event
  instead: $event->setResponse($response);

I'm not sure exactly where he means by setting the response "in the event" instead.

Now, as this issue only is a problem on urls with ? in them, I did find I could correct the issue by wrapping the line above, line 37 thusly:

if (strpos($current_uri, '?') != TRUE) {
  $event->setResponse(new RedirectResponse($redirect_uri));
}

However I worry this might cause unpredictable behavior and I prefer to fix this the right way the first time. Can someone tell me what I'm doing wrong or overlooking or explain how I can "set the response in the event" instead?

You can try to manually add the query parameters to the redirect URL.

Add this code:

$query = [];
parse_str($current_uri, $query);

just below this code:

$current_uri = \Drupal::request()->getRequestUri();

And then change this line:

$url = Url::fromRoute('entity.node.canonical', ['node' => $nid]);

To this:

$url = Url::fromRoute('entity.node.canonical', ['node' => $nid], ['query' => $query]);


How can I generate thumbnails for PDF files? I am working on this website which has a documents gallery that will be updated periodically. One of the core requirements is to generate a thumbnail from the uploaded PDF file(First Page of the PDF file) and to be displayed in the documents gallery page(Implemented with views). I have installed Imagemagick on my test server and configured it in PHP.ini and also installed the drupal module successfully. But I have not been able to go beyond that because of the following:

I can't upload a pdf to an image field so there is no way of applying an image style to the uploaded pdf
I can't find any Drupal 8 Module that can generate the thumbnail and attach it to an image field in the content type.
I tried installing spatie/pdf-to-image, which is supposed to be able to do that, via composer but it doesn't show in the admin/modules page and I can't find any folder with it's name in the modules directory

Please can anyone point me in the right direction on this? A module which can perform this task or how I can create one myself. This is my first drupal website and this requirement has made life hell for me in the past two weeks. Any help on this will be really appreciated.

For similar purpose i was using Media Entity in Drupal 8, so on this way you can use reference field to upload document and get preview like thumbnail.


Can't find my website page listed under admin/structure/pages Driving me crazy!
I have a website page: http://www.randymtrader.com/contact that I cannot find anywhere in drupal admin/structure/pages. There is nothing with the path /contact. Where else could it be listed? I need to edit the page.  Any ideas?

Thank you!

The /contact page is provided by the Contact module, which you must have enabled. It displays the contact_site_form form, which is declared in /modules/contact/contact.pages.inc.

Configuration options for this form can be found at the site.com/admin/structure/contact URL.

If you're looking to change form structure, you may need to create a custom module and implement hook_form_alter(). If you're after changing layout, you may be able to get away with adding/moving blocks (in which case have a look at Context for more options than the core blocks page), but more likely should use something like Panels to create a new page and insert a new contact block on it. You may want to have a look at the Webform module, which can be used to create & configure forms through the UI.


How to integrate the Fusioncharts library with Drupal 7? I have been trying to integrate the Fusioncharts library with my Drupal 7 site.

Just to check if everything is working properly, I followed this documentation for creating a basic graph with data contained in Data.xml file; the entire documentation is here.

FYI, I need to use PHP as I am more comfortable with it.

I have extracted the downloaded folder into /sites/all/libraries/FusionChartsFree/; with changes in paths (nothing else); I have pasted the code in the given example into my Drupal 7 node with the php input filter enabled. I also have the libraries module installed.

<?php
  //We've included ../Includes/FusionCharts_Gen.php, which contains FusionCharts PHP Class
  //to help us easily embed the charts.
  $name = "FusionChartsFree";
  if ($path = libraries_get_path($name)) {
    include $path . '/Code/PHP/Includes/FusionCharts.php';
  }
?>
<html>
  <head>
    <?php
      //You need to include the following JS file, if you intend to embed the chart using JavaScript.
      //When you make your own charts, make sure that the path to this JS file is correct. Else, you
      //would get JavaScript errors.

      include($path.'/Code/FusionCharts/FusionCharts.js');
    ?>
    <script type="Javascript" SRC="/sites/all/libraries/FusionChartsFree/Code/FusionCharts/FusionCharts.js"></SCRIPT>
    <title>FusionCharts - Simple Column 3D Chart</title>
  </head>
  <body>
    <?php
      //Create the chart - Column 3D Chart with data from Data/Data.xml
      echo renderChart("/sites/all/libraries/FusionChartsFree/Code/FusionCharts/Column3D.swf", "/sites/all/libraries/FusionChartsFree/Code/PHP/BasicExample/Data/Data.xml", "", "myFirst", 600, 300, false, true);
   ?>
  </body>
</html>

I get the below output. It is pretty long; hence, I have put then in part by part in these pictures.

(FYI, those Flash files that appear in the output, do not display anything if I click on them.)

Now, suppose I remove the below line from the code.

<?php
 include $path . '/Code/FusionCharts/FusionCharts.js';
?>

I get nothing. I mean only a text which reads "cahrt" in the below output.

My Question: How can I make Fusioncharts work in DRUPAL 7?

I am also having similar trouble with the pChart library too: Even pChart does not display anything, not even an error, or warning. Simply there is nothing in the node body.

There's a couple of problems in your code:

include($path.'/Code/PHP/Includes/FusionCharts.php'); you have to use ./ to include files.
include($path.'/Code/FusionCharts/FusionCharts.js'); you should use drupal_add_js() to include javascript in your code.
FusionCharts documentation seems a little old as Column3D.swf is now FCF_Column3D.swf

Here is a working example, I haven't used the librarie module but you should be able to adapt it easily. I put this code in a node with PHP filter activated.

<?php
$file = './sites/all/libraries/FusionChartsFree/Code/PHP/Includes/FusionCharts.php';
if (is_file($file)) {
  require_once $file;
}
drupal_add_js('sites/all/libraries/FusionChartsFree/Code/FusionCharts/FusionCharts.js');

//Create the chart - Column 3D Chart with data from Data/Data.xml
echo renderChart("/sites/all/libraries/FusionChartsFree/Code/FusionCharts/FCF_Column3D.swf", "/sites/all/libraries/FusionChartsFree/Code/PHP/BasicExample/Data/Data.xml", "", "myFirst", 600, 300, false, true);

?>


Can I search for parent nodes from deep child nodes using Views? I've a complicated hierarchy of nodes.
Node A contains(by node reference) multiple B nodes, each B contains multiple C nodes and so on.

Using Views will it be possible to reach C from A or vice versa given even higher depth level?

I think this is independent of D6/D7 views but I'm on D6.

There will be thousands of such nodes. Each top level A is an organization and there are a 1000 of them now. Information about each employee or department will be held in File(aka file cabinet) which again is a node).

I want to give users facility to search information from one end to another.

Update: The parent to child relationship is one to many

You can probably do it with the Corresponding Node References module. Otherwise you can't do reverse references at all. You'll use relationships, of course, to go both ways.


Content entity form not displaying the previously selected value Even though I can see that my data is being saved it doesn't ever appear to be set when I go back to edit my entity via a form. Am I missing something in my setup?

Here's what I have:

      $fields['content_display'] = BaseFieldDefinition::create('list_integer')
          ->setDisplayOptions('form', [
              'type' => 'options_buttons',
              'weight' => -4,
          ])
          ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
          ->setSetting('allowed_values', $values)
          ->setDisplayConfigurable('form', TRUE);

You need to set a default value for the field. Drupal's field system by default assumes a field is empty, you will have to manually add a default value to the field definition.

This default value should be based on your entity's value, or be an empty string or NULL in case there is no value yet. Try something like this:

// Use the entity value if available, or NULL otherwise.
$default_value = !empty($entity->my_value) ? $entity->my_value : NULL;
$fields['content_display'] = BaseFieldDefinition::create('list_integer')
  ->setDisplayOptions('form', [
    'type' => 'options_buttons',
    'weight' => -4,
   ])
  ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
  ->setSetting('allowed_values', $values)
  ->setDisplayConfigurable('form', TRUE);

  // Set the default value on the field.
  ->setDefaultValue($default_value);


D7 - How to get mlid value from path of menu item Quick question. How to get mlid value from path of menu item. There is a function called menu_link_load() but it requires an mlid value, but I need something exacly the same function using path.

There's no build-in function for this. You can use menu_tree_all_data(), but it returns all the menu. After that you can compare in loops your path with the paths returend. But there is a better and easier answer. Here it is:

$mlid = array();
$q = 'your-path';
$menu_info = db_select('menu_links' , 'ml')
  ->condition('ml.link_path' , $q)
  ->fields('ml', array('mlid', 'plid'))
  ->execute()
  ->fetchAll();

foreach($menu_info as $key => $value) {
  $mlid[] = $menu_info[$key]->mlid;
}


How can I stop a specific page in the Omega Responsive theme from being responsive I need to stop a specific page from resizing and display the styles specified in the normal stylesheet. I have an iframe that is a set width and height and will not display properly when viewed on smaller screen sizes. Is this possible?

You can use the Context and Delta modules. Delta was developed by the Omega developers and Context+Delta is part of the Omega philosophy.

Use Delta to create a variation on the original theme that does not respond to theme width.  Uncheck "Enable the responsive grid" setting in the theme, for instance. Then use Context to enable your Delta'd theme variation to trigger only on a certain path, in your case the page with the iframe.


How to organize better the taxonomy-selection drop-down box in Views? I made a View to list a series of items. Each item has been assigned a Taxonomy term.

My taxonomy terms go like this:

--- Main1
----- Sub1
----- Sub2
--- Main2
----- Sub3
----- Sub4
----- Sub5

So there's a main category and inside other terms.

In my view, you can filter the entries to only display items for a certain category. But the dropdown menu is a mess. It goes like Sub3, Main2, Sub1, Sub5...

So, is there a way to organize it in a way it appears as I listed it above? And also, is it possible to give some kind of indentation for the  subterms in the dropdown? (So people can easily tell what is a main term and what's a sub-term).

You can use Hierarchical Select module to manage taxonomy terms in select list.

See this discussion to implement hierarchical select with Views module : http://drupal.org/node/1170192


How do I get a user field from an entity reference? I'm working with the Twilio module to create a Rule that will send out an SMS message when a user creates a specific piece of content.  Here's how I've got things laid out at the moment.

I have a content type called Office (field_office), which contains the regional office name (imported from LDAP, but that probably doesn't matter.)
I have an entity reference user profile field called field_user_office that links to the Office content type.
I created a content type called Blast Message with an entity reference field called field_office_sms which also links to the Office content type.  When a user wants to create an SMS they create one of these nodes and select one or more offices to send to.

When I set up my rule I'm not seeing the fields exposed as I expected.  I tried adding two Entity has field conditions, Parameter: Entity: [node], Field: field_office_sms and Parameter: Entity: [node], Field: field_mobile_phone, the last of which is the actual mobile number saved in the users' accounts.

How do I navigate from the original content (Blast Message) through the Offices, then to the specific Users who are linked to that office, and ultimately retrieve their mobile phone numbers?

You need to use the action: Fetch entity by property.

Condition: Entity has field > node: field_office_sms
Fetch entity by property > User > Property: field_user_office > Value: node: field_office_sms:nid
Loop: List: [entity-fetched]
Action: Send SMS > list-item: field_mobile_phone


How to define the time-range for the Time Field in Webform 4.x is it possible to change the selectable time range in a time-field in Webform? I don't want the users to have the choice to select between 00:00 and 23:59. I only want them to choose between 15:00 and 23:00.

Webform validation doesn't work on time fields. Is there any other way?

Thanks in advance.

You can check with Clientside Validation Module. Otherwise you can alter the webform to add validation.

You may refer https://stackoverflow.com/questions/6785882/how-do-i-apply-webform-validation-in-drupal-7 link for a reference.


When is cache_menu flushed? I was caching some goodies related to the menu, and putting it in the 'cache_menu' bin, assuming they would get cleared whenever someones edits the menu.

cache_set($cachekey, $mymenu, 'cache_menu', CACHE_TEMPORARY);

When I edit the menu, it isn't cleared. When is it cleared, then?

In what sense is it different from the cache bin?

Looking at menu_link_save(), you will see that it calls menu_cache_clear() to clear only the cache of the menu the menu item belongs to. Other entries in the menu cache are not cleared.

The entire menu cache is only cleared when menu_cache_clear_all() is called directly (eg. by menu_enable(), which runs whenever a module is enabled) or indirectly (often through menu_rebuild() or drupal_flush_all_caches()).

If I were you, I would store my own data in the default 'cache' bin. I consider the menu cache to be private to the menu system; I don't want to touch it and accidentally mess something up. To clear my cache data at the right moment, I would implement hook_meu_link_insert() and/or hook_meu_link_update() and clear/rebuild my cache data from there.


Why is the test runner not picking up tests for a contrib module? I recently added tests to Cache Register, but the test runner on drupal.org doesn't seem to be picking them up. The tests are all located in tests/src/Kernel (repo) but aren't queuing up in the issue queue for either patches or merge requests. Am I missing something?
EDIT: Current answer references the namespace of the base test class, but that's no longer relevant. I refactored that Base class into a testing Trait instead and made sure that the remaining "real" tests use the proper namespace. Everything runs locally but still not getting picked up by the runner as far as I can tell.

If I look at https://www.drupal.org/project/cache_register/issues/3184391 , there is no option for me to test/retest a patch.
That tells me that you don't have testing configured for your project. To do that, you need to go to https://www.drupal.org/node/3183102/qa and choose "Add test / retest", then configure a test with the Drupal version, PHP version, database type/version that you want and choose when the test gets run. Once you submit that new test, it should immediately run. If you select "issue testing default" when you configure the test, then that configuration will run for Needs Review patches in your issue queue, and that will be the configuration that will run if someone in the issue queue manually triggers a test.
I don't see anything obviously wrong with the tests themselves, but it is clear that you don't have tests configured to run so it doesn't matter if the tests are working or not ...


How do I block google analytics from my development sites? Is there a way (in code or configuration) that I could prevent google analytics from collecting visits on any of my development websites?

just add the following line in in hosts file in computers which you want to exclude analytics tracking:

127.0.0.1 www.google-analytics.com


How to make the 'Module Updates' report available again? I have a 7.18 Drupal site running since a long time without updates. The update manager was deactivated since then as well.

Now I had to move the site to another server and after reactivating the update manager, it does not work properly. I have the status message that there are updates available, but the paths admin/reports/updates or admin/reports/updates/update only lead to the reports overview page.

Does anyone have a hint about how to fix this?

Here is a list of items to check:

Make sure core module update (= Update Manager) is enabled.
Clear all caches: if you get a WSOD while doing so, it indicates memory shortage.
Try running update.php: if you get a Fatal error like "Allow memory size of ... bytes exhausted", it indicates memory shortage.
Verify if it is a memory shortage issue: try increasing the memory a bit to check if there is any difference.


How are better exposed filters - checkboxes value - assigned I have been wrestling with this for a number of days. I apologize if this has been asked elsewhere, I am not able to find the fix, or maybe I am just not thinking in an incorrect way to make this work. One of my exposed filters searches using "Content:Has Taxonomy Term", I use the dropdown not autofill. With that created, I pull up my settings for better exposed filters. I expose my filter as checkboxes. the checkboxes that the Better Exposed Filters creates adds a number value to each of the checkboxes, not the taxonomy term name. Is there a way I can manipulate the output of the Better Exposed filter to show the name as the value, not id?

Here I create add a filter/filter criteria. you can see on the left I added a Content Has Taxonomy term (exposed)

Here you can see the criteria. I have clicked the "expose the filter to visitors" to allow the visitor to select how to filter. I click a couple options in the select list to show different predetermined options. and not shown, I select the option "limit list to selected items"

from the highlighted 1st image above, shows settings for Better Exposed Filters. I click the setting option, and for the display of that criteria, and for that filter, display filter as checkboxes.

After that, I can preview my checkboxes here.

If you inspect each of those checkboxes, you can see the value assigned to the checkboxes, is a number.

I believe it to be the Taxonomy Term ID?...

In this next screenshot, you can see the value from the checkbox represented as the same id.

This is where I get stuck... I want to show the term as the taxonomy term name, not id.
thanks in advance for your help!

This has nothing to do with Exposed filter settings, it's to do with what information is stored in the Taxonomy term Entity Reference field on your Content Type, and it's the term ID, not the term name.
So when you add the most ready-available Taxonomy Fields/Filters to your Content Views you will get the term ID.
Other Taxonomy term information (term name included) is stored in another database table and you have to add the Relationship for that particular field in order to pull information from that table into Views.
What you want is to add the Relationship for the Field on your content that stores the Taxonomy term reference. You can require the Relationship if you only want to see nodes in results where that field isn't empty.
After you add that Relationship you will get more options under Fields and Filters, one of those options is the Taxonomy term Name. They will use the Relationship by default since they can't be added to the Views without it.
Add the Name Filter to your Views and expose it. Adjust the Vocabulary settings and other options to your particular need.


Personal Contact Form granular permissions I want to be able to set specific permissions by role for the use of the Personal Contact Form.

Searching drupal.org shows a few modules to work with Contact forms, but none do what I am looking to do, so I'm wondering if I'm overlooking something simple.

What I would like to do:

Role A

Can have own Personal Contact form BUT it is only available to other Authenticated Users
Can access and use Personal Contact form for any other user (Role A or Role B)

Role B

Can have own Personal Contact form available to Anonymous AND Authenticated Users
Can access and use Personal Contact form for any other user (Role A or Role B)

Anonymous Users

Can only access Personal Contact Form for Role B Users, NOT Role A Users.

The idea is that Role B Users have the privilege of allowing the public / anonymous users to contact them via the Personal Contact Form, but all Authenticated Users should be able to contact each other using the form.

Should I do this with the Webform module?
Or is there some permission setting for the Personal Contact Form I am missing?

I don't want it to be binary (either you have a Personal Contact Form or you don't), but I want some types of users to be able to access some other users Personal Contact Form.

I would do this using hook_form_alter.

Set up your roles,  then create a function using hook_form_alter that checks if it's building the contact form or not.   If building the contact form,  check the current user's role,  and either redirect to a 403 or allow it to go through.


Show link only to user with permission to edit I'm using the following code to show the Edit button to edit pages in my blog teasers and others content types.

<a href="<?php echo '[node:edit-url]';?>">Edit

It works fine, but it shows for all users, even the users with no permission to edit. How can I hide it for users that don't have permission to edit?

Assuming that you are talking of the blog content type, you should need to use code that checks:

If the user who is currently viewing the blog node is the author of the node and has the "edit own blog content" permission
If the user who is currently viewing the blog node is not the author of the node and has the "edit any blog content" permission

<?php
  if ('[node:author:nid]' == $GLOBALS['user']->uid) {
    $permission = user_access('edit own blog content');
  }
  else {
    $permission = user_access('edit any blog content');
  }
?>
<?php if ($permission): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit
<?php endif; ?>

A more generic code would be the following one.

<?php $item = menu_get_item('[node:edit-url]'); ?>
<?php if (!empty($item['access'])): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit
<?php endif; ?>

This code is more generic because it shows the link whenever the current user has access to the edit link, whatever permissions are required to see that link. It could be a module alters which users can see the node edit page, and this code would take that in consideration.
The code is assuming [node:edit-url] is a URL like node/10/edit; if the URL is /node/10/edit or http://example.com/node/10/edit, then the code needs to be changed to extract the node/10/edit part, since that is the string menu_get_item() is expecting. See for example the code used by blog_menu_local_tasks_alter().

  // Add action link to 'node/add/blog' on 'blog' page.
  if ($root_path == 'blog') {
    $item = menu_get_item('node/add/blog');
    if ($item['access']) {
      $item['title'] = t('Create new blog entry');
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }

That code is part of the Blog module, and it uses menu_get_item() to check if the currently logged-in user has access to the page to create a new blog. It doesn't merely verify the user has the permission to create a blog node, since that would not be enough if a module changes when a user can access the node create form.
Also note that the argument passed to menu_get_item() doesn't have a / at the beginning.

Notice that the Token module defines a URL token type, for which it makes available the following sub-tokens:

path, the path component of the URL
relative, the relative URL
absolute, the absolute URL
brief, the URL without the protocol and trailing backslash
unaliased, the unaliased URL
arg, the specific argument of the current page (e.g. 'arg:1' on the page 'node/1' returns '1')

Unfortunately, at the moment the type for node:edit-url is not set to url; when it is, the following code will work.

<?php $item = menu_get_item('[node:edit-url:path]'); ?>
<?php if (!empty($item['access'])): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit
<?php endif; ?>


How to remove unwanted form state values before validation What is the good way of validating a form in Drupal 8 ?

I have a bunch of fields which are supposed to be filled by a positive numeric value (and that's all, no other input types, just positive int).

public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();

foreach ($values as $method => $fee) {
  if ($method != 'Free order') {
    if (!is_numeric($fee) || floatval($fee) < 0) {
      $form_state->setErrorByName($method, t('Value must be a positive integer.'));
    }
  }
}

}

The issue is when using $form_state->getValues() it also returns "submit", "form_token", "form_build", "form_id", "op" which is quite boring as those infos are not needed for performing validation.

So what I did is removing those four unwanted values with :

$values = array_splice($values, count($values) - 5, 5);

But it's really annoying, am I doing something wrong, or is just as it ? Because I think those values are really not necessary in the validation process.

The FormState class has a method for that: FormState::cleanValues(). From its description, it's the method you should use.

  This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.

  form_id
  form_token
  form_build_id
  op

You simply call it before getting the submitted values.

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->cleanValues()->getValues();

  foreach ($values as $method => $fee) {
    if ($method != 'Free order') {
      if (!is_numeric($fee) || floatval($fee) < 0) {
        $form_state->setErrorByName($method, t('Value must be a positive integer.'));
      }
    }
  }

Since FormState::cleanValues() returns the FormState object, you can simply call it in the same line you call  FormState::getValues() concatenating the two calls.

If you need to add more keys to remove from the submitted values, you could use FormState::setCleanValueKeys(), but keep in mind that:

The array passed to the method needs to contain also the default array keys Drupal would remove
The method alters the array keys that are removed from FormState::cleanValues() for every Drupal form


Access Value of variable content in twig template I'm new in a Drupal 8 and using Devel kint() function for debugging. In my twig template menu--main.html.twig, I have looped for the menu items like this:-

{% for item in items %}
   {{kint(item.url)}}

The output like this:-

What I should write to print the URI, I've tried {{item.url.uri}} but not working

You can try {{item.url.getUri}}.

You can change to tab Available methods to see other method. Example isExternal. :D


custom menu/sub-menu output what would i have to do to change the menu output structure for my theme?

this is the current structure:

                                //menu

Home

    Other Stuff

                            // sub-menu

Sub-Page 1

Sub-Page 1

what i would like to get is something like that:

Home

        Other Stuff  // the 'drop' class is for the styling of a menu item with child-items

            Sub-Page 1
            Sub-Page 2

Do you know of the nice menus module?  Nice menus will allow you to make dropdown menus without writing any code on your own.  You can also find instructions for customizing the Nice menus CSS here.

Nice menus has almost 60,000 installs as of this writing, indicating that it is likely to be supported well into the future compared to modules that aren't so popular.


Possible to hide admin toolbar for testing display I've worked on and off with Drupal for a few years.

One thing that has bothered me a bit, is that the admin toolbar at the top doesn't give you the full flavour of what the public will see.

I usually get around this by using a second browser where I'm not logged in.

I wonder if there is a simple url parameter or some other setting that can turn off or hide the toolbar for testing display.

searching the web reveals a trick with some permissions.

https://kitt.hodsden.org/blog/2011/02/turning_drupal_7_admin_toolbar

But using a second browser seems easier as I'll want this for just a few minutes at a time.

Could I write a simple plugin that will catch some url parameter and hide the admin toolbar, is there such a thing already?

If your using the built in D7 tool bar, take a look at Toolbar Hider.

  This module will hide/show the toolbar with the press of a key that
  you configure. It will optionally adjust the page padding to hide the
  white space. You can also configure if you would like to hide the
  toolbar by default.

If your using the contributed admin menu, there is also Admin Menu Hider, which does the same thing, but is in alpha.