Feeds: Error Importing Node Reference I am trying to import a node reference in my users's profile using feed and feeds profile modules and using a CSV file like this:

"Name","Email","Team"
"Pepe","Pepe@example.com","Team A"
"Juan","Juan@example.com","Team B"
"Pedro","Pedro@example.com","Team C"

My mapping configuration is like this:

SOURCE         | TARGET                                        | TARGET CONFIGURATION
Name             User name (name)                                Used as unique
Email            Mail                                            Used as unique
Team             team nid nid (profile2:main:field_team_nid_nid)

Team is a node reference to a content type that I had created.
When I try the import y receive this error message:

Invalid data value given. Be sure it matches the required data type and format.

The feed was expecting a node id and I was delivering a text value. I replaced the text value for node id corresponding in the CSV file and it works. I had to looking for node id value using phpmyadmin.


How can I show an image in a view using the Search API Views integration? I am using the Search API Views module; I have created an index of users, and on this site, there is an image field on the user profile with a single value (not a user picture, just a standard image field).

I am now making a view and trying to show the image from each user in a field of the view.  I added the Index User: Picture field, but when I do so, I have three choices for the display:

Show entity label (gives me the filename (image.jpg) with a link to the image)
Show entity ID (gives me the number of the entity)
Show complete entity (doesn't display anything)

I read this issue on images in Search API, which is marked as a duplicate of a fixed issue, but I don't understand how it is fixed or what I am supposed to display the image.

I want to show the image as a thumbnail in the view.  What's the easiest way to do this? (Given the filename, I imagine I could write a custom views template to print the thumbnail image as suggested in this question on Apache Solr Views, but it seems like there is probably an easier way (the linked Search API issue was fixed four years ago).

You're on the right track. To achieve this in Views:

Add the indexed image field to the View Fields list
Set 'Display' to 'Show entity label'
Untick 'Link to entity' - this adds additional HTML in the token used below that will stuff things up
Select 'Rewrite output of this field', and use this code:

<img src="/sites/default/files/[field_files_file]" />

Check the token is right, under 'Replacement tokens', but this should allow you to render the image into the View output.

From here, you can specify any inline attributes you want, e.g. width, height and so on.

You could achieve a thumbnail look this way, or alternately you could use image styles to generate a thumbnail of the image your users upload, then index that field instead. Note that image styles will save your new image under a different directory, so sites/default/files won't work.


How can i sell files using ubercart I want to sell files as product using ubercart.

How to add files using product content type?

I want user to pay for the file first and then get file downloaded.

Is it possbile?Then how ??

Also i want each role called 'vendor' to have there own payment details and get paid from buyers. Is that possbile?

Thanks.

There is already module File downloads in the ubercart which allow user to sell file with the product.

Install the module File downloads from the module list.

Assigning directory to file donwload:

Go to Administration -> Store -> Configuration -> Product
In the File download settings section, set the path of the directory of the files and save the form.

Uploading files:
- Go to Administration -> Store -> Products -> View file downloads
- Upload files into directory (which you have configured in above step) using upload file action.

Adding files to product:

Edit your product and you will get the feature link in top of page. click on this link.
In feature form, you can add file download feature to the product and it will redirect you to form to assign file to product.
Select file name in File download text field. This is autocomplete field, so you need to configure correct files and save form.

When the user purchase product and pay the amount, it will send a link to user in his mail to download the files.

Regarding your second question, there is module Ubercart Marketplace.

  Ubercart Marketplace adds multiple seller support to the Ubercart
  module. It includes a series of modules that limit the access to
  Ubercart functions for sellers. Additional functionality is added to
  support this from both a marketplace seller's point of view and the
  store administrator's view. Sellers (with the proper access
  permissions) gain the ability to view their products, track and
  fulfill their orders, and monitor their sales reports. Store
  administrators can view seller reports based on seller order statuses
  and seller sales. Support is included for Paypal Mass Payments, with
  which an administrator can automatically pay his/her sellers for
  custom periods.

Kindly see that Ubercart marketplace is still in development version for Drupal 7, so may be there could be some issue in this module.


How to insert custom redirect script in index.php without losing it on update At the moment I'm migrating an old site to Drupal. To redirect all old url's to new ones, I made a script that has to be inserted before anything goes off, so in index.php at the top.
   <?php

    include 'custom.php';

    use Drupal\Core\DrupalKernel;
    use Symfony\Component\HttpFoundation\Request;
    etc.etc.

All is fine until an update wipes this out.
Could (should?) it be done some other way to preserve this?

If you want to run code before the Drupal kernel is started use a middleware.
Use the drush code generator drush gen middleware and put your code in handle() of the generated middleware class:
MymoduleMiddleware.php
<?php

namespace Drupal\mymodule;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * MymoduleMiddleware middleware.
 */
class MymoduleMiddleware implements HttpKernelInterface {

  use StringTranslationTrait;

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

  /**
   * Constructs the MymoduleMiddleware object.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
   *   The decorated kernel.
   */
  public function __construct(HttpKernelInterface $http_kernel) {
    $this->httpKernel = $http_kernel;
  }

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

    if ($request->getClientIp() == '127.0.0.10') {
      return new Response($this->t('Bye!'), 403);
    }

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

}


drupal 6 to 7 site upgrade using drush_sup - how to download compatible drupal 7 modules I used drush_sup to upgrade my drupal 6 to 7 site. everything went smooth except the drupal 7 modules were not downloaded to the upgraded website.

During the upgrade process it did list the installed D6 modules, and the recommended D7 counterparts. I'm not sure what caused it to skip downloading it or maybe it just doesn't?

Thanks, any help appreciated.

I would run through the site upgrade process with the --prompt-all flag set to see if anything strange appears.

drush drush_sup will upgrade core and find good candidates for contrib modules, I think it'll even accept dev releases, but with a warning.

You could also pass in --auto to the command which will just do the defaults.

Source: http://drupalcode.org/project/drush_sup.git/blob/refs/heads/7.x-2.x:/README.txt


How to display image height and width in pixels? I have image size, but I can't find any field for image height and with in Views.

I need to display orginal image height and weight, something like: Resolution: 800px x 600px.

Have you created an image style for the image (what used to be ImageCache in Drupal 6 now in Core)?  Configuration -> Media -> Image Styles

If not perhaps you should because this will give you much more control over the size of an image without having to worry about theming the size directly.  Set up a preset for the image display in question and you can choose the size it should be generated at for a particular use.


Add/hide blocks on user page I have some blocks for navigation and side bars that are appearing all over the site.

I want to hide the navigation and sidebars on the following urls:

node/78
node/19
user
messages

For some reason, drupal will hide the nav and side bars on node/78 and node/19 but not the user and messages pages.   How do I make it disappear from the user and messages page as well?

What I've done so far was click on Structure>Block, then go to the block I want, configure it, and list the paths for the blocks I want to hide.

I think your solution here is to also include user/* and messages/* in your list.

So the whole list would read:

node/78
node/19
user
user/*
messages
messages/*


Create Content Type from code Following this post:
    http://www.sitepoint.com/creating-a-new-drupal-node-type/

I have tried to create a custom content-type from code like here:

Update code
https://github.com/jmvelasco/drupal

But the way, after install/activate it I get these warnings:

Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 270 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 274 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in FieldInfo->getField() (line 291 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 270 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 274 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in FieldInfo->getField() (line 291 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 270 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 274 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in FieldInfo->getField() (line 291 of /users/gen00/web/html/modules/field/field.info.class.inc).

Although the content-type is apparently created.

EDIT the content could be created once I update the base value

But when go to Create Content of this new content-type, I have the following error

array
  'error' =>
    array
      0 => string 'Warning: Missing argument 3 for node_form(), called in /users/gen00/web/html/modules/node/node.pages.inc on line 161 and defined in node_form() (line 107 of /users/gen00/web/html/modules/node/node.pages.inc).' (length=324)

Also, when uninstall the module I get this notice:

Notice: Trying to get property of non-object in content_access_node_type_delete() (line 524 of /users/gen00/web/html/sites/all/modules/contrib/content_access/content_access.module).

I can't figure out where is my mistake and I have come here wondering if any drupal-ninja could help me to understand my mistake and create this content-type correctly. Anyone?

Thanks in advance.

In your hook_node_info, 'base' should not be node. It has to be something else and generally your module name is advised.

Explanation from the node_example.module

// 'base' tells Drupal the base string for hook functions.
// This is often the module name; if base is set to 'mymodule',
// Drupal would call mymodule_insert() or similar for node
// hooks. In our case, the base is 'node_example'.


Find all contexts in which a block appears Is there a quick way to find, for a particular block, all of the contexts that can display it?

(I'm curious about Drupal6 and Drupal7.)

You can quickly find all the contexts in which a block appears by performing a code search. Exported Contexts are placed inside name_of_your_feature.context.inc files. So when searching your Contexts for a particular block name you could restrict your search to *.context.inc files. Here's an example Zend Studio/Eclipse search as described above:

My team generally puts Features (which contain exportables such as Contexts) in their own dedicated folder, making your code search faster and more efficient.

/modules
  /contrib
  /custom
    /features


Strip exif data from images It seems most people rather keep the exif data, and have trouble keeping it. I have the opposite problem - we have a profile picture upload and it keeps the exif data. I'd like to strip that off the images. Is there a way to actively do that?

You can do this by implementing hook_file_presave($file)

  This hook is called when a file has been added to the database. The hook doesn't distinguish between files created as a result of a copy or those created by an upload.

In this hook, you need to:

Test if file is really an image. I suggest using mimetype for this task: $file->filemime
Recognize which image processing library your Drupal is using. See image_get_available_toolkits(), image_gd_check_settings() and ImageMagick.
Process that file. This part is general programming issue already well answered on Stack Overflow - I see no point in reposting it here, I think I covered Drupal part of the question now.


Accessing content for a specific node revision via a relationship in Views A module I've written implements hooks defined by the Field API to provide a custom field for defining references to specific node revisions by storing vids. (The module borrows functionality from the Entity Reference, Node Reference and Node Revision Reference modules.)

I have a requirement for "parent" nodes to reference a specific version of one or more "child" nodes. The child node(s) may be modified (i.e. new revisions created) after a reference to it is stored against a parent node. It's essential that the reference on the parent node continues to refer to the same revision of the child node unless the reference is manually updated to a newer revision by a user with sufficient permissions.

I'm currently working on Views integration for the field defined by my module. When creating displays containing one or more parent nodes, I'd also like to be able to display field data for any referenced revisions of child nodes. I've defined the following relationship in my module:

/**
 * Implements hook_field_views_data().
 */
