Truncate field storage tables added by module before uninstall I've added a field via hook_entity_base_field_info(). It has data stored in it. I then go to uninstall my module and I get the following error:

-> drush8 pm-uninstall massing -y
The following extensions will be uninstalled: massing
Do you really want to continue? (y/n): y
exception 'Drupal\Core\Extension\ModuleUninstallValidatorException' with message 'The following reasons prevents the modules from being uninstalled:    [error]
There is data for the field massing_memberships on entity type User' in
/Users/les.peabody/Sites/drupal8/core/lib/Drupal/Core/Extension/ModuleInstaller.php:347
Stack trace:
#0 /Users/les.peabody/Sites/drupal8/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(95):
Drupal\Core\Extension\ModuleInstaller->uninstall(Array, true)
#1 /Users/les.peabody/opt/drush8/commands/core/drupal/environment.inc(227): Drupal\Core\ProxyClass\Extension\ModuleInstaller->uninstall(Array)
#2 /Users/les.peabody/opt/drush8/commands/core/drupal/pm_8.inc(80): drush_module_uninstall(Array)
#3 /Users/les.peabody/opt/drush8/commands/pm/pm.drush.inc(1190): _drush_pm_uninstall(Array)
#4 [internal function]: drush_pm_uninstall('massing')
#5 /Users/les.peabody/opt/drush8/includes/command.inc(364): call_user_func_array('drush_pm_uninst...', Array)
#6 /Users/les.peabody/opt/drush8/includes/command.inc(215): _drush_invoke_hooks(Array, Array)
#7 [internal function]: drush_command('massing')
#8 /Users/les.peabody/opt/drush8/includes/command.inc(183): call_user_func_array('drush_command', Array)
#9 /Users/les.peabody/opt/drush8/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
#10 /Users/les.peabody/opt/drush8/drush.php(70): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#11 /Users/les.peabody/opt/drush8/drush.php(11): drush_main()
#12 {main}

So what I'm trying to figure out how to do is how to drop the data in this table after I've called for an uninstall on the module, but before the check happens for whether or not there is data in the table. I've tried implementing hook_uninstall() and hook_module_preuninstall() but neither of these hooks are invoked before the check for data presence. Thoughts?

EDIT: Looking at ModuleInstaller.php at line 343 (D8 RC1), it runs uninstall validators prior to triggering hook_module_preuninstall and hook_uninstall. This is where it is failing. So, maybe there is a way to add an uninstall validator for my module and run it first? There doesn't look to be any other way to do it besides adding some kind of mechanism to the module which makes it "purge" itself of any data it's added to the system, which then lets you uninstall it. Seems terribly convoluted and not side builder friendly in the slightest, very frustrating.

I was able to solve this problem by implementing hook_uninstall() in my module's install file and explicitly deleting my custom entities.

For example:

function mymodule_uninstall() {
  //remove_fields_user();

  $results = \Drupal\mymodule\Entity\MeetEntity::loadMultiple();
  foreach ($results as $entity) {
    $entity->delete();
  }
  $results = \Drupal\mymodule\Entity\Team::loadMultiple();
  foreach ($results as $entity) {
    $entity->delete();
  }
}

See Drupal 8 hook_uninstall() docs for more details


Ajax callback is not working on views exposed filters I am implementing dependent filters in views exposed filter for content:datasource search(Solr search). I have a requirement that in exposed dropdown field when a category is selected, by ajax i need to fetch the sub-categories and show up in another dropdown.For this I tried like below but its not going to callback function only. There is nothing logging in the network console also. Can anyone help me here to resolve.

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

function module_form_alter(&$form, &$form_state, $form_id) {
$form['field_categories']['#ajax'] = array(
        'callback' => 'module_get_subcategories',
        // 'callback' => '::module_get_subcategories',
        'event' => 'change',
        'wrapper' => 'edit-field-subcategory',
        'progress' => array(
          'type' => 'throbber',
          'message' => NULL,
        ),
      );
}

function module_get_subcategories(&$form, FormStateInterface $form_state) {
   $response = new AjaxResponse();
   $message = 'test';
   $response->addCommand(new HtmlCommand('#edit-field-subcategory', $message));
   return $response;
}

Something is weird in the code,
What is that return statement in the last two lines?

For the ajax, try using $form['field_categories']['widget']['#ajax']

Make sure that you have cleared the cache too and that your module is actually called module.


A good markdown that supports syntax highlighting like SE sites? I'm looking for a Markdown module or something similar to Stack Exchange sites Markdown.
It would be great if it provides syntax highlighting for some languages.

Do you have any suggestions?

There is the Markdown filter module, which uses the files you can download from http://daringfireball.net/projects/markdown.

  Provides Markdown filter integration for Drupal input formats. The Markdown syntax is designed to co-exist with HTML, so you can set up input formats with both HTML and Markdown support. It is also meant to be as human-readable as possible when left as "source".

  This module is a continuation of the Markdown with Smartypants module, and only includes Markdown support to simplify configuration. It is now suggested that you use Typogrify module if you are interested in Smartypants support. Also note, that if you use the GeSHI filter for code syntax highlighting, arrange this filter after that one.

There are versions for both Drupal 6 and Drupal 7. In the case you are using Drupal 6 for your site, you would not need to change module when updating to Drupal 7.


Delete a field from the database manually I installed a module that left a ghost field that isn't tied to any entity bundle :(

How would I go about safely and thoroughly deleting this field from the database?

I have to delete this field to uninstall the module. I have attempted to run cron and clear cache to see if that would remove the field (it does not).

MYSQL command: show tables like '%<string in field>%'; only produces one result (the field I want to delete). Do I just drop that table?

I am using Drush 9.x, so unfortunately it looks like drush field-delete is not available. Is there a way to do this with Drush 9 or Drupal Console?

Thanks in advance for your help!

In Drupal 8 bundle fields are configuration. This looks like you still have the field storage configured.

In this case export configuration:

drush cex

remove the field storage:

rm field.storage.node.field_example.yml

and import configuration again:

drush cim


drupal 7 join two tables How can I join two tables together in drupal 7.

I have a simple database schema and I want to join it to the user table could someone give me a coded example of joining a custom build table to the user table.

If I take a basic table example

$schema['location'] = array (

'descritiption' => 'location',

'fields' => array (
    'locationID' =>  array(
        'description' => 'primary key for patients table',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE),
 ),

'addressone' => array (
 'description'    => 'this shows the first line of the address',
    'type'         => 'TEXT'
),
'county' => array (
    'description' => 'this is a county list'

),
'postcode' => array (
  'deescription' => 'stores the postcode'
),

    'primary_key' => array('locationID')

    );

How would I join this to the user table.
I would like to query data from both tables. So when I add a record into the user table I want the custom table to have the data added as well so there is a link between the two tables.

here is a high level example

user table data

uid 1

username alex

visitor

vis id 1

firstname Alexander

lastname  Brown

So what i want to happen is when i add data into the user table I build a relationship to what is entered in the visitors table. I know you can use a join which has kindly been explained to me but I am not sure what is meant by building the relationships in code.

JOINs are a query-level concept and don't really make a lot sense in the context of a schema definition.

I suspect what you're asking is how to add a foreign key from your location table to the users table. If so I'm afraid you're out of luck; Drupal does not enforce foreign key relationships, so you'll need to define and maintain your relationships at a code level.

There is a foreign keys property that can be applied to tables defined by the schema API, but it is for documentation purposes only, no foreign keys are ever added at the database level.

Just in case you are asking how to join a table in a query:

$query = db_select('location', 'l')
  ->fields('l');

$query->join('users', 'u', 'u.uid = l.uid_column_name');

$results = $query->execute();


Pre-process to change the name of a file field in node I have a file field in a node and I would like all instances of this field to have a different display name.

I use the file field to upload images that users can download - e.g. flower.jpg, horse.jpg.

Instead of the field displaying " flower.jpg",I want it do display the text "download".

The machine name of my field is "field_source" and the name of my theme is " kickstart". The content type is " resource".

What would a pre-process function in my template.php look like to do this?

This is as far as i get:

function kickstart_preprocess_node(&$vars){
  if($vars['type'] == 'resources'){
    $vars['content']['field-source']['#title'] = 'download';
  }
}

Thanks!

if you only want to change the label maybe the module string overrides is your best option https://www.drupal.org/project/stringoverrides

you can also edit your settings.php file to change the label https://www.drupal.org/node/522036


Webform send multiple email I have created a webform. There is one field "Send invitation to your friends" . In this field user can enter their friends email ids (Comma seperated) For example A@gmail.com,B@yahoo.com,C@hotmail.com etc. I want to send a common email "Welcome and join us" to all these people. Can anyone help me, how can I proceed?

You can send custom emails to addresses submitted in the form. When creating the form, you have to select 'email' for the field type. Once you've done that, go to the 'Emails' tab in the webform, and add a new email using the 'Component value' menu; you should see your Email field in there (you can add as many of these as you want). This sets it up to send an email to the email address entered in the form, in your case the friends' email addresses.

From there you can customise the email options.

Edit: Whoops, this answer is for Drupal 7 specifically, but (if I remember correctly) the option exists in Drupal 6 as well.


How to remove HTML code from rss.xml I want to remove all the HTML code from the feed created using the Views module, since LinkedIn doesn't seem to like it that way it comes. I have seen the module clean links, but I'm running Drupal 7 and even with the patch I found I can't get it to work.
Is there any file I can edit and add "strip_tags" to get it to work?

Note, that Im the biggest newbie on Drupal, but I know my way around PHP.

Easy way to do this in D7 is through the Display Format settings. Under the content type(s) of the nodes in your view, you want to add a custom display for RSS and then set the fields you want to alter to plain text.

Go to Structure -> Content Types, and select 'Manage Display' next to your content type.
On the bottom of the list of fields, expand 'Custom Display Settings' and check the box for RSS and save
Now, in the upper right-hand corner you should see that you have display format settings for Default, Teaser, and RSS - select RSS.
In the format settings for each of the fields, you want to select 'Plain Text' or whatever equivalent you like.


