How do I run drush migrate for specific path site I want to use drush to run the migrate command to upgrade my drupal version 6 to 7 using Data Export Import module.

I have two site in different path.

How do I run drush migrate for the Testing website below. Drupal version is 6.

  Main website

  /domains/site.com/public_html

  Testing website

  /domains/site.com/public_html/testsite

To use Drush to more effectively migrate sites from one VPS to another, to manage more than one site and to synchronize easily between them. It assumes that you are running your own cloud server, have Drush on it, and have already installed a Drupal site.

Drush Aliases

Drush aliases are a simple set of configuration that allows you to reference Drupal sites from anywhere in your server's folder structure by using a shortcut of the following format @site. Before being able to use these shortcuts though, you'll need to configure the respective alias. To do this, and if you don't have one already, create a file called aliases.drushrc.php in the .drush folder that resides in your server's root folder:

nano /root/.drush/aliases.drushrc.php

Here, you have to create a php opening tag, <?php, for the file and below copy the following array declaration:

$aliases['site1'] = array(
 'root' => '/var/www/drupal_folder',
 'uri' => '88.88.88.88/drupal_folder',
);

Save the file, exit, and the alias is set. To test it out, navigate to a folder that is outside of your Drupal site and run the following command:

drush @site1 status

Now you should get the regular status information about the site you just referenced in the alias. And you can use this shortcut also with other commands.

Migrating sites

Now that you know how to reference sites, we can look at migrating (copying) a site from one folder to another using Drush. Let's say you want to move @site1 from /var/www/drupal_folder to /var/www/drupal_folder2.

First, you need to create a new alias for this future installation. For this, like always, edit the aliases.drushrc.php file:

nano /root/.drush/aliases.drushrc.php

Here, you need to create below two aliases, both with the same format. Just copy-paste the old one and make the appropriate changes:

$aliases['site2'] = array(
 'root' => '/var/www/drupal_folder2',
 'uri' => '88.88.88.88/drupal_folder2',
 );

Save the file and exit. If you run drush @site2 status, it will not work because obviously the folder not only does not contain a Drupal installation, but it doesn't even exist. So let's create it:

mkdir /var/www/drupal_folder2

In order to prepare for the new Drupal installation, you'll need to create a new database as well. So login to your MySQL through your preferred way and create a new database, making a note of the access username and password. If you are unsure how to do this, read the tutorial that shows how to deploy a Drupal site with Drush.

Now that your database is set up, you can proceed to migrate the site. To copy all the codebase from the first folder to the other, run the following command:

drush core-rsync @site1 @site2 --include-conf

Now, edit this newly copied settings.php file in the drupal_folder2 copy and change the database information to reflect the new database you just created.

nano /var/www/drupal_folder2/sites/default/settings.php

In this file, you need to make changes to the following block of code to reflect your own database information:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'your_db',
      'username' => 'your_username',
      'password' => 'your_password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Save the file and exit. Now you can also migrate the database using Drush because it knows that the site in the drupal_folder2 now uses this database, even if it's currently empty. All you need to do is run the following command:

drush sql-sync @site1 @site2 --create-db

This will drop the tables in the database associated with @site2 (the one that is currently empty) due to the --create-db option and insert the ones from the database associated with @site1 - your original Drupal installation. So now you have 2 exact replicas of the same site.

You may run into the following error message (with the applicable credentials):

ERROR 1044 (42000) at line 1: Access denied for user 'your_username'@'localhost' to database 'your_db'

If this is the case, make sure that your user has the required privileges.

Log into MySQL (mysql -u root -p).

Grant the following privileges:

grant all privileges on your_db.* to your_username@localhost with grant option;
grant reload  on *.* to druser2@localhost;
flush privileges;

Synchronizing Drupal Sites

Now that you have a duplicate of your original site (@site2), you can use it for development work. If you make codebase modifications to it, you can use the core-rsync command to sync the files with the original (@site1):

drush core-rsync @site2 @site1

Obviously, you would not want to copy the settings.php file again, which prevents making database changes again. Next, to sync the database as well, run the same sql-sync command:

drush sql-sync @site2 @site1 --create-db

In most cases, it's recommended that the receiving database is emptied before the copy (using the --create-db option) to avoid conflicting configuration saved in the database that will then cause problems.

Remote sites

nano /root/.drush/aliases.drushrc.php

And let's create a new alias for a site on a remote server. Copy the following code below and replace appropriately with your information:

$aliases['site3'] = array(
   'root' => '/var/www/drupal_folder3',
   'uri' => '99.99.99.99/drupal_folder3',
   'remote-host' => '99.99.99.99'
 );

So, what does this mean? The site with the alias @site3 is located in the folder drupal_folder3 on the remote server and has that URI pointing to it on the remote server. This is to be expected. Additionally, you have to specify the remote host (which is the IP address of the remote host). Given that you have set up SSH keys, you will not be required to enter a password unless of course you have a password protecting your private SSH key itself, which I recommend if you are creating keys between two remote hosts (none being your personal computer).

And that's it. Now when you run the commands we've be talking about, you can perform the same actions remotely, as well as migrating and keeping sites synchronized. But just to test out the alias, run:

drush @site3 status


A view with exposed sort: can i turn off 'grouping field' for different sort criteria? My Views list of events is grouped by the date (using the Grouping Field checkbox in the Style settings).

But my exposed Sort Criteria can sort the list by either date or by name.

An alphabetical list of events grouped by date really doesn't make any sense.

What would make sense is for the Grouping Field to turn off when the Sort Criteria is by name.

I'm thinking either i do two views, and my template decides which view to embed depending on the URL query. Or perhaps a views hook like hook_views_query_alter() could turn off the Grouping Field depending on the circumstances?

Ok, i think i've managed it with a Views hook. Took an hour's worth of tinkering. I plopped this into my template.php...

/** Find out what the sort criterion is.
    @return The sort criterion fieldname. IMPORTANT: this isn't sanitised!
*/
function MYTHEME_get_sort_by() {
    if (isset($_GET['sort_by']))
        return $_GET['sort_by'];
}

/** Turn off Views grouping-field when sorting by title.
*/
function MYTHEME_views_pre_build(&$view) {
    if ($view->name=='event_programme') {
        if (MYTHEME_get_sort_by()=='title')
            $view->display_handler->options['style_options']['grouping']='';
    }
}


Convert boolean field to custom style I have a Boolean field with Yes/No values with default style of Drupal .

I want to change that field to ON and OFF toggle style like below .

I understand that it can be done using the bootstrap theme and the bootstrap toggle module. But I don't need to change my theme. How can I do that ?

A quick look at the bootstrap toggle JavaScript code does not show any actual dependencies in it for the actual bootstrap theme.  You may be able to install the bootstrap_toggle module without the Bootstrap theme and it will work.

Won't hurt to try on a dev environment. :)


how to link a menu item to a block? i have a site with menu items and i want to make the item link to any block i want for example :

i have "About me" item in the menu and i want this item to link to a block that user can find it at the bottom of the page if he click on it will directly takes him down to the block.
any suggestion please to do that ?

i add an ID for the block by block_attributes module

You can use the Void Menu module to achieve this.

  Void menu allows you to configure special values to tags for use in the Drupal 7 menu system. You can customize up to 10 different void tags with any value you wish and use them freely inside the Drupal menu system.

For example, to link to a block with an id of #about, go to the Void Menu configuration page (admin/config/user-interface/void_menu), and set one of the "tags" to your block id (including the #).

Then set your menu link path to the tag name.

For smooth scrolling you can use the Scroll to destination anchors module.

  This module modifies the default behavior of destination anchor links...so that users will be smoothly scrolled to the destination instead of immediately being jumped.

You will need jQuery to use the Scroll to destination anchors module.


How to use ajax_command_invoke() with an argument that's a JavaScript object? I'd like to use ajax_command_invoke() to enable jQuery UI Droppable when returning from an AJAX request.

If I run the following command from the JavaScript console, jQuery UI Droppable is properly enabled:

jQuery('.elements-to-make-droppable').droppable({
  drop: function( event, ui ) {
    jQuery( this )
      .addClass( "ui-state-highlight" )
  }
});

However, when I try to return this command from my AJAX callback:

$commands = array();
$commands[] = ajax_command_invoke('.elements-to-make-droppable', 'droppable', array('{
  drop: function( event, ui ) {
    jQuery( this )
      .addClass( "ui-state-highlight" )
  }
}'));
return array('#type' => 'ajax', '#commands' => $commands);

...it doesn't work.

How should I be doing this?

I solved this by creating a little jQuery Plugin that calls droppable(), and using ajax_command_invoke() to call my plugin.

In the PHP code that builds the page, I added:

drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js');

In my_module.js, I added:

jQuery.fn.my_module_make_droppable = function() {
  jQuery(this).droppable({
    drop: function(event, ui) {
      jQuery(this).addClass( "ui-state-highlight" );
    }
  });
}

And my AJAX callback is now:

$commands = array();
$commands[] = ajax_command_invoke('.elements-to-make-droppable', 'my_module_make_droppable');
return array('#type' => 'ajax', '#commands' => $commands);


Practical concerns for changing text on the "add to cart" in Drupal Commerce to use it as a "wishlist" Apologize for the roundabout question, just not sure how to get at this more directly. I'm developing a commerce site where our clients will be submitting inquiry lists that we will respond to, rather than orders. In essence, what I need is the shopping cart, minus the payment gateway (which is where the site is headed). As a quick fix, I was thinking of just changing the text on the "add to cart" and "check out" buttons, as the basic functionality we need is there out of the box without a payment gateway. Is there a glaringly obvious reason not to do this? I am developing a parallel wishlist application with flags, but I haven't hacked the functionality I need into that yet.

So, upon conducting a lot of research, modifying the existing architecture in DC is possible, but appears to be non-trivial to apply. The checkout process has many hard coded titles and elements that, while instructive to research and attempt to modify lead me to believe that this implementation as a work-around is probably more effort than just throwing together a custom module for the functionality I'm looking for. If anyone reads this from the Drupal Commerce team: the internet is LOADED with requests on how to modify this stuff through the admin functions of DC, great work and much appreciated, but this noobs head hurts.

function bartik_form_alter(&$form, &$form_state, $form_id){
dpm($form_id);
dpm($form);
if (commerce_form_callback($form_id, $form_state) == "commerce_cart_add_to_cart_form"){
    $form['submit']['#attributes']['title'] = $form['submit']['#attributes']['value']=t("Add to Inquiry List");
    }
if(strpos($form_id, 'views_form_commerce_cart_form_default')===0){
    $form['actions']['submit']['#value'] = t("Update List");
    $form['actions']['checkout']['#value'] = t("Submit List");
}
if(strpos($form_id, 'commerce_checkout_form_checkout')===0){
    $form['buttons']['continue']['#value'] = t('Proceed to final list submission.');
    }
if(strpos($form_id, 'commerce_checkout_form_review')===0){
    $form['buttons']['continue']['#value'] = t('Submit your inquiry list');
    }

}


Negative value for graphicXOffset not being applied Please compare these two maps.

On this map ...
http://dev.lambeth.gotpantheon.com/map
Notice the location police helmet image, bottom-left near to Union Road.

On this map ...
http://test.lambeth.gotpantheon.com/map
The actual location of this police station is indicated by a blue circle.

The problem is that we need to have the graphic raised by 20px or so so that it points to the correct location.

When we add a negative graphicXOffset in the style settings, nothing happens. (A positive value does work, but that's not what we want).

See screenshots here: http://drupal.org/node/1808794

Actually, I've successfully used both negative x and y offsets.

However, since you're trying to raise the graphic (move it up, I'm assuming), you need to be using the y offset.  That's the one that controls the vertical placement.  ;0)


How to render a Drupal 7 field in stand alone PHP file? Hi this is probably a really basic question, but hopefully you guys can help me out...

I have a javascript client application (Separate to my main Drupal 7 website) and rather than maintaining a duplicate select list with a large number of values, I would like to use an AJAX call to a PHP file on the Drupal server which will render the HTML for the list I need.

The list is configured as a custom field (Text List type).

Can I create a PHP file in the root of the website, and include the required module files?

An example would be fantastic!

Thanks!

You could definitely bootstrap Drupal in a standalone file, but if you're doing it inside the same document root as the Drupal installation you'd be better off implementing a custom menu path in a module, and using the callback for that path to output the necessary value.

If you print directly from a page callback function and don't return anything, the standard theme wrappers won't be included and you'll just be left with the value you've printed.

A basic example might look like this:

function MYMODULE_menu() {
  $items['custom-path'] = array(
    'title' => 'Custom page', // Required, won't actually be displayed anywhere
    'access arguments' => array('access content'),
    // 'access callback' => TRUE, // This is an alternative to the access arguments if you don't need any access control for this path
    'page callback' => 'MYMODULE_ajax_page',
    'type' => MENU_CALLBACK
  );

  return $items;
}

function MYMODULE_ajax_page() {
  $output = function_to_produce_field_output();

  print $output;
}

After you clear Drupal's caches any request for http://mysite.com/custom-path should produce the un-themed results from your page callback; you can then use that path as your AJAX callback.

You might also want to look at drupal_add_http_header() to set an appropriate content type before you print the output.

As far as getting the field output goes, it's a bit of a pain but this should work:

$entity_type = 'user';
$bundle = 'user';
$field_name = 'field_field_name';

// Get field info for the allowed values
$field_info = field_info_field($field_name);

// Get instance info for label/required/description/default value
$field_instance = field_info_instance($entity_type, $field_name, $bundle);

// Build the select list
$select = array(
  '#type' => 'select',
  '#value' => $field_instance['default_value'],
  '#options' => $field_info['settings']['allowed_values'],
  '#required' => $field_instance['required']
);

// Build the element wrapper
$wrapper = array(
  '#title' => t($field_instance['label']),
  '#description' => t($field_instance['description']),
  '#children' => theme('select', array('element' => $select))
);

// Get the fully rendered element
$rendered = theme('form_element', array('element' => $wrapper));

print $rendered;


how to give the same style as the back-office theme for people allowed on edition? Allowing some roles to edit content, these people get the css from the front theme.

How to set to use the back-office theme for ?

 /admin/content

and

 /node/add/article

Set the permission View the administration theme and make sure that the option Use the administration theme when editing or creating content is enabled on page /admin/appearance.


How do I add a suffix to the price field? I'm using drupal commerce in my current project, I want to display the price like "$299 excluding tax/month", but the price field is not editable by default.
there is a way to add this suffix to the price?

Do you need to include the value in the field? If not, you could just put it in place with a template file. You can create a template file that formats that specific field, for example; see Drupal 7 Template (Theme Hook) Suggestions.

Otherwise, you can use the Simple Field Formatter module.

  The Simple Field Formatter module allows site administrators to easily control the display of field values with following features.

  Features:

  Prepend the field value with specified text/HTML
  Append the field value with specified text/HTML
  Reverse the Field Value
  Trim the Field Value
  Convert the field value to lowercase letters
  Convert the field value to uppercase letters
  Convert the first character of the field value to uppercase
  Convert the first character of each word in the field value to uppercase (7.x-1.x-dev)
  Replace some characters with some other characters in the field value (7.x-1.x-dev)
  Link the field value to node(7.x-2.x-dev)


Disabled date field on node form stops it from saving I have a date field on a drupal node edit form using the pop-up calendar widget. When certain things happen on my site I have to disable some fields on that node edit form, including the date.

However, when this happens, I can no longer save the form because I get this message:

  The value input for field [my field] is invalid.

I tried changing the widget to plain text, and it works fine, so it is an issue with the pop-up calendar widget.

Any ideas?

If using hook_form_alter you can use #limit_validation_errors to exclude that field from validation.

  The #limit_validation_errors property is a list of "sections" within
  $form_state['values'] that must contain valid values. Each "section"
  is an array with the ordered set of keys needed to reach that part of
  $form_state['values'] (i.e., the #parents property of the element).

Example 1: Allow the "Previous" button to function, regardless of whether any user input is valid.

  $form['actions']['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Previous'),
    '#limit_validation_errors' => array(),       // No validation.
    '#submit' => array('some_submit_function'),  // #submit required.
  );

Example 2: Require some, but not all, user input to be valid to process the submission of a "Previous" button.

  $form['actions']['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Previous'),
    '#limit_validation_errors' => array(
      array('step1'),       // Validate $form_state['values']['step1'].
      array('foo', 'bar'),  // Validate $form_state['values']['foo']['bar'].
    ),
    '#submit' => array('some_submit_function'), // #submit required.
  );

More info: form_set_error


Why Drupal changes the module (system table) bootstrap value after i set it with an SQL query? I need to run some hooks very early in the boostrap like enhanced_page_cache does.

I copied the same hook_update to set my module as available in Drupal bootstrap
and alter its weight.

/**
 * Ensure the weight of the module is pretty high.
 */
 function MYMODULE_update_7000() {
   // Make sure this module is available on bootstrap.
   db_update('system')
    ->fields(array('bootstrap' => 1, 'weight' => 98))
    ->condition('type', 'module')
    ->condition('name', 'MYMODULE')
    ->execute();
  }

After the update the values are there, but if the caches are cleared, the module's bootstrap value on system table reverts back to 0.

Why is this happening?

How does the Enhanced_page_cache module does it and keeps the value intact?

Do i forget something?

Thanks

ok got it,

in system.module there is a function called _system_update_bootstrap_status()

this function changes bootstrap value to '1' for all modules that implement one (or more) of the hooks: 'boot', 'exit', 'watchdog', 'language_init'

so i just needed to implement an empty hook_boot() and my module is present in bootstrap.


Adding checkbox to select records in a view I have a list of students and I have added a custom handler to add checkboxes against each student to mark as present. When I use filter, I loose the state of checkbox and I have to use filters because I have many students in the list and are on many pages. Same happen when I move to the next page. How can I retain the state of checked text boxes.

Thanks in advance.

This sounds like a task for VBO, this module provides a new view style with checkboxes for a wide array of actions you can perform on the row returned. This also comes with javascript which will allow you to remember selections between paginated pages etc which should also help with your issue.


Display summary + read more links if body content is long, otherwise display body alone We have a content type which has a customized template. In general, the body content of these nodes is short -- one to two sentences at most.

In some cases, however, the body content is a paragraph or more.

If the body content is shorter than 200 words, we would like to display the body field as-is.

If the body content is longer than 200 words, we would like to display the summary with a customized "read more" link.

Besides digging into the content array and counting words in the template, is there a graceful way to do this with view modes or field templates?

At the moment our clunky solution is to render both display types and swap between them with javascript, but this displays the "read more" link even when the body content is short enough to be displayed without the need for a summary.

node--custom.tpl.php

<?php
// Other fields above..

$summary = field_view_field('node', $node, 'body', [
    'label' => 'hidden',
    'type' => 'text_summary_or_trimmed',
]);

// Render summary of body, which is visible by default
print render($summary);

// Render full body as hidden with 'element-invisible' class (see field--body--timeline.tpl.php)
print render($content['body']);

?>