function mymodule_field_views_data($field) {
  $data = field_views_field_default_views_data($field);

  // Get database table info for $field.
  $storage = $field['storage']['details']['sql'];

  foreach ($storage as $table_data) {
    $table = key($table_data);
    $columns = current($table_data);
    $id_column = $columns['vid'];

    if (isset($data[$table])) {
      // Relationship: node revision referenced from $field.
      $data[$table][$id_column]['relationship'] = array(
        'title' => t('Referenced node revision'),
        'label' => t('Node revision referenced from !field_name', array(
          '!field_name' => $field['field_name'],
        )),
        'help' => t('A bridge to the node revision that is referenced via !field_name.', array(
          '!field_name' => $field['field_name'],
        )),
        'group' => t('Node revision reference'),
        'handler' => 'views_handler_relationship',
        'base' => 'node',
        'base field' => 'vid',
      );
    }
  }

  return $data;
}

This relationship allows me to display field content for child nodes where the referenced revision is the current revision. However, if an old revision is being referenced by a parent node, the field data is empty. This behaviour occurs when I create a view displaying either content or content revisions.

Does anyone know of a way of accessing field data for a specific node revision via a relationship in Views regardless of whether it's the current revision or not?

Thanks in advance to anyone who can offer any suggestions!

One thing you could try is creating a class that extends views_handler_relationship and override it's query() method using logic that's specific to your use case rather than the generalised logic that's in views_handler_relationship->query().  Then change the "handler" in your relationship declaration to point at your subclass.

Hope it helps.


Attach an image gallery carousel to nodes I want to attach an image gallery to a node, showing the images in a carousel view so that only a few thumbnails are shown and clicking on them opens a ColorBox overlay.

I have a gallery content type that contains all images in a field, and in an article the gallery is referenced using an entity reference field.

I found the Gallery Formatter module which does nearly want I want. But I don't want to display the large image on the page, only the carousel showing thumbnails. To get the full size image one should click on one of the thumbnails.

So I need a field formatter that can display the contents of an image field as a carousel. Any ideas on how I can achieve this?

Check out Adding a jQuery Image Carousel to your Node View.

Though the above article is for Drupal 6, you can follow this like below:

As the gallery is referenced in the "Article" content type, you can modify the template file for that content type, and fetch the gallery images.
After that, you can display that in carousel.

The other way is using a theme preprocess function.

function YOURTHEME_preprocess_node(&$variables) {
  // Your code.
}


How do I send a variable from PHP to JavaScript from a function that returns a render array? I'm trying to send a variable to my JavaScript. I would like to send a class name to my twig template and the same class-name to my javascript from a function that returns a render array. The function is called from a routing yml to display a page from a link in a page (which is beside the point).
The returned render array is similar to the following one.
return [
  '#theme' => 'theme_name',
  '#form' => $form,
  '#data' => [
    'customer' => $obj_customer,
    'customer_subscription' => $obj_customer->getSubscription(),
    'subscriptions_explanation' => $arr_subscription_text,
  ]
];

Passing data from PHP to javascript variable available to all pages in Drupal 8 says you can do something with '#attached' => ['drupalSettings' => ['do' => $something]] in hook_page_attachments(), but that doesn't seem to apply to the method I am using.
How can I do in my case? Adding stylesheets (CSS) and JavaScript (JS) to a Drupal theme doesn't seem to cover this use case.
In my JavaScript I define my JS functions inside:
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.portalCore = {
    someFunction() {
      ...
    }
  };
});

Is there perhaps a way to attach a variable to the portalCore from my example code?
EDIT (edited):
After applying kiamlaluno's answer: So If I call the drupalSettings in the console I see my assigned variable in there. But if I try to reach that variable from within (function ($, Drupal, drupalSettings) {} I get a cannot read property of undefined, obviously as logging drupalSettings logs undefined. When I remove the drupalSettings from (function ($, Drupal, drupalSettings) {}, I can reach my variable through drupalSettigs.myVar.
I, obvjously, should have included the drupalSettings in the final parentheses of the closure, like so (thank you @kiamlaluno):
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.portalCore = {
    attach(context, settings) {
      ...
    },
    functionName() {
      // Do stuff
    },
  };
})(jQuery, Drupal, drupalSettings);

It does apply to the method you are using. You can add metadata like #cache or #attached to any render element (#theme, #type, #markup, #plain_text):
return [
  '#theme' => 'theme_name',
  '#form' => $form,
  '#data' => [
    'customer' => $obj_customer,
    'customer_subscription' => $obj_customer->getSubscription(),
    'subscriptions_explanation' => $arr_subscription_text,
  ],
  '#attached' => ['drupalSettings' => ['do' => $something]],
];


allowed values for node/entity/user reference field Can you get allowed values for reference field?

i tried with:

$all_fields_info = field_info_fields();
$allowed_values= list_allowed_values($all_fields_info["field_user_ref"]);

but it is not working ..

For an entityreference fields use:

$allowed_values = entityreference_get_selection_handler("field_user_ref")->getReferencableEntities();


Addition to an integer field with a form I have a bundle of image nodes of the same content type that I create in my custom form. Each image node has a field that contains a unique reference number to that node. Currently it is up to the user to add +1 to the previous image node saved and type that in the form for the next reference number. How can I add +1 to the last saved field and use the result to populate the saved field displayed on the saved node? More advanced: If I use an AJAX form that allows users to add more fields to add more pictures on the image creation form, how could I save the images with consecutive IDs?

You can use the module Prepopulate ; latest release is dev but I use it on a production site and it works like a charm.

If it doesn't work tell me, there are two other solutions : send an arg in the URL to the form (and then use Panels or the php template) and JavaScript (I can give you the code if you need it).


How to to redirect a form to a certain node for anonymous users? In a custom module, I have a form that is triggered by an option in a menu.
I'd want this form to be redirected automatically (without action of the user) to a certain node (/node/2) when the user is not authenticated.
In the public function buildForm(array $form, FormStateInterface $form_state) {, I know how to not display the fields of the form for the anonymous user:

$oCurrentUser = \Drupal::currentUser();
if ($oCurrentUser->isAnonymous()) {
} else {

some fields...

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

I guess that redirection might be done with   $form_state->setRedirect('entity.node.canonical', ['node' => 2]);
but I don't know how to make it work...
Any idea?

In buildForm() you can return a redirect response the same way as in a controller:

  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect('entity.node.canonical', ['node' => 2]);
    }

    // build $form for authenticated users

    return $form;
  }

Use $form_state->setRedirect() if you want to redirect in a form submit handler.