How to get error messages to display on the form, rather than after the page is refreshed? I have a form that has radio buttons and the user needs to select at least one option. If they do, a modal window will pop-up.
If they don't, I need to redisplay the form with the saved values and the message "Please select one item" in the message area.
Right now, if they don't select one item nothing happens and then the message is displayed after the page is refreshed.

public function buildForm(array $form, FormStateInterface $form_state, $form_config = NULL)
{
    if (!empty($form_state->getBuildInfo()['args']['form_ajax'])) {
        $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
        $form['actions']['submit']['#ajax'] = [
            'callback' => '::crmform_ajax_submit',
        ];
    }
    return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state)
{
    $selected = $this->crmform_validate_element_selected($form_state, 'radio');
    if (!$selected) {
        $form_state->setErrorByName('form', t('Please select one item'));
    }
}
public function crmform_ajax_submit(&$form, FormStateInterface $form_state)
{
    $errors = $form_state->getErrors();
    $response = new AjaxResponse();
    if (!empty($errors)) {
       $form_state->setRebuild();
       return $response;
    }
    $response->addCommand(new OpenModalDialogCommand($dialog_title, $form_data, $options));
    return $response;
}

You can use contributed module Clientside Validation which is very close to your requirement.

  This module adds clientside validation (aka "Ajax form validation")
  for all forms and webforms using jquery.validate. The included
  jquery.validate.js file is patched because we needed to be able to
  hide empty messages.


How to pass contextual filter to a view pane? I have a taxonomy page where different view panes of a single view are displayed. I want to pass contextual filter to only kind of View pane. I wrote this code but this passes the contextual filter to all the view panes on the page. How can I pass contextual filter to a single specific view pane? Thank you for your time.

function intrakicalendarrss_views_pre_view(&$view, &$display_id, &$args) {
    $arg0 = arg(0);
    $arg1 = arg(1);
    $arg2 = arg(2);
    if($view->name = 'current_event_list')  {
        if($arg0 == 'taxonomy' && $arg1 == 'term' && ($arg2 == 1 || $arg2 == 2)) {
            $Cfilter = $arg2;
            $args[0] = $Cfilter;
        }
    }
}

Add another condition to check the specific display name

if($view->current_display == 'display_name')

Here display_name of particular display can be found in Advanced Option -> Machine Name


How to find out allowed memory for a specific Drupal page I want to find out how much allowed memory a page uses after it is loaded on my drupal 6 site. I know that you can do this when a page is not loading correctly, by enabling errors in php.ini. How do find this out on successful page loads?

Check out the performance module (formerly part of Devel):

This module provides performance statistics logging for a site, such as page generation times, and memory usage, for each page load.
This module is useful for developers and site administrators alike to identify pages that are slow to generate or use excessive memory.

emphasis mine.


How to create a an image gallery with a short description below each image I have created an image gallery using views and a custom content type, Photo. It has 2 rows of three images each. I have uploaded the 6 images via the Photo content type, added a body describing the images and then used the views module to create the gallery. However in the gallery only the images and their titles are visible.

What I want is that the title should be displayed below and also the description for images should appear.

Here's a wireframe of what I am trying to build: http://imgur.com/bVgJyEN

Creating an Image Gallery Of images in nodes.

Add a content type to be used for the image gallery.
Add the image field
Add one node per image with the description in the body field.
Create a view of the type content
Add the fields Title, Image, Body (In this order so that they are displayed in that order itself
set the format to grid.

Now when you visit the page you should see the gallery as you wanted.


Migrating user profile picture from D6 to D7 I'm migrating a site from D6 to D7 and I want to do the User migration in code. The basic profile works fine except for the user picture. I read that it's best to write a separate class for this file so I did. Unfortunately I'm getting nowhere with it.
Can you see anything wrong with this code? I plan to use this class as a dependency in the user profile migration class where I should be able to attach the image based on file id generated in this class.

class MigrateDAFiles extends Migration {
    public function __construct(array $arguments) {
        $this->arguments = $arguments;
        parent::__construct($this->arguments);
        $this->description = t('Profile images');
        $this->map = new MigrateSQLMap($this->machineName,
            array(
                'picture' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                ),
            ),
            MigrateDestinationFile::getKeySchema()
        );
        $this->destination = new MigrateDestinationFile();
        $query = db_select('users', 'u')
            ->fields('u', array('picture'))
            ->isNotNull('picture');
        $query->distinct();
        $this->source = new MigrateSourceSQL($query);

        $this->addFieldMapping('value', 'picture');
        $this->addFieldMapping('source_dir')->defaultValue('http://www.example.com/sites/default/files/artist-pictures/');
        $this->addFieldMapping('file_replace')->defaultValue(FILE_EXISTS_REPLACE);
        $this->addFieldMapping('status')->defaultValue(1);

        $this->removeFieldMapping('path');
}

I believe you need to do picture migration separately per the docs (assuming you are using Migrate D2D, which you probably should).  This is all I had for picture migration from one I did last year:

$picture_arguments = $common_arguments + array(
  'machine_name' => 'pictures',
  'description' => t('Migration of user pictures from Drupal 6'),
  'default_uid' => 1,
  'source_dir' => '/some/path/to/sites/default/files/',
  'destination_dir' => 'public://pictures',
);

Migration::registerMigration('DrupalPicture6Migration', $picture_arguments['machine_name'], $picture_arguments);


Automating exporting of a view I'm running a system where has a view with export functionality in order to export results in xls format.

Is there anyway I can automate it so every week it auto generates a report and email it.

I'm guessing I can use rules to do it but dont know how.

Thanks

If you are using the views_data_export module and you have command line access you can try the following:

cd [your_drupal_docroot]
drush views-data-export [view-name] [display-id] > [path-to-output-file]

You could then add this to cron as a one-liner, e.g. this would run every Monday at 5:59 AM:

59 5 * * 0 cd [absolute_path_to_drupal_docroot] && drush views-data-export [view-name] [display-id] > [path-to-output-file]


How can I redirect a user after login to the current page? I have a Drupal 8 site. And I have approximately 5 pages in a site.

For example if a user hits login from the contact-us page the user should not redirect anywhere, they should stay on same page. How can I accomplish this?

The way to solve this can be done by adding the destination parameter to the login link.

Whenever the user is navigating a page, you update the destination based on the current page.

This can be done by implementing the hook_link_alter as the following:

/**
 * Implements hook_link_alter().
 */
function custom_link_alter(&$variables) {
  $routes = [
    'user.login',
    'user.logout',
  ];
  /* @var Drupal\Core\Url $url */
  $url = $variables['url'];

  if (!$url->isExternal() && $url->isRouted() && in_array($url->getRouteName(), $routes)) {
    // Get current path.
    $current = \Drupal::service('path.current')->getPath();
    $variables['options']['query']['destination'] = $current;
  }
}

This works fine for login and also for logout links. So when user login/logout through menu link he will be redirected to the previous page.

One problem might face you with that is cache, Drupal will start caching the destination value and won't be updated when you move between pages.

You can solve this problem by implementing hook_preprocess_menu and add destination as cache contexts.

/**
 * Implements hook_preprocess_HOOK().
 */
function custom_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'account') {
    $variables['#cache']['contexts'][] = 'url.query_args:destination';
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, \Drupal::service('path.current')->getPath());
  }

}


How can I access XMLSitemap links from external PHP script? I have an external PHP script that does a lot of back end processing for a website.  I need for this PHP script to query, insert, and delete various links from the XML Sitemap.

I want to use XMLSitemap's API instead of raw SQL so any additional functionality that needs to happen on inserts and deletes are called, like any alter hooks, etc.

I don't want to bog down the website for this processing, hence why I need to do this from a back-end script.

You'll need to bootstrap the Drupal environment in your PHP script to do this. There are many ways to do this, probably the easiest is Drush's php-script command:

drush php-script my_custom_script.php

This will let you execute any arbitrary PHP script in a bootstrapped Drupal environment.

Once you have your script running your Drupal environment, you can utilize the XMLSitemap API functions for all your CRUD operations.


Can I deploy my Content on drupal using scripts? If suppose I have a drupal application in Github and I have automated drupal installation using chef. Now I want to deploy that application content such that i can see it on my content page.
I am unable to put php and drupal tags due to reputation.

If you would like to automate your deploys of content, just like you automate your code deploys, you'll probably want to look into the migrate module.  This model is best for sites where the content is managed by a content-generation team; it is less applicable for sites that have a lot of user-generated content.  This is a viable model that some people use, though, and is a very compelling workflow if your use-case supports it. One good extant site that uses this technique and has a public GitHub repository is Gizra's Negawatt.


User field imported with Feeds but not showing in user edit page? I'm using Feeds Importer to create users from a csv file, in my Drupal 7 site.