field--body--custom.php

<?php if($element['#view_mode'] !== 'full'): // Display trimmed version ?>
    <div class="<?= $classes; ?>">

        <?php foreach($items as $delta => $item):
            print render($item);
        endforeach; ?>
        Read More&hellip;

<?php else:
    // Display full body text with the element-invisible class and hidden by default ?>
    <div class="element-invisible <?= $classes; ?>">

        <?php foreach($items as $delta => $item):
            print render($item);
        endforeach; ?>
        &hellip;Read Less

<?php endif; ?>

Resulting HTML on render

Leverage agile frameworks to provide a robust synopsis for high level overviews. Iterative approaches to corporate strategy foster collaborative thinking to further the overall value proposition. Organically grow the holistic world view of disruptive innovation via workplace diversity and empowerment.

    Read More…

Leverage agile frameworks to provide a robust synopsis for high level overviews. Iterative approaches to corporate strategy foster collaborative thinking to further the overall value proposition. Organically grow the holistic world view of disruptive innovation via workplace diversity and empowerment.

Bring to the table win-win survival strategies to ensure proactive domination. At the end of the day, going forward, a new normal that has evolved from generation X is on the runway heading towards a streamlined cloud solution. User generated content in real-time will have multiple touchpoints for offshoring.

    …Read Less

Have you seen the Smart Trim module, that allows you to trim text fields to a given length, in words or characters, you can also add a read more link.

From the module description:

  After installing and enabling Smart Trim, you should see a "Smart trimmed" option in the format dropdown for your text fields. This is located in the "Manage Display" section of "Structure->Content types. With smart trim, you have control over:

  The trim length
  Whether the trim length is measured in characters or words
  Appending an optional suffix at the trim point
  Displaying an optional "More" link immediately after the trimmed text
  Stripping out HTML tags from the field


How to display the TID of a term reference field in a content type? In Drupal 8, I have a blog content type with a taxonomy term reference field called category.

How can I print out the Term ID of the taxonomy term of the category field in my node.html.twig file.

I can print the term name using {{ content.field_category }} but I also want to print out the term ID which should be a unique number. How should I go about doing this as I have search for days without any clue?

One "hacky" way to do this:

{# First step: capture the rendered output of the internal path link for a term #}
{% set tid %}{{ content.field_category.0['#url'] }}{% endset %}

{# Second step: do some string processing on the captured output, removing the /taxonomy/term/ prefix and getting the TID #}
{{ tid|trim|replace({ '/taxonomy/term/' : '' }) }}

Good luck!


Have to hook into a function from a module I am using the LinkedIn Integration module and have created a custom module to add some functionality.

Please see the linkedin.inc file at line 17 - function linkedin_access_token($account)

When a user links their LinkedIn account, I want to add to the db_write_record to also write to a custom field in my database for a timestamp.

Not sure what hook to use since it is a function.

Just making a quickly research (I don't have time at this moment to test the code) inside the Linkedin Integration module I can tell you that I found a hook named linkedin_external_login

See the code in the linkedin_auth/linkedin_auth.module file in the line 124

/*
 * Implementation of hook_linkedin_external_login
 */

function linkedin_auth_linkedin_external_login($uid) {
  $name = db_query("SELECT authname FROM {authmap} WHERE uid = :uid AND module = :module", array(':uid' => $uid, ':module' => 'linkedin'))->fetchField();
  user_external_login_register($name, 'linkedin');
  drupal_goto();
}

Just implement your own hook_linkedin_external_login()


Image Styles and Progressive Images I am specifically asking for a D7 site, however I wouldn't mind know for D8 as well.

Scenario

Save an image in Photoshop as a progressive image.
Upload this to an Drupal image field that utilizes image styles.

Question

When doing this image styles creates a new image, is the new image still progressive or is there something I would need to configure to make sure that image styles does this automatically?

Basically Drupal does not change that kind of attribute on an image.
But I thinkg you can check this way :
1- Make a very large image with Photoshop ;
2- Save it without making it progressive ;
3- Upoad it on the website and try displaying it.

NB : Very large image because for this test you want to make sure the image will display slowly.

4- save your image again with Photoshop, making it progressive this time. And then :
5- Upload the new one ;
6- Try to display it in a new tab and compare.
Certainly you will see if there is a difference.

That's what I would do....


Disable caching for the front page How can I disable caching for the front page, programmatically?

I think one way to achieve that is by altering '<front>' route with a RouteSubscriber service.

  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    arguments: ['@config.factory']
    tags:
      - { name: event_subscriber }

Then in your RouteSubscriber.php class :

/**
 * Event subscriber.
 */

namespace Drupal\mymodule\Routing;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Subscribe to KernelEvents::REQUEST events and redirect if user is press.
 */
class RouteSubscriber extends RouteSubscriberBase  {

    protected $configFactory;

    /**
     * RouteSubscriber constructor.
     * @param ConfigFactoryInterface $config_factory
     */
    public function __construct(ConfigFactoryInterface $config_factory) {
        $this->configFactory = $config_factory;
    }

    /**
     * {@inheritdoc}
     */
    public function alterRoutes(RouteCollection $collection) {
        if ($route_front = $collection->get('<front>')) {
            $route_front->setOption('no_cache', TRUE);
        }
    }
}


Overcoming 255 character URI limit for files_managed I recently stumbled upon an interesting limitation of Drupal. It seems that in the table files_managed there is a field called "uri" which represents the path to the files being managed by Drupal. This field is defined as a VARCHAR(255). I was blissfully ignorant of this fact/limitation until one of our users initiated a chain of events that lead to Drupal trying to manage a file with a 261 character path, at this point Drupal gave a nasty database error which lead me to this issue.

Is there anyway to configure Drupal to allow file paths longer then 255 characters?

You can alter the database defined from another module, but this is generally a bad idea. As said from Letharion, it is probable you are going to cause issues with other modules that take assumptions.

If you really need to do it, then you should implement code that (at least):

Alters the database table defined from the other module
Implements hook_schema_alter() to make other functions know the new schema used for the database table

The latter step is necessary because there are functions, such as drupal_write_record(), that use drupal_get_schema(), which invokes hook_schema(), and hook_schema_alter() to know the schema used for a table.

Your code should be at least the following one.

mymodule.install

function mymodule_install() {
  if (db_table_exists('file_managed') && db_field_exists('file_managed', 'uri')) {
    $schema = drupal_get_schema_unprocessed('system');
    $schema['file_managed']['uri']['type'] = 'varchar';
    $schema['file_managed']['uri']['length'] = 12288;
    db_drop_unique_key('file_managed', 'uri');
    db_change_field('file_managed', 'uri', 'uri', $schema['file_managed']['uri']);
    db_add_unique_key('file_managed', 'uri', array('uri'));
  }
}

function mymodule_schema_alter(&$schema) {
  if (isset($schema['file_managed']['uri'])) {
    $schema['file_managed']['uri']['type'] = 'varchar';
    $schema['file_managed']['uri']['length'] = 12288;
  }
}

What is missing in the code I shown is the code to unistall the module. It should change the database table as it was before the module was installed, but what happens if another module installed after yours alters the same field in that table?

Notice that, generally, managed files have a URI that is similar to public://field/image/100_0140.JPG. If the problem is the path being too long, then you should use less directories, or a shorter filename.


Drupal 7 and CSS - How to have a default style for links without affecting other css styles? I'm theming a Drupal 7 website using Bootstrap and a sub theme that I have put together. I have used CSS to design some of the menus. For this I have included code in the overrides file so as not to hack the original Bootstrap file.

Here's an excerpt from the CSS file to customize the look of a menu.

#block-menu-office li {
  display: inline;
  list-style-type: none;
  padding-right: 20px;
  font-size: 1.1em;
  font-style: bold;
  text-decoration: none;
  text-transform: uppercase;
  padding-right: 0.1em;
  padding-top: 0.1em;
}

This works well.

Now I want to customize how links on the website look like. For some reason they seem to be black with no underline. I want them blue with an underline.

When I add this code, the links do turn blue and show up with an underline. However the menu items also get underlined.

a:link {
    color: red;
}

How do I alter the default appearance of the links without affecting how the menu items look? I added a class to the CSS and used this class in the CKEditor when adding the link to the node. However this seems tedious. I would prefer to have a default appearance or alternatively a default class assigned to each link within the node when it is being created. Thanks!

First, I would expect that the styling of menu links by Bootstrap would be more specific than the (general) CSS rules you provide for styling links. But a workaround would be to reapply the styling on the menu links in your sub-theme (with more specific CSS rules).


Custom css only for one content type I want to include custom css only for one content type, is that possible?

use node-type-"node-type-machine-name" class from body, it appears in body, and then apply inherited CSS on child classes or on elements. e.g. if you are using a content type conference use

.note-type-conference{
//style
}

or

.note-type-conference .any-other-child-class{
    //style
    }

open your developer console of browser and check body element it contains many unique and specific classes.


module_load_include loads file but also prints path to the file I am using the api function module_load_include to include some markup in a custom module. The markup gets included and I indeed see it on my page but I am getting a side effect that the path to the include file also prints on the page along with my markup. Here is what I have that's working but with the unwanted path being printed out.

function mymodule_page_build(&$page) {

  if (!path_is_admin(current_path())) {
    $page['page_top']['mymodule'] = array(
      '#type' => 'markup',
      '#weight' => 25,
      '#markup' => check_plain(module_load_include('inc', 'mymodule', 'inc/markup')),
    );
  }

}

so the markup from my include file renders as HTML but I also see this on the page as well.

/sites/all/modules/custom/mymodule/inc/markup.inc

Just not sure what I am doing wrong, could not find any examples where this api function is used to include within the #markup context.

module_load_include returns the file path not the html. However the reason you are seeing the html is due to module_load_include also doing a require_once. An easy way to fix this would be something like the following

function mymodule_page_build(&$page) {
  module_load_include('inc', 'mymodule', 'inc/markup');

  if (!path_is_admin(current_path())) {
    $page['page_top']['mymodule'] = array(
      '#type' => 'markup',
      '#weight' => 25,
      '#markup' => get_my_html(),
    );
  }
}

So now your #markup is a function call. Just make sure your html is wrapped in the function name you want and then use your function name in the #markup key.

Also, you function that contains the markup will be something like this.

function get_my_html() {
  $output = '';

  $output .= '

Here is some of my HTML OR ALL of my HTML';

  return $output;
}

Hope this helps!


How set div in a specific position inside .tpl.php file I use views module in my website (built in drupal-7). I have a custom theme.
I have set a views-view-fields--XX.tpl.php like follows.

    <?php /**`
 * Default simple view template to all the fields as a row.
 *
 * - $view: The view in use.
 * - $fields: an array of $field objects. Each one contains:
 *   - $field->content: The output of the field.
 *   - $field->raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - $field->class: The safe class id to use.
 *   - $field->handler: The Views field handler object controlling this field. Do not use
 *     var_export to dump this object, as it can't handle the recursion.
 *   - $field->inline: Whether or not the field should be inline.
 *   - $field->inline_html: either div or span based on the above flag.
 *   - $field->wrapper_prefix: A complete wrapper containing the inline_html to use.
 *   - $field->wrapper_suffix: The closing tag for the wrapper.
 *   - $field->separator: an optional separator that may appear before a field.
 *   - $field->label: The wrap label text to use.
 *   - $field->label_html: The full HTML of the label to use including
 *     configured element type.
 * - $row: The raw result object from the query, with all data it fetched.
 *
 * @ingroup views_templates
 */
?>

<?php foreach ($fields as $id => $field): ?>

<?php if ($id == 'field_voti'):?>

<?php endif; ?>
    <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
    <?php endif; ?>
    <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
    <?php print $field->wrapper_suffix; ?>
    <?php if ($id == 'distance'): ?>

<?php endif; ?>
<?php endforeach; ?>`
"

in order to insert some fields into a new div with a specific class.

With firebug I see the following:

..

    ..
    ..

..

..

..

All that I want to do now is to have the div with class="uniscicampischeda" before the div with class="views-field views-field-field-foto", so that with css I will give the right attributes (I want class "uniscicampischeda" with float=right attribute)
HOw can I do that? do I have to write some code into views-view-fields--XX.tpl.php file? How?
Can anybody help me?
Thanks.

Well, there are three solutions for your problem,

Forget about the div with class uniscicampischeda and try to work with the existing classes in order to align them to right.
If you want to insert the div.uniscicampischeda, try to find out which one of the PHP lines generates the
..
, then edit the .tpl file and put the DIV before that PHP line.
As the last solution and also the most complicated one, in your template.php create function hook_preprocess_views_view_fields(&$var), in this function get the Views fields value and insert them in to the $var array, then in the .tpl file use those keys of the $var array as the variable that generates the corresponding value. Using this solution you will have much more freedom to theme your view output.

If you need help about any of these solutions just let me on it.


How to add Email field in Checkout page and sending E-mail in Drupal Commerce? I did cart using "commerce_kickstart-7.x-2.4-core" module. I would like to add "Email Id" field when doing a checkout. Actually I need that If user provides different email Id's rather than registered mail-id in "BILLING INFORMATION" and "SHIPPING INFORMATION" then after completion of Checkout process, the product payment details should send mail to those E-mail Id's.

Rules export

{ "rules_check_order_for_billing_information_mail" : {
    "LABEL" : "Check order for Billing information Mail",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "commerce_customer_profile",
            "param_type" : "billing",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "mail" : {
          "to" : [ "entity-created:field-billing-email" ],
          "subject" : "Test Subject for Billing mail",
          "message" : "Test Message for Billing mail",
          "language" : [ "" ]
        }
      }
    ]
  }
}

I believe you are using Customer Profile for asking customer billing and shipping address.

So navigate to
Store->Customer profiles->Profile types->Billing/Shipping Information->Manage fields.
Add one more fields in there for email & make that mandatory.
Add a checkout rules, put condition like "Entity has field" & check your added field.
Add a action "Send mail" and select your added field in TO field & organize your template using tokens of commerce-order.

I hope this will work, though there are other way working around code.


Change the url parameter 'search_api_views_fulltext' used in views exposed filter Im trying to modify the url parameter 'search_api_views_fulltext' so that it becomes nicer to read.

i would like something like "s" or "search"

Im using search_api + search_api_db + facet_api modules, with views.

Ive been looking every where but couldn't find any way to do this

Maybe someone among you guys could have an idea ?

There is a settings "Filter identifier" under More fieldset when you expose a field.


How to show the content type diffrent types in a block? I have a news website, I have one content-type what named news, news has some fields like:

  news_title

  news_date

  images

  body

  news_type

I want each news type shows in a block dynamically, my news_types are Sport, Economy, Political, Health and some others. and I want each of this shows in one block, is there any way is view or even in content-type settings to do this?

Use Views module to create multiple blocks for different news types. Once you creates blocks using views, assign them to regions from Admin -> Structure -> Blocks.


How does drupal 7 know its version? which file does it check? Hi Im just curious to know where is the metadata of the version info, where does drupal have defined its version in the files...

The VERSION constant is defined on line 11 of bootstrap.inc:

/**
 * The current system version.
 */
define('VERSION', '7.41');


custom views slideshow tpl from unformatted list of views drupal 7 I want to create a slideshow in the front page. the slide show must have banner image of particular content type of recent nodes. how should i achieve this? should i create a view and theme it?

Butterfly

you can use very options:

Create view with the slider content and theming tpls adding slick.js fe. as block or node to display only in frontpage
Add carousel module (there are many modules..carousel bootstrap, flexslider...) and create new view of this type with the slider content as block and display this block in frontpage .

Regards,
Iván.


How to prevent newline character in textarea I'm building a form in a module for Drupal 7 and I want to add a textarea as I would like it to be multiline so that text overflows on the next line, etc. but I don't want users to be able to create a new line if that makes sense. How can I achieve this?

Also, I would like to add a "Select All" button for the textarea and I have followed this article but it doesn't seem to have worked.

I know have the first part of my question solved, but still can't get the "Select All" button working. I have confirmed that the Javascript function does run by adding console.log, but it doesn't do the job. All that happens is the page reloads and no text is selected in the text area.

If using jQuery is an option for you, you can do something like this:

$('#yourTextAreaID').keyup( function() {
  $(this).val( $(this).val().replace( /\r?\n/gi, '' ) );
});

This code will replace the newline character on the fly, after the user types it. This code can be added in a custom.js file of your theme that you include in every page of your site, or you can alternatively use a hook_form_FORM_ID_alter in your custom module in conjunction with the drupal_add_js function to add the specific js file only in the specific form's edit page.

Keep in mind that if Javascript is disabled in the user's browser, he will be able to insert newline characters. In order to prevent this, you will have to add a custom validation function in your form. A very good tutorial on how to do this can be found here. The most important parts are:

1) Use a hook_form_FORM_ID_alter (in the tutorial he uses the old-school approach with hook_form_alter).

2) Add an extra validation function with something like:

array_unshift($form['#validate'], 'MYMODULE_form_validate');

3) Write your custom validation function (name it: MYMODULE_form_validate) that checks for \r?\n in the value of the textarea in the $form_state variable and return a descriptive error if there is a newline character.

Regarding the second part of your question, you should add some more information about what exactly didn't work. Did you clear the cache after following the steps? Do you get any errors in the log messages? Did you add console.log in your Javascript to verify that is being executed?


How to allow content editors to choose from Image Styles during content creation? Say I have an image field and several different Image Styles (image cache presets) set up. I would like to allow my content editors to be able to choose from the list of available presets during content creation.

Any Ideas on this is achieved? Off the top of my head it seems like a custom module might be in order...

Luckily enough there's already a module that does exactly this, Formatter Field. The example use case given on the module page is exactly the same as yours:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.


Drush Not detect Database connection I'm using Acquia DevDesktop application on Mac, I installed a new website on that , everything seems Ok but when I got to the installed path and try to update Drupal core with drush up faced with

➜  thunder-8.x-1.0-core drush up
Command pm-update needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal         [error]
environment to run this command.
The drush command 'up' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                  [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another
site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic
docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed
shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  8.2.5
 Site URI               :  http://default
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush script           :  /Users/yms/.composer/vendor/drush/drush/drush.php
 Drush version          :  8.1.10
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/yms/Sites/devdesktop/thunder-8.x-1.0-core
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

In the issues reported I found about this problem, adding Mysql path to PATH resolve the problem, but in my case when I type mysql on command prompt it works correct and that means The mysql path is added to PATH. but I don't know why Drush couldn't find the database connection.

Also in my connection to db Acquia used 127.0.0.1 So changing localhost to 127.0.0.1 is not the solution

After wasting a few hours I resolve it with adding driver property to $databases in settings.php .

$databases['default']['default'] = array (
  'database' => 'XXX',
  'username' => 'XXXX',
  'password' => 'XXX',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '33067',
  'driver' => 'mysql',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
);

I hope this could save another guys time in future in the same problem.


How to change the path of views content? have developed a website for my team and used VIEWS for all the link in the website.

While trying to click the links from client system it shows some error that says remote connection doesn't accept it.. like localhost some problem.. i don know how to resolve it..

I use to paste the IP address of the server and open in client system, so while doing like that in client system it will show this "http://localhost:8082/" . So i think the client system takes the local host so can anybody have an idea to resolve it.

The remote device or resource won't accept the connection.
after troublshooting the result is this.

may be you have used absolute url(starting from http://localhost:8082/content/..) instead of relative url(starting directly from content/..)


Content type itself as entity I need to classify and mark my content types.
As example I have three content types for group messages in OG, ten content types which used as UC products, etc.
So I need to add taxonomy and fields to my content types (NOT for nodes of content types, but to content types!) and then filter them. As example I could show only OG message types, or only product types, or only products which are clothes etc.
So I thing I need a module which turn content type to something like entity.

Is there any module which implements such feature?

It is hard to search such module, because if I search like "add fields to content types" I see results how to add fields to nodes of content types, which will be populated in node forms. But I need to add fields to content type form, to classify and mark content types, not nodes of content types.

I don't know if it goes far enough for you, but the Content type groups module helps you categorise content types.

  Content type groups was designed to handle the use case when you need to populate select boxes or other interface elements with certain content types but not others. This module allows you to create an unlimited number of groups of content types through the UI. Once a group is created, it can be referenced in code using API functions and in Views.

  Example

  Let's say you're organizing your media collection. You have the following content types: book, movie, audio, article (for your blog about your collection), and page (for some static content).

  Create a content type group called Media and add the book, movie and audio types. You have just created a logical grouping between the content types to show that they are related. This makes it easier for future developers to understand the relationship between various content types.

  Now let's say you start collecting old magazines. You create a new content type called magazine and add it to the Media content type group. Any place where Media is referenced will automatically reflect the change; there is no need to track down all Views or lists.

  This module is being rewritten to turn content type groups into entities, with a dependency on Entity API. The 2.x branch is heavily under development and not ready for any site use.


Error when trying to extend a db_select query I'm trying to add a field to my query by using addField(). However, whenever I add this to the query I get a whitescreen and an apache error message on the line after. Any help in resolving this would be much appreciated.

Apache error log:

PHP Fatal error: Call to a member function extend() on a non-object

db_select query:

$query = db_select('z_revision', 't')
    ->fields('t', array('drupal_user_id'))
    ->addField('t', 'z', 'category')
    ->extend('PagerDefault') # error on this line
    ->extend('TableSort')->orderByHeader($header)
    ->limit(30)
    ->execute();

Ideally this would give me a two column table with headers 'drupal_user_id' and 'category' - all the rows in the category column having 'z' as a value.

addField returns the alias of the field that's added, not the query object. You just need to break your code up a bit:

$query = db_select('z_revision', 't')
  ->fields('t', array('drupal_user_id'));

$query->addField('t', 'z', 'category');

$result = $query->extend('PagerDefault')
  ->extend('TableSort')
  ->orderByHeader($header)
  ->limit(30)
  ->execute();


Can not unset rows of a view programmatically I created a view of terms using views_tree module. I need to remove some of the terms under some conditions. This is my code

function THEME_views_pre_render(&$views) {
    for($i = 0 ; $i < sizeof($views->result) ; $i++)
       unset($views->result[$i]);
}

But it still prints all of the terms and doesn't delete any of them. I tried this code

function THEME_views_pre_render(&$views) {
    for($i = 0 ; $i < sizeof($views->result) ; $i++){
        $views->result[$i]->taxonomy_term_data_name ="Hello";
    }
}

It successfully renamed every term, But when I tried the following code, every name turned back to what it was from the beginning and nothing removed.

function THEME_views_pre_render(&$views) {
    for($i = 0 ; $i < sizeof($views->result) ; $i++){
        $views->result[$i]->taxonomy_term_data_name ="Hello";
        unset($views->result[$i]);
    }
}

How can I remove some terms ?

It should work on template.php too. Module implementation does not look mandatory here.
I have noticed a few issues in the code sample that you have pasted.

There is a typo. It should be $view not $views.
Instead of

for($i = 0 ; $i < sizeof($view->result) ; $i++){
}

Do

$sizeof_result = sizeof($view->result);
for($i = 0 ; $i < $sizeof_result ; $i++)

The following code works for me:

function MYTHEME_views_pre_render(&$view){
  if($view->name == 'MY_VIEW'){
    $sizeof_result = sizeof($view->result);
    for($i = 0 ; $i < $sizeof_result ; $i++){
      //IF Condition
        unset($view->result[$i]);
    }
  }
}

The reason for using variable $sizeof_result instead of sizeof($view->result) in for loop is:

For each execution of the loop, the value of sizeof($view->result) changes(decreases by 1). Due to this, the for loops does not work as expected.


How to unpublish content that is under moderation I am using the Content Moderation module in Drupal 8.2 and I have noticed there is no way to re-unpublish a node once it has been moderated into a published state. I'm able to create a new draft of the content and moderate that through to published state but I can't find a way to actually unpublish the node.

There is a bug issue on DO that seems related, but looking at the patch it only adds a message informing you that you can't unpublish content directly once under moderation. Which makes sense as having content moderation enabled means you are handing over control of publish/unpublish to that module. But that leaves the question of how to actually unpublish a node that is under moderation?

I understand this module is currently experimental but am fairly sure I am missing something here.

You can enable the default revision for all the states. If there is any transition in any state from publish to draft or any state.


How can I display a form button on top of the form? In my custom module, I have added a button to the node edit form, using the following code.

  $form['actions']['my_submit'] = array(
    '#type' => 'submit',
    '#value' => t('My custom action'),
    '#weight' => -1000,
    '#submit' => array('node_form_submit', 'my_custom_node_form_submit')
  );

It is currently displayed either to the left or to the right of the standard "Save" button, depending on the weight value. Is there a way to display it on top of the form, before the first field?

If you use $form['actions']['my_submit'] like this, then you will get the button inside $form['actions']. $form['actions'] weight would be considered with the weight of other fields. Try the following code.

 $form['my_submit'] = array(
  '#type' => 'submit',
  '#value' => t('My custom action'),
  '#weight' => -1000,
  '#submit' => array('node_form_submit', 'my_custom_node_form_submit')
 );


How to hide my hook_menu items from the navigation menu? I've got a custom module which I use to define some urls that are used for a json api. I don't want them to show up in the Navigation menu. How do I change my hook_menu configuration so these urls are excluded from the menu?

Here is an example of two of my menu items that I want to hide, and a third one I would like to be visible:

$items['mymodule/1/login'] = array(
    'page callback' => 'mymodule_login',
    'access callback' => TRUE,
);
$items['mymodule/1/signup'] = array(
    'page callback' => 'mymodule_signup',
    'access callback' => TRUE,
);
$items['mymodule_bulkupload'] = array(
    'title' => 'Bulk Upload',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymoduleapi_form_bulkupload'),
    'access callback' => 'mymoduleapi_user_is_mymodule_owner',
);

I end up getting a bunch of empty items in my Nav menu. I would like to be able to hide those api menu items.

How do I control that from within hook_menu?

I think what you need is MENU_CALLBACK in 'type.

It's for hidden items like API calls that don't want to go in menus

https://api.drupal.org/api/drupal/includes%21menu.inc/constant/MENU_CALLBACK/7


Drupal alias to the last node of one type Imagine I have a node type of congress, i want to create a menu called congress.html how always go to the last node of this type.

How can i do it.

What you want is neither an alias, nor a menu. You want a view of nodes, filtered by type and sorted by date, that displays 1 item.


Check if a node field has changed upon save I am parsing pdf's in a field for a custom content type in a cron job. I have a boolean on each node that determines whether their pdf has already been parsed. I grab the ones I need like so:

$query = \Drupal::entityQuery('node')
    ->condition('status',1)
    ->condition('type', 'issue')
    ->exists('field_pdf')
    ->condition('field_indexed',false)
    ->sort('created','ASC');
if($range > 0){
    $query->range(0,$range);
}

$issue_nids = $query->execute();
$issue_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($issue_nids);

foreach ($issue_nodes as $issue_node){
    //do my pdf parsing magic on field_pdf
    $node->field_indexed->value = true;
    $node->save();
}

This works fine but if the user replaces field_pdf and uploads a new one I want to make field_indexed false again so I know to reindex it. The problem is I don't really have a way of knowing whether the field changed.

I considered using a presave hook but I didn't see a way to compare the form state to what was currently on the node.

Is there a way I can detect when a field has changed when a node has saved?

Clive is correct.
$node->original does give access to the original node values. I was able to accomplish what I needed like so

function my_module_node_presave($node) {
    $type = $node->getType();
    if($type == 'issue'){
            if(isset($node->field_pdf->entity) && !isset($node->original->field_pdf->entity) || empty($node->original->field_pdf->entity) || $node->field_pdf->entity->id() != $node->original->field_pdf->entity->id()){
                $node->field_indexed->value = false;
            } else {
                $node->field_indexed->value = true;
            }
    }


Clean URLs enabled but main-menu keeps replacing clean URL with ugly node/ URL I have enabled clean URL's on my website and had a menu item in my main-menu that pointed to a View that had a URL alias set up for /ebook-register. I just removed that alias and assigned the same alias up to a page (content item). However now the menu item keeps getting set to node/2 instead of ebook-register. How can I get the menu to stop changing my clean URL into ugliness? If I manually navigate to localhost/ebook-register I get to the right page, and under URL aliases in the admin I can see the alias and confirmed it's pointing to the correct page, and the menu doesn't throw an error when I set ebook-register to the path so it's finding the alias.

It does give me the following message:

  The menu system stores system paths only, but will use the URL alias for display. ebook-register has been stored as node/2.

However, despite saying it will display the clean URL, clicking the link sends you to the ugly node/2 URL.

I am using Drupal 7 and have tried clearing the cache already.

You need to also install the Global Redirect module to handle redirection to aliases.


Is there a way to print out a list of all possible template files for a page? Including template files used for views, rows, blocks, etc. on that page?

I suggest review Theme Developer module http://drupal.org/project/devel_themer, it will help to find possible templates that can help to modify (theming) specific parts of your site.

in this resource http://drupal.org/node/209561 you will find how to use the module.


t() and {% trans %} show no effect although rest of site is translated I'm a bit hesitant to ask this, but I have a drupal 8 site with 2 languages enabled - English as default and German. I have URL prefixes 'en' and 'de' to detect the chosen language. When setting German as default, the menus are translated, fields etc. It all works reasonably well. However, none of strings I use in my custom modules are translated. A very simple example

class testController extends ControllerBase {

...
drupal_set_message(t("Sorry, that does not work"));
....
}

The string is not translated when using german as the site's default language. Furthermore in my twig templates {% trans %} Hello {% endtrans %} have absolutely no effect.

Is there something I am missing here or I have to specifically set up ? I have used google for hours but do not find any solution to this weird problem. I've also tried all kinds of language detection methods in the Drupal settings - no effect. I have modules: Configuration Translation, Content Translation, Interface Translation and Language enabled.

If the strings in your custom module are in English but the site's default language is in German, you will need to translate the strings in the admin UI:

/admin/config/regional/translate

If you search for the string on this page but don't see it, you will need to first visit the page/path on the site that causes the string to be displayed so that the string will be created for translation purposes.  Then you can return to the translation page and translate the string.

To translate strings in a twig template, do it like this:

{{ 'This is a string to translate.'|trans }}


how to migrate a multi-value term reference field? I am setting up a drupal migration where the destination node contains a multi-value taxonomy term_reference field, called 'field_features'. The machine name of the drupal taxonomy vocabulary of the field is called 'voc_features'.

My field mapping for this field is configured like this:

$this->addFieldMapping('field_features:create_term')->defaultValue(true);
$this->addFieldMapping('field_features:ignore_case')->defaultValue(true);

//i don't have tid's in the source, so i leave the source_type for what it is
$this->addUnmigratedDestinations(array('field_features:source_type'));

//i link the drupal vocabulary to the multivalue field.
$this->addFieldMapping('voc_features', 'field_features')->separator('|');

The terms are added in the 'voc_features' vocabulary, but not in the 'field_features' field.

When i add the field mapping like i do with all the other fields:

//my source fields have the same name as my destination fields
$this->addFieldMapping('field_features', 'field_features')->separator('|');

i get the following error:

strtolower() expects parameter 1 to be string, array given File ...\sites\all\modules\migrate\plugins\destinations\fields.inc, line 402

Other single value term_reference fields import just fine.
What am i missing?

Yes. The migration of term doesn't allow to migrate multi-value. You have to process the source ahead.

Create a new migration and import the data to terms of vocabulary named 'voc_features' at first.
Add a dependence to your current migration using previous migration. Such as $this->dependencies = array('MigrateXXXMigration');.
The field mapping should be like this,$this->addFieldMapping('field_features', 'Features')->arguments(array('source_type' => 'tid'));
In the function prepareRow($row), you should prepare the Features field and put it into your $row variable. $row->Features=array(tid1,tid2,tid3);. The 'tid1','tid2' and 'tid3' should be replace the live tid from your term tables.


Best approach for [back][next] form submitting I've been doing a [back][next] to [finish] set of forms for user input fields, think of it like a questionnaire for user info where the user can still go back to the previous pages to update their info.. until it reaches the end of the pages to [finish]

I've done this before (hardcoded) but my code is too long and all the debugging gave me a headache. My first approach was:

Use a PHP case to find out which phase/step the user is in now
If the user clicks on [next], the page variable appends a +1 to the page count
If the user clicks on [back], the page var deducts -1 to the page count, until it reaches
[finish]
If the user leaves the page for some reason and comes back to it, the session/cookie saved fills in the form values and which phase/step the user is in

This method of mine isn't very dynamic as the php case is hardcoded to a set of page numbers & phases, if the client wants to add another page; that can be a problem.

I'm new to Drupal; maybe Drupal already has some part of the API that makes this [back][update][next][finish] easier, or a easier way to store cookies? If by PHP only, is there a better approach?

You should always use the Form API for forms, unless you really wanted to use the Webform module. The learning curve it steeper but you gain more maintainability (everything is in code from the start) and flexibility. You can create multisteps form with the API. See form_example_wizard.inc and Drupal 7 multistep forms using variable functions (also with Drupal 6) for examples. Another solution, is to use the CTools' wizard API.


Can we display region label from Layouts? We have a MYTHEME.layouts.yml file which defines regions...

layout
  label: 'Layout Name'
  path: templates/panels
  template: layout-template
  default_region: theregion
  regions:
    theregion:
      label: 'This is The Region'

In the template we display fields added to the region with

{{ content.theregion }}

Can we display the label that we defined?

The labels are for administration purposes and should not be used in templates as they are hard coded and can't be changed in the UI. A better option would likely be to use a Text field where you want to display the label as that can easily be changed.

That said, you can output the region name in the twig template like this:

{{ layout.regions.theregion.label }}


How do I index all the content with the search_api module? I am using the Search API module with Search API Solr. When I visit my index page at http://example.com/admin/config/search/search-api/index/my-example-index, I see the "Index Now" button is disabled and inactive. I see "Content (7796/7796 indexed)" for the data source.  However, recent content items are not showing up in my search results.

At admin/config/search/pages, I see "6% of the site has been indexed. There are 7693 items left to index."  Ok, how do I index the rest?

I know that not all content is indexed, because recent content is not showing up in search results. I don't want to index just 50 or 100 content items at this time. I want to index everything, so all content can show up in search results.

You must click the "Queue all items for reindexing" link that appears below the "Start Indexing Now" fieldset, and then once you run that process, you can return to the index UI (example.com/admin/config/search/search-api/index/my-example-index) and at that point the "Index Now" button is active.


How to prevent email address from displaying on edit profile page? I have set up my site so that some users with a specific role can't edit their email address. This works fine - users with role type A can navigate to the edit tab on their profile and edit their email address, and users with role type B are unable to edit their email address. However, these users can still view their email address field on the edit tab, it just appears disabled. I do not want this to be the case.

I used the User Protect and Field Permissions modules to achieve this. For all of the other fields that I prevented users with role type B from editing (e.g. their name), the fields did not appear at all on the edit tab. I have used the same settings in field permissions for these fields and the email field but for some reason the email field appears under the edit tab but the others don't. How can I prevent the email field from displaying when users don't have permission to edit it?

You can to this using hook_form_FORM_ID_alter(), like this:

function MY_MODULE_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (in_array('role_B', \Drupal::currentUser()->getRoles())) {
    // We restrict access if the field is disabled.
    $form['account']['mail']['#access'] = FALSE;
  }
}


How to insert an image into a drupal form Is it possible in drupal7 to insert a photo in drupal form? I have a start interface that contains two buttons leading to two athors interfaces and I would like to insert a photo above the two buttons. I have tryed the next but it didnt work

function my_module_start_form($form, &$form_state) {
  $image_options = array(
    'path' => 'path/to/img.jpg',
    'alt' => 'Test alt',
    'title' => 'Test title',
    'width' => '50%',
    'height' => '50%',
    'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
  );

  $image = theme('image', $image_options);

  $form['start']['image'] = array(
    '#markup' => $image,
  );

  $form['start']['next'] = array(
    '#type' => 'submit',
    '#value' => t('Create charts')
  );

  $form['start']['examples'] = array(
    '#type' => 'submit',
    '#value' => t('See charts examples')
  );

  return $form;
}

May be this will help..

 function my_module_start_form($form, &$form_state) {
 $image_options = array(
'path' => 'path/to/img.jpg',
'alt' => 'Test alt',
'title' => 'Test title',
'width' => '50%',
'height' => '50%',
'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
);

 /*$image = theme('image', $image_options);
  $form['start']['image'] = array(
    '#markup' => $image,
  );*/
    print theme_image($image_options);//print the image

    $form['start']['next'] = array(
    '#type' => 'submit',
    '#value' => t('Create charts')
  );
  $form['start']['examples'] = array(
    '#type' => 'submit',
    '#value' => t('See charts examples')
  );
    return $form;
}


hook_node_view can't change content I've read through many questions asking this same thing, but I feel like I'm doing what they are suggesting and it's still not working.

I've created a custom module and enabled it. This is my code:

function mymodule_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'teaser' && $node->type == 'article' && count($node->field_video) > 0) {
    kpr($node);

    $markup = sprintf("<video style='width: 502px; height: 282px;' poster='%s'>\n",
        image_style_url('video_thumbnail', $node->field_video[$node->language][0]['thumbnailfile']->uri)
      );

    foreach($node->field_video[$node->language][0]['playablefiles'] as $video_object) {
      $markup .= sprintf("<source src='%s' type='%s' />\n",
          file_create_url($video_object->uri),
          $video_object->filemime
        );
    }

    $markup .= "</video>";

    $node->content['field_video_embed_code'] = array(
      '#markup' => $markup,
      '#weight' => 10,
      '#type'   => 'markup',
    );

    kpr($node);
  }

}

When I look at the krumo output, I see my changes to the $node object, however, when it renders the new field I'm adding is not included.

What am I doing wrong?

EDIT: I just realized I'm using Display Suite (it's been awhile since I set this site up) which is overriding which fields are shown and in what order. My guess is that DS is getting my modified content, but not showing the additional field because it isn't listed in my teaser fields? I'm not sure.

You must declare the field for the DS be able to handle it. In your case:

/**
 * Implements hook_field_extra_fields().
 */
function mymodule_field_extra_fields() {

  $extra['node']['article']['display']['field_video_embed_code'] = array(
    'label' => t('Custom field embed video.'),
    'description' => t('Adds a custom field.'),
    'weight' => 0,
  );
  return $extra;
}


Drupal hook_theme() Template Issue I am creating a block and I cannot get it to render correctly. I need to render a list of links but it is not working and it is showing nothing on the page.

I have the hook_theme() function like this:

function list_city_theme() {
  return array(
    'list_city_display' => array(
      'variables' => array(
        'title' => NULL,
        'locations' => NULL
      ),
      'template' => 'filter-by-city--display.tpl.php',
    ),
  );
}

And heres where i'm trying to set the theme inside the block view function:

$args = array(
  'title' => 'Filter by Town / City',
  'locations' => $locations
);
$block['content'] = theme('list_city_display', $args);

It is working for me. I have created a module called testtheme and mytemplate.tpl.php file is under testtheme/templates/.

Please try following sample code

/**
 * Implements hook_block_info().
 */
function testtheme_block_info() {
  $blocks['testtheme'] = array(
    'info' => t('Test Theme'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function testtheme_block_view($delta=0) {
  $black = array();
  if ($delta == 'testtheme') {
    $block['subject'] = t('Test Theme');
    $args = array(
      'title' => 'Filter by Town / City',
      'locations' => 'Bangalore',
    );
    $block['content'] = theme('list_city_display', $args);
  }
  return $block;
}

/**
 * Implements hook_theme().
 */
function testtheme_theme() {
  $path = drupal_get_path('module', 'testtheme');
  return array(
    'list_city_display' => array(
      'variables' => array(
        'title' => NULL,
        'locations' => NULL
      ),
      'template' => 'mytemplate',
      'path' => $path . '/templates',
      'type' =>'theme',
    ),
  );
}


A container for items for each taxonomy I have a content-type called "Member", which has four taxonomy terms.

Now in my block, i want to display entries in a different DIV for each taxonomy.

For example all items with the taxonomy "Boss" should be placed inside the first DIV, items with the taxonomy "Manager" should be placed in the second DIV, and so on..

How can i achieve this?

Hope this will help you.

Create a new view content type

add field Content: All taxonomy terms (checked Exclude from display )
add field Content: Title

add filter Content: Type (= Member)

go to format select HTML list on settings Grouping field Nr.1  select Content: All taxonomy terms unchecked "Use rendered output to group rows"

from add create a block you will get a new block in your block page.


How can I show just one content with 5 images I create search page with views in Drupal 8.

In filter criteria, I choose "Content: images:target_id" because I want show contents that have images. (I set operator to not empty.) If a node has 5 images, the search page show that node for 5 times.

How can I fix this problem?

This can be solved by using aggregation

Change the No to Yes.


Apply condition between two fields in drupal 7 by using JQuery This is updated JQuery code I have created condition between two fields in drupal 7 i.e. If we select item from first field then as per there selected item, some items of second field is going to hidden. But problem is that : If first I select item from second select field & after that I have select same item in first field then in this condition my created condition is wrong. Please Help to solve this. Thanks

Please check this DEMO

Below is my my updated JQuery code

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function(){
abc();
$("#edit-main-field-i-am-field-und").change(function() {
    var value = $(this).val();
    var optionText = $(this).find('option[value='+value+']').val();

    $('#edit-main-field-look-for-field-und').find('option').show();

       if(optionText=="sbf" || optionText=="smf" )
       {

           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).val()=="sbf" || $(this).val()=="smf")

                 return true;
              else
                 return false;
           }).hide();
       }
      else
       {

           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).val()=="sdm" || $(this).val()=="sbm")
                 return true;
              else
                 return false;
           }).hide();
       }

    });
});

function abc()
{

   var value = $('#edit-main-field-i-am-field-und').val();

if(value=="sbf" || value=="smf" )
       {

           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).val()=="sbf" || $(this).val()=="smf")
                 return true;
              else
                 return false;
           }).hide();
       }
      else
       {

           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).val()=="sdm" || $(this).val()=="sbm")
                 return true;
              else
                 return false;
           }).hide();
       }

}
</script>

I have tried your code and got a quick solution i.e. reset second select box every time first is changed.

look how I have implemented the same:

$(function(){
$("#edit-main-field-i-am-field-und").change(function() {

    $('#edit-main-field-look-for-field-und').val("_none"); // added to reset second select box on chanage of first one

       var value = $(this).val();
       var optionText = $(this).find('option[value='+value+']').text();
    $('#edit-main-field-look-for-field-und').find('option').show();
       if(optionText=="A" || optionText=="C" )
       {
         //alert("12345");
           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).text()=="A" || $(this).text()=="C")
                 return true;
              else
                 return false;
           }).hide();
       }
      else
       {
           //alert("98765");
           $('#edit-main-field-look-for-field-und').find('option').filter(function(){
               if($(this).text()=="B" || $(this).text()=="D")
                 return true;
              else
                 return false;
           }).hide();
       }
    $('#edit-main-field-look-for-field-und option:visible:eq(1)').prop('selected',true);
   // alert($('#edit-main-field-look-for-field-und').val());
    });
});

I have just added $('#edit-main-field-look-for-field-und').val("_none"); in .change function.


Google keeps indexing /comment/reply URL With the new update of Google algorithm called Penguin, I think my site was being penalized due to webspam. But of course I don't create post which seems to be spam to Google. It is just I think how Google index my site.

I found out that Google index the URL of my site like:

http://www.example.com/comment/reply/3866/26556

So there are so many comment/reply URL index by Google. I have already added:

Disallow: /comment/reply/
Disallow: /?q=comment/reply/

but still Google still index this URL.

Any idea how to prevent Google from indexing comments?

Here's my .htaccess:

<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

Options -Indexes
Options +FollowSymLinks
ErrorDocument 404 /index.php
DirectoryIndex index.php index.html index.htm

<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

<IfModule mod_expires.c>
  ExpiresActive On

  ExpiresDefault A1209600

  <FilesMatch \.php$>
    ExpiresActive Off
  </FilesMatch>
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule "(^|/)\." - [F]
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  <IfModule mod_headers.c>
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      Header set Content-Encoding gzip
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

I would try adding

RewriteCond %{HTTP_USER_AGENT} ^Googlebot
RewriteRule ^comment/reply/$ - [G,L]
RewriteRule ^comment/reply/(.*) - [G,L]

to .htaccess or Apache config to inform spiders that the links should be removed.  Just make sure to put it before the catch-all rule at the bottom of the standard Drupal .htaccess.  The problem is coming up with a list of spiders to add as [OR] conditions to the RewriteCond so that they get a 410 but Drupal handles normal requests.

Google Webmaster Tools has a URL removal tool, too, but I have never tried using it with patterns before.


Drupal custom Fullcalendar breaks jQuery version > 1.8 I have a project where I have created a pretty extensive (custom) fullcalendar implementation.

I am using fullcalendar 2.6 (the latest version at this point).

All is working like a charm untill i change the jQuery version (via jquery_update) to anything that is higher than 1.8...
Then the fullcalendar just dissapears completely (the div is empty)

No errors in the webdeveloper console (chrome), nothing!

I have tried to narrow down the fullcalendar js implementation to the bare minimum (just a title, prev & next buttons) but even that does not work.

Since i want to implement bootstrap into the project, I need to increase the jQuery version...

I have been googling around for this but can't seem to find a clear answer for this.

Anyone?

All suggestions are highly appreciated.

I have located the problem, sharing to whom it might concern.

Apparently there was a conflict between the contrib admin_menu rc4 version and jQuery, causing the fullcalendar to fail.

After upgrading the admin_menu to rc5, (latest release), all was fine.


Drupal trip and hotel reservation Is there a Drupal module that would allow you to use custom tables for making hotel and trip bookings and reservations? In my project, I have to use a specific API from a third party tour operator for gathering data for the offers, and displaying them. Thank you in advance.

Look for booking / reservation modules. There are some that would be a good starting point for you.

Rooms, Simple Reservation, Easy Booking and Open Hotel are just a few worth trying.


Context within context? I need 2 context that are identical expect that a single block will not be shown for one. Do I have to create 2 completely separate context (which will be more work to maintain)? Or is there someway to not show a single block within a context based on a new criteria?

For instance my context is page = front page. Im using mobile detect and I need to hide a certain block in this context for mobile devices.

I dont think this can be done but its not too hard to have an elegant solution anyway. This is probably pretty obvious to anyone whos used Context for a while but here it is:

Create a front page context that has every block except for the one thats hidden on mobiles. Then add another context that is front page and not mobile devices, and add the block.


Is it possible to have an external script run index.php that bootstraps Drupal? It seems like such a simple question, and I apologize for my Drupal ignorance, but I am unable to get our Drupal contractors to accomplish what seems to be a simple request.  I need the below script to work without paying for a month of contracting work:

The user will be logged in, and of course, there is a valid database.  If it matters, the site is hosted by "Pantheon", and the script will also call a custom Drupal function to return a recordset.

Is this code not possible?  Am I asking something that cannot be done ind Drupal thus the endless stream of complicated files that they keep giving me?

root\myscript\index.php  (to run as www.mysite.com\myscript\index.php)

<?php
/* Check for Drupal Instance and then bootstrap to get User and Database connection */
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $db_url;
$creds      =  parse_url($db_url);
$db_host    = isset($creds['host'])     ? $creds['host']    : null ;
$db_user    = isset($creds['user'])     ? $creds['user']    : null ;
$db_pass    = isset($creds['pass'])     ? $creds['pass']    : null ;
$db_name    = isset($creds['db_name'])  ? $creds['db_name'] : null ;

$db = mysqli_connect ($db_host, $db_user, $db_pass, $db_name);
if(!$db){
    die('Failed! Could not open a db connection'.mysqli_connect_errno() . mysqli_connect_error());
}elseif(!$user){
    echo 'Failed! Connected to database, but did not get $user - we canNOT proceed';
    echo '
'.print_r($db,true).'
';
    die('Connected to database, but did not get $user')    ;
}else{
    echo "Success! User and DB are set and ready to use - we can proceed";
    echo '
'.print_r($user,true).'
';
    echo '
'.print_r($db,true).'
';
}

This (I think) is at least the start of the Drupal function that will return a recordset when the main code above is working.

/**
* Implements hook_block_info().
*
*/
function xyz_listofmyitems_block_info() {
    $blocks['xyz_listofmyitems'] = array(
        // The name that will appear in the block list.
        'info' => t('List of available items'),
        // Default setting.
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return $blocks;
}

To answer your question - Yes, it is possible to have an external script to bootstrap Drupal.

If Drupal is installed in the folder [root], and the index.php file that you want to get working is in [root/myscript], you'd first get the working directory and then call bootstrap.inc and bootstrap Drupal.

<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// do your thing
?>


How do I determine the route of my view? I made a new view page and I want it to be in the router table so that I can know its route, but it's not there.  How can I determine the route of this view or insert it into the router table?

To find out what the route was for a view, I actually ended up doing this in a custom module, and then looking at the page route in the object.

/**
 * Implements hook_preprocess_HOOK().
 */
function my_module_preprocess_page(&$variables) {
  dpm(\Drupal::request());
}


How to programmatically take a quiz? I need to programmatically make some users take an existing quiz. The quiz has only one question, which is a long answer one, and I have the text needed to fill it. I just can't find any function in the Quiz module that I can call to submit the answer. Is it possible?

I found a way to solve that:

// Load user who will take the quiz
$account = user_load($quiz_taker_uid);
// Load quiz and question nodes
$quiz = node_load($quiz_nid);
$question = node_load($question_nid);
// Create a new result id
db_query("INSERT INTO {quiz_node_results} (nid, vid, uid, time_start) VALUES (%d, %d, %d, %d)", $quiz->nid, $quiz->vid, $account->uid, time());
$rid = db_last_insert_id('quiz_node_results', 'result_id');
// Submit the answer
$result = quiz_question_evaluate_question($question, $rid, $long_answer_text);
quiz_store_question_result($quiz, $result, array('set_msg' => FALSE));
// Finish the scoring and properly invoke hooks
$score = quiz_end_scoring($quiz, $rid);
quiz_end_actions($quiz, $rid, $score);


How to fetch the status of profile flag? I have a profile flag called "keep my photos private" using which user can flag his content and can keep it private. I want to fetch the status of the flag by the specific user. I have tried php code but its not working.

global $user;
$user_uid=arg(1);
$flag=flag_get_flag('keep_photos_private');
print "Flag Name : ".$flag->title;
print "User : ".$user_uid;
if($flag->is_flagged($user_uid)) {
  print "flagged";
}
else {
  print "not flagged";
}

Is my code wrong?

I worked with Profile2 a while ago and it was not a joy for me. I remember having to implement a hook_user_insert and creating the profile right there and there as the profile was only created after a user saved a new profile. So if you have a flag on it and flag it without saving the profile it might just go lost as the profile does not really exist yet.


Alter Search Results display Currently when I search for something it displays the title of the node and if there is a match a small excerpt from either the content short summary or a small excerpt from the paragraph bundle. If there is no match it displays nothing.

How can i change this so it displays content even if only the title match. How can i change this so it displays the date it was published as well.

The modules involved are paragraphs, solr, searchAPI, Display Suite.

You can simply add a new view mode for search results:

Go to admin/structure/types/manage/page/display (where "page" is your content type)
Expand the Show Custom display settings fieldset
Check Search index

Click Save
Go to admin/structure/types/manage/page/display/search_index (where "page" is your content type)

My advice would be to use the Display Suite module as well for extra fields and more options.


Form Api File upload I have the following code in my form.

$form['new']['upload'] = array(
  '#type' => 'file',
  '#title' => t(''),
  '#size' => 40,
);

On the submission handler, it returns the file name but it does not save the file and return a file object. What else do I need to do?

What I am trying to do is create a block where you can upload a file that it is saved in a node's file field.

Take a look at file_save_upload() and the functions which call it.

The function will handle the validation of the file, and save it to a new location. In Drupal 7 this also adds the file to file_managed table.
Note that the file will be stored as a temporary file, so make sure to set the status of the file to permanent afterwards.

You will probably want to implement the file_save_upload function inside your form's validation hook (before the submit handler), so you can alert the user if the file upload failed, or did not meet your validation requirements.

If the name of the image field you are trying to validate is image, then the first parameter of file_save_upload should be image, as such:

$path = file_save_upload('image', ...);

This function will then return the path on the server to which the image was uploaded (so you can for example store that path in a custom database field).


Does the Services module implement caching on GET requests? Before I build a REST server with the Services module, I'd like to know if the responses to the GET requests are being cached? I searched Google and it seems that caching wasn't implemented, however, those articles are from 2011 and 2012.

No, the Services module does not support caching on GET requests:

http://cgit.drupalcode.org/services/tree/resources/node_resource.inc?h=7.x-3.x#n253

As you can see, each time the resource's callback function is invoked, it makes a call to node_load(). You can use the Services API to preprocess/overwrite the resources to implement caching though:

http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x


Set term tid programmatically I've a csv with taxonomy terms, with tids.
I've to import, with a module, these terms in a new drupal installation, but if I try to set the tid programmatically, the module does not create the term. Instead, if I don't set the tid, the term is created with but with the autoincremental tid.
This code doesn't work:

$term = new stdClass();
$term->name = 'Test';
$term->vid = 3;
$term->tid = 10; // if I remove this line the term is created
taxonomy_term_save($term);

The doc says:
tid: (optional) The unique ID for the term being saved. If $term->tid is empty or omitted, a new term will be inserted.

Is there a way to set the tid programmatically?
Or is there a module that do this?

If you set $term->tid for a taxonomy term you save with taxonomy_term_save(), the function will take you are updating an existing taxonomy term, with the consequence that the taxonomy term is not saved.

You could change the taxonomy term ID for the taxonomy term you right saved, but there is the risk of conflict with an existing taxonomy term you didn't import. You should change more that one database  table, and you should let other modules handling data related to taxonomy terms know they need to update their data, which means you probably should make those modules think a taxonomy term is deleted, and a new taxonomy term is created.
See also the code for taxonomy_term_delete() to understand what Drupal does when a taxonomy term is deleted.

If you really need to export taxonomy terms from a site, and import them in a different Drupal site, you should be interested to the Universally Unique Identifier module. In that way, the taxonomy term exported from site A, and imported in site B will have the same UUID.
In Drupal 8, any entity defined from Drupal has a UUID. The schema definition used for taxonomy terms in Drupal 8, for example, is the following one.

  $schema['taxonomy_term_data'] = array(
    'description' => 'Stores term information.',
    'fields' => array(
      'tid' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique term ID.',
      ),
      'uuid' => array(
        'description' => 'Unique Key: Universally unique identifier for this entity.',
        'type' => 'varchar',
        'length' => 128,
        'not null' => FALSE,
      ),
      'vid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {taxonomy_vocabulary}.vid of the vocabulary to which the term is assigned.',
      ),
      // …
    ),
    // …
  );


Removing posted by admin date from a contact form I am making a contact form in Drupal with using panels but in contact form it is showing posted by admin date. I want to remove these two things as shown in image.

There are multiple ways you can do it

For all content of same content type

Go to the content type for which you want to hide Author info.
Scroll down to see the tabs at the bottom and select Display settings.
Uncheck Display author and date information.
Save content type

For Single Node

Go to node.tpl.php and search for $submitted
Give below condition for you case

if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE AND arg(1)==7) {  print $submitted; }


How to disable aggregation from either drush or PHPmyadmin? I've been searching for this and ALL I found deals with Drupal 7. Old drush command drush vset preprocess_js 0 doesn't work for Drupal 8 and the "variable" table in DB doesn't exist in 8...

Yet, I can't disable aggregation in my D8 site for some reason and want to disable it from either drush or DB.

Do you know a way?

Drupal 8 version to disable aggregation:

disable CSS/JS aggregation

drush -y config-set system.performance css.preprocess 0
drush -y config-set system.performance js.preprocess 0


How to get event node to pull in data from a seperate node? I'm trying to setup an events calendar in drupal 6. I have an event content type and a location content type. My problem is that I want the event node to display relevant data from the location node such as location name, address, hours, etc.. I'm not sure of the best way to set this up?

Additional info: My event content type has a cck node reference that points to the location node. I was looking at the reverse node reference module but wasn't sure if that was necessary, maybe this can be accomplished using existing views and block functionality.

As I understood from you question you want to know the best way to display some information from the location inside the event node view page, if this the case you might need to create a  block view (from views module) takes the reference node location (nid) in the current node event being viewed, and as you have the view you can display all the information needed.

I hope this will help.