Using buildForm() as controller by specifying _form instead of _controller is documented and widely used (not in FormInterface, but on DO: https://www.drupal.org/docs/8/api/routing-system). It's unlikely core will ask devs to replace it by their own controller.


Drupal 7 - eRecruiter profile with Solr Fatal Errors I just installed Drupal 7 using the eRecruiter profile release but I am gettig loads of errors. I know it's not me server as I run 10 other drupal site on my server and there is nothing showing up in the drupal logs.

These are the errors:

This one when I click in Job Search:
Fatal error: Call to a member function pre_execute() on a non-object in /var/www/vhosts/xxx/public_html/profiles/recruiter/modules/views/plugins/views_plugin_display.inc on line 2432

This one when I click on Resume Search:

Fatal error: Call to a member function pre_execute() on a non-object in /var/www/vhosts/xxx/public_html/profiles/recruiter/modules/views/plugins/views_plugin_display.inc on line 2432

And this when I click on My Resume:
Fatal error: Call to undefined function entity_i18n_string() in /var/www/vhosts/xxx/public_html/profiles/recruiter/modules/field_collection/field_collection.module on line 913

I used the exact drupal and module releases that were included with the profile from here:
http://epiqo.com/recruiter

I got the errors... did some searching on line and one person recomended updating Drupal and ALL the mondules. I did all the updates but the errors are still present.

I have installed Apache Solr and it's working fine and drupal says that it has found it.

I then tried to install it localy on my mac and I'm getting the same errors.

My php_error.log reported the following:

[01-May-2012 17:50:28] PHP Fatal error:  Access level to SearchApiViewsHandlerField::$additional_fields must be public (as in class views_handler_field) in /Users/xxx/Sites/vhosts/eRecruiter/profiles/recruiter/modules/search_api/contrib/search_api_views/includes/handler_field.inc on line 195

and:

I get the same sort of log message when I click on Job search, Resume search and my resume.

Here's a link to the online demo version: http://drupaljobs.epiqo.com/

I'm desperatly needing help with this as I have spent hours search forums and blogs.. got me nowhere :(
Any help will be much appreciated.

C

A lot of errors here, let's see if we can do something..

Job/Resume Search

Fatal error: Call to a member function pre_execute() on a non-object..

When you try to invoke the action, the result does not return the query object, and for that reason you have this error, for example.

php_error.log

PHP Fatal error: Access level to SearchApiViewsHandlerField

Changing from protected to Public Field made solve this issue.

My Resume

Fatal error: Call to undefined function entity_i18n_string() in

Entity 7.x-1.x-dev released on February 28, 2012 - 08:13 no longer contains the function entity_i18n_string().


Records with identical uid and timestamp in node_revision I'm investigating an issue on a D7 site where a handful of node revisions have apparently gone missing. The issue was discovered on 3/5, and I just noticed in my node_revision table that several records were created on 3/4 with the same uid and the same timestamp (1362422613). How is this possible? Might it indicate a MySQL problem?

DISCLAIMER : Not a Drupal Developer, just a pure MySQL DBA
Here is a sample node_revision table:
mysql> show create table node_revisions\G
*************************** 1. row ***************************
       Table: node_revisions
Create Table: CREATE TABLE `node_revisions` (
  `nid` int(10) unsigned NOT NULL DEFAULT '0',
  `vid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL DEFAULT '0',
  `title` varchar(255) NOT NULL DEFAULT '',
  `body` longtext NOT NULL,
  `teaser` longtext NOT NULL,
  `log` longtext NOT NULL,
  `timestamp` int(11) NOT NULL DEFAULT '0',
  `format` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`vid`),
  KEY `nid` (`nid`),
  KEY `uid` (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=227825 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql>

Strictly in terms of MySQL, there is nothing in place to prevent the same UID and timestamp from entering this table multiple times. The index uid is a non-unique index on the uid column. What you need is a UNIQUE INDEX to prevent this at the database level.
Run this query:
SELECT uid,timestamp,COUNT(1) ut_dups FROM node_revisions
GROUP BY uid,timestamp HAVING COUNT(1) > 1;

and this will uncover other UIDs with the same timestamp issue.
If you want to block rows from entering this table with duplicate (uid,timestamp), change the indexes as follows (making a backup first):
#
# Backup node_revision
#
CREATE TABLE node_revision_backup LIKE node_revision;
INSERT INTO node_revision_backup SELECT * FROM node_revision;
#
# Change Indexes
#
CREATE TABLE node_revision_new LIKE node_revision;
ALTER TABLE node_revision_new DROP INDEX uid;
ALTER TABLE node_revision_new ADD UNIQUE INDEX uniq_uid_timestamp (uid,timestamp);
INSERT IGNORE INTO node_revision_new SELECT * FROM node_revision;
DROP TABLE node_revision;
ALTER TABLE node_revision_new RENAME node_revision;

The UNIQUE INDEX uniq_uid_timestamp physically prevents (uid,timestamp) from appearing more than once. Check the contents of node_revision and make sure it is proper.
If it looks good, you could run:
DROP TABLE node_revision_backup;

or keep the backup.
If it does not look good, run this:
ALTER TABLE node_revision RENAME node_revision_old;
ALTER TABLE node_revision_backup RENAME node_revision;
DROP TABLE node_revision_old;

Give it a Try !!!
CAVEAT
You will need to check all modules involved that writes to the node_revision table.


Create a module that add text/image to a specific type nodes So.
I need to create a module that add something like text, to all my nodes of type "Article" for example.

I need a module that do:
- Find the type of nodes "Article"
- And add a label that says "Made by me ..."
And everytime i see articles, they all have the normal fields (title,body,tag,image) and my label..

Its possible?

Various ways of doing this. Either edit your tpl file. Create a node--article.tpl.php in your theme folder (copy the syntax from node.tpl.php) and modify the code to add your desired label. If you need to print username then the global $user is available. Just define it as global and access username as $user->name.

Or you could use Panels module. It's very flexible and powerful.

For creating custom module to do this, there are various approaches. One good way is this:

In your custom mymodule.module file, use the hook_node_view like this:

function mymodule_node_view($node, $view_mode) {
    if ($node->type=="article"){
        if ($view_mode == 'full'){
            $node->content['my_extra_content'] = array(
                 "#markup"=> 'Made by me!',
                 "#weight"=> 100
              );
           }
         return $node;
   }
}

After this, Made by me should appear at the bottom of each node. If you want it to appear at the top, then just modify the weight and give it some negative value.


How to add contextual fields to breadcumb links? How can contextual fields be added to breadcrumb links?

For example, I have a hierarchical taxonomy vocabulary like this:

Animalia
--Chordata
----Vertebrata

On the Vertebrata page, the default breadcrumb looks like this:

Home >> Animalia >> Chordata

Each taxonomy term in the vocabulary has a "common name" field, so for Animalia it would be "animals", and for Chordata it would be "chordates". I would like the breadcrumb to look like this:

Home >> Animalia (animals) >> Chordata (chordates)

A similar example can be seen on this page, where a taxonomic rank field appears after each link in the classification breadcrumbs.

Besides achieving this with taxonomy breadcrumbs, I would be interested to know if a similar solution is achievable for menu breadcrumbs generated by the Menu Breadcrumb module.

I'm not aware of any contrib module that is capable of adding custom fields as suffix to breadcrumb links.

Fortunately, Drupal 8's modular architecture enables you to add your own breadcrumb builder service with a little bit of custom programming.

You will have to create an own module (within the following example, I'll call it my_module or MyModule respectively; you'll have to replace it accordingly) and add a my_module.services.yml file to its root directory.

Within this file you can define your own breadcrumb builder service. Make sure to let Drupal know, that it is a breadcrumb builder and in which order it should be processed by adding the relevant tags (read more about service tags here):

services:
  my_module.breadcrumb:
    class: Drupal\my_module\Service\MyModuleBreadcrumbBuilder
    arguments: ['@entity.manager']
    tags:
      - { name: breadcrumb_builder, priority: 10001 }

Now that Drupal knows about your breadcrumb builder and will process it fairly early because of the high priority given, you will have to create the according class.

Create a service class MyModuleBreadcrumbBuilder.php in your my_module/src/Service/ folder. Apart from the convention to letting its name end on BreadcrumbBuilder, you can actually name it to your liking. Just make sure to change the class name within the .services.yml file and the follwing example accordingly.

As you are up to creating a taxonomy breadcrumb builder, a good starting point is the TermBreadcrumbBuilder of the taxonomy core module, which we will extend in our example:

namespace Drupal\my_module\Service;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\taxonomy\TermBreadcrumbBuilder;

/**
 * My custom breadcrumb builder for Animalia.
 */
class MyModuleBreadcrumbBuilder extends TermBreadcrumbBuilder implements BreadcrumbBuilderInterface {

}

As your requirements seem to apply to a certain taxonomy vocabulary only, you should implement the BreadcrumbBuilderInterface::applies() method to check whether you are on a term page of that vocabulary.

This assures your breadcrumb builder won't run on other entities/vocabularies that don't feature your custom field (I used the ID my_vocabulary for your vocabulary; you will have to replace it accordingly):

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\taxonomy\TermInterface;

[...]

/**
 * {@inheritdoc}
 */
public function applies(RouteMatchInterface $route_match) {
  return $route_match->getRouteName() == 'entity.taxonomy_term.canonical'
    && ($term = $route_match->getParameter('taxonomy_term')) instanceof TermInterface
    && $term->getVocabularyId() == 'my_vocabulary';
}

The next step is to implementing the BreadcrumbBuilderInterface::build() method, that returns the actual breadcrumb. Here, we'll add your custom field value to the shown parent term link labels.

As we extended the taxonomy breadcrumb builder before, we already have the entity manager and term storage available, which enable us to loading the localized versions of the terms.

Most of the proceedings match the TermBreadcrumbBuilder::build() method, so that I added a comment only where the term field value is added:

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Link;

[...]

/**
 * {@inheritdoc}
 */
public function build(RouteMatchInterface $route_match) {
  $breadcrumb = new Breadcrumb();
  $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
  $term = $route_match->getParameter('taxonomy_term');
  $breadcrumb->addCacheableDependency($term);
  $parents = $this->termStorage->loadAllParents($term->id());
  array_shift($parents);

  foreach (array_reverse($parents) as $term) {
    $term = $this->entityManager->getTranslationFromContext($term);

    // The 'magic' happens here by loading the field value and
    // adding it to the link title; alter 'field_common_name' to
    // match your custom field ID.
    $my_field = $term->get('field_common_name');
    $term_name = $term->getName() . (!empty($my_field->getValue()[0]['value']) ? ' (' . $my_field->getValue()[0]['value'] . ')' : '');

    $breadcrumb->addCacheableDependency($term);
    $breadcrumb->addLink(Link::createFromRoute($term_name, 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));
  }

  $breadcrumb->addCacheContexts(['route']);
  return $breadcrumb;
}

After enabling the module (or flushing the caches, if you already enabled it before), you should now see your custom breadcrumbs when you open a term of your vocabulary.


Define module parent item to contain other module items I want to define section of items in administrative area, for my custom module operations.

I defined some items with hook_menu in /admin/config/development/
But i would like now to make a section, that will containt those menu items, so on click on that parent item i would be presented with those "contained" items.

It is like, when you have admin/, you click Configuration and you get to the screen with all the items contained ( admin/config/ ).

It is probably very simple, but somehow could not trample on it!
Thanks!

What you are trying to achieve is really simple. You need not use any additional code. You just need to follow the correct menu structure. I've posted a sample code below

     function mymodule_menu() {
      $items['admin/config/development/mymodule'] = array(
      //Your code here
      );
     $items['admin/config/development/mymodule/sub-module-1'] = array(
      //Your code here
      );
     $items['admin/config/development/mymodule/sub-module-2'] = array(
      //Your code here
      );
      return $items;

}

You need to clear the cache. Sometimes you might need to disable and re-enable your modules to register the menu. Now when you click mymodule menu item, a list of all your sub modules will be displayed.


Drupal 7 - Exposed form block also inside results In Drupal 7 I created a view with an exposed form in a block.
The view has a "page" display.

Users can make their searches using the exposed form in the pages where I placed the block.

I would like to put the filter also in the results page, but it is placed always after the results, while I would like to have that between the page title and the results.

Example:

what happens

PAGE TITLE

VIEWS RESULTS

EXPOSED FORM

what I would like to do

PAGE TITLE

EXPOSED FORM

VIEWS RESULTS

Any idea?
thank you in advance

As I write below, I found the solution:

I had to:

1) Create the view
2) Expose the form
3) Add a "Global PHP" in the view header with the following code:

$block = block_load('views', '-exp-myview-page');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
print $output;

Surely it can be done also using template instead of the php in the header.

You can override View tpl file and do the arrangement as per requirement. Also check the setting for exposed for under view.


Add custom orderBy in ViewsSort plugin I'm attempting to sort the results of a View by matching one of the Entity IDs in the result set to the referring URL Entity ID. I'm trying to do this in a custom Views Sort plugin. I did some research on Custom Views Sort plugins and came across this link:

https://medium.com/oleksandr-trotsenko/drupal-8-views-tutorial-for-developers-part-iii-sorts-filters-49baa40418de

Following the tutorial, I arrived at the simplest hook_views_data() entry:

$data['node_field_data']['nid'] = array(
    'title' => t('Custom trials sort'),
    'group' => t('Content'),
    'help' => t('Sort events by by referral source.'),
    'sort' => array(
      'id' => 'trials_sort'
    ),
  );

I added this sort to the View in question. In the class with the id trials_sort I've added this method:

public function query() {
  $this->ensureMyTable();
  $has_custom_sort_id = $this->detectCustomSorting();
  if($has_custom_sort_id !== FALSE){
    $id_to_top = $has_custom_sort_id;

    $sql_snippet = <<<EOF
CASE $this->tableAlias.nid
  WHEN nid = $id_to_top THEN 1 ELSE 2
END
EOF;
    $this->query->addOrderBy(NULL, $sql_snippet, $this->options['order']);
    dd($this->query);
  }

}

The goal was to get an ORDER BY like:

ORDER BY (CASE WHEN nid = $id_to_top THEN 1 ELSE 2 END);

All of this is executing on the appropriate view. However, Drupal is adding the SQL in an odd way. In the above code, my ORDER BY looks close to right:

But my fields array looks very wonky:

I'm clearly missing something that tells Drupal to interpret this additional orderBy as a formula. How do i do that?

As shown in this SO answer:

How to sort on different columns in the same view?

the views SQL object uses ->addField instead of ->addExpression. This code ended up working for me:

  public function query() {
    $this->ensureMyTable();
    $has_custom_sort_id = $this->detectCustomSorting();
    if($has_custom_sort_id !== FALSE){
      $id_to_top = $has_custom_sort_id;
      $this->query->addField(NULL,
        "nid = ".$id_to_top, 'is_match');
      array_unshift($this->query->orderby,['field' => 'is_match', 'direction' => 'DESC']);
    }
  }

The array_unshift just moves the is_match sort before the draggableviews sort which is also on this View. For some reason, re-arranging them in the View UI caused the draggableviews sort to drop off. Hope this helps someone in the future.


How to parse mysql query output as variable into another command in linux via Drush? Currently I'm doing a mysql query via the command line using Drush and I want to parse the query output and grab the Node ID #, then put that ID # into a drush php-cli 'node_delete(X)' command. How can I do this? Currently I have the command:

drush sql-query 'select * from node where type="feed_item" AND status=0 limit 1 \G'

then

drush php-eval 'node_delete(X)'

I think I'm suppose to use the command xargs?

From there how can I make this as a loop and delete everything that get's outputted? Yes I know I can just do it via the site, but i want to know how to do it via the command line using only Drush. Eventually I just want to make an interactive bash script where I can just put in the node ID range numbers and it will just delete it at once.

Based on the query that you've provided, you're just getting one unpublished feed_item, then deleting it. This can be done in one line, without an intermediate bash step.

drush ev "node_delete(
  db_select('node')
    ->fields('node', array('nid'))
    ->condition('status', '0', '=')
    ->condition('type', 'feed_item', '=')
    ->range(0, 1)
    ->execute()
    ->fetchField()
);"

If you wanted to delete multiple nodes at once - or all nodes returned with your conditions, then use https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_delete_multiple/7 , remove the range and use fetchCol() to return an array of NIDs.

drush ev "node_delete_multiple(
  db_select('node')
    ->fields('node', array('nid'))
    ->condition('status', '0', '=')
    ->condition('type', 'feed_item', '=')
    ->execute()
    ->fetchCol()
);"


Will migrating content types be possible? I have a Drupal 7 site with 40 content types. When Drupal 8 will be released than I would like to migrate these content types.

Would this be possible, or would I have to create this content types from scratch?

I guess the best place to search for upgrade process is UPGRADE.txt file. Here you can find the step-by-step approach to follow in upgrading the site from Drupal 6/7 to Drupal 8.

Drupal 8 core will include a robust data migration API: https://drupal.org/node/2121299, part of the IMP initiative: https://groups.drupal.org/imp . Also you can check the recently updated list of modules that are included in Drupal 8 core: http://blog.merge.nl/2014/01/21/drupal-which-drupal-7-modules-went-into-drupal-core

Few of the links that you check:

Getting your site ready for Drupal 8: http://www.acquia.com/blog/getting-your-site-ready-drupal-8
Drupal 8 - Improved upgrade process: http://www.acquia.com/blog/d8migrate
Converting modules from Drupal 7 to Drupal 8:http://webchick.net/upgrade-modules-d8
Converting 7.x modules to 8.x: https://drupal.org/update/modules/7/8


How can I unpublish the content profile node when users update their user account? I would like to unpublish automatically the content profile node of the users who updates their user account at user/%/eidt.

I found a event "User account details have been updated" in Rules but didn't find the action to unpublish their content profile node.

You can use the "Set data"-action to set the profile node's status to 0: status=1 means published, status=0 means unpublished.


Multi step form with click and state logging in Drupal 7? I need to create two separate forms flows. Essentially the one case has 3 pages (intro, questions, thank you), while the other has 4 pages (intro, questions, questions, thank you). I want to be able to:

Log the states of each "step" as the user proceeds
Keep track of where the user clicks and in what sequence

I am thinking of doing the second part with Google Analytics, as I know it has ways to do this. However, I am not sure what is the best way to go with the multi step form process.

So far it sounds like I would have to create content types for each step and use rules to "guide" the user as he creates the different content types. However, this sounds like a nightmare when it comes to "back" and 'next" functions.

Can anyone please tell me what is the best way to implement a form like this, keeping in mind how important it is that the logging works perfectly.

I can't say that this is the best way, but you can achieve that using the Webform module.

You can create multi step form using Webform module. Add Page break type to form components to split the form.

In Advanced Form Settings you can manage the multi step form actions like 'Automatically save as draft between pages and when there are validation errors' options.

In you want to provide advanced navigation bar for multi step web from you can try the Webform steps module

  This module provides a navigation bar for multi-page webforms. The navigation bar is a set of buttons placed at the top of each webform page. The buttons allow free navigation between steps that have already been visited.


Display Nested Content Type References In D8 I would like to know how best to manage a content type having 1:n parent-child relations in Drupal 8.

I need to display a view of the relationships. Although in theory unlimited I anticipate the depth will not exceed 4 generations.

As shown in my diagram below, C is a child of B. D & E are children of C etc:

-instanceA
-instanceB
--instanceC
---instanceD
---instanceE
----instanceF
...

I presume entity reference is the way to go. From my limited D6/7 experience I prefer having a parent ref on a child (having unlimited child inline entity references can seem confusing to my less web savvy users - a single parent from a drop down select is clearer). Although I am happy to be convinced otherwise if other factors outweigh this.

This stack exchange answer suggests the Views Tree module might have worked but it does not seem to be porting to D8.

I think waiting for the Views Field View module to be ported to D8 might provide a solution but this seems overkill.

This is such a basic need I suspect in my lack of experience I am missing a simple solution. Any suggestions how best to approach this appreciated.

Yes I was missing an obvious answer. As provided by steeph on drupal forum.

Have an entity reference (unlimited) that points at the children. In the content type teaser display include the children field and set that to display the teaser view. You then have a recursive view of all descendants in teaser view mode. Obviously you could create a custom view mode if needed but this is the principle.

Create a view which at the top level only displays views which have no parent (using relationship and filter). Make sure it is set to display content>teaser and you should be seeing a flat list of instances. Use css to add a margin-left to your list-items and job done.


How To Hide the Contact Button and Replace with a Message I'm building a room letting website.
Next to every advert is a send user private message button.

If the room is no longer available.
I want to replace the button with the message "Sorry room no longer available"
how can I do this please?

Many Thanks for your help
Charles

You can use hook_form_alter. Find your form name and use the code below (form api doc).

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
if($form_id=='your_form_id'){
 hide($form['#submit']);
$form['mymessage']= array(
   '#type' => 'markup',
   '#markup' => 'sorry , no one available in room',
   '#weight' => 0,
);
}
}


Drupal Commerce Relationship Description A small question:

Shouldn't the Help text in the commerce_line_item module at line 1582 that defines the relationship between commerce_line_items and commerce_orders say something like "Relate this entity to the order to which it is attached".  As it now stands, the text says "Relate this entity to the line items reference by its commerce_line_items field".  Which doesn't seem to make much sense.

OK, I think I understand this now, and the Help text is actually correct as it stands.

Each order, it turns out, has a commerce_line_items [note the plural] field attached to it, and it is this field, of unlimited cardinality, that stores all of the commerce_order/commerce_line_item pairs that are associated with this order.  What this relationship does, then, is make the commerce_line_item reference field that is stored in the commerce_line_items field available to the view designer. Once this commerce_line_item reference field is available, all of the fields in the commerce_line_item itself become available.

The thing that was confusing is that the commerce_line_items field does not show up in a Site Builder's "Manage Fields" configuration screens, and I had not been able to find it in the code.  Many thanks to argiepiano, who showed me where to find the definition of the commerce_line_items field [in the commerce_order module], and the place where data is saved into that field [in the commerce_cart module].

So that is the way that this all works ...

... I think.


modifying option text in ubercart attributes I am made an attribute with mulitple options on my Ubercart Product. I made an adjustment to the price of some of the options ie: -38 (its 38 less dollars) but now on the dropdown, it has the option name followed by ', -$38.00). How can I get rid of this text?

Go to this URL in your Drupal site:

admin/store/settings/products
You will find a list of menu in that click Attribute settings
You will option for price format in that select the first radio button do not display


How to fire a Rule when an image is removed from Image field with unlimited values? Working with Drupal 7.58 and File Entity 2.19 and Rules 2.10

First I needed to fire a rule when saving a new file and I found a solution (here).

Now I would like to fire a rule when an user removes an image (file) from a content (Image field with multiple values).

I can not find any event to start working after an image is removed?

EDIT 1 :

Following @Pierre.Vriens "check list approach", I have tried to create a simple rule fired when an image is removed :

{ "rules_verify_pictures_removed" : {
    "LABEL" : "Verify pictures removed",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "image" ],
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node-unchanged:field-pictures" ] },
          "ITEM" : { "list_item" : "Previous list item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : { "list" : [ "node:field-pictures" ], "item" : [ "list-item" ] } },
                  "DO" : [
                    { "drupal_message" : { "message" : "Picture has been removed.", "type" : "warning" } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

Unfortunately, condition is always False and I get the message even if no item has been removed (One message for each item, unchanged, added or removed)

To my knowledge there is no Rules Event like the one you are looking for. However, as illustrated in my answer to the question you linked to, you can use an approach like so:

iterate over all field values of your field of the unchanged node.
within each iteration step, check if the list of items in the changed node does NOT contain the field value being processed in the current iteration step ... If it is NOT contained in it anymore, it means  the values is removed.

Note: processing image fields in Rules is a bit special. You may have to use a token like [node:field-pictures:file:url] and [list-item:file:url]. And if they appear to be empty, then retry by adding a Rules Condition like "content is of type = article"


How to print all Webform messages outside the form? Does anybody knows how to print all messages (confirmations or error messages) outside the form (created using the Webform module, for example right after the body tag?

I've changed the markup of my alerts. I want them to be full screen, but I can't achieve this, when they're inside the form.

Yes, Webform is working on drupal default message

<?php if ($messages): ?>

    <?php print $messages; ?>

<?php endif; ?>

You need to put this code according to your requirement on the template (page.tpl.php).

Finally, webform submission thank you message will be shown on your content section which is coming on node.tpl.php

<?php print $links; ?>


Add class to body depending on role of author of user page I need to add a class to the body based on the author of the user profile page. I have two roles on my site: standard and premium. I would like to create a body class to reflect this. So, if I am on a standard member's profile page (regardless of my role) "standard-member" would be added to the body classes. If I am on a premium member's profile page (again, regardless of my role) "premium-member" would be added to the body classes.

Is this something that can be done with the context module?

This can be achieved by using the template_preprocess_html function in the template.php file of your theme.

function yourtheme_preprocess_html(&$vars) {
  if (arg(0) == 'user' && is_numeric(arg(1))) {
    $user = user_load((int) arg(1));

    if (in_array('standard', $user->roles)) {
      $vars['classes_array'][] = 'standard-member';
    }

    if (in_array('premium', $user->roles)) {
      $vars['classes_array'][] = 'premium-member';
    }
  }
}


Set the Contextual Filter: Author uid. to a default user? I have a view called Map Items showing a list of map markers in a chart.

Info: I have 3 Accounts in my drupal installation called person1, person2, and admin.

I've set the contextual filter to Author uid: User ID from Logged in user. and its working perfectly, but what I want some additional setting that when there is no logged in user I could set person1's map item to show. Right now when there is no logged in user the view shows the map item of admin user and not person1.

How am I going to accomplish this?

In contextual filters instead of selecting User ID from Logged in user select php code and write some code like

global $user;
if($user->uid > 0){
$uid = user_load($user->uid);

$roles = $uid->roles;
if(in_array('administrator', $roles)){
return 'uid of the logged in user';
//print_r($uid->roles['3']);exit;
}
else{
return FALSE;
}
}
else {
return 'return here person1 uid';
}


Change value on validate form when I create or edit a block I need change a value to element on form validation.

I have this code:

/**
 * Implements hook_form_FORM_alter().
 */
function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'block_content_MY_BLOCK_form' || $form_id == 'block_content_MY_BLOCK_edit_form') {
    $form['#validate'][] = '_custom_validate';
  }
}

I want change the value of field field_test. This field is plain text.

function _custom_validate($form, FormStateInterface $form_state) {
  $form_state->setValueForElement($form['field_test'], 'changed');
}

But when I saved this block, the field field_test doesn't change its value.

What I am doing wrong?

Please insert the validate method inside the #element_validate function and then change the element value.

/**
 * Implements hook_form_FORM_alter().
 */
function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'block_content_MY_BLOCK_form' ||  $form_id =='block_content_MY_BLOCK_edit_form') {
       $form['field_test']['widget'][0]['#element_validate'][] = '_custom_validate';
      }
    }

function _custom_validate(&$element, FormStateInterface $form_state, &$complete_form) {
  $form_state->setValueForElement($element,['value' => 'See the change']);
}


Example of how to configure contextual filters with taxonomy using php arguments to display a view of commerce products? Currently I am trying to configure view to display a grid of commerce products that matches a specific taxonomy term. This term is a term reference field in the product display. I also have a view reference field in the product display. Right now I am trying to pass that taxonomy term into the referenced view as an argument.

I am having the issue of grabbing the 2nd argument path in views. I'm using the PHP option of the context filter.

As you can see from the sql statement it selects only the 1st argument, its suppose to select the 2nd one as seen in the contextual filter options. I'm not sure if its a bug in itself or i have something wrong with my code.

screenshot of view: http://prntscr.com/18qy2f

screenshot of contextual: http://prntscr.com/18rn4v

when it is working it should look like this: http://prntscr.com/18rs0i

In this scenario, i made the first argument as 3ds, which gives me the output i want. But on the top scenario where I want the 2nd argument, it still grabs only the 1st argument.

This is what it should look when it works. It takes the 1st argument. http://img844.imageshack.us/img844/4830/lgt7424d.png

it also seems that the TITLE doesnt recognize  %2 or %3. see here: http://prntscr.com/18rx3i

On the first run, I was taking the approach of fetching the URL path that contained the related taxonomy data using the contextual filter's path argument selector.

After a good number of hours, I took a completely different approach to solve this problem. I actually figured out how to load the taxonomy field data into the contextual filter via php using the following code:

It will now grab any taxonomy data on the page if it exists. You will need to change it to your field settings.

return menu_get_object()->field_EXAMPLE_vocabulary[und][0][tid];

You can view my views configuration setup here: http://prntscr.com/18snhm

Looks like this once implemented:

http://img703.imageshack.us/img703/3733/lgt1356.png


Configure Panels That Uses View With Entity Reference For User Profile I am having a hard time setting up my Panels page for the
user profile page   ie:  /user/%user

I am using the "Reference" module, and have my content type "News" reference users.
I created a view for this called "User News Reference" to make sure it is working correctly.  The view has a "page" and a "block".  The "page" display for the view correctly returns the referenced data when you manually put the user's id in the path.

I then went to panels and used the Panel's page for the User Profile Page, ie: /user/%user
I created a variant and my user's profile to the top of the content and then I added the view "User News Reference" to the center content.  I then loaded the user page with a valid user that has referenced "news" content, but the referenced material never shows up.

I created images of every step along the way to help you help me diagnose the problem:

1) First here is my view that I created that returns "news" content that references the user.

2) Here is the view in page display showing the "news" content that references the user with id = 1 (added to show that the references are configured correctly)

3) here is the panel page. In the context section I first have the User Profile, and then the "User News reference" view.  I followed it up with some custom content to show that the panel page is actually loading correctly and the page shown is the User Profile Panel page.

4)After setting all of that up here is the page for user 1.  This is the Panel's version of the user profile.  Note that you can see the profile and the custom content, but not the "news" referenced content from the view.

5)To be sure that the view was loading properly, I went to the view and changed the contextual filter from "display no results if the filter value is not in the url" to "display all results for the specified field" and reloaded the user profile for user 1.  then all of the "news" content is returned on the user profile page for user 1, proving that the "User News Reference" view is loading properly for the user profile panel.

Can someone help me understand what I need to do correctly to get the user:Uid to show up in the url for the view used in the panel?  I believe the view used in the panel is using the "block" display of the "User News Reference" view, but not sure how it is misconfigured.

I thought it might have something to do with the "context" section in for the Panels User Profile.

I thought I had to add another context, and tried under "user", but the only option was the currently logged in user, or a user by name.

The %user portion of your URL is called an argument.  Your final screenshot shows that argument and that you can use %user_uid in your page.  So that's the context handled.

Instead of a page or block, make a content pane for your view, you will need to enable the Views content panes if you haven't already.

In that content pane, set your argument to From context and choose User->User ID from the dropdown.  This tells the view where to get the information for your contextual filter (which looks ok I think).

Once you have saved that, go back to your page in page manager and insert the view pane as content, it will ask you where to get its argument from, choose Argument 1 because that will refer it to the %user portion of your URL.


Webform theming field labels through webform-form.tpl.php I'm theming a Webform I created by using a custom webform-form-[nid].tpl.php template. I've been able to render individual fields fine, but I'm having a problem with the date field which is split into 3 fields (month, day, year).

To wrap each item in custom HTML, I render each of those fields like this:

 <?php print drupal_render($form['submitted']['birthdate']['day']); ?>
 <?php print drupal_render($form['submitted']['birthdate']['month']); ?>
 <?php print drupal_render($form['submitted']['birthdate']['year']); ?>

But the label is automatically being rendered separately, so how can I render it manually?

This is the output that I'm getting: (simplified for ease of understanding)

    Month
    <select name="submitted[birthdate][month]">
      <option selected="selected" value="">Month</option>
      <option value="1">Jan</option>
      ...more options...
    </select>

    Day
    <select name="submitted[birthdate][day]">
      <option selected="selected" value="">Day</option>
      <option value="1">1</option>
      ...more options...
    </select>

    Year
    <select name="submitted[birthdate][year]">
      <option selected="selected" value="">Year</option>
      <option value="2014">2014</option>
      ...more options...
    </select>

  Birthdate

So I need to somehow print that "Birthdate" label manually so I can place it wherever I need, like so:

row
  column label
  column month
  column day
  column year
/row

I need to do this so I can wrap each element with CSS classes for a responsive grid.

You can simply hide the label from date field setting and add like this :

  Label here

    <?php print drupal_render($form['submitted']['birthdate']['day']); ?>
    <?php print drupal_render($form['submitted']['birthdate']['month']); ?>
    <?php print drupal_render($form['submitted']['birthdate']['year']); ?>


how do i add a login menu to superfish menu module? I thought i would be able to add the default User Login menu to a Superfish block, but it doesn't appear in the drop down list to be able to select when configuring the Superfish block.

Can anyone advise how to create a login menu for superfish that disappears when users are logged in. I have my Main Menu in Superfish 1 block, and my User Menu (contains logout) in my Superfish 2 block (works perfectly as only appears when logged in), and wanted a Superfish 3  for User Login (to only appear when logged out).

Perhaps there is an easier way to do this, so open to suggestions?

Instead of using SuperFish, you should consider using:
TB Mega Menu

TB Mega Menu allows you to create a mega menu with an innovative
back-end user interface and synchronized with Drupal core menu.

Synchronized with Drupal core menu, auto updated if there’s any change with - -  - Drupal core menu
Bootstrap framework
Responsive ready
Multiple built-in styles designed with years of theming experience
Visual and friendly user interface - what you see is what you get
Custom style for each element of your mega menu, just input extra css class name
Multiple built-in CSS3 animated effects
Work independently with themes

Speaking from experience, I know you can add the login block to TB Mega Menu
Here is a Video Tutorial


Translating the months in the archive view I need the months in views' default archive view to display in a different language, just changing the language in Drupal doesn't seem to be helping, string overrides in settings.php aren't doing the trick either. I also tried downloading and importing the views language file but that too has failed. Where can I make this change?

Well, if you have tried all those options, what if you try to replace the respective values from a common view template, using for example, preg_replace() PHP functions, to change this values?

for example: Here is the part of views-view-unformatted.tpl.php when each result is printed:

<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

you can use a custom views-view-unformatted.tpl.php specific to your view, and use preg_replace() to detect and replace any specific term in $row, according terms that you want. for example

<?php
$string = $row;
$patterns = array();
$patterns[0] = '/jan/';
$patterns[1] = '/feb/';
$patterns[2] = '/mar/';
$replacements = array();
$replacements[2] = 'othermar';
$replacements[1] = 'otherfeb';
$replacements[0] = 'otherjan';
echo preg_replace($patterns, $replacements, $string);
?>

see preg_replace() to get more details. I guess that you can use Devel module to see impact of this way against your site performance.

I hope information be useful.


How to display default image in Drupal 8 I have an image field that has a default image if no image is uploaded. In mytheme.theme file I am trying to get the default image and display it. Here is the code that I am using:

$field = $entity->get($fieldName); // Loading from field definition
if ($field) {
  $default_image = $field->getSetting('default_image');
  if ($default_image && $default_image['uuid']) {
    $entityrepository = Drupal::service('entity.repository');
    $defaultImageFile = $entityrepository->loadEntityByUuid('file', $default_image['uuid']);
    if ($defaultImageFile) {
      $image_uri = $defaultImageFile->getFileUri();
    }
  }
}

The issue is that the $default_image['uuid'] is empty. I am not sure how that can be if the default image is set. Since the image uuid is empty, the image cannot be loaded and now I am stuck.

What is wrong with the code that I am using? Or is there another way to accomplish this that works?

Instead of doing this in code, the Drupal core image fields provide a default image setting in the UI as well.

If you navigate to an image field in the UI (Structure > Content types > [Add/Edit a content type] > Manage fields > [Add/Edit image field]), you can upload a default picture that will be used by Drupal in case no image was provided.


Drupal 6 - Build Menu "...not available at this time." Issue I was just recently given administrative rights to the Drupal account to our firm to do some front-end work. I need to revamp a lot of the structure and content, however I do not see the 'Menus' option under 'Site building', more so I cannot access it via URL with I type "http://mysite.com/admin/build/menu". I get the following 404 Message "This content is not available at this time." My DBA says that it used to be accessible for he gave me an account. My question is what did he or I do wrong? I edited some of the Input Type Profiles and used the Rebuild Permissions option several times but have had no luck. I have not be able to find much mention of this through research. Is this a common scenario?

Full HTML prefs:

WYSIWYG Configs:

Type Settings Per User:

Filters for Filtered HTML:

Since you are saying ../admin/build/menu , I assume that you are using Drupal6.

Step 1: Navigate to example.com/admin/user/permissions

Step 2: Search for menu module and give permission for your user roles as required.


How to disable new user registered email to admin When a new user registers, there's an email sent to the admin in the form:

Subject: Account details for [name] at [site name] (pending admin approval)
Message: [Name] has applied for an account.
[profile URL]

How can I remove this email alert? The reason being, that I've created a customised message triggered by the Apply for role module.
Thanks.

This email is not configurable via the UI.

You can use hook_mail_alter(), which will allow you to stop the sending of a message.
So you would create a custom module that does this:

/**
 * Implements hook_mail_alter().
 */
function MODULE_NAME_mail_alter(&$message) {
  // Stop the default drupal email that goes out to admins when a user
  // registers on the site. An alternative email is sent out via other means.
  if ($message['key'] == 'register_pending_approval_admin') {
    $message['send'] = FALSE;
  }
}


How to make sure that panels classes are added to a CTools pane? I am attempting to define a CTools content pane based on the tutorial here.  However, when I add my pane to the panel, no matter what region (left sidebar, header, footer) I add it to, it is printed at the top of the page without any of the region or pane CSS classes.

This is the function I am using to render the pane:

function MYMODULE_messagelimits_content_type_render($subtype, $conf, $args, $context) {
  if (!empty($conf)) {
    $block = new stdClass();
    $block->title = check_plain("");
    // Show message limits
    $block->content = MYMODULE_show_message_limits();
    return $block;
  }
}

MYMODULE_show_message_limits() is a function that prints out some information to show users what their messaging limits are, for example:

if ($sent_total > 1) {
  print '
';
  print t('You have already started conversations with 2 people this week.') . '
';    }
else if ($sent_total == 1) {
  print '
' . t('You can start a conversation with 1 more new person this week.') . '
';
}
else {
  print '
' . t('You can start conversations with 2 new people this week.') . '
';
}

If I make a change such as $block->content = t("my sample content"), then the pane is printed with the correct classes in the proper place on the page.

So how can I set the output of $block-content to be the output of my custom module's function while retaining the panels CSS classes?  Please help me stop abusing the PHP filter within Panels!

In the following function, the content is provided by t(). t(), when called, returns the text "my sample text". Because that text gets assigned to $block->content, the pane is rendered with "my sample text" as the content.

function MYMODULE_messagelimits_content_type_render($subtype, $conf, $args, $context) {
  if (!empty($conf)) {
    $block = new stdClass();
    $block->title = check_plain("");
    // Show message limits.
    $block->content = t("my sample content")
    return $block;
  }
}

By contrast, this function:

function MYMODULE_messagelimits_content_type_render($subtype, $conf, $args, $context) {
  if (!empty($conf)) {
    $block = new stdClass();
    $block->title = check_plain("");
    // Show message limits
    $block->content = MYMODULE_show_message_limits();
    return $block;
  }
}

Assigns the return value of MYMODULE_show_message_limits() to $block->content, rendering the pane with that function's return value. To understand why that doesn't work as expected, we must ask, what does MYMODULE_show_message_limits() return?

if ($sent_total > 1) {
  print '
';
  print t('You have already started conversations with 2 people this week.') . '
';
}
else if ($sent_total == 1) {
  print '
' . t('You can start a conversation with 1 more new person this week.') . '
';
}
else {
  print '
' . t('You can start conversations with 2 new people this week.') . '
';
}

The function above, lacks a return statement, so in pratice, it returns NULL. Hence the pane output is empty, not even an empty string.

MYMODULE_show_message_limits() does, on the other hand, execute several print calls. Since that happens at a stage when content is still being assembled, remember, this is not a template, the prints are thrown right out onto the page, in the same way it would have if it was executed in any hook invocation for example.

The solution then, is to do:

$output = '';
if ($sent_total > 1) {
  $output .= '
';
  $output .= t('You have already started conversations with 2 people this week.') . '
';
}
else if ($sent_total == 1) {
  $output .= '
' . t('You can start a conversation with 1 more new person this week.') . '
';
}
else {
  $output .= '
' . t('You can start conversations with 2 new people this week.') . '
';
}
return $output;


What's the difference between the "Mime Mail" and "Mail MIME" modules? There appear to be two ways of sending HTML e-mail using Drupal:

Mail MIME with HTML Mail
Mime Mail

Mime Mail has significantly more installs, but it depends on Mailsystem, which is maintained by the maintainer of Mail MIME.

What is the difference between these modules?  Is one a fork of the other?

There are many more than 2 ways to send mail with Drupal. But, the modules you are showing are not for sending mail at all, they are there only to encode / decode mime content.

The problem you are facing is common in Drupal land: Developers re-inventing the wheel. You will often bump into modules that do similar tasks.

Mime mail has more support, is much more active, and has more features, (it can decode incoming html mail if I understood correctly).   I would go for this over Mail Mime with HTML Mail Pear class.

As for sending the emails, I can strongly recommend SMTP Authentication module if you don't want to use Drupal's built-in mechanism.

Hope this helps, cheers!


How to remove colon in a label which is not in a form - D6 How can I remove colon from the labels which is not in a form?

If it is a form, themename_form_element() can be used, but my question isn't related to forms.

For example, I need to remove colons from the profile view page. How can I do that?

I would like to do this the "Drupal way" (meaning not using JavaScript/jQuery)

Thanks in advance.

Drupal 6 or Drupal 7? The Drupal way to do this would be to modify the content field template in your theme to remove the colon OR create a custom node template to render the fields without the colon. For the content-field option, in Drupal 6 this file is in your cck folder under:

./modules/cck/theme/content-field.tpl.php

Copy this file to your themes folder and modify it to remove the colon at line 18:

<?php print t($label) ?>:&nbsp;

For a node template, check out the handbook on node templates, theming, etc:

http://drupal.org/node/190815#node-suggestion

There's also this module

http://drupal.org/project/no_colons

if you want another alternative.


Region not displaying in module I'm working on a site where much of the back-end is handled by a site-specific custom module.

I have a sidebar region and within

Within module-thing.php is a call to <?php print render($page['sidebar']); ?> to print a region but it is not showing anything despite the region being set with content within the Blocks administration. I'm wondering if this is expected to work from within a module.. is there something i can do to show it?

I found this (right at the top) but doesn't seem to work in drupal 7 http://www.chrischen.me/content/drupal-how-access-regions-blocks-themes-or-modules..

The code to print page regions must be in your theme's page.tpl.php file, not in a file in a custom module.

If you want to put your code in a separate file (sidebar.php) you need to make sure it's included in page.tpl.php, like

include './sidebar.php'; // file is in the same folder as page.tpl.php

or

module_load_include('php', 'MYMODULE', 'sidebar'); // file is in a module folder

hope it helps


After enabling MySQL replication getting deadlocks when clearing cache I recently setup my production MySQL server for replication. To do this I enabled innodb_flush_log_at_trx_commit and sync_binlog and set bind-address. A slave server on the opposite corner of the US is now happily replicating the master.

It's been fine, except that every time the cache is cleared (manually, because a module was enabled/disabled, etc) the site becomes unresponsive for about 5 minutes. It reports the following error (though, sometimes the query changes, the error is the same. This is the most common query to show this):

  PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: DELETE FROM {semaphore} WHERE (name = :db_condition_placeholder_0) AND (value = :db_condition_placeholder_1) AND (expire <= :db_condition_placeholder_2) ; Array ( [:db_condition_placeholder_0] => variable_init [:db_condition_placeholder_1] => 300377225537241be5ddc00.97685038 [:db_condition_placeholder_2] => 1399996863.3809 ) in lock_may_be_available() (line 181 of /usr/local/www/r/example.com/web/includes/lock.inc).

Clearing the cache now takes much longer. Before it would take 10 seconds at most. Now, it takes 5+ minutes. While I have run into this error occasionally elsewhere (during an hours long batch process with update.php; randomly in other places, though very rare), it's really causing problems when needing to push updates and clear the cache.

Note that the slave server is not actually serving the website at this time; it is only a backup.

mysql  Ver 14.14 Distrib 5.5.14, for Linux (x86_64) using readline 5.1
PHP 5.3.8 (cli) (built: Aug 31 2011 16:27:31)
Drupal 7.8

And the master server's my.cnf:

[mysqld]
datadir = /usr/local/mysql/db
socket  = /usr/local/mysql/mysql.sock
user    = mysql

old_passwords      = 1
key_buffer         = 16M
max_allowed_packet = 16M
thread_stack       = 128K
max_connections    = 1024

log_slow_queries     = 1
slow_query_log_file  = /usr/local/mysql/log/slow.log
long_query_time      = 10
ft_min_word_len      = 2
skip-external-locking

# Query cache configuration
query-cache-type  = 1
query_cache_limit = 2M
query_cache_size  = 16M
thread-cache-size = 8

# InnoDB Buffer Pool
innodb_buffer_pool_size=8G

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links                 = 0
innodb_flush_log_at_trx_commit = 1
innodb_file_per_table
default-storage-engine=InnoDB

# For replication
server-id        = 100
log_bin          = /usr/local/mysql/log/mysql-bin.log
sync_binlog      = 1
expire_logs_days = 10
max_binlog_size  = 100M
bind-address     = example

[mysqld_safe]
socket     = /usr/local/mysql/mysql.sock
log-error  = /var/log/mysqld.log
pid-file   = /var/run/mysqld/mysqld.pid

[client]
socket = /usr/local/mysql/mysql.sock

In my searches, I've seen some suggest enabling inndb_locks_unsafe_for_binlog though the name itself seems to say that it shouldn't be used along with sync_binlog.

Follow this and you should be good to go: Fixes for MySQL Deadlocks in D7


how to overide prvatemsg url 'messages' to 'something'? function _MY_MODULE_custom_submit($form, &$form_state) {
    $form_state['redirect'] = url('thank-you', array('absolute' => true));
}

If what you want is to do a redirect to a thank you page after you handle your form posted data then just add to your function a redirect via a call drupal_goto().

Something like this:

function _MY_MODULE_custom_submit($form, &$form_state) {
  // process your form stuff...
  drupal_goto('thank-you');  // redirect to page 'thank-you' providing this is one of your drupal pages
}


Cannot delete / re-install sharethis module I upgraded my Drupal to the latest version. I also did this with the modules. When I was doing this I got an error for the "sharethis" module. I got a message that told me to upgrade that module myself, so I uploaded the new module files.

But the module isn't working anymore, and when I look at the module-list I cannot find "sharethis".

This is what I see:
ShareThis Block   7.x-2.2   This module creates a custom block for the ShareThis widget.
Vereist: Sharethis (MISSING)

When trying to reinstall the module I get this message:
"Sharethis is aleady installed"

So I can't uninstall/install this module! Also when deleting the directory it gives the same error. (already installed) So I want to delete and re-install a module that's not visible in the module-list.

I had the same problem previously, turns out I had copied the module inside itself.
Duplicating modules inside modules directory might give this error.


Programmatically search nodes according to the value of fields in their bundle I am working on a script to search groups within the site according to criterias, such as group city, group languages and so on.

So far i am trying to do this by manually querying the database though it s seems to be an unnecessary hassle since the fields i am searching all live in different table like field_data_field_city, field_data_field_language and it can get very tedious task.

So i am wondering if i could to that programmaticaly using views so that it returns me all the NID according to the filters i mentioned above. i'd rather not use views UI as later this data is populated to the page via a Jquery templating system witch is already in place so the best would be to just get all the NID that match my selection.

If anyone had any incite / experience on how i should go to achieve this result would be much appreciated .

Personally I would stick to writing your query manually instead of using Views.

This way you have much more control over the final query, and in most scenarios you should be able to make it much smaller (and thus much faster) than that created by Views - by joining only with tables you really need to join in a specific situation, while Views will always do all the joins required by all possible scenarios.

Also, this way you could return the result formatted whichever way you want, without the need of installing additional modules, which is just unnecessary overhead.

IMHO. :)


Passing user id argument to filter I have a view that lists the (ubercart) orders of a user. I created a view for that with a filter applied: "User: current". This works perfectly this way, I use this view in my profile page template like this:

$view = views_get_view('user_orders_custom');
$result = $view->execute_display('default', array($account->uid));

My problem is that when admin is inspecting the profile page of a user, this lists the orders of the admin, not the user being watched. Of course the passed $account->uid is not used by the applied views filter User:current.

I don't know how to make my view filter on the passed uid. I tried creating a relationship, arguments but the filter thing is not clear to me.

May be what you need is contextual filters, the user can go to view-name/% where % is a contextual filter for the uid


How to i programatically change the page thats loaded from hook_init? I am in the process of building a drupal module that will block access to certain IP addresses, i've built the whole thing and it works a treat except from one area of functionality; i would like to be able to redirect blocked users to a node.

The code that i have does everything except display the node:

if (variable_get('lock_denied_response_type') == 2){
  $node_id = variable_get('lock_denied_node');
  $node = node_load($node_id);
  $node_view = node_view($node, FALSE, TRUE);
  drupal_render_page($node_view);
  exit;
}
else{
  echo variable_get('lock_denied_html');
  exit;
}

I've scanned google, stack overflow etc but not much luck. So far as i can tell, it appears my approach is wrong and rather than triggering my own render page, i should just change which node the standard rendering process uses, something like this:

if (variable_get('lock_denied_response_type') == 2){
  $node_id = variable_get('lock_denied_node');
  /* insert awesome node override code here */
}
else{
  echo variable_get('lock_denied_html');
  exit;
}

Suggestions?

Cheers!

you can do somthing like this:

function MY_MODULE_init() {
    global $user;

    // or you can also use ip_address() function
    if($user->hostname == 'MY_BLOCKED_IP') {
      drupal_goto('node/NID_OF_IP_BLOCKED_NODE');
    }
  }

2-aproach (this is a recommended way. Because hook_init() will be removed from drupal v8):

// in template.php
function MY_THEME_preprocess_page(&$variables) {
  if($variables['user']->hostname == 'BLOCKED_IP') {
    drupal_goto('node/NID_OF_IP_BLOCKED_NODE');
  }
}


Unable to add new OpenID identity in Drupal 7 I have been using OpenID authentication in Drupal 7 for quite a while, using an myopenid.com identity.  Now, since myopenid.com has announced that they are going away, I want to add a new OpenID identity to my account.

However, I am not able to add another identity.  When I try to add another identity, the browser starts loading a page, but then stops loading.  I am not taken to the provider's login page, whether or not I am logged in to the provider's site.  (I am already logged in to my Drupal 7 site -- I am adding the new ID from my profile's OpenID Identities tab.)

When I manually go back to that OpenID Identities tab, the myopenid.com identity is there, but the new one is not.

There is nothing in the Apache error log or access log suggesting what is going on.

Any idea how to debug what is going wrong?

Thanks to Mołot's comment, I was able to figure it out.  The problem was the administrative overlay.

Using the Chrome Developer Tools console (Chrome Menu/View/Developer/Developer Tools) I was able to see the request history.  The last request included:

referer:http://mysite.com/user/1/openid?render=overlay&render=overlay

The response from Google also contained a header that looks like an error, although it may not have been relevant:

p3p:CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."

I don't know if the referrer header was the actual problem, or if it just reflected a problem caused by including "render=overlay" in the request going on in the background between my server and the OpenID provider.  In any case, by turning the administrative overlay off (Admin/Modules/Core/Overlay), I was able to add and use my new OpenID.  It worked for both Google and Yahoo.

I would also add, as noted elsewhere, the URL to use to set up the OpenID for Google is:

http://www.google.com/accounts/o8/id

That initially confused me because that does not appear to be a unique ID.  However, using that ID both to add the OpenID for Drupal, and to log in using OpenID, works.  The string stored as my "OpenID" is different, and has what appears to be a unique identifier, but the user never has to enter that long, unique string.

Not only did the Administrative Overlay prevent the OpenID from being added, it also prevented me from seeing the error message when I used the wrong string to add the OpenID.


Using fields as variable in views I'm not sure how to explain this in a good way, and my title may be way off.

I am using Views Data Export module and want to export a report for a specific user, and use his/hers name in the filename.

I have created a field in my user registration called "full name". Is there a way I can use this in my views etc. like for example "%full-name"? Any way I can achieve this?

I have tried to use "Report for [user:field-navn].doc", but then I get the filename "Report for [user:field-navn].doc" as filename, and not the name in it.

as arpitr says, you need to include the field so that it becomes visible to Views. You can exclude it from view in the field settings if you don't want it to show - then try, borrowed from (adjust appropriately for your setup) here:

  It's not super-obvious how to do this, but it is pretty easy.

  The downloaded filename has nothing to do with the "path" in the "data
  export settings" - that is simply the path that is used to trigger the
  generation of the file.

  To set the actual filename, click "settings" next to "CSV file" in the
  View's "format" section. Then, check the "provide as file" box and
  then set the filename (including token) there.


How to implement a mysql date or datetime field correctly in hook_schema()? I have written a mymodule.install file which contains a schema definition to create a table in my database. This table contains two data fields. Theese fields will be populated by the users when they will fill in the specific content (example: to specific a publish date for a news). Now i didn't used the Date contributed module on purpose, cause i needed that theese two fields were on the same row in the database table for other reasons.

The hook_schema defines the two fields this way:

'pubblish_date' => array(
    'description' => t('The pubblish date for the single news'),
    'mysql_type' => 'datetime',
    'not null' => FALSE,
  ),
  'unpublish_date' => array(
    'description' => t('The unpublish date for the single news'),
    'mysql_type' => 'datetime',
    'not null' => FALSE,
  ),

The table is created correctly in the database, but i always get theese advice messages:

Field news_board.pubblish_date: no Schema type for mysql type datetime.
Field news_board.unpublish_date: no Schema type for mysql type datetime.
news_board.pubblish_date: no  type for Schema type :normal.
Field news_board.pubblish_date: no Schema type for type .
news_board.unpublish_date: no  type for Schema type :normal.
Field news_board.unpublish_date: no Schema type for type .

Seems strange to me cause I red on the documentation to use the mysql_type specification in order to store the datetime format in mysql database.

I know that Drupal supports natively timestamps and if you want to store a different date format you have to use specific definitions like mysql_type or pgsql_type according on the database yuo are using.

In discussions I found online lot of people used mysql_type definition and from what I seen they solved the problem, so why it doesn't work for me?

Thanks a lot.

You should provide a fallback type (varchar) for the case that the database is not mysql.

'pubblish_date' => array(
  'description' => t('The pubblish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),
'unpublish_date' => array(
  'description' => t('The unpublish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),

However, the messages you see come from the Schema module. This problem is already recorded as issue #468644.

The implementation of the mysql datetime in your schema is fine. You can safely ignore these messages.  I would say that these "advice messages" are caused by a bug in the Schema module.


How can I track stale content and alert content owners to it? I'm building a new version of a corporate web site, and want to make it easy for content owners to keep their content updated regularly.

In the current site, most of the content has not been updated for years, and it's unclear who is responsible for various pieces of content.  In the new site, each part of the site (usually a section but in some cases individual pages) will have a person or group of people designated as the owners of that content, and responsible for keeping it updated.  I'm pretty certain, however, that they won't do anything unless they are prodded.

One possibility is to add a Dated boolean to all nodes to flag certain content as something that will go out-of-date regularly, such as an About Us page that says "we currently have 127 locations across states X, Y, and Z in the U.S. and provinces A, B, and C in Canada.  Then there would need to be some mechanism to send e-mail notifications to the designated owner of that content after (for instance) 3 months, including the content and a link to edit it, and asking them if it is still accurate.   Content not marked "Dated" could have e-mails sent out after (say) 9 months, or whatever time frame seems logical.

I've searched for a module that helps solve this problem, but have found nothing.  How would you go about doing this, or something like it (if you have an alternate idea to solve the problem)?

It's been awhile since you asked and I'm assuming you found an answer. For those who come across this post, the Rules module should handle this requirement.

Create a rule to react when content is viewed, which should suffice as a trigger.
Add a condition to run a data comparison on node modification date or write custom PHP comparison code.
Set the rule to send an email to the node's author.


How can I do "Buy one get two free" with Ubercart? For example the firs item is $3 and the second one & the third one are $0. Can I do this?
Maybe Ubercart Discounts (Alternative) can do the result but I don't want to show the discount price and just want to show the second and the third item $0 on the cart page.

I found the solution using Ubercart Custom Price module and the code below.

// Load the current shopping cart.
      $items = uc_cart_get_contents($cid = NULL, $action = NULL);

    // Count the number of items
      $number_of_items = count($items);

    $firstPrice = 10;
    $secondPrice = 0;
    $thirdPrice = 0;

    switch ($number_of_items) {
      case 0:
        $item->price = $firstPrice;
        break;

      case 1:
        $item->price = $secondPrice;
        break;

     case 2:
        $item->price = $thirdPrice;
        break;
    }


Printing field item attributes with Twig / Drupal 8 In Drupal 7, I can do this in a custom field template to print the alt tag of an image:

<?php print $item['#item']['alt']; ?>

And though "item" seems to be a variable in Twig / drupal 8 fields, I can't seem to do the same thing. I've tried these:

{{ item.alt }}
{{ item.item.alt }}

These don't work but I don't get any errors either. Looking at the API does not give me much insight. I saw this gist but again, no alt tag rendered separately. My image is rendering the alt tag as i can see it in the code though.

The syntax to print the alt tag in that case is this:

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

Twig in Drupal 8 doesn't deal with hash keys like #item in render arrays cleanly. Part of the problem is that # signifies a comment in Twig, so {{ item.#item.alt }} wouldn't work.

There is the possibility of working around this with a Twig extension to allow drilling down into hash attributes with the syntax {{ item.item.alt }} but I'm not sure if anyone is working on that. I should mention that Twig extensions can be added in contrib as well.


How do I hide the page title in Drupal 7? I'm a site administrator for my university and I'm using Drupal through their servers, but I can't figure out how to hide the page title from the screen. I can't install modules because I'm not on their lab computer (using my personal laptop and I don't have the permission to) and I don't see anything that I can uncheck that says "Automatically update Menu Title". Is there a way to work around this? Or does this mean I have to use my school's lab computers?

You can update the template for the Content type or that specific node.

I tend to use CSS to hide the page element if it is only one page title/node I am trying to hide.


How to contribute a converted module? I recently converted a Drupal 6 contributed module to Drupal 7 for one of my client project.  I would like to contribute this converted module to the community.  How to upload this in the existing project page?  Do I have to create a patch or will it be a sandbox project?

For this you need to create a sandbox project and open up an issue in the issue queue of the existing module, posting a link there and urging the maintainer of that project to have a look.

If they wish, they can commit that module as the official 7.x version, or might even add you as a co-maintainer of the module if you are interested. In case they do not find this module interesting, you can create it as a separate project: Create the sandbox, apply for project application approval in the Drupal.org project approval queue, and get this published as independent module.


Does Organic Groups Views allows post to group relationships? Does anyone know how to create relationships between Post entity and Group entity. I have a view that lists group posts and I want to add group title on the same row. This issue (http://drupal.org/node/1006860) says it is possible, but it is probably not. But strange, since it is views integration basics.

it's possible, see the screenshot: (open image in new window to see full size) . Add the 2 relationships as "required" to only show nodes belonging to groups.
The naming conventions of the group objects is very confusing to me, it helped me to look at the "og" and "og_membership" tables in the DB and then check the SQL that views builds for you.


Display only the value of a field in a content-type template I'm attempting to display a plain text field so that I can use it to embed youtube videos

In my template I have

However when it renders it produces a mess

<iframe width="420" height="315" src="https://www.youtube.com/embed/&#10;&#10;&lt;!-- THEME DEBUG --&gt;&#10;&lt;!-- THEME HOOK: 'field' --&gt;&#10;&lt;!-- FILE NAME SUGGESTIONS:&#10;   * field--node--field-video--beer.html.twig&#10;   * field--node--field-video.html.twig&#10;   * field--node--beer.html.twig&#10;   * field--field-video.html.twig&#10;   * field--string.html.twig&#10;   x field.html.twig&#10;--&gt;&#10;&lt;!-- BEGIN OUTPUT from 'core/themes/stable/templates/field/field.html.twig' --&gt;&#10;&#10;            &lt;div data-quickedit-field-id=" node="" 15="" field_video="" en="" full"="">C0DPdy98e4c&lt;/div&gt;

&lt;!-- END OUTPUT from 'core/themes/stable/templates/field/field.html.twig' --&gt;

" frameborder="0" allowfullscreen&gt;

I understand that part of it is because I'm in debug mode, but it's also wrapping it in a quick edit field div. And even if it didn't I'd rather not exit debug mode just to work on this. Is there a way to output just the value and nothing more?
Like something similar to {{ content.field_video.value }}?

If I can't disable quick edit field by field, is there a way to print a field while keeping the HTML intact? When I put the entire iframe into field it turns the html tags into text.

I tried

{{ content.field_video|raw }}

but the output still showed the html tags as text. I tried

{{ content.field_video.value|raw }}

But that did not show anything.

I was able to print the value by using

{{ content.field_video[0] }}