It works perfectly, except one case. I added some custom fields to user profile and I can set all them with my importer, except one (a simple text field, let's say 'foo').

The value for 'foo' is correctly imported: if I open the 'View' page for a user profile I can see it, listed as supposed. In the 'Edit' page of the user profile, however, the value of the field is showed empty. If I modify the value in this edit page and save, the value is stored AND showed in the edit page.

I tried even to create another custom field similar to 'foo' and it works perfectly in any case. (I can't delete foo and recreate it for it contains several data)

How could this be debugged? I checked the csv, the importer, even the database (in the table field_data_field_foo the value is stored correctly), and all seems fine. No error in drupal log, neither in importer log.

I can't delete foo and recreate it for it contains several data

Here is how I would try to fix this:

Backup your entire Drupal Database.
With phpmyadmin or some other database manager/viewer, find the field_foo table and extract the table as a CSV file.
In Drupal, go to user manage fields and Delete field foo
Flush the cache (not necessary, but eh, just in case)
Add a new field, foo
Edit user 1 and put something for field foo. (This is just so we get the table structure on step 7)
Find field_foo in DB and extract.
Open Original field foo .csv in excel and highlight all data and copy.
Open new field foo .csv and paste data and save
Import new field foo .csv to DB.
Flush/Clear the Cache
Try importing with feeds again and see what happens.


Domain Access permissions issue I am having an issue with Domain Access in Drupal 7.

The admin user (and seemingly any user I add to the system) is unable to edit content attached to any child domains on the site.  The main domain is fine, but all others on the same site is effected.

When I attempt to edit content on the Admin (or other user) I get:

  You are not authorized to access this page.

I can view all content with no problem.

How do I fix these permissions issues?

The following is the screenshot of the permissions implemented by the module.

The "Bypass content access control" permission is disabled for all roles including the "Administrator" one; no other access module is enabled. Two Domains have been set up, the primary one and a sub-domain, which shares some content and has its own. Two languages are enabled for each domain (English and French) using the i18n module.
The "Edit any content on assigned domains," and "Delete any content on assigned domains" permissions are set, but the users still cannot edit the content.

Hi try to configure this setting
http://yoursite.tld/admin/structure/domain/roles


Trying to pass id to the ajax callback function, keeps overwriting, how to solve this? I created a form which have a lot of images and a delete button on every each one of them. I used ajax to create a callback function which would delete the image. Here is part of my form:

foreach($result as $key=>$some){
    $form['image-entry'][$some->id] = array(
      '#type' => 'fieldset'
    );

    $form['image-entry'][$some->id]['image_' . $some->id] = array(
      '#markup' => theme('image', $variables[$key]),
    );

    $form['image-entry'][$some->id]['description_' . $some->id] = array(
      '#type' => 'textarea',
      '#default_value' => $some->description,
      '#attributes' => array(
        'placeholder' => t('Describe this picture'),
       ),
    );
    $form['image-entry'][$some->id]['submit3' . $some->id] = array(
      '#type' => 'submit',
      '#value' => 'Delete',
      '#ajax' => array(
        'callback' => 'image_gallery_delete_photo_callback',
       ),
    );
   $form['#foo'] = array($some->id);
  }

As you can see I have 3rd submit button which is ajax callback and from example I found out that I need to create a new form element (foo) in this case, which stores some data that I can pass. Everything works like a charm, this is my callback function:

function image_gallery_delete_photo_callback($form, $form_state, $args){
  $arguments = $form['#foo'];
  dpm($arguments);

  /*$photo_delete = db_delete('image_gallery_photos')
                  ->condition('id', $arguments)
                  ->execute();*/
}

I am able to fetch the id of the photo from the form, but here I face a brick wall.

Problem: id is overwritten because it is in a foreach loop, taking it out, doesn't help. It only stores last value from the loop.

How can I get an id of the element selected?

I'm sure you can pass some arguments to your callback by doing this:

$form['image-entry'][$some->id]['submit3' . $some->id] = array(
  '#type' => 'submit',
  '#value' => 'Delete',
  '#ajax' => array(
    'callback' => 'image_gallery_delete_photo_callback',
    'parameters'=> array('param1'=>$some->id)
   ),
);

Try to catch those parameters at your function image_gallery_delete_photo_callback($form, $form_state, $args)

The variable $args should contain 'param1'as your ID

Hope it helps !


Multilingual Paragraphs fields are not present in node content Following these Instructions I set up a paragraph field in custom node type. The field is called field_content_sections and it holds the paragraph elements. Next to it I created another field, the plain old list field called field_content_rating_level.

But when i create a node of that type with filled out parapgraph elements, the paragraph field doesn't appear in the nodes content, but the plain old list field does:

What I've done wrong?

I tried it with Drupal 8.5.6 and 8.6.0 and the most recent versions of the paragraphs module itself.

Turned out, that there was a conflict with the field_layout module. Just uninstalled it and voilá!


After logging in the user is not directed to the homepage I noticed that when I login I get redirected to localhost/mysite/user/1 and not localhost/mysite or localhost/mysite/homepage. Why is this and what can I do about to make the user go to the homepage after logging in ?

It is a default option.
But you can redirect user to any page by using hook_form_FORM_ID_alter
Example:

 /*
* Implements hook_form_FORM_ID_alter
*/

     function YOUR_MODULE_OR_THEME_NAME_form_user_login_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      // Alter login form and add own custom submit handler.
      array_push($form['#submit'], '_custom_user_login_form_submit');
    }

 /**
 * Custom submit handler for login form.
 */

    function _custom_user_login_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
        $parameter = 'some_value';
        // Set redirect to login form.
      $form_state->setRedirect('custom_page', ['parameter' => $parameter]);
    }

For the front page default front page name is view.frontpage.page_1. So it should be

 function _custom_user_login_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {

          $form_state->setRedirect('view.frontpage.page_1');
        }


Views 7.3.1.3 ajax error I am running a 7.41 with views 7.3.1.3 version and editing views causes ajax error?

here is the current error code :

an ajax http error code.
http status :500
[{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"seven","theme_token":"L0_2m6Pw1Y-YlW1YH8Xlfc_C0oFxmC1n0tPxBJZyDLA","jquery_version":"1.10"},
"artPortfolio":{"art_portfolio-block_1":{"columns":"3"}},"better_exposed_filters":{"views":{"art_portfolio":{"displays":{"block_1":{"filters":[]}}}}},
"viewsImplicitFormSubmission":{"views-ui-preview-form":{"defaultButton":"preview-submit"}},
"ajax":{"preview-submit":{"wrapper":"views-preview-wrapper",
"event":"click","progress":{"type":"throbber"},
 "method":"replaceWith","url":"\/admin\/structure\/views\/view\/art_portfolio\/preview\/block_1\/ajax","submit":{"_triggering_element_name":"op","_triggering_element_value":"Update preview"}}},
"urlIsAjaxTrusted":{"\/admin\/structure\/views\/view\/art_portfolio\/preview\/block_1\/ajax":true,"\/admin\/structure\/views\/view\/art_portfolio\/preview\/block_1":true}},
"merge":true},

Why is this happening in this version? Do I need to downgrade, or is it due to the jquery_update module? I tested on the following jquery versions :

1.5
1.7.2
1.8
1.9
1.10
but all are not working.

Any help would be appreciated.

Rooby is right, this views happen because of the server not providing enough memory limit to run it and that happens, so I solve it when I asked the server guy to add more memory limit to the site and all good, thank you!


How can I make Search Terms in a View to look fo into the edited Summary? I have a View of a type of content, and it has a Search Terms contextual filter. It searches perfectly (after indexing the content and running cron), but when I have a node which has the summary edited (not the default trimmed body text), the search does not return any result. How can I include the edited version of the Summary in the search?

I have discovered how to get it work: just selecting in the Manage Display --> Search Indexing, Body Summary or trimmed. Isn't it confussing? It seems that it will search only in the summary, while it searches in both Summary and Body. And now it works with edited Summaries.


How do I include ? and = in a form redirection? I have a form and I would like to take the value from it, and use it as input for a page view which is created using exposed filters.
I have created a submit handler for my first form. I then redirect to the page view. The challenge is that I want to include search keys in the redirection. I can't figure out how to get this to work because the characters ? and = are converted.

I have created this function.

function my_module_my_button_submit($form, &$form_state) {
  $url = 'some-path/search?keys=' . check_plain($form_state['values']['input']);
  $form_state['redirect'] = $url;
}

The URL that is created from this is 'http://site/some-path/search%3Fkeys%3Dtest'; the URL I want is 'http://site/some-path/search?keys=test'.

In Drupal 6, instead of setting `$form_state['redirect'] with a string, you set it with an array with tree items.

$form_state['redirect'] = array('some-path/search', 'keys=' . check_plain($form_state['values']['input']), '');

The last item would be a value used as anchor. As in your case you don't need it, pass an empty string.


What could be causing duplicate nodes to be posted? One of the content editors for our site is encountering a duplication error when she posts calendar events. You can see what's happening on the front end here: https://www.library.drexel.edu/events

I'm pretty much brand new to administering drupal (outside of some minor content editing) and am just taking over the site in the interim after an employee left while we seek to fill the position.

We see this (or somthing similar) quite often. Some users create a new node, add text, hit save. So far so good, but sometimes they see an type error or so and go back with the browser Back button, make the corrections and hit then save again. Usually this creates a new node instead of editing the one they think they edited.


How to make the permissions of a module more granular? Assume a (contributed) D7 module, say module ABC, comes with only a few permissions (which can be set on the typical /admin/people/permissions page). For example:

Administer module ABC.
Access (view) "all results" produced by module ABC.

Whereas "all results" can be found within a site via a combination of URLs (with corresponding menu items also) like:

ABC/SomethingX (X=1, 2, ...).
ABC/SomethingElseY (Y=1, 2, ...).
node/*/ABC.

Which site building techniques can be used (without hacking the module), to grant access to such URLs as in this example:

Access to ABC/SomethingX is allowed for anybody.
ABC/SomethingElseY is only allowed for authenticated users.
node/*/ABC is only allowed for authenticated users.
For any URL that is only allowed for authenticated users, its corresponding menu item should be visible to anonymous also. This to show such users that such menu item is available, but with some type of Drupal message to inform them that login is required to actually use such link.

Real world situations (use cases):

The question about "content access + menu block => not shown all links in menu block": by using the Content Access module access to selected nodes is restricted (of course). But how can menu items corresponding to such selected nodes remain visible for anonymous users anyway?
The Visitors module: replace 'ABC' by 'visitors' in the example above, and assume that you want to grant access to "some" reports (= ABC/SomethingX) for anybody, but not to "some other" reports (= ABC/SomethingElseY).

If permission Access (view) "all results" produced by module ABC would be set to "authenticated", then anonymous users cannot see any URL. While if that permission would be set to "anybody" (= either "anonymous" or "authenticated"), then anonymous users also have access to (eg) ABC/SomethingElseY (which is not what is desired).

How can menu items corresponding to ABC/SomethingElseY remain visible for anonymous users anyway?

Rules (the module) is your friend ... Here is the rule (in Rules export format), that does exactly what this question is about (using the Visitors module as an example, like the ABC in the question):

{ "rules_limit_access_to_some_urls_related_to_visitors_" : {
    "LABEL" : "Limit access to some URLs containing \u0027visitors\u0027",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "visitors\/hosts",
                  "visitors\/hits",
                  "visitors\/referers",
                  "visitors\/user_activity",
                  "visitors\/pages"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/\\d+\/visitors",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "visitors" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.\r\n\u003Cbr \/\u003E\r\nAnonymous users can only see its corresponding menu item (login required).",
          "type" : "warning"
        }
      }
    ]
  }
}

After you enable the above rule, you can safely grant Access (view) "all results" produced by module ABC permission to anybody. That will make the menu items visible to anonymous users also (of course). The above rule will ensure that anonymous users will NOT be able to actually "view" the specified URLs. Instead they'll get a message starting with "Access to the report located at ...".

To make the above rule work in similar situations, just adapt the URLs (change 'visitors' to whatever fits), and the message to be shown for those who are not allowed to access those URLs.

Possible variations: instead of using the above rule for anonymous versus authenticated users, it can also be used for any combination of 2 roles. eg: "authenticated" versus "editors" (or whatever other role), in which case you'd grant the permission to "authenticated" (and use the role id for authenticated users).

Remarks:

This won't prevent the path from being omitted from menus. But that is exactly what is desired (as mentioned in the last phrase of the question).
What is above does not relate to any "other places" where path checks happen that aren't direct page access. But whenever one attempts to use those paths in those "other places" to actually visit such paths (URLs), the above rule will catch those situations also (provided such URL is correctly mentioned in either of the Rules Conditions in my sample above).


Creating an RSS from Scratch I'm converting a site to D7 that does not currently have an RSS feed. I'm trying to find a way to create something that will help me avoid having to manually move over each and every page, but I'm coming up empty.

I thought of wanted to try to generate a feed, with the goal being to use the Feeds module to import the feed as pages, but I've not found anything to do that sufficiently.

Right now all the pages are stand-alone pages meaning that none of them are stored in a database, but it's all written up in PHP & HTML and it's a bit of a mess. So I'm having to work with the raw pages. That's why I thought creating a feed would be the way to go.

If I could get the existing pages in to a CSV or XML file I could work with them a little easier, but there are numerous pages and it would take forever to do that.

Thanks in advance for any help/advice you can offer!

Maybe try Goutte. I thought there was a similar Migrate module + Goutte frontend out there ... but can't find it.


AJAX submitted form redirection I just found out that when I try to submit a form with AJAX, in that instance user_login, the redirection doesn't work anymore. Is this normal? How can I make the redirection happen after the AJAX request comes back?

I had the same situation: ajax login/register form until the fields are correctly filled, and then redirect the user to the logged in section.
This is what I used, and it works fine for me, in the ajax callback function:

ctools_include('ajax');
ctools_add_js('ajax-responder');

$commands[] = ctools_ajax_command_redirect('<front>');

return array('#type' => 'ajax', '#commands' => $commands);

the full function looks like this:

function ajax_signup_detailed_submit_callback($form, &$form_state)
{
  $commands = array();
  $messages = drupal_get_messages(NULL, FALSE);

  if (count($messages))
  {
    $commands[] = ajax_command_replace("#better-messages-wrapper", theme('status_messages'));
  }
  else
  {
    ctools_include('ajax');
    ctools_add_js('ajax-responder');
    $commands[] = ctools_ajax_command_redirect('<front>');
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

Hope this helps,
Istvan


Migration from drupal to platform.sh I have developed website which is hosted on hostgator now I want to host it on platform.sh. Could anyone give me step by step procedure to migrate my website to platfrom.sh?
I am using windows 8.1 for development. Could you please explain how to use git. Could please give step by step procedure how to use it. I am on windows platform. I am bit confused how to use it.

To migrate your existing site into Platform.sh, there are 3 components you need to import: code base, database and files.

Import code base

If your project already uses Git you've to go to your Git project folder and add platform as a remote and push your local branch to your platform remote.

$ cd ~/Sites/platform
$ git remote add platform [PROJECT-ID]@git.[CLUSTER].platform.sh:[PROJECT-ID].git
$ git push platform HEAD:master

Import your database

Create drush alias for your platform.sh, e.g.

$ cd ~/.drush
$ sudo vi platform.aliases.drushrc.php

In your new alias file, you can create aliases for your various Platform.sh projects. For example:

<?php
// Platform environment
$aliases['master'] = array(
  'uri' => 'master-[project-id].eu.platform.sh',
  'root' => '/app/public',
  'remote-host' => 'ssh.eu.platform.sh',
  'remote-user' => '[project-id]-master',
);
// Platform branch environment
$aliases['BRANCHNAME'] = array(
  'uri' => 'BRANCHNAME-[project-id].eu.platform.sh',
  'root' => '/app/public',
  'remote-host' => 'ssh.eu.platform.sh',
  'remote-user' => '[project-id]-BRANCHNAME',
);
// Platform local environment
$aliases['local'] = array(
  'site' => 'platform',
  'env' => 'local',
  'uri' => 'platform',
  'root' => '~/Sites/platform',
);

Backup your database.

$ drush @platform.local sql-dump > backup_database.sql
Export your local database and then import it into your remote Platform environment.

$ drush @platform.local sql-dump > local_database.sql
$ drush @platform.master sql-cli < local_database.sql

When the process completes, you can visit the URL of your development environment and test that the database has been properly imported.

Import your files

Use drush alias to import your existing local files:

$ drush rsync @platform.local:%files @platform.master:%files

The above steps assume that you're using drush and Git scm (which is the easiest way).

More details information can be found at: Migrate an existing site to Platform.sh


Removing Queue Table Items / Queue UI Module D7 While attempting to export the mysql database, I found that there was a large number of items in the drupal 7 queue tables "feeds_importer_expire" and "feeds_source_import", both have about 80,000+ records dating back over a year.

I have installed the Queue UI module but have a question before I proceed.

In the "Queue Manager" at "admin/config/system/queue-ui" there is a delete queues button. If I delete the queue e.g. "feeds_importer_expire" will it regenerate the next time it is needed? Or am I deleting the queue all together and causing major issues.

The default Drupal supplied queues only exist when they have $items within them. It will be regenerated when it's next inserted into.

Depending on whether or not a worker process is working on a claimed item the queue item(s) when you delete the queue -- you may raise like a warning when the process tries to notify the queue of completion of an item. It shouldn't break the queue itself; the worker processes may need to be reset of course.


How can I make a usable backup of the site on CD? The client would like to archive off a copy of their drupal 7 site every 6 months or so. By archiving, they are referring to copying the site (in a usable format) onto a cd.

What are some of the options for doing this?

The Backup and Upgrade module can be used to schedule automated database backups. One of those backups, combined with the codebase, gives you a full backup of the site. If this is to be burned to a disc every 6 months, I wouldn't bother automating anything - the time investment won't be worth the future time savings.


Form returned from AJAX callback missing JS and CSS I have a form set up like this:

function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save',
        '#ajax' => array(
            'wrapper' => 'ajax-node',
            'method' => 'replace',
            'callback' => 'mymodule_callback',
            'effect' => 'fade'
        ),
        '#submit' => array('node_form_submit'),
    );
}

And then the callback:

function ajax_complaint_save_callback($form, &$form_state) {
    $nid = $form_state['build_info']['args'][0]->nid;
    $node = node_load($nid);

    return drupal_render(node_view($node));
}

Now this does work sort of, but the node is not rendered correctly. I have some more AJAX stuff on the same page which uses the ajax links api and that produces the node forms correctly. Here are some pictures to demonstrate.

In this picture, one of the links in the table was clicked and the stuff circled with blue was loaded using the links api - this is how it should look.

But if go to the edit tab on the loaded node (which is also loaded up through the ajax links api) then press the save button, I get this:

There's more to this picture, but this is loaded in the same div as the other stuff was - but it seems like it is missing style information, and also the view/edit tabs are missing.

How do I make it load up the node form properly?

I ended up loading the form with tabs in to my ajax-node div using the links api, but then within the form I made the submit button replace the form container.

My full solution:

/* Drupal caches all ids of form elements and when ajax request happen, this
 * results in the new form have id's appended with --2 --3 etc, so css breaks.
 * Unsetting this makes the ids always the same. Maybe hook_init is not the best
 * place for this, but for now it works.
 */
function mymodule_init() {
    if(isset($_POST['ajax_html_ids'])) {
        unset($_POST['ajax_html_ids']);
    }
}

function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    //only do the do if this is and ajax request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Save',
            '#ajax' => array(
                'wrapper' => 'my_form_id',
                'method' => 'replace',
                'callback' => 'mymodule_callback',
                'effect' => 'fade'
            ),
            '#submit' => array('node_form_submit'),
        );

        /* For some reason this _has_ to be in form_alter. Putting it in a submit
         * callback doesn't work. What this is doing is setting the changed time
         * of the form to be in the future, if we don't do this, when the form is
         * reloaded after a submit, it's not possible to submit the reloaded form
         * because Drupal thinks someone else has edited it (I think it checks
         * the last update time of the node VS this value). This adds a 5min window
         * where changes can still happen. It's not the best solution but I think
         * it will work.
         */
        $form['changed']['#default_value'] = time() + 300;
    }
}

function mymodule_callback(&$form, &$form_state) {
    $new_form = drupal_rebuild_form('my_form_id', $form_state, $form);
    $form_html = drupal_render($new_form);

    return $form_html;
}


Taking over an existing Drupal site On ServerFault, this question "Ending company IT Admin relationship" has a pretty good general checklist for taking over an existing IT system, but I'm wondering as it relates to Drupal:

What system access controls should I get, or confirm have been changed after the takeover?
What is the most effective way to assess the scope of existing custom configurations, development, etc done?

If it matters, the existing site is on Drupal 6, but talking about porting the site from 6 to 7 is beyond the scope of this question.

To save yourself access headaches:

Get credentials for the "user 1" account that has full Drupal access
Get database access or a copy of the most recent database
Get SSH Access to the production server

To audit the site once you get access:

Install http://drupal.org/project/hacked to make sure there haven't been any undocumented changes to Drupal core or contrib modules.
Look in /sites/all/modules/custom to find any custom modules. If nothing is there one good way to tell if you're missing any hidden ones is by looking at http://example.com/admin/build/modules and looking for modules without a version number. They may be hiding in /modules or /sites/*site_name*/modules.
Have a look at the theme and especially the contents of template.php. Often times a site will have a lot of modifications happening here.
After looking at the items found in #1, #2 and #3 you shouldn't expect to have found a whole lot. The custom modules should be mostly hook implementations and 'glue code' not re-inventing the wheel or re-creating functionality found in popular contrib modules but your mileage will vary here depending on how custom the site requirements originally were.


Apache Solr server URI problem I rebulding solr server after VPS crash, so I'm not completely newbie, but this time something went wrong and I can't manage the problem:

I configuring Apache Solr to use with Drupal. Acoording to may manuals Solr server URI should look like
xx.xx.xx.xx:8983/solr/corename

but my Solr ULR looks like

xx.xx.xx.xx:8983/solr/#/~cores/corename

However, Drupal reports "The Solr server could be reached", but when indexing I get errors:

SearchApiException while deleting items from server New SOLR server:
"400" Status: Bad Request HTTP Status 400 - HTTP method POST is not
supported by this URL The request sent by the client was syntactically incorrect.
SearchApiException: Could not index items since important pending
server tasks could not be perfor

med.

System info: Ubuntu 14, solr 4.7.2, tomcat 7

The URL that the Drupal modules need is different than the one on which you browse the Solr server as an admin. Thus, for you, assuming 8983 is server port, it should be:

xx.xx.xx.xx:8983/solr/corename


Need help with superfish module on Bartik theme Need your help on this subject.
Pretty like Bartik theme but as you know can’t have sub menu on Main menu on Bartik theme, so I would like to use Superfish module on it.

I have searched internet to find solution but failed, and I don’t think there is same post here, so please allow me to post it here.

What I have done:

Have installed superfish module successfully, I am sure.
Have created subtheme of Bartik successfully, I am sure too. (name is subtheme3)
Added a region calls superfishmenu to subtheme3.info below header region.
Copied page.tpl.php to sbuntheme3 folder and change some code to it.
Disabled Main menu in Menu Setting, so there is only Superfish menu shows.

My problem:
No.1, Superfishmenu block shows but the width is not like others short and at the center of screen. I would like to make it as same wide as other regions like featured region.

No.2, the sub menu of superfish menu doesn’t show sub menu but if I flush all the cache and the message shows, which give a lot padding space, then the sub menu shows. When the message is gone, the sub menu can’t show again.

I am not good at CSS and PHP, and I believe the problem is CSS and the PHP code in page.tpl.php.

Is there anyone can give me the correct codes for them?

You need to add this block in Featured region.Check out this https://d25zd.ply.st/

You don't need any code just place block by admin interface.


Auto Complete displaying wrong for non-admin users I've recently started a module that runs an autocomplete via the taxonomy. It's attached to a form textarea element:

$form['bb_occupation'] = array(
    ...
    '#autocomplete_path' => 'taxonomy/autocomplete/field_occupations_list',
);

My issue is as follows, The options returned from the auto complete display correctly for admin/logged in users:

Full size image

While, if a non-admin/non logged in user visits said site, they're greeted with this:

Full size image

Where the options appear well off screen. I did a little research on Drupal & Google and came up with these:

Autocomplete fields appear in wrong place for non-admins in...

Which lead to an answer that did the following sort of deal (taken from here):

$($input).parent().addClass('autocomplete-wrapper');

in the autocomplete.js and this:

.autocomplete-wrapper {
  position: relative;
}

to the system.base.css files. That didn't work for me, and I've been playing with positioning for practically the whole day now, do you guys have any suggestions as to how I can amend/fix this?

It is not related to anything like this:

(custom )Autocomplete won't work when the user is not logged

as it isn't a custom function doing the autocomplete, it's through the taxonomy.
It can't be a permissions error either because the menu with suggestions shows up, just not where it's supposed to.

I think anonymous user doesn't have a permission of autocomplete. Can you please visit permission tab of your site. May be you get some luck!

Hold on, you are using taxonomy right, then please check this module permission. I think that time you get some luck.


Drupal 7 not sending emails of any kind My drupal site isn't sending email for some reason. What are some ways to debug this issue of mail sending?

Use a module that allows you to route email through a real SMTP server.

What is probably happening is that Drupal is sending the mail, but it's being blocked as a spammy looking email message.

edit: you can Alphabet for "drupal smtp module", but this is one I've used https://www.drupal.org/project/smtp


Best way to store not publicly viewable data? I wanted to know what is the most suited to store not publicly viewable data? Here is an example what I want to achieve:

Imagine having a personal section about me. On this site I show the visitors an online CV which includes a section of my skills. In the section "skills" I have listed each skill with a specific rating like 8/10 depending on how good I'm in it.

For helping you to visualize it, here is a normal CV with a section skills:

https://creativemarket.com/GraphicsToll/492647-Resume

Now my question is how do I store this kind of data? I know that a normal custom content type would be an overkill because not one of the skills should be separately viewable, it should be only visible with all the other skills on my online CV. Further I looked into custom content entities but I think this also an overkill because you could also view each skill separately (canonical).

What other ways are there? Do I have to create a module which just interacts with the database abstraction layer?

I appreciate any kind of help!

The simplest way to do this is to put the two fields "skill name" and "rating" in a field collection:

Field collection

But I would suggest to use the new module Paragraphs. This will extent Drupal's flexibility to design content types for structured data a lot:

Paragraphs

Edit:

Changed module name (thanks to @Berdir).


change the date format to dd/mm/yyyy in views of the webform I have created the fields for the view extracte from a webform. It is working perfectly. But when i try to extract the date field it just get the date it yyyy/mm/dd format. Now I searched alot but no where i could find easy steps to convert the date format of this field to dd/mm/yyyy.
Please explain in easy steps how to convert my field to my required date format.

Visit admin/settings/date-time/formats in you instance & add a custom date format. See PHP manual for the options which you can.

Use your created date format to show the field value wherever you want like views.


Include HTML in theme_pager_next $text variable? Is it possible to include markup in the $text variable of theme_pager_next()? I find that whatever I set the variable to gets output as a string, rather than being rendered as HTML. Here's some example code as would be found in template.php:

    function theme_pager_next($variables){
      $text = 'test value';

      /* Remainder of function call goes here ...*/

      return $output;
    }

I would like be able to add an image to the pager text. I realize I could also use CSS background images, but would prefer to print markup to the page if at all  possible.

Is there something I'm overlooking?

If the rest of the code is the same used in theme_pager_next(), then it is not possible to add HTML tags to $text.

This is because theme_pager_next(), and theme_pager_last() call theme_pager_link(). theme_pager_next()'s code is the following one.

if ($page_new[$element] == ($pager_total[$element] - 1)) {
  $output = theme('pager_last', array('text' => $text, 'element' => $element, 'parameters' => $parameters));
}
// The next page is not the last page.
else {
  $output = theme('pager_link', array('text' => $text, 'page_new' => $page_new, 'element' => $element, 'parameters' => $parameters));
}

theme_pager_link() then contains the following code.

$attributes['href'] = url($_GET['q'], array('query' => $query));
return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';

As it calls check_plain(), if $text contains HTML tags, they are shown as plain text.

To achieve what you are trying to do, you should override theme_pager_link() with a theme function that doesn't call check_plain(). filter_xss() could be a better function to use in this case, but remember to pass in $allowed_tags the list of the tags you want to allow.

As side note, when you want to alter the content of the $variables array a theme function gets, in Drupal 7 you can use its preprocess functions. Every theme function has preprocess functions, and in your theme that is THEME_preprocess_pager_next(). (Replace THEME with the short name of your theme.)


How to Limit Node Revisions in Drupal7 I added the diff module that keeps all node Revisions (it seems that I can't limit the
number of Revisions to keep).
Is there a code I can use where I can set a limit of the number of Revisions to keep?
If so, where to add it?

Thanks.

You can use the Node Revision Restrict module for this.

  The Node Revision Restrict module allows you to restrict revisions of node for each content type. This module has an admin interface to specify node revision threshold for each content type available. The possible settings include node type, the number of count provided on configuration form for each content type and more. Users with specific permissions can delete any unwanted revisions. Note that this module does not and cannot delete the current revisions of a node.

You could either use the module, or incorporate some of its code. It is a short module. Most of the code relevant to your task can be found in the node_revision_restrict_node_presave function:

/**
 * Implements of hook_presave().
 */
function node_revision_restrict_node_presave($node) {
  $node_type = $node->type;
  $nid = $node->nid;
  $node_data = db_query('SELECT * FROM {node} WHERE nid = :nid', array(':nid' => $nid));
  foreach ($node_data as $node) {
    $revision_data = node_revision_list($node);
    foreach ($revision_data as $revision) {
      $revision_ids[] = $revision->vid;
    }
    $count_to_restrict_set_value = variable_get('restrict_node_revision_number_for_' . $node_type);
    if (isset($count_to_restrict_set_value)) {
      $node_to_restrict = array_slice($revision_ids, $count_to_restrict_set_value, count($revision_ids));
      foreach ($node_to_restrict as $revision_id) {
        node_revision_delete($revision_id);
      }
    }
  }
}

In general, I prefer using a contributed module, if it provides the functionality needed, over maintaining my own code, because I won't have to worry as much about security updates, and other debugging issues, down the road.


How to geocode a form field on submission? I'm writing a module with form alter that should geocode a text field value to the lat\lan format upon triggering the submit function. Should I use the Geocoder module for this? Are there any sample queries to learn how to perform geocoding with that module? Thanks.

Personally, rather than form_alter upon submission, I would wire up an AJAX function to fire on the address/location textfield's onchange event, which would use the Google Maps Javascript API's Geocoder function.  This would then populate a hidden text field (or two) with the lat/lng pair for form submission.

If you want to use the Geocoder module, it should probably go in the validate function so you can double check that you actually have a valid address.

Ideally, you would do both.  Doing it client side is faster, and doing it server side supports users w/o Javascript.


How to properly add a Commerce Shipping Service option via AJAX during checkout I have the Payment and Shipping service block in the same
checkout pane.
I update the Shipping service block with AJAX when
selecting a Payment method, as available Shipping services depend on
the selected Payment method.

But once the Shipping service block is reloaded, if I select another Shipping service and submit the form, I will be redirected to the initial pane as if my selection was unvalid - with no error message.

This is the code I use to update the Shipping services block, after saving the order to update the available Shipping services. (Inspired by some other posts)

And I can't find a way to make the Shipping selection work on submit after being reloaded via AJAX.

Should I also update the form state?
commerce_shipping_service_rate_order($service, $order) didn't change
anything
Nor commerce_shipping_pane_service_details_refresh($form,
$form_state)

Would someone have an idea what could go wrong?

/**
 * Alter checkout shipping form.
 */
function mymodule_checkout_shipping_alter(&$form, &$form_state) {
    // Replace AJAX callback by a custom one.
    $form['commerce_payment']['payment_method']['#ajax']['callback'] = 'mymodule_payment_pane_checkout_form_details_refresh';
}

/**
 * Checkout shipping pane AJAX callback function.
 */
function mymodule_payment_pane_checkout_form_details_refresh($form, &$form_state) {
    // Commands initialization.
    $commands = array();
    // Load the current order
    $order_id = $form_state['order']->order_id;
    $order = commerce_order_load($order_id);

    // Set the newly selected payment option to the order
    $order->data['payment_method'] = $form['commerce_payment']['payment_method']['#default_value'];
    // Refresh the current order (more specific: update it's line items
    commerce_cart_order_refresh($order);
    // save the refreshed order (more specific: recalculate the order total and save it)
    commerce_order_save($order);

    // Default Commerce AJAX callback for the payment pane.
    $commerce_wrapper = '#' . $form_state['triggering_element']['#ajax']['wrapper'];
    $commerce_output = commerce_payment_pane_checkout_form_details_refresh($form, $form_state);
    $commands[] = ajax_command_replace($commerce_wrapper, render($commerce_output));

    // Update Commerce shipping pane.
    $panes = commerce_checkout_panes();
    $shipping_pane = drupal_get_form('commerce_shipping_pane_checkout_form', $panes['commerce_shipping'], $order);
    $form['commerce_shipping']['shipping_rates'] = $shipping_pane['shipping_rates'];
    $form['commerce_shipping']['shipping_service'] = $shipping_pane['shipping_service'];
    $form['commerce_shipping']['service_details'] = $shipping_pane['service_details'];
    $commands[] = ajax_command_replace('#commerce-shipping-service-ajax-wrapper', drupal_render($form['commerce_shipping']));

  return array('#type' => 'ajax', '#commands' => $commands);
}

Since Stackexchange does not allow me to comment, did you find a solution? I am experiencing exactly the same issue. Thanks.


Drush sql-dump but exclude multiple tables with a pattern I have a gigantic database due to having over 1000+ individual tables created for every time someone logged in. (wasnt me that made this).

I want to now create a dump of the database using drush sql-dump but the file ends up to be over 15GB and 1GB zipped.

Is there a quick and easy way to exclude a bunch of tables matching a pattern using drush? The tables I want to exclude all begin with the word "result-<username>"

Drush has a number of options to exclude tables from sql-dump. These all now support wildcards (thanks @MPD for pointing this out), so for example you can do this:

drush sql-dump --skip-tables-list='result-*'

This will completely exclude any tables matching the pattern result-* - that is, beginning with result- - from the dump. You can pass multiple patterns (or individual table names) by separating them with commas. The quotes are necessary to prevent your shell from expanding the pattern.

If you want the tables' structure to be included but just not the data in them, use --structure-tables-list instead.

The other options are --skip-tables-key and --structure-tables-key which work similarly, but instead of providing the table names or patterns directly on the command line, you add them to an array in drushrc.php and specify the array key on the command line. This is useful if you have a set of tables that you routinely exclude, such as 'cache_*'. The example.drushrc.php provided with drush gives the following example:

/**
 * List of tables whose *data* is skipped by the 'sql-dump' and 'sql-sync'
 * commands when the "--structure-tables-key=common" option is provided.
 * You may add specific tables to the existing array or add a new element.
 */
# $options['structure-tables']['common'] = array('cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');


Unable to send user-entered data to PayPal along with credit card info I need help. I used this as a guide. When my user fills out and pays for something on my site using a product form the information they supplied in the form (other than their payment) is not being sent to PayPal. So I built this module to send the information using the module I'm supposed to hook into. However, it throws no errors but still sends no data to PayPal.

    if ($payment_method['base'] == 'commerce_paypal_wpp') {

    $order_wrapper = entity_metadata_wrapper('commerce_order',
$order);
    $shipping_info = $order_wrapper->customer_profile_billing-
>commerce_customer_address->value();

             $nvp += array(
                    'ORGANIZATION' => $shipping_info['field_organization'],
            'NAME' => $shipping_info['field_name'],
         );
    }
}

Am I perhaps referencing my user-entered data incorrectly?

Here's how the fields show with dpm($form) [before the user submits the form]:

Name:

$form['customer_profile_billing']
['commerce_customer_address']['und'][0]'name_block']['name_line']

Organization:

$form['customer_profile_billing']['field_organization']

From your above code i have seen that dpm($form) showing 2 fields. when you submit your data in form please ensure that your order is created or not. Becuase in your code you are getting customer order details and pass it to the array() (which is empty). Thats why it not going to Paypal website. Please check your custom code.

hook_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method):  What this function will do, it will alter the array before pass this data to paypal website. So you must ensure that array data you are passing to paypal is not empty or you can check the condition for it.


How can I view nodes on my site from Drupalgap? I am getting started with Drupalgap and trying to access nodes on my Drupal site by node ID from within Drupalgap.  I have checked the Node and Node Services documentation.  I thought I could use the node_page_view(nid) function like this:

function mymodule_sample_page() {
  try {
    node_load(11, {
        success:function(node){
        alert("Loaded " + node.title);
      }
    });
    return node_page_view(11);
  }
  catch (error) { console.log('mymodule_sample_page - ' + error); }
}

However, when I attempt to test this in my module, I get the alert "Loaded your node" but the content is not actually displayed on the page by node_page_view().  What do I need to do to display the content?

In mymodule_sample_page() just return an empty div container, for example:

Then attach a pageshow handler to your page via hook_menu(), then in the pageshow handler call node_load(), and in its success inject the content into your empty div container.

The page_callback can not have any async calls in it, as all async calls have to be handled after the page is actually shown.

FYI, DrupalGap has built in support to view nodes, just navigate to node/11 in the app. Here's a brief example demonstrating pageshow: http://www.drupalgap.org/node/154


perform action if user is not logged in for 24 hours I wrote this script using poor man's cron to send an email in 24 hours if a user has not logged in during that amount of time. It works but I can't figure out why after 24 hours passes the email sends, but then it starts sending again every hour.

function dreamcharts_cron() {
      $now = time();
      $result = db_query("SELECT u.uid, u.mail, u.access
                      FROM {users} u
                      INNER JOIN {users_roles} ur ON ur.uid = u.uid
                      WHERE ur.rid = 4 AND u.uid NOT IN (0,1)");
      $i = 0;
      while($user = db_fetch_object($result)) {
        if ($user->access + 86400 < $now) {

         // drupal_set_message('<pre>' . print_r($user->mail, 1) . '</pre>');
               $message = array(
            'to' => $user->mail,
            'subject' => 'you have not logged in in 24 hours',
            'body' => t('Please log into your Account Today', array('@title' => $title)),
            'headers' => array(t('From') => variable_get('site_mail', ini_get('sendmail_from'))),
               );
              drupal_mail_send($message);
          $i++;

      }
      }
      }

It is sending every hour because cron is running every hour, and the user has not yet logged in to change the timestamp. There is no check to see if the email has been sent, or when it was sent.

You can either update the user's timestamp to $now, which will stop the email from being sent for the next 24 hr., or set a flag on the account to say that an email has been sent.


Quick tabs module change title to bottom I am facing a problem. I have a module called QuickTabs, new to Drupal and confused.

I like to change the position of the title of the quicktabs, instead of top and I would like my buttons or links to be on the bottom. I worked the css but it seems that the render is on the inc.

    tile1 title2
---------------------------
    content content

Change to:

     content content
---------------------------
     title1  title2

Any hints of how I can do this? I am using Drupal 7

I would recommend you to start by downloading the excellent devel_themer module from Drupal.org and install it on your site. It will also require that you install the devel module.

Once you install it and enable it, devel_themer will tell you what template (*.tpl.php) is being used. You can then go to that template and alter the order of the HTML elements directly. You will also find devel_themer to be a great tool for learning Drupal theming.


Creating a view to show nodes with multiple aliases generated by Path Module I got a tough problem that I don’t even know how to start, any help would be appreciated.

I am on a D6 site.  The Path Module is installed and there are articles that have more than one alias because the previous admin didn't overwrite the previous alias when saving the new ones.

I am doing a data migration and the migration is grabbing the old alias and not the new one.

What I need to do is find all NIDs that have more than one Path aliases, display them, delete the old one with bulk views

When I create a view to show field Path, it only displays the current one. Any thoughts how to display both aliases or any other way to tackle this.

Thanks for looking!

As this is a one-off requirement, there's not a lot of point creating a view for this purpose, as it would mean writing code to add extra entries for path in views tables.

You will be better off writing SQL. Here's a query that'll give you what you are after:

SELECT src, COUNT(*) AS alias_count FROM url_alias WHERE src LIKE 'node/%' GROUP BY src HAVING alias_count > 1

The result will be every source path like 'node/nnn' which has more than one alias.


Manually removing an orphaned entity type I have been handed an older Drupal 8 site and asked to update it to run with composer. I didn't do it in the cleanest possible way but it is working. I have run into trouble updating it.
I am most of the way there. Have rebuilt it and it is now managed with composer. However, In trying to run the final DB updates I am stuck with the following error blocking update:
[notice] Update started: system_post_update_entity_reference_autocomplete_match_limit
[error]  The "support_ticket" entity type does not exist.
[error]  Update failed: system_post_update_entity_reference_autocomplete_match_limit
[error]  Update aborted by: system_post_update_entity_reference_autocomplete_match_limit
[error]  Finished performing updates.

The "support_ticket" module was on the old site and in the DB but not enabled. I have tried adding and removing it and the "support" module that is its parent but the above error remains.
Is there a way for me to manually stop the system updating that entity type? Or inserting a placeholder? Or some other solution that lets me update the site.
MORE INFORMATION
The module Support and it's sub-module support ticket don't even appeat to be current drupal 8 projects. The last contribution to their d8-port github page is from 2015.
After some messing around I realise the sub-module support_ticket does not only fail to uninstall but it can't be re-installed either. If you try to re-install it you get the following error:
Unable to install Support ticket, comment.type.support_ticket_update,
core.entity_form_display.comment.support_ticket_update.default,
core.entity_form_display.support_ticket.ticket.default,
core.entity_view_display.comment.support_ticket_update.default,
core.entity_view_display.support_ticket.ticket.default,
field.field.comment.support_ticket_update.comment_body,
field.field.comment.support_ticket_update.field_revision_changes,
field.field.comment.support_ticket_update.field_revision_reference,
field.field.support_ticket.ticket.body,
field.field.support_ticket.ticket.field_assigned_to,
field.field.support_ticket.ticket.field_priority,
field.field.support_ticket.ticket.field_related,
field.field.support_ticket.ticket.field_state,
field.field.support_ticket.ticket.field_ticket_update,
field.field.support_ticket.ticket.field_watchers,
field.storage.comment.field_revision_changes,
field.storage.comment.field_revision_reference,
field.storage.support_ticket.body,
field.storage.support_ticket.field_assigned_to,
field.storage.support_ticket.field_priority,
field.storage.support_ticket.field_related,
field.storage.support_ticket.field_state,
field.storage.support_ticket.field_ticket_update,
field.storage.support_ticket.field_watchers,
filter.format.support_ticket_diff, support_ticket.settings,
support_ticket.type.ticket, system.action.support_ticket_delete_action,
system.action.support_ticket_lock_action,
system.action.support_ticket_publish_action,
system.action.support_ticket_save_action,
system.action.support_ticket_unlock_action,
system.action.support_ticket_unpublish_action,
views.view.support_ticket_overview, views.view.users_support_tickets
already exist in active configuration.

I am guessing at this point I would need to manually delete entries from the DB?

In case it is of use to anyone else dealing with an old module that doesn't uninstall correctly. The solution to my problem was the following.
WARNING: Do this on a copy of your actual site and database. You could break a live site doing this.
Most of the troublesome database entries are in the config table.
You can use the error list produced above when trying to install the module to track down the rows to purge.
In the database a query such as:
SELECT name FROM config WHERE name LIKE '%support_ticket%';
should show you most of the problematic entries.
In my case that exactly matched the offending active configuration so i could just change the above to:
DELETE FROM config WHERE name LIKE '%support_ticket%';
I would be very careful about doing this with a LIKE query unless you are sure you won't accidentally delete something else.
I assume directly removing entries like this in the database is probably a bad idea but I really couldn't find another way to move forward.
Once the above is done Drush updb worked and the update completed.


Not able to connect to remote database after migration I am moving a running site from staging to production. The production environment has 2 servers, one for frontend and the other for the database.

The issue is when I try to browse the website, I get this error

  PDOException SQLSTATE[HY000] [2002] Permission denied in [ROOT]/core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php on line 79

The real problem is I am sure that the database connection is set right. Permissions and ports are set right.

I tried the same database connection info from an external PHP file on the same server and I got successfully connected.

Also, I tried drush st and it told me that database status is Connected, and Drupal bootstrap status is Success.

Even tried drush sqlc and I got connected to the remote database. I can list tables, execute queries, etc.

Any ideas what might be the problem?

In case you're using SELinux see this article.

setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_connect_db 1


How to filter articles that are in front page with taxonomy i have made quick moqup of the site to explain it better :

At this moment i made site in drupal 8 that has some articles in it and thous articles are shown in front page (landing Page).

I have made new taxonomy -> vocabulary -> and Add 4 term as shown in picture.

I have created new region and placed it in the front page and from views i call all articles that i have...

My problem is that, how to filter thous articles accordingly to the taxonomy and if there is possible not to refresh page (if Can't than there is no problem)...

Thanks in advance

You could just create a views filter using the taxonomy field of your article and expose it.

If you don't want the page to refresh then turn on "Use Ajax":

I think that should do it.


Drush make: "Found makefile: myfile.make. Aborting" I have a custom drush make file and custom drupal installation file for a new site. Both work fine on my local VM, and the local VM's of the three other developers who have tried it. However, when I try to run it on our test server, it chokes:

sudo drush -y make stub.make
Make new site in the current directory? (y/n): y
Beginning to build stub.make.                                       [ok]
drupal-7.37 downloaded.                                             [ok]
drupal patched with 1093420-22.patch.                               [ok]
drupal patched with comment-node-type-delete-1565892-3.patch.       [ok]
Generated PATCHES.txt file for drupal                               [ok]
MYPROFILE cloned from git://github.com/MYPROFILE.                   [ok]
Checked out branch development.                                     [ok]
Found makefile: MYPROFILE.make                                      [ok]
Aborting.

The first time this error occurred, my investigation uncovered a permissions issue. However, that is fixed, and I'm still getting the error.

The MYPROFILE.make begins with:

api = 2
core = 7.37

And continues with a bunch of

project[MODULE_NAME][subdir] = contrib

As well as

projects[CUSTOM_MODULE][type] = module
projects[CUSTOM_MODULE][download][type] = git
projects[CUSTOM_MODULE][download][url] = git://github.com/CUSTOM_MODULE
projects[CUSTOM_MODULE][download][branch] = development
projects[CUSTOM_MODULE][download[branch][working-copy] = TRUE

projects[CUSTOM_THEME][type] = theme
projects[CUSTOM_THEME][download][type] = git
projects[CUSTOM_THEME][download][url] = git://github.com/CUSTOM_THEME
projects[CUSTOM_THEME][download][branch] = development
projects[CUSTOM_THEME][download][working-copy] = TRUE

Everything works fine on the Vagrant for Drupal Development box downloadable from Drupal.org, and also on a custom Vagrant box another of the developers set up that integrates better with components beyond the website. But on the dev server, it chokes without giving a reason why. Googling for drush make found makefile aborted didn't turn up anything.

Is there some sort of diagnostic tool that I can use to get a more helpful message than 'Aborting'?

Forgot to add:

Before posting this, I tried running drush make directly on the MYPROFILE.make:

sudo drush -y make profiles/MYPROFILE/MYPROFILE.make
Make new site in the current directory? (y/n): y
Beginning to build profiles/MYPROFILE/MYPROFILE.make.              [ok]
No core project specified.                                           [error]

But as you can see from my excerpt of the make file above, it does specify a core. And again, it works on two different VMs. -- Since MYPROFILE.make was designed to be called by stub.make, the above error is the expected reaction when running it alone.

Have you tried this recently?  It's hard to tell from the info you posted above, but your problem could very well have been caused by the ssl certificate problem on updates.drupal.org.  Since sometime yesterday until a few hours ago, https connections to updates.drupal.org were failing due to a limitation of the new CDN they are using now.  This caused drush dl and drush make to fail.  (n.b. Drush caches update information, so things likely continued to work from the cache on systems that were working before the cert problem started.)

The drupal.org team has things patched up now, so try doing everything again from the beginning, and see if it starts working again.  If that does not clear up the problem, try running drush make again with the --debug option, and post the results.


Views: how to override a linked "Content: Title" field's href programmatically? I would like to override a Views-generated block's "Content: Title" field's href path (linked to nodes with "Link this field to the original piece of content") to append a query string ($_GET['page']).

An example:

this is the generated link:

Blabla

I would like this one:

Blabla

I would like to override the path and append a query string before it gets rendered as an HTML-link ().

How should I do this? I think Views uses views_handler_field_node::render_link() and views_handler_field::render_as_link() which calls function l() or sg. like that which should be overridden. Of course, overriding theme_link() for modifying ALL the links is not a good way.

Here's an export of the simplest possible block view for Articles with pager id 3; the titles are linked:
http://pastebin.com/tmq0kZwT
I want to override the title links of this list to append a query string (to remember the actual pager when clicking on a node).

Here is the solution:

Put the following code to your theme's template.php file, and substitute MYTHEME with your own theme's name (or you can even put it in your module's file, and substitute MYTHEME with your module's machine name):

<?php

/**
 * Implements template_preprocess_views_view_field()
 * @see http://api.drupal.org/api/views/theme!theme.inc/function/template_preprocess_views_view_field/7
 * Process a single field within a view.
 * This preprocess function isn't normally run, as a function is used by default, for performance. However, by creating a template, this preprocess should get picked up.
 */
// /* -- Comment out this line if you want to use this function
function MYTHEME_preprocess_views_view_field(&$vars) {
  // $vars['output'] = $vars['field']->advanced_render($vars['row']);

  // @see http://drupal.org/node/939462#comment-4476264
  if (isset($vars['view']->name)) {
    $function = 'MYTHEME_preprocess_views_view_field__' . $vars['view']->name . '__' . $vars['view']->current_display;

    if (function_exists($function)) {
      $function($vars);
      // we can return to only use the specific preprocess function (it matters if there are more codes below in this function)...
      return;
    }
  }
}
// */

/**
 * Implements template_views_view_field__VIEW_MACHINE_NAME__DISPLAY_MACHINE_NAME()
 * @see template_views_view_field()
 * @see MYTHEME_views_view_field()
 */
// /* -- Comment out this line if you want to use this function
function MYTHEME_preprocess_views_view_field__block_of_articles__block(&$vars) {
  // $vars['output'] = $vars['field']->advanced_render($vars['row']);

  if (isset($vars['row']->nid, $vars['row']->node_title)) {
    $path    = drupal_get_path_alias('node/' . $vars['row']->nid);
    $options = array();
    if (isset($_GET['page'])) {
      $options['query'] = array(
        'page' => $_GET['page']
      );
    }

    $vars['output'] = l($vars['row']->node_title, $path, $options);
  }
}
// */

Don't forget to clear your cache!
This should only be done in cases when it's really needed: for example when an Article listing block (like this really simple one which you can import: http://pastebin.com/tmq0kZwT) is also displayed next to the article nodes, and we want the current pager position to be "remembered".


View filter to include title and body text I created an exposed view filter so that users can search for words in the body of a node type but I would like the search to also look for words in the title without having a separate search box for titles. Can this easily be done?

See code for exported view.

This module will help to do you job Views filters populate

  This is an utility module. Its sole purpose is to fill in one blank
  that seems not easy to be done using normal views, which is to use one
  exposed string filter to search on multiple fields.

  Bear in mind, that, for now, only populates STRING exposed filters, so
  those filters that take an array (options) or special types won't
  work, although it may not be difficult to extend it.

You need to make use of Global: Populate filters or Global: Combine fields filter its explained in steps  here


Can Views Bulk Operation be used to re-index specific nodes Can the Views Bulk Operations module be used to reindex nodes that fulfill some criteria (e.g. nodes of specific type)?

I didn't deal with that for a few time but since I found the answer my self I thought about posting that here in the hope that someone finds it useful. I dug into Views Bulk Operations and into the Search API devel, copied and modified some code.

For this to work we need to create a custom module and put in the module the following:

<?php
/**
 * Implements hook_action_info
 */
function MY_MODULE_api_action_info() {
  /**
   * Defines an array of actions to be performed on nodes
   */
  return array(
      'MY_MODULE_api_reindex' => array(
          'type' => 'node',
          'label' => t('Reindex node'),
          'behavior' => array('changes_property'),
          'configurable' => FALSE,
          'vbo_configurable' => FALSE,
          'triggers' => array('any'),
      ),
  );
}

function MY_MODULE_api_reindex(&$node, $context) {
  /**
   * function to implement the action defined above (see the key of the array
   * returned in vbo_search_api_action_info()
   */
  //copied the code from the search_api_devel module
  //load all indexes
  $indexes = search_api_index_load_multiple(FALSE);
  foreach ($indexes as $index) {
      if ($index->enabled) {
        search_api_index_specific_items($index, array($node->nid));
      }
    }
}

There might be a better way to go around this problem. For example the code now loads the index for each visited node, whereas Search API supports indexing an array of nids. So potentially we could gather all nids and then submit to Search API


Minimum entity properties for field_attach_update()? Question: What are the properties that are essential to be defined in the entity passed to field_attach_update() for the function to update the appropriate fields (and not silently do nothing)?

This is not detailed in the field_attach_update API page and, in articles I can find written about it, it seems that what I have defined above (ID, bundle, field data to update) should be enough.

Context: I'm using field_attach_update(); to keep some fields on seperate entities in sync with each other, using code like this:

        // Load entity, get entity type data data...
        $entity = array_pop(entity_load($entity_type, array($entity_id)));
        $entity_info = entity_get_info($entity_type);
        $id_key = $entity_info['entity keys']['id'];
        $bundle_key = $endpoint_info['entity keys']['bundle'];

        // Do stuff with the entity, modify field_some_field
        do_stuff($entity);

        // Build stripped down object containing only essential data
        $lightweight_entity = new stdClass();
        $lightweight_entity->$id_key = $entity->$id_key;
        $lightweight_entity->$bundle_key = $entity->$bundle_key;
        $lightweight_entity->field_some_field = array(
          'some_key' => 'some_data'
          'another_key' => 'more_data'
          );

        // Save it
        field_attach_update( $entity_type, $lightweight_entity );

This did work fine, but has recently (since updating to Drupal 7.14 I believe) been silently failing. No errors, nothing in logs - but no updates to the fields within Drupal and no changes to the field_data_field_some_field in the database. It seems like field_attach_update() isn't so much failing, as judging that it doesn't have any work to do. My theory is, that something is missing from the $lightweight_entity object, causing field_attach_update() to dismiss it as not a match or not a change.

(I'm piping in an entity object that is as simple as possible, partly because this sync function needs to run often and on many entity types, and partly because I have found that sending the whole original modified $entity object to field_attach_update() can result in PDO database fatal errors due to issues like this one, so simplicity is key. I'm using field_attach_update because it's syncing fields rather than updating the entity - new revisions data doesn't make sense in this specific context - from a user's perspective, the content hasn't been revised, and reverting the sync to become out of sync wouldn't make sense)

EDIT - Actually, it turns out that the core team have decided that passing in anything less than the whole entity to field_attach_update() is officially Wrong and not to be done. See http://drupal.org/node/1483736, if there is a file field (therefore, also media fields, image fields), and you update using field_attach_update() without including all the file field data, the file fields will be wiped.

So the correct answer in terms of the thinking of the core team is actually, all of them. As far as I know, it's only file fields that break like this, so you theoretically, in cases where passing in the whole entity object breaks, you could pass in entity id and bundle as below plus any previous file fields, but there's no guarentee nothing else would break.

Original answer -  Actually after more testing and debugging, that first article seemed to have it spot on. The entity needs:

The entity id (as above)
The bundle (as above)
The field data, keyed with language (even if not applicable) and delta

(basically, so there's enough data to identify the entity and field instance)

...so my example above should have had:

$lightweight_entity->field_some_field[LANGUAGE_NONE][] = array(
      'some_key' => 'some_data'
      'another_key' => 'more_data'
      );

And if the field name is dynamic, needs curly braces:

$lightweight_entity->{$field_name}[LANGUAGE_NONE][] = array(
      'some_key' => 'some_data'
      'another_key' => 'more_data'
      );

Another relevant thing to note is, on a multi-item field, it replaces all items with what is entered here, regardless of what you put for the delta. E.g. if you have 5 items already, and try to add a sixth like this:

$lightweight_entity->{$field_name}[LANGUAGE_NONE][6] = ...

...it'll wipe the other 5. So, for multi-item fields which can already have data, you need to populate the mini-entity with all the items for that field before saving, for example:

if (!empty( $entity->{$field_name}[LANGUAGE_NONE])) {
  $lightweight_entity->{$field_name}[LANGUAGE_NONE] = $entity->{$field_name}[LANGUAGE_NONE];
}
$lightweight_entity->{$field_name}[LANGUAGE_NONE][] = ...


Add views exposed filter programmatically I used the below code in hook_views_pre_view to add two exposed filter to a view, the first filter which provides available brand works perfectly but the second filter is not added at all, no error is logged though, any help on that?

  $available_brands = dpspec_get_available_brand_name($mid);

  $filter_options = array(
    'value' => $available_brands,
    'exposed' => TRUE,
    'reduce_duplicates' => TRUE,
    'type' => 'select',
    'required' => FALSE,
    'expose' => array(
      'operator_id' => 'field_brand_op',
      'label' => t('Brand'),
      'operator' => 'field_brand_op',
      'identifier' => 'sp_brand',
      'reduce' => TRUE,
      'vocabulary' => 'tags',
      'multiple' => TRUE,
    ),
  );
  $view->add_item($view->current_display, 'filter', 'field_data_field_brand', 'field_brand_tid', $filter_options);

  $available_colors = dpspec_get_available_color_names($mid);
  $options = array(
    'value' => $available_colors,
    'exposed' => TRUE,
    'reduce_duplicates' => TRUE,
    'type' => 'select',
    'required' => FALSE,
    'expose' => array(
      'operator_id' => 'field_color_op',
      'label' => t('color'),
      'operator' => 'field_color_op',
      'identifier' => 'sp_color',
      'reduce' => TRUE,
      'vocabulary' => 'tags',
      'multiple' => TRUE,
    ),
  );

  $view->add_item($view->current_display, 'filter', 'field_data_field_color', 'field_color_tid', $options);

OK the code is working fine, the only problem was that the color field was added to product, while views was set based on node, so when I added a relation to product, it started working.


Display user name with flags I've this code who show the number of users who 'flagged me' (I'm using flag module)

$flag = flag_get_flag('poke');

if ($flag) {
  print "The number of people who voted for this proposal:";
  print $flag->get_count($user->uid);
}

I want to show a list of the user name instead.

Thanks for your help !

I don't know the particular flag api to get the usernames of flagged node.
But it can be possible using custom implementation. Here is code

function get_usernames_flagged_node($entity_id, $flag_name) { //Supply node_id and flag_name
  $get_all_nodes_of_flagged = flag_get_flag_flagging_data($flag_name);
  $flagged_content_detail = array();
  $username = array();
  foreach($get_all_nodes_of_flagged as $get_all_nodes_of_flags) {
    $flagged_content_detail[] = $get_all_nodes_of_flags;
  }
  foreach($flagged_content_detail as $flag_content) {
    if($entity_id == $flag_content->entity_id) {
     $user=user_load($flag_content->uid);
     $username[]=$user->name;
    }
  }
  return $username;
}

It can be also possible using views and flag modules. For your reference see this page


What is the easiest way to install clean Drupal from scratch using drush? What is the easiest/quickest way to install clean Drupal from scratch on empty folder for testing purposes by using drush (without resorting to shell scripts or aliases).

drush qd

Downloads Drupal, runs site install, launches a lightweight webserver, opens a browser and logs you in as 'admin'.

I might have answered drush quick-drupal, but Clive said there might be a contest.  :)


Populate a multivalue image field when importing xml data with Feeds I created an importer to fetch data from an http xml file. To create the importer I'm using Feeds and Feeds XPath Parser

So far so good. Thing is that the xml file has several images to import in a single multivalue image field of my nodes.

Then I guess I have to concatenate these images into one value and then after populate my field. To do this I'm using Feeds Tamper. This one allowed me to REWRITE the multivalue image field using tokens where I set one token for each image.
It seems simple but it doesn't work. What am I missing here?

Is there any other way to do this?

Image capture of the xml: https://drive.google.com/file/d/0B71-gfIvQWAUU3ZpWVpVZzJjTFk/view

For Multi-Valued field you could use Explode Plugin in feeds Tamper
Also Use Trim Plugin to Remove white spaces if any in Image URL.
Reference: Feeds Example


Use of render array in theme layer Why does the theme layer uses render arrays when all the theming functionalities can be implemented with print statements in templates files?
Is there any analogy that explains the use of render array in the theme layer and how it interacts with the template files?

Drupals render arrays are a great invention which make it possible to alter the output of content by others (modules, themes etc.).

If you would hard-code your output in variables to print, no one other can alter it. But if you use render arrays, then other modules can implement hooks to alter the rendering of your output if they need to do so.

For this flexibility it is best practice to use render arrays until the very last moment and let the twig template build the html from it.