How to add custom metatags in drupal 7? I need to add a custom metatag to D7 site, something like here: http://groups.drupal.org/node/83069. What are the possible options? I know there is a metatag module, but seems it doesn't support custom tags.

I could modify the theme, but I need some user configurable solution.

Metatag does support custom tags by implementing hook_metatag_metatags_view_alter(). See the following hook implementation to add the Open Graph video:duration metatag from a custom entity:

/**
 * Alter metatags before being cached.
 *
 * This hook is invoked prior to the meta tags for a given page are cached.
 *
 * @param array $output
 *   All of the meta tags to be output for this page in their raw format. This
 *   is a heavily nested array.
 * @param string $instance
 *   An identifier for the current page's page type, typically a combination
 *   of the entity name and bundle name, e.g. "node:story".
 */
function mycustommodule_metatag_metatags_view_alter(&$output, $instance) {
  if ($instance == 'mycustom:entity') {
    $entity = mycustomentity_load(someid);
    $duration = $entity->duration;
    $output['video:duration']['#attached']['drupal_add_html_head'][0] = array(
      array(
        '#theme' => 'metatag_opengraph',
        '#tag' => 'meta',
        '#id' => 'video:duration',
        '#name' => 'video:duration',
        '#value' => $duration,
      ),
      'video:duration',
    );
  }
}


How to hide title of any content type without using a module? I want to hide the title field of a particular content type (such as Article), but without using any modules.

How can I do this?

You could do it in template.php in your theme dir, technically not a module.

e.g:

/**
 * Implements hook_preprocess_node
 */
function MYTHEME_preprocess_node(&$variables){
  if ($variables['node']->type == 'article') {
    $variables['title'] = FALSE;
  }
}

Replace "MYTHEME" with your theme name and clear all caches at Admin > Config > Performance to apply.

node.tpl.php: Check for $type before printing the $title
e.g. line #87 change to something like
if (!$page && $type != "your_type" ):


Migrate class not registering properly I am having trouble creating and registering migrate modules. At the moment, when I go to the UI screen, it says 'Class X no longer exists' (so, at least its being picked up) and wont show in the list of migrations on  the page. At the moment, I have only implemented one class and had this issue (when I figure this out, I will create everything else). Here is my code:

function migrate_rcmd_migrate_api() {
  $api = array(
    'api' => 2,
    'groups' => array(
      'Test' => array(
        'title' => t('Test Migrations'),
      ),
    ),
    'migrations' => array(
      'EventNode' => array(
        'class_name' => 'EventNodeMigration',
        'group_name' => 'Test',
      ),
      'CareerNode' => array(
        'class_name' => 'CareerNodeMigration',
        'group_name' => 'Test',
      ),
      'NodeRegistrationEntity' => array(
        'class_name' => 'NodeRegistrationEntityMigration',
        'group_name' => 'Test',
      ),
      'JobPostingEntity' => array(
        'class_name' => 'JobPostingEntityMigration',
        'group_name' => 'Test',
      ),
      'CoverLetterFileEntity' =>array(  //may only need one file entity migration class
        'class_name' => 'CoverLetterFileEntityMigration',
        'group_name' => 'Test',
      ),
      'ResumeFileEntity' => array(
        'class_name' => 'ResumeFileEntityMigration',
        'group_name' => 'Test',
      ),
    ),
  );
  return $api;
}

and

abstract class Test_Migration extends DynamicMigration {
  public function __construct() {
    // Always call the parent constructor first for basic setup
    parent::__construct();

    // With migrate_ui enabled, migration pages will indicate people involved in
    // the particular migration, with their role and contact info. We default the
    // list in the shared class; it can be overridden for specific migrations.
    $this->team = array(
      new MigrateTeamMember('Liz Taster', 'ltaster@example.com', t('Product Owner')),
      new MigrateTeamMember('Larry Brewer', 'lbrewer@example.com', t('Implementor')),
    );

    // Individual mappings in a migration can be linked to a ticket or issue
    // in an external tracking system. Define the URL pattern here in the shared
    // class with ':id:' representing the position of the issue number, then add
    // ->issueNumber(1234) to a mapping.
    $this->issuePattern = 'http://drupal.org/node/:id:';
  }
}

class EventNodeMigration extends Test_Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    //WE WILL NEED THIS
    //$this->dependencies = array('BeerTerm', 'BeerUser');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'nid' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'The primary identifier for a node.',
          'alias' => 'n',
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );
    //example
    $query = Database::getConnection('default', 'legacy')
             ->select('node', 'n')
             ->fields('n', array('nid','vid','type','language','title','uid','status','created', 'changed','comment','promote','sticky','tnid','translate','uuid'))
              ->condition('type', 'events','=');
              //ADD JOINS TO FIELD TABLES HERE
    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationNode('events');

    $this->addSimpleMappings(array('nid','vid','type','language','title','uid','status','created', 'changed','comment','promote','sticky','tnid','translate','uuid'));
    //$this->addFieldMapping('title', 'page_title');
    //$this->addFieldMapping('body', 'page_body');
  }
}

Be sure:

your migrate_rcmd_migrate_api function is in the file migrate_rcmd.migrate.inc.
your Classes are included in .inc files defined in your modules .info file. See this documentation page on Migrate: https://drupal.org/node/1006982
Lastly in Migrate > 2.5 (i think thats the right version) migration auto discovery is now gone. You can use drush migrate-register to register your migrations and classes. See drush help migrate-register as needed.
when in doubt clear your caches: drush cc all to be sure the .inc files are registered in drupals code registry.

Add this code your module hook_enable().

/**
* Implements hook_enable().
*/
function MODULENAME_enable() {
  Migration::registerMigration('MigrationClassName');
  $migration = Migration::getInstance('MigrationClassName');
  $result = $migration->processImport();
}


How do you add validation (constraints?) on a paragraph? Compare two fields How does one go about adding validation (contraints?) on a paragraph?

I need to compare two entity reference fields on submission. If one field has a certain entity referenced, the other cannot have certain entity references.

I'd be interested in restricting the autocomplete options as well, but that simply won't be enough as I need to ensure that they user doesn't manually enter another entity value.

You simply inherit from the the default EntityReferenceWidget and you will call it like MyParagraphEntityReference widget. You can here both change the way how the autocomplation works and also how you validate the entered data.

This is page may help you.


Custom module and block API Have followed all the steps at http://www.packtpub.com/comment/reply/7089 to create a custom module.

I am able to create it and it is showing under the Modules and is getting enabled. However as the purpose of this module is to create a new block it is not doing so. Its not showing under the Structure/Blocks. Any reasons?

name = First
description = A first module.
package = Drupal 7 Development
core = 7.x
files[] = first.module

;dependencies[] = autoload
;php = 5.2

/**
 * @file
 * A module exemplifying Drupal coding practices and APIs.
 *
 * This module provides a block that lists all of the
 * installed modules. It illustrates coding standards,
 * practices, and API use for Drupal 7.
 */

/**
 * Implements hook_help().
 */
function first_help($path, $arg) {
  if ($path == 'admin/help#first') {
    return t('A demonstration module.');
  }
}

/**
 * Implements hook_block_info().
 */
function first_block_info() {
  $blocks = array();

  $blocks['list_modules'] = array(
    'info' => t('A listing of all of the enabled modules.'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function first_block_view($block_name = '') {
  if ($block_name == 'list_modules') {
    $list = module_list();

    $theme_args = array('items' => $list, 'type' => 'ol');
    $content = theme('item_list', $theme_args);

    $block = array(
      'subject' => t('Enabled Modules'),
      'content' => $content,
    );

    return $block;
  }
}

Let you try with this code. Clear performance cache.

function example_block_info() {
  $blocks['my-block-id'] = array(
    'info' => t('Block Name'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function example_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
      $block['subject'] = t('Block Name');
      $block['content'] = example_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function example_contents() {
  return '

      Hello World, this is a example custom Block

  ';
}

For more info see this http://www.summasolutions.net/blogposts/how-create-basic-block-code-new-drupal-7


Create taxonomy terms on the fly As far as I know, the way to create a taxonomy term is having to go into the taxonomy module and creating on there, and THEN assigning the term to the node.
Is there a way to create taxonomy terms on the fly? When the node is created, if the taxonomy term doesn't exist, it should be created too.

Use the Hierarchical Select module:

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!

Another way is selecting Autocomplete term widget (tagging) as field widget, when creating your term reference field

As another option, there is the Simple hierarchical select module.

I'd like to suggest the Manage Multiple Terms module:

  Manage Multiple Terms provides a simple mechanism to add, update,
  delete many terms in the same time easily and quickly.


How to resize automatically when users upload images by CCK image field I would like to make the size of images smaller automatically when users upload them using CCK image field.

For example, I would like to let users upload big sized images like 5MB but resize them smaller automatically like 0.5MB before saved on the server.

The reason is that the capacity I can use on the shared server is very limited. Of course I can set "Maximum upload size per file" to a small size but then users who have big sized images but don't know how to resize them before upload will not be able to upload them. I have tried also "image cache" a bit but it doesn't seem to save the files with the name, attributes and in the directory specified by CCK image field.

I don't know if this kind of thing is possible to achieve or not.. Any Idea?

Imagecache is great, but since it keeps the original file around, it won't save space. In fact, if you have multiple presets, it will increase your disk usage as it creates its caches of images of those sizes.

What you may want to investigate is putting some logic into nodeapi() (or, if on Drupal7, its equivalent function) when saving your node that looks at the filepath of whatever image field you are concerned with and does some image manipulation on it if it is over a certain size and then saving it in place.

Not really what you're asking for but anyway: You already discovered the Drupal way of handling big images: image cache. If you can, switch to a hoster with a lot of storage (some offer unlimited space).


Setting up Drupal without a domain name A site's been developed on localhost and I want to move it to my new hosting, which uses Plesk.
This hosting doesn't have DNS pointing to it, although the domain is added. (The domain name is currently pointing to my old hosting.)

I have changed $base_url to the preview URL Plesk provides:

$base_url = 'https://the-url-pleskprovides:8443/sitepreview/http/myurl.com';

I can access the site and even browse, but I can't login because login redirects to https://the-url-pleskprovides:8443/user instead of https://the-url-pleskprovides:8443/sitepreview/http/myurl.com/admin/.

Is there any way to work with Plesk preview, or with Drupal without a domain?

Any help will be highly appreciated.

Ok, the answer is unfortunately Drupal can not handle this situation. What should be done is the following:

On Windows

Go to: C:\Windows\System32\drivers\etc

Open: hosts file

Add at the end:

100.200.10.20 yourdomainname.com
109.200.10.20 www.yourdomainname.com

On Mac

Open Terminal (Applications -> Utilities -> Terminal)

Open hosts file: $ sudo nano /private/etc/hosts

Type your user password when prompted

Add at the end:

100.200.10.20 yourdomainname.com
109.200.10.20 www.yourdomainname.com

Save the file Flush the DNS cache: $ dscacheutil -flushcache

NOTE: The IP is the IP of your server. You can get it by logging into Plesk, Home>System Overview

I would do the following if I was in your shoes: Put a temporary entry in your robots.txt file so it won't get crawled. You can also add something in your /index.php; check $_SERVER['HTTP_HOST'] to see if it's the temporary one or not.

Basically, just run the site from the temporary plesk domain until you're ready; then, change the settings file.


Node custom property exposed as extra field I'm trying to add custom property to node bundle, my code so far:

/**
 * Implements hook_entity_property_info_alter().
 */
function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['node']['bundles']['program']['properties'];

  $properties['last_episode_date'] = array(
    'label' => t("Last episode date"),
    'type' => 'date',
    'computed' => TRUE,
    'entity views field' => TRUE,
    'metadata controller class' => 'EntityDefaultMetadataController',
    'extra fields controller class' => 'EntityDefaultExtraFieldsController',
    'getter callback' => 'mymodule_last_episode_date_getter',
    'description' => t("Date of the last episode."),
  );
  return $info;
}

/**
 * last_episode_date property getter.
 */
function mymodule_last_episode_date_getter($data, array $options, $name, $type, $info) {
  return REQUEST_TIME;
}

The goal is to have this property available in views and in node as extra field - in views it is available, but I cannot make it to work as extra field. Anything is missing/is wrong? Documentation on this is kind of lacking :( .

Looking at Entity module's hook_field_extra_fields() implementation:

/**
 * Implements hook_field_extra_fields().
 */
function entity_field_extra_fields() {
  // Invoke specified controllers for entity types provided by the CRUD API.
  $items = array();
  foreach (entity_crud_get_info() as $type => $info) { ... }
  return $items;
}

It only looks for entity types provided by the CRUD API -- in other words, entities whose controllers inherit from EntityAPIControllerInterface. Node entities use NodeController.

You can still do this conventionally, outside of Entity API -- implement hook_node_view() to insert your pseudo-field in $node['content'], then implement hook_field_extra_fields() to expose that pseudo-field to the node's "Manage display" tab.


How to override VBO redirect after performed action? My problem is that I can't override the URL where VBO redirects me to after I performed a default action. When I write my own actions I simply put $_GET['destination'] = 'my/target'; inside my custom form submit and that works. I tried to alter VBO's form submit to attach my own submit but that doesn't work:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_bulk_operations_form') {
    array_push($form['#submit'], 'MYMODULE_vbo_redirect');
  };
}

function MYMODULE_vbo_redirect() {
  $_GET['destination'] = 'my/target';
}

When I testhack the VBO module and inside views_bulk_operations_form_submit($form, &$form_state) replace the final redirect with my custom one, it works. How can I get inside there and get my custom redirect executed without hacking?

I tried to alter the wrong form. VBO somehow merges its form stuff with the views form itself. So I had to look there to attach my custom submit. Then I had to pay attention to attach it in the same moment the views_bulk_operations_form_submit is attached. Then I set the cancel button to also bring me back where I want. And finally set $form_state['redirect'] in my attached submit.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_MYVIEW_page') {
    $form['#action'] = '/my/target'; // the url that is displayed when in VBO multistep

    if (!empty($form['actions']['submit']['#submit'])) {

      if (in_array('views_bulk_operations_form_submit', $form['actions']['submit']['#submit'])) {
        $form['actions']['submit']['#submit'][] = 'MYMODULE_vbo_redirect';
        $form['actions']['cancel']['#href'] = 'my/target';
        $form['actions']['cancel']['#options']['path'] = 'my/target';
        dpm($form);
      }
    }
  }
}

function MYMODULE_vbo_redirect($form, &$form_state) {
  $form_state['redirect'] = array('my/target');
}

Only problem left is that this redirect always gets triggered when performing any VBO action from this view. But I can live with that for now.

function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{
 if ($form_id == 'views_bulk_operations_form') {
$form['#submit']='MYMODULE_vbo_redirect';
}
}
function MYMODULE_vbo_redirect() {
// Use die('here') and submit the form.if it dies then redirect it
drupal_goto('my/target');
}

Hope this will helps you


How can I change the Add to Cart button text on specific product forms? What is the easiest way to change the Add to cart form button text to something custom? I want to change the text only on certain product types. How should I approach this?

Take help of hook_form_alter. Get the ID of the form for the product display where you are trying to change the text & do something like this --

function MYMODULE_form_alter(&$form, &$form_state, $form_id){//replace your module name with MYMODULE
  if(strpos($form_id, 'commerce-cart-add-to-cart-form-65') !== false){//my form ID is "commerce-cart-add-to-cart-form-65", replace it with your form ID.
    $form['submit']['#value'] = t('Check Out');//Put the text which you want to make appear instead of "Add to cart".
  }
}

I also have several product display with custom text for "Add to cart". It took some time for me figure out the easy way. Have Fun :)


How to show a view of content types on another content type I have one content type 'class' and I have another content type 'lesson' and I want to easily display all lessons that belong to a class on the view of a 'class.' Is this possible and if so, how?

I would take a look at the "Panels" module, which allows you to create custom pages that can display multiple Views displays in one page.

-

Alternatively, instead of creating multiple content types, consider utilizing taxonomy terms to differentiate your classes and lessons.

For instance, create a list of terms for a new vocabulary "Class", which differentiates the different types of class.

Then, for each of your "Lesson" content type nodes, apply the specific class taxonomy term which applies.

Finally, you can create a View which displays Lessons content nodes, and have it filter the results to those Lessons which are tagged with a specific "Class" taxonomy term.

Good question. This requires a trick which is not easy to discover unless you've seen it before!

I'm assuming your Lesson type has a 'node reference' linking each Lesson to its appropriate Class?  If not, that's a good place to start.

(I'm going to refer to Drupal 6 here: If you're using D7, I think you need the 'Entity Reference' module, and some things may be different.)

Then, create a View which lists all the nodes of type Lesson that are also Published.

Add an argument, which links to the node reference field mentioned above.  You should then be able to enter, say, '2' in the Preview box at the bottom of the view-editing screen and get just a list of all the lessons for the class represented by node 2.

As an aside, let's assume you'd like to have a separate page listing those.  Create a page display for the view, give it a URL path (say 'classlessons') and then you can add the node number to the URL to get your page:

mysite.com/classlessons/2

I think a different URL format is nicer, though, something that indicates this is class 2 that we're talking about, not lesson 2.  If you set the path of the view to be 'class/%/lessons', then the argument is taken from the location of the % sign, ie:

mysite.com/class/2/lessons

Isn't that nice?

OK, now in your case, you want this to appear on the class page itself.  Create another display for your view, but this time a Block display rather than a Page display.  This will give you a block that you can include on the page, but it has a problem:  blocks don't have URLs, so how can they have arguments?  There's a way to deal with this.

In your block display, click on the argument, and you'll see a section called 'Action to take if argument is not present'.  One option is 'Provide Default Argument', and you can select 'Node ID from URL'.  This basically says, "I know this block doesn't have a URL, but I want to take the argument from the node id of the page that it's in".

Finally, add this block to the relevant pages - the easiest way is probably to do this by URL: if your class pages have consistent URLs you can choose 'Show only on the listed pages' and enter, for example,

class/*

If they don't have consistent pretty URLs, take a look at the Pathauto module.

This should, I think, do what you want.  Note that the 'Node ID from URL' default argument thing will work even if the URL you use doesn't actually have the node id in it but has an equivalent alias:

mysite.com/class/geography

The system knows which node is being referred to and substitutes the appropriate ID.


Fatal error: Failed opening required file I am quite new in Drupal. When installing Kickstart module in a Acquia based Drupal 7 setup on a localhost, I got this message. I looked on the internet and saw a lot of answers, but it didn't help me. It seems the plugins.inc file is fine, but I can't do anything now.

  Fatal error: require_once() [function.require]: Failed opening required '/Users/aztem/Sites/acquia-drupal/sites/all/modules/panels/plugins/export_ui/panels_layouts.inc' (include_path='.:/Applications/acquia-drupal/common/pear:/usr/lib/php') in /Users/aztem/Sites/acquia-drupal/sites/all/modules/commerce_kickstart/modules/contrib/ctools/includes/plugins.inc on line 475

Commerce Kickstart isn't a module, it's an installation profile. If you want to add Commerce to your site, try install using drush, or just load all the modules manually.

drush dl commerce

Using the drush command will install Ubercart essentially, and you can setup commerce that way.


how to achieve a sliding effect to show the rest of elements in a grid, with views I have a view set to grid, displaying 5 items per column. I set it to display 5 items at a time too, but I have 10 items total. What i want to achieve is, when I click on page 2, instead of having it load the rest of thumbs, for them to slide into the position of the first 5 items displayed. It would be something like SlideShow effect, scroll to the left, but instead of displaying a single frame, displaying 5 at a time.

Im using drupal 6x, views, (cck of course), and have slideshow installed but I couldn't manage to figure it our on my own. I appreciate any prompt response.

Here is an example of jquery slide show.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>jQuery Animating an Element</title>

        Animating an Element

Animate Me

    <button id="right">Grow Right</button>
    <button id="text">Big Text</button>
    <button id="toggle">Move Div</button>


What's best practice when working with the language[und]? I'm starting to use this form to access data in my module. (See comment #1.)

$node->field_test[$node->language][0]['value']

I thought that looked like a pretty good solution, but further down that same question I found this:

  Don't assume that 'und' is for fields of entities without language, it is also for fields that are not translatable, and without the entity translation module that is all fields. Moreover, there are differences in this between the various 7.x versions of Drupal.
  Better to use the field_get_items() function which will sort out for you under what language code the data is stored.

And now I don't know if what I'm using could break something down the road.

I find that using the Entity API module is a great help and also makes code more readable. The above code will not always work, since the language of the node and the language of the field can be different.

With the entity API module, and its wrapper, you can use the following code:

 $node_wrapper = entity_metadata_wrapper('node', $node);
 $field_val = $node_wrapper->field_test->value();

This should be bullet proof. One thing about using the entity module is that if you try to access a field that doesn't exist, you will get a nasty error and an exception thrown instead of a notice and wrong behavior.

To avoid this, you could do try/catch like this

try {
  $field_val = $node_wrapper->field_doesnt_exist->value();
} catch (EntityMetadataWrapperException $e) {
  $field_val = 'default/fallback value';
}

Or you can use isset() which EntityMetadataWrapper handles internally:

$field_val = 'default/fallback value';
if (isset($node_wrapper->field_doesnt_exist)) {
  $field_val = $node_wrapper->field_doesnt_exist->value();
}

$node = node_load($lot_id);
$field_language = field_language('node', $node, 'field_name');
$node->field_name[$field_language][0]['value'] = $custom_value;


Dynamically fetch feeds and html content from other website and show Is there any module that pulls data from external feed or html link and displays in drupal. It should not create any corresponding nodes in drupal. It should just go and scrape data or feed and display in a page or block.

Feeds is the way to go. It includes an HTML parser and can fetch data from existing URLs.

Here are some links to parsers for Feeds that can suit your needs.

Not Aggregator Module alone, you need Aggregation also. Here is a quote about it (from the module's project page):

... aggregates content from XML feeds. RSS 2.0, ATOM 1.0 & RDF 1.0 are supported, but its architecture is easily expandable to support any XML format, check out the README file for details. Following are some of its features :

Highly efficient. This module was created for performance.
Ability to assign term(s) to all items generated from a feed.
Ability to dynamically tag all incoming items during feed handling phase. For example, RSS, ATOM & RDF categories are automatically extracted, added as terms, and auto-attached to aggregated items.
Integrates with OG. If the feed is set as a group, all items are assigned as posts under it (parent->child). If the feed is set as a post, all items are assigned as posts under the feed's group (siblings).
Built-in support for handling feeds that require HTTP authentication.
Built-in support for handling feeds that require FTP authentication.


Multiple Context block order / weight I have 2 Contexts set up that each place a block in the same region.

There are times when both these contexts will happen at the same time and as such both blocks appear together.

Currently when both appear they are not in the order I require, is there a way of weighting these across contexts?  I know the weighting works within a context however this is not what I need at this point.

Currently using:
Drupal 6.22,
Context 6.x-3.0

UPDATE:

Hi All,

This post appears to get quite of interest but I'm afraid I don't use Drupal anymore or have any time (or sites) to check these answers.  If any answer gets enough interest and appear to be right then I'll happily mark it correct but I can't actually verify anything.

This patch worked for me. Enable the patch at admin/build/context/settings.

There is a lot that gets discussed after that comment and one contributor even created a module. I haven't read much of the other comments, implemented the module nor any of the patches posted after the one I referred to above.

You can edit (carefully) the serialised values in the context table through phpMyAdmin.  This has to be done again every time the context is edited through the UI.  But it's not a bad solution which avoids the overhead of installing extra modules to solve this.


Theme suggestion template is not being picked up I add template suggestion in my discount module:
function discount_theme_suggestions_field_multiple_value_form_alter(array &$suggestions, array $variables) {
    if ($variables['element']['#field_name'] == 'user_discount'){
      $suggestions[] = 'field_user_discount';
      kint($suggestions);
    }
}

And I can see template suggestion on my admin form:

However I added template field-user-discount.html.twig (I don't place it here as it simply the copy of classy one with change of order) in discount module templates folder and it is not being picked up, it still picks up the classy one. I cleared all the caches, both from drush and site itself. I also tried to add this template to theme templates, it is not being picked up there as well. Other templates from both theme and discount modules are being picked up.
How can Drupal pick it up? It is the field on admin pages.

After you add your theme suggestion:
function discount_theme_suggestions_field_multiple_value_form_alter(array &$suggestions, array $variables) {
    if ($variables['element']['#field_name'] == 'user_discount'){
      $suggestions[] = 'field_user_discount';
    }
}

You need to tell Drupal in this hook you should pick my template by implementing hook_theme like the following.
/**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field_user_discount' => [
      'base hook' => 'field_multiple_value_form'
    ],
  ];
}

Now just put your template in you templates module folder clear cache and it will be picked.
Note: if you want to use a different name from the suggested one (field-user-discount) of your template like field-user-discount-something.html.twig just tell the hook_theme the name of template like:
 /**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field_user_discount' => [
      'base hook' => 'field_multiple_value_form',
      'template' => 'field-user-discount-something'
    ],
  ];
}

I added template field-user-discount.html.twig ... in discount module
templates folder

That's the wrong place to put it. You need to put this in your theme, not in the module's templates folder.


Search index in drupal7 I tried following methods for search index in drupal 7:

Click on re-index site.
Number of items to index per cron run is 100.
Save Configration.
Run Cron and check the items count left to index.

I got "There are no new nodes. Cron run successfully." still I am getting (0% of the site has been indexed. There are 51996 items left to index) in index status.

if you have drush installed, you can do it this way:
 drush search-reindex --immediate --verbose

There is a dev module available that does the same thing.
https://drupal.org/project/reindex

It's probably a good idea to have the site in maintenance mode while you try this.

Drupal's search engine indexes the text content of the nodes on your site. You can tweak the way it does this.

The search engine does its indexing at intervals you choose by setting "cron runs." Cron (which stands for chronograph) is not a part of Drupal. It's a scheduler that resides on your server and runs tasks (called "cron jobs") at intervals, which you specify. The jobs can run weekly, daily, hourly, or whatever you like.

you can better check Search: an internal site search system


how to overreide page.tpl.php with my custom menu I have override page.tpl.php with my new custom menu created in my custom module. my menu look like below

$items['node/edit/restaurant/%/barcodes'] = array(
    'title'=>'Barcodes',
    'menu_name' => 'barcodes',
    'description'=>'Barcodes',
    'page callback'      => 'drupal_get_form',
    'page arguments' => array('leo_MSTag_barcode', 5),
    'access callback'=>TRUE,
    'type' => MENU_CALLBACK,
  );

I already try with page--barcodes.tpl.php, page--node--edit--restaurant--barcodes.tpl.php but not work for me. any new template suggestion for override mu menu page?

I guess you could do something like this:

function MYMODULE_preprocess_page(&$vars) {
  $patterns = 'node/edit/restaurant/*/barcodes';
  if (drupal_match_path($_GET['q'], $patterns)) {
    $vars['theme_hook_suggestions'][] = 'page__node__edit__restaurant__barcodes';
  }
}

That would let you use page--node--edit--restaurant--barcodes.tpl.php after a cache clear.

As an aside, your page arguments are wrong in the router item, should be:

'page arguments' => array('leo_MSTag_barcode', 3), // <-- Index of arg is 3, not 5

You can use themeName_preprocess_page in your template.php.

Check the below url.

http://drupal.org/node/1089656.


How can I add a currency field to a content type? I would like to have a field that accepts U.S. dollar amount. I installed the module: https://www.drupal.org/project/currency. Structure > content type > I do not see a field type "Currency". I am not sure how I can add a field to accept USD amount.

How can I add the price field to the content type?

So to add a decimal field.

edit your content type.
manage fields
add new field
select Decimal from the Field Type dropdown.
Click the 'Save' button
Change 'Scale' to 2. These are the cents.
Click the 'Save field settings' button.
In the Prefix field add '$'.
Click the 'Save settings' button


Triage / decision tree / simple guided entry / expert system for Drupal 8? Is there a Drupal 8 module or technique for asking a series of screening questions of visitors, and then spitting out a computed response? This might be called a guided interview, expert system, intake triage, or decision tree.

Specifically, we have client eligibility guidelines. I'd like a visitor to be able to put in their zip code, household size, and income to determine if they meet those guidelines. Ideally they get the result on the same page without hitting submit.

I have located this: https://bdsworks.org/triage-text-doc which is not for Drupal 8. I also read this previous result: Module for decision tree / guided entry. Hierarchical select looked promising, but I don't think it's quite the same thing I'm trying to do.

I also checked out the webform module, but it looks like the conditional logic isn't really aimed at this use. E.g., when testing against a specific value, there's no ability to test for presence in a list of multiple entries (like one of dozens of zip codes) or a range of numeric values.

Maybe this isn't as common a need as I thought?

This is not a common need of most websites. But, the building blocks exist within the Drupal API to create such business logic at the end of a webform or custom form.


How do I get the raw URL as a field in Views? In views I need to return the raw url that is provided as the href value to the title field (when as a link) or the Content: link value.  I thought originally I could choose Content:link and strip the HTML in a rewrite, but no go.

I need the full URL so that I can pass it as a parameter in a field rewrite. Thoughts on how to get this only?

As per the comment here http://drupal.org/node/458316#comment-6236984

In views 3.x you can use "Path" field with option "Use absolute link (begins with "http://")" in Rewrite results section.

There is number of ways you can do this but the following is fairly easy.

In your view add NID as a field.

Create a 'row style' template that loops through the $fields object.

In your template file, before the loop assign a variable with the NID value from the field.

$nid = strip_tags($fields['nid']->content);

Then use the node_load() function to load a node object.

$node = node_load($nid);

You should be able to access anything you want including the path from this node object.

To see whats in it use Devel if you have this installed or just use the PHP var_dump() function.

Even better check whether you have a 'path' field the you can add.


Can't change image attribute src I want use Lazy Load jQuery Plugin. So, I must change image src to data-original path.

And I added this code to my template.php:

function mytheme_preprocess_image(&$variables) {
   if ($variables['style_name'] == 'slides') {
       $variables['attributes']['class'][] = 'lazy';
       $variables['attributes']['data-original'][] = file_create_url($variables['path']);
       $variables['path'] = '/sites/all/themes/mytheme/images/grey.png';
   }
}

Yes, this code add data-original attribute. But not add grey.png image to src

What's problem? How can I fix it? Thanks.

function mytheme_preprocess_image(&$variables) {
   if ($variables['style_name'] == 'slides') {
       $variables['attributes']['data-original'][] = file_create_url($variables['path']);
       $variables['attributes']['class'][] = 'lazy';
       $variables['path'] = '/sites/all/themes/mytheme/images/grey.png';
   }
}

Regards


Need Ability to Override Default text field When the textfield is left blank, a default value populates. But when a value is placed into the text field, that value should show on the front end. It currently does not.

I have  admin rights to edit,view any pages. I have enabled everything for adminstartor roles under User Management->roles. Even then am unable to update a new value to that field. It is populating the default value.

You can change the field default text in the field settings page of the content type, for example:

admin/structure/types/manage/[your-content-type]/fields/[your-field]

You need to change [your-content-type] and [your-field] by the real values on your drupal website.


How to make CSS and JS both load in the footer We have a library slick_carousel in our mytheme.info.yml and mytheme.libraries.yml defined in our sub-theme (see below).

How can we make the CSS and JS both load in the footer? Currently only the JS file is showing in the footer.

Current mytheme.libraries.yml:

slick_carousel:
  css:
    theme:
      //cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css: { type: external, attributes: { async: true } }
  js:
    //cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js: { type: external, minified: true  }
  dependencies:
    - core/jquery

We have tried, but didn't work. We need to do this without a module.

Removing dependency on core/jquery.
Change theme to component under css.

You can just add 'scope' option and pass either 'header' or 'footer' as the value.

slick_carousel:
  css:
    theme:
      slick.min.css: { type: external, attributes: { aysnc: true }, scope:footer }
  js:
    slick.min.js: { type: external, minified: true, scope: footer }
  dependencies:
    - core/jquery


Use Url Argument in contextual filter for Block View I have a View which uses contextual Filter to compare my URL last Argument with Taxonomy term. This Works when my view is Page but doesn't work in block mode. This is my View Below.

Attaching my view and Site Description along this.
My Pdf Category View is placed as a block.

When I Preview by entering the brand name emax in the view, it give me proper results but it doesn't fetch from url(RAW Value from URL). Correct me if i failed to mention anything wrong.

I found the solution for this issue. I used PHP code by selecting "Provide Default" and Select PHP code as below to extract arguments from URL and provide a filter to your view.

$path = drupal_get_path_alias();
$path = explode("/", $path);
return $path[2] /* Since explode function return array of url arguments, select required arguments starting with 0.*/


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.

Atlast, I found the solution. Just by Adding Actions -> Send mail -> In Field "TO" -> [commerce-order:commerce-customer-billing:field-billing-email]. Simply I got Mail. Thanks for your Contribution.


How can I add an unescaped script tag and contents to a page? I would like to add to my pages the structured data in JSON-LD (https://developers.google.com/search/docs/guides/intro-structured-data)

Basically, what I need to do is to add somewhere in the HTML for, let's say a basic page, a snippet like the following:

<script type="application/ld+json">
{  "@context":"http://schema.org",
   "@type":"WebSite",
   "name":"Site name",
   "alternateName":"Site alternatime name",
   "description":"Site description",
   "keywords":"list of keyword",
   "inLanguage":"en",
   "url":"http://www.example.eu/en",
   "potentialAction":{
   "@type":"SearchAction",
   "target":"http://www.example.com/en/find/{search_term_string}",
   "query-input":"required name=search_term_string"
   }
}
</script>

I've tried to use the full HTML input but the snippet gets (kind of) escaped with the CDATA and google cannot parse it.

So, how can I provide that snippet without any escaping?

Here's a simple way to do this with no additional modules required. For the sake of this example, I'm going to add this field to the Basic page content type that comes with the Standard installation profile.

First, let's create a new Text format. Go to admin/config/content/formats and click Add text format. I name the Text format JSON-LD and make it only available for Administrators. Be sure to leave all options blank and set Text editor to None, like so:

Then, let's add a new field to the Basic page content type. Go to admin/structure/types/manage/page/fields/add-field and select Text (formatted, long). I name the field JSON-LD with an automatic machine name of field_json_ld.

Then let's make sure we hide the field's label. Go to admin/structure/types/manage/page/display and make sure to set the Label to our new JSON-LD field to - Hidden -, like so:

Now it's time to add the script to a new page. Go to node/add/page and fill in the Title and Body as you like. Here's the important bit: for the JSON-LD textarea, be sure to set the Text format to JSON-LD, like so:

Now click Save and publish. Your node will look like this:

Nothing special, right? Now let's take a look at our source code:

Bingo!

use :

      your codes here

.

this is the way all sites render any type of codes in HTML.

and this way write code in code tag, i think code will not escape.


how to output image file from database drupal 7? I have created testing module that will upload image and outputting it to my page. but, I can't seem to output my image file from my database. here's my code

function database_ex_menu() {
  $items = array();
  $items['database-ex'] = array(
    'title' => 'My Database Form',
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit database_ex'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('database_ex_form'),
  );
  return $items;
}

function database_ex_form($form, $form_state) {
  $form['myimage'] = array(
    '#type' => 'file',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add item'),
  );
  return $form;
}

function database_ex_form_submit($form, $form_state) {
  $fe_id = db_insert('example')
    ->fields(array(
      'myimage' => $form_state['values']['myimage'],
    ))
    ->execute();

  drupal_set_message(t('Your entry has been added'));
}

//This function supposedly will output my image file inside a div.

function database_ex_submission(){
  //What to do From here!
}

Firstly save image to your server and then you can output the image.

You can save image by using file_save_upload().

  file_save_upload : Saves a file upload to a new location.

$file = file_save_upload('myimage',array(), 'public://');

Get fileid(fid) of the image

$fid=$file->fid;

And then save this $fid to your database.

After it get fid from database

  $upload_record = file_load($fid);
  $url = $upload_record->uri;

  $render_image = theme(
    'image_style',
    array(
      'style_name' => 'Style_name',
      'path' => $url,
      'getsize' => TRUE,
      'attributes' => array(
        'width' => '250',
        'height' => '162')
      )
    );

Now print $render_image variable where you want to display image.

To output the image from database you can use theme_image

<?php
  $variables = array(
      'path' => 'path/to/img.jpg',
      'alt' => 'Test alt',
      'title' => 'Test title',
      'width' => '50%',
      'height' => '50%',
      'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
      );
  $img = theme('image', $variables);
?>


How to build custom breadcrumbs I have to build a breadcrumbs, In fack I only need to add a breacrumbs between the "home" and the "books breadcrumbs" to get something like this:

  home>>view-path>>book-breadcrumbs-with-deep

I have try with paths breadcrumbs, with hansel, and with custom breadcrumbs, I don't get nothing.

There is another module, or I should make my own module?

Thanks

Oskar

You can accomplish this with hook_menu_breadcrumb_alter():

function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  $home = $active_trail[0];

  $new = array(
    'title' => t('Some title'),
    'href' => 'internal/drupal/path',
    'link_path' => '',
    'localized_options' => array(),
    'type' => 0,
  );

  $active_trail = array_merge(array($home, $new), array_slice($active_trail, 1));
}

This is a fairly simplified example that creates a new breadcrumb item, and sticks it after the first entry.  The $item parameter will be the router entry for the current page.  If you want to use that, you need to dpm() it to see what is there.  A more concrete example, which assumes that you are on a node page would be:

function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  $home = $active_trail[0];

  if (arg(0) == 'search') {
    $active_trail = array($home);
  }
  else if (isset($item['load_functions'][1]) && !empty($item['map'][1]) && $item['load_functions'][1] == 'node_load') {
    $node = $item['map'][1];

    $new = array(
      'title' => $node->title,
      'href' => 'node/' . $node->nid,
      'link_path' => '',
      'localized_options' => array(),
      'type' => 0,
    );

    $active_trail = array_merge(array($home, $new), array_slice($active_trail, 1));
  }
}

My favorite method is to use the Custom Breadcrumbs module is for me the only one that takes into account all possibilities and is capable of generating a real Breadcrumb. I have a post explciando obtaining a real Breadcrumb for example if a node has multiple paths to reach it.
Get a real breadcrumb, Drupal

Good luck!


Get latest revision vid in views I'm using the revisioning module to handle the status of nodes. As far as the nodes go, they've been working perfect and the work flow is exactly what I want. However, I'm running into an issue when trying to construct a view.

What I'm able to do so far:

Create the view
Set the node type
Limit it to only nodes that have pending revisions

(I get the two nodes with pending revisions (an unpublished rev)

Get the nid of the node

Where I'm having issues:

I try to select the vid of the pending revision, but instead I get the vid of the currently published revision.

I'm not sure where to go. I've tried using "Type: Content" and "Type: Content revision" and get the exact same behavior. I've tried playing with Relationships and still get the same behavior, but I don't think a relationship touches what I need.

... This is incredibly irritating because I'm obviously getting the pending nodes that I want, I'm just not getting the vid for what's pending (which is what my filter uses to get those nodes in the first place) and instead getting it for what's published.

I can imagine there might be some headache because it's possible to have multiple pending revisions, in that case, I should see two lines for that one nid since nid and vid /should/ be unique.

Instead of views_php use something like this. Add it as a field - you just need a custom handler to call the revisioning function that returns the latest vid.

/*
* Implements hook_views_data_alter().
*/
function MYMODULE_views_data_alter(&$data) {
  $data['node_revision']['latest_revision'] = array(
    'title' => t('Latest revision'),
    'help' => t('Get the latest vid.'),
    'group' => t('Content revision'),
    'real field' => 'nid',
    'field' => array(
      'handler' => 'MYMODULE_field_handler_latest_revision',
      'click sortable' => TRUE,
    ),
  );
}

And the handler:

/**
 * Provide the latest revision number from the nid field.
 */
class MYMODULE_field_handler_latest_revision extends views_handler_field {

  // Return latest vid as the field value.
  public function render($values) {
    $value = $this->get_value($values);
    return revisioning_get_latest_revision_id($value);
  }
}

What I needed doesn't exist. I had to write something with views_php to get what I needed. What worked was heavily influenced by https://drupal.org/node/1081804.


How do I use $form_state['storage']['my_key']? The question is clear from the title itself .

I looked in the api specified in :  https://www.drupal.org/node/2310411 .

But it only mention to convert

$storage = &$form_state['storage'];
$form_state['storage'] = &$storage;

to

 $storage = &$form_state->getStorage();
 $form_state->setStorage($storage);

But not a key in the $form_state['storage'] ? any help is appreciated .

The example in the documentation link seemed to cause confusion.  Simply set your values in an associative array and use set/get storage.

$vals = [
  'name' => 'bob',
  'age' => 50
];

// save the data.
$form_state->setStorage($vals);

// retrieve the data
$vals = $form_state->getStorage();
$str = $vals['name'] . ' is ' . $vals['age'] . ' years old.';

https://www.cyberdev.co/how-to-store-temp-form-state-data

The example uses the reference. It's okay if you do not need one. So

$storage = $form_state->getStorage();
$form_state->setStorage($storage);

also working.


Hide an entire View Block when query returns no data I have a view block and - because of the filters being applied - it may show data or may not. If the view's query returns no results, I need to hide the entire block - the .block - not just the .view or .view-content. I've seen several other questions and pages that offer solutions but all either don't hide the entire .block or just flat out don't work.

The solution that appears to be most discussed uses the Global: Null contextual filter, but that always hides the entire block regardless of any other condition. In fact, it doesn't even run the query when this filter is active. I need the block to be hidden if and only if the query returns no results.

I have the default, barebones Drupal 7 installed with only Bartik, CTools and Views so I am sure there aren't any other conflicts coming in from the theme or other modules.

One of the solution is:

Under FIELDS: click each field and in the "No results text" area, check the "hide if empty" box.

This will allow the field not to show if there is nothing actually there to show. But will not affect how the block itself displays on the page.

Another solution for this is :

  Go to the advanced tab of you view
  Add contextual filters
  Select Global: Null
  When the filter value is NOT available: Select 'Hide view'


How to restrict user posting a node in certain circumstances I've created a new user role (country_admin) and I have created a field for these users called user_country. This can be set when registering a user to UK or USA.

I have created a taxonomy 'Countries' and have added UK and USA as terms. I have also created a term reference on my articles so that articles can be assigned to a country.

The functionality I require is that only the user who has UK in the user_country field can post an article with the term set to UK.

I am looking at hook_node_access_records() and hook_node_grants() and have got the functionality working so UK users can only VIEW or UPDATE UK articles using this, however, in hook_node_grants() there doesn't seem to be an "ADD" operation.

How would I do this?

Current hook_node_grants() below

/**
* Implements hook_node_grants().
*/
function curator_scraper_node_grants($account, $op) {
    if ($op == 'view') {
        if (array_key_exists(DRUPAL_AUTHENTICATED_RID, $account->roles)) {

            //Let's get the country id the user is linked with
            $uid = $account->uid;
            $user = user_load($uid);
            $country = $user->field_user_country['und'][0];

            $grants[MYMODULE_REALM] = array(
                MYMODULE_GRANT_ID_PUBLIC, // Allow public data
                $country, // this should be users' country link
            );
        }
        else {
            // this is an anonymous user, give them the 'public' grant ID
            // that allows them access to public nodes
            $grants[MYMODULE_REALM] = array(
                MYMODULE_GRANT_ID_PUBLIC,
            );
        }
    }
    if ($op == 'update'){
        //We can grant update permissions here similar to the above
        // but where is $op == "add"???
    }
    return $grants;

}

You can use the Node access user reference module:

  Gives content access permissions to users for content that references
  the users with User reference or Entity reference.

  This is great if you want your content authors to be able to choose
  additional authors, or choose who can view their content, as well as
  being able to display the list of authors or viewers within your
  content, or in views displays.


How do you set up ubercart to filter/sort by price I'm new to Ubercart and just set-up a simple shop (Using Drupal 7 and Ubercart 7.x-3). In the default uc_catalog (table) view you are able to sort by product title.

When going to format -> table settings, there is an option to allow the title field to be sortable, but there is no such option for price. Is there a solution to allow the products in the table to be sorted by price?

I've tried adding a price to the sort criteria but the sort filter doesn't work.

Any help or pointer would be appreciated.

Use Ubercart advanced catalog. Very useful views. Here is a quote about it (from the module's project page):

... add custom filters on Ubercart catalog and provide taxonomy, products attributes (select) and CCK (option widget) support.
Filters are fully configurable. Product display is fully configurable with Display suite and Node display.

I use Drupal 7 and uc_catalog is not upgraded for this edition. So, you can also use a view and sort by price, reference, title, etc... everything you want.


Permission to edit orders, but not delete The title is mostly self-explanatory: I need a user to have permission to edit an order, but not be allowed to delete it. I don't think the currently defined permissions for orders allow this.
Am I wrong? Is there a workaround/extra module/hackneyed solution you can think of?

Here's the proper way to do it with

hook_commerce_entity_access

  Allows modules to deny or provide access for a user to perform a
  non-view operation on an entity before any other access check occurs.

  Modules implementing this hook can return FALSE to provide a blanket
  prevention for the user to perform the requested operation on the
  specified entity. If no modules implementing this hook return FALSE
  but at least one returns TRUE, then the operation will be allowed,
  even for a user without role based permission to perform the
  operation.

  If no modules return FALSE but none return TRUE either, normal
  permission based checking will apply.

Example

/**
 * Implements hook_commerce_entity_access
 */
function MODULE_commerce_entity_access($op, $entity, $account, $entity_type) {
  if ($entity_type == 'commerce_order' && $op == 'delete') {
    // Require administer orders permission to delete orders
    if (!user_access('administer commerce_order entities', $account)) {
      return FALSE;
    }
  }
}

In the end I settled on the worst kind of solution. I added a little jquery script that selects the "Delete" link (Drupal commerce helpfully gives it its own css class) and hides it. It's stupid, but the customer is happy.


Add classes to form select option item How can I add classes to a form option tag without JS?  At the moment in Form API I can pass a keyed array like this

array(
  '0' => 'option 0',
  '1' => 'option 1',
)

and I'll get html like this

<option value="0">option 0</option>
<option value="1">option 1</option>

Is there a way to do something like this:

array(
  array(
    'value' => 0,
    'text' => 'option 0',
    'class' => 'bob 0',
  ),
  array(
    'value' => 1,
    'text' => 'option 1',
    'class' => 'bob 1',
  ),
)

and then get this

<option value="0" class="bob 0">option 0</option>
<option value="1" class="bob 1">option 1</option>

Unfortunately this isn't very easy using the Form API currently.

There's an issue open to add this functionality (it goes all the way back to 2008) that would theoretically allow you to do something like this:

$form['optiontest'] = array(
  '#type' => 'select',
  '#title' => t('Option test'),
  '#options' => array(
    array(
      '#return_value' => 0,
      '#value' => t('First option'),
      '#attributes' => array('class' => 'first', 'title' => t('First option')),
    ),
    array(
      '#value' => t('Option group'),
      '#attributes' => array('class' => 'group', 'title' => t('This is an optgroup')),
      '#options' => array(
        array('#return_value' => 2, '#value' => t('1st sub-option')),
        array('#return_value' => 4, '#value' => t('2nd sub-option')),
      ),
    ),
  ),
);

But unfortunately there are nothing but failed patches attached to the issue at the moment.

The only way I can think of to do it at the moment would be to add a #process function to the select element, and add the class(es) to each option when they're broken down individually.

There is actually a way to override individual option items, but it works with checkboxes and radios. I've been told that it doesn't work with SELECT though. Also, I'm not sure if it works in Drupal 7.
Here's some code that works in Drupal 8. Might be worth a try.
$form['select'] = [
  '#type' => 'select',
  '#title' => t('Select'),
  '#options' => [
    '0' => t('Bob 0'),
    '1' => t('Bob 1'),
  ],
  // You define attributes for individual options as follows.
  '0' => [
    // I have tried 'disabled' = TRUE and it works.
    'disabled' => TRUE,
    // I have never tried #attributes, but I think it should work.
    '#attributes' => [
      'class' => ['bob-0'],
    ],
  ]
]

I hope it helps. Cheers! Alternatively, go for one of the other solutions.


How to delete a Feature? I created a feature module in site-1.

Then I instaled the feature module in site-2. This features creates a new content type and enable a module. Then I got the new content type and the module enabled.

So far so good.

Now I disabled and uninstall de feature module(drush). I expected the content type to be deleted and the module to be disabled, I mean the content type and the module that the feature created.

But they are still there...

How do I disable a feature and remove all the things that the feature created?

UPDATE: Steps I did to disable the feature:

1) drush dis myFeatureModule

2) drush pm-uninstall myFeatureModule

3) in admin/structure/features the feature myFeatureModuleis disabled

4) The delete button for the content type (created by this feature) in admin/structure/types is missing...

The first thing you will want to do is disable (and uninstall) the feature module.  That doesn't always remove everything the module initially created.  Once that feature module is uninstalled however you can go in and manually delete the content type and anything else that was left on the site.

Some additional detail can be found at this other question.  It provides an example of how the feature module can add an uninstall hook to unlock the content type. Looking at the query used in that example you should be able to run the query manually and unlock the offending content type.

After you disable your feature, you should be able to go to:

sites > all > modules > custom > features

Find your module in there and just delete the files.


Showing user image for custom comments created in a view I am using a Drupal view for displaying comments.

I have the show: in the format field set to comments.
Therefore I won't be able to add extra fields in the field's section.

I have a custom URL where I show the contents of a node along with its comments and a comment box which I have custom coded.

How can I add a user image along with my comments?

Try adding a "Relationship" to the comment author, and then add the user picture from the updated field list.


.info file is not loading the JavaScript code I added the references to some JavaScript files, in my .info file, hoping that they would be output by the $scripts variable in my header. I cleared the cache, and they are still not there.

$Id$
name = site
base theme = boron
core = 6.x
engine = phptemplate
; We do not have a Left sidebar.
;regions[left] = Left sidebar
; We do not have a right sidebar.
;regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer
scripts[] = sitename/sites/all/themes/custom/jivamukti/js/jquery.nivo.slider.pack.js
scripts[] = sitename/sites/all/themes/custom/jivamukti/js/scripts/jquery-1.6.1.min.js

I put the JavaScript in the root of the themes folder I am using, instead of /js, and now it is output in this function in my header:

jQuery.extend(Drupal.settings,…);

How do I just get it to display inside the <script></script> tags?

The file path should be relative to the theme directory not the root directory; try it with js/jquery.nivo.slider.pack.js instead of sitename/sites/all/themes/custom/jivamukti/js/jquery.nivo.slider.pack.js.

Go to "Administrator > Site building > Themes"; select the theme, save again, and refresh.


How to display jQuery UI dialog in submit button's onclick and prevent form submission? I'm using Drupal 7 and jQuery Update module set to jQuery version 1.8. I have a form. In it's definition I have:

$form['#attached']['library'] = array(
  array('system', 'ui.dialog'),
  array('aat_pc_product', 'product_form'),
);

In the behavior, I use:

if(!isFormValid) {
  $('<div>' + Drupal.t('Some fields was left blank even when not disabled. Either check "skip line" or fill missing data.') + '</div>').dialog({ modal: true });
}

return isFormValid;

Now, with good old alert it worked great. But when I try do use dialog, in chrome in my console I get:

  Uncaught TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'curCSS' jquery.ui.position.min.js?v=1.8.7:13

In FireFox it fails in similar way:

  TypeError: c.curCSS is not a function
  ...his,"marginTop",true))||0,v=l+p+parseInt(c.curCSS(this,"marginRight",true))||0,w...
  jquery...v=1.8.7 (row 13)

Updating to dev version of jQuery Update and seelcting jQuery 1.9 or 1.10 does not help - it does not complain about curCSS, but about lack of $.browser() that was removed in jQuery 1.9, and deprecated long ago.

My question is: Am I doing something wrong, or it's a bug between jQuery Update and Drupal? And if it's a bug, is there any version of jQuery update without it?

Is there a way to update jQuery UI to make it match jQuery, without hacking jQuery Update module or updating directly in D:\UniServer\www\misc\ui ?

when c.curCSS is not a function error occures ,just do the following
if any two js included check and remove .. after add this into script

jQuery.curCSS = jQuery.css;


CSS not work after ajax replace I  have found that when I replace forms with AJAX, then the new forms loose their display styling. It seems like the css for the forms are not working any more.

How to solve this issue?
Do i have to write js bind with .on() function to add css again? Any other suggesions?

In some cases it can depend on how and where you have added your CSS to the page.

The best way to do it is using #attached on your field via hook_form_alter() or similar.

If your CSS is already on the page though it should work on new elements added with ajax.

One possible cause is that your CSS selectors are too specific and the ID/class used isn't matching properly with the markup added by the ajax.

Yes, any event handlers that were attached will be disconnected when content is replaced by AJAX. You can use jQuery's .on() or .live() as alternative event hooks to prevent this.


View poll *results* as anonymous user doesn't allow access Has anyone come across this problem before? When an anonymous user tries to view the current poll results (from the current poll block) they get an ACCESS DENIED error. However, if they view the poll (not the results) they can see it just fine.

For example:

http://cypress.supportedns.com/~actionin/node/11/results
(Access denied)

http://cypress.supportedns.com/~actionin/node/11/
(No problem)

In the permissions administrative page, I gave the Anonymous User access to view results, so I'm not sure what's going on. Any ideas? Thanks in advance.

Stumbled upon the same problem when I wanted to redirect some anonymous users to see only the results of a poll depending on what email address pattern they entered in a form before. So I thought sending them to node/%nid/results would be fine and somehow it also worked AS LONG AS for testing purpose I didn't vote before (as other anonymous user with allowed email address pattern). Then the IP got stored somehow and when accessing the poll node you automatically get the results view presented WHILE AT THE SAME TIME the node/%nid/results URL gets unavailable.

I dont know the problem but when I check this url
I get the results

so you can use hook menu alter to change permission


Show image filenames on Drupal 7 node I upload multiple images to a node using one content type image field. I need to render the file name for each image under the image when viewing the node, all I get at the moment is just a page of images. Tried a view but that REALLY screws everything up. Any ideas how this can be done on the node?

Thanks.

You can do this using hook_preprocess_node() either in your theme's template.php file, or a custom module file. You'll want to use API functions to get the data from the node rather than accessing the arrays directly, so you don't need to worry about language codes etc.

function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  if ($node->type == 'the_type' && $vars['view_mode'] == 'full') {
    $field_items = field_get_items('node', $node, 'field_name');

    if (!empty($field_items)) {
      $filenames = array();
      foreach ($field_items as $item) {
        $filenames[] = $item['filename'];
      }

      $vars['filenames'] = theme('item_list', array('items' => $filenames));
    }
  }
}

You can obviously change the output to whatever HTML you need, but the above will produce an unordered list of image filenames, available in the $filenames variable in your node.tpl.php file.

in templete.php file create

    function THEMENAME_preprocess_node(&$vars){
       dpm($vars)//find image name etc with devel module enabled
       //for example i have field - field_image first element is 0 and filename is = file_name
       $vars['image_name'] = $vars['field_image'][0]['file_name']; //i have created a new variable
  //  $image_name, now u can out this variable in your tpl file
    }

output them
in your *.tpl.php file  do this

<?php print render($image_name) ?>

you can actually put them into array and foreach


node_save does not save language I cannot programmatically create a node in anything other than en language.

My site has 3 languages:

en
fr
de

And the code for creating a node is:

define('DRUPAL_ROOT', ...);
require_once DRUPAL_ROOT . 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$node = new stdClass();
$node->type = "foobar";
node_object_prepare($node);
$node->title = 'test title';
$node->uid = 1;
$node->language = 'fr'; // *** this doesn't seem to work

if ($node = node_submit($node)) {
  node_save($node);
}

No matter what I type in the $node->language = '...'; the result is always the same. The node is created in the English language. I confirm that via looking at admin/content.

I've even tried stuffing this variable with a proper language object which I got out of the enabled languages of my site:

$languages = language_list('enabled');
$lang = $languages[1]['de'];
$node->language = $lang;

The behavior was an unfortunate side-effect of the admin_language module and the setting Force use of default language.

The "offending" code is at http://drupalcode.org/project/admin_language.git/blob/0167e36c45661502ee6907a5b2b7cad8538b19cf:/admin_language.module#l112

Disabling this options solves the issue.

Some of the hooks might not be firing, instead of node_save($node), try drupal_execute($form_id, $form_state)

That last link was bad... lullabot's should help:

http://www.lullabot.com/articles/quick-and-dirty-cck-imports

doh... drupal 7. Looks like they have changed it to drupal_form_submit

http://www.lukaswhite.com/blog/post/2011/drupal-7-drupal_execute-has-gone-say-hello-to-drupal_form_submit


After submission of a webform block how to replace that webform block with thank you message in the same page? I have created a webform block and assigned to a page in the right sidebar. After successful submission of that block, I want the thank you message with the values submitted in the webform to displayed where block was there before in the same page.

I have given no-redirect option in the form settings of the webform.

Also in the block settings  of the webform block given view mode as form only.

But how would I replace the webform block with thank you message on successful submission of webform in the same page? Is there any Drupal way to achieve this. Have I missed any settings ??

Any help will be much appreciated.Thanks in advance.

If you have the webform set as a block, you can go to admin > structure > block. Look for your webform block. It should be named something like Webform: 'name of webform node'. Click on the configure link to the right. When the edit form for the block loads, look for the section Confirmation message. Select the option Display the confirmation page in the block on the same page (no redirect). Now when you submit the form from the block, it will redirect back to it and show the confirmation message on reload.

You may need to fill out a message in the webform settings. I have attached an image of the edit block page for you to compare.

Goto your Webform Form Setting & add your Confirmation message.

Confirmation message : Put your message in this field.

Redirection location : Check "Confirmation Page"


Sort nodes based on the amount of tags that match a specific node tags Is there anyway to sort the nodes on a views display using the amount of matching tags of a specif node? I would like to have a views display that shows me all the nodes that most match with a given node.

For example: I have one node with three terms associated with it and I'll pass this node to a views as an argument. The views should display first the nodes that have this same three terms, after that it should display the nodes which match with two of the three terms, after that the nodes that match one of the three terms and after that the nodes that doesn't match any of the three terms.

I couldn't find something that could solve this problem for me. If there isn't any implemented solution I'd like to know if it's feasible to implement this on Drupal 7.

Check out Similar by Terms module. This Drupal module attempts to provide context for content items by displaying a block with links to other similar content. Similarity is based on the taxonomy terms assigned to content. Blocks are available based on similarity within each of the defined vocabularies for a site as well as a block for similarity within all vocabularies. There are two methods of sorting. 1) Based on the most number of matching terms. 2) Based on lest used terms.

Or you could use the Relevant Content module. This module provides two ways of referencing relevant content. Both of these methods provide configuration to filter for specific content types and vocabularies, limit the maximum size of the result and provide some header text. The result on both cases are a list of nodes which the module considers most relevant based on the categorization of the current page. This is achieved by finding other nodes which are of one of the allowed types and have the most number of terms in common.

I don't know if have a specific module to use, but I have two options, you can use query_alter to change the arguments, but I guess that you will need to execute the views other times to get the other results. Another option is execute a specific query to get a list of nids ordered by the sum of matching terms.


How to create a union of two views? I'm trying to get a union of a user's nodes and comments sorted by "post date".
This post links to sandbox projects for D6 but there is nothing for 7.

This post has an example of using hook_views_pre_execute() and a SQL UNION in D6. This doesn't work for D7 with views 3.

I came across merlinofchaos' comment

  Because we're now using Drupal's new query generator, the query is a SelectQuery object which you will have to modify or replace. Look up Drupal 7's new database layer for more information.

Does anyone have an example of how to do this or any other solution to combine two views?

Here's a working and tested example:

/**
 * Implements hook_views_pre_execute().
 */
function mymodule_views_pre_execute(view &$view) {
  if ($view->name == 'my_view') {
    $query1 = &$view->build_info['query'];

    // Basic setup of the second query.
    $query2 = db_select('another_table', 'at')
      ->condition('some_field', 0, '>')
      ->condition('some_other_field', 12345);

    // The number of fields (and their aliases) must match query1.
    // Get the details with:
    // dpm($query1->getFields());
    $query2->addField('at', 'some_field', 'alias1');
    $query2->addField('at', 'some_other_field', 'alias2');
    $query2->addField('at', 'some_other_field2', 'alias3');
    $query2->addField('at', 'some_other_field3', 'alias4');

    // Verify that queries are very similar.
    // dpq($query1);
    // dpq($query2);

    // Matrimony.
    $query1 = $query2->union($query1, 'UNION ALL');

    // Manual test.
    // dpm($query1->execute()->fetchAll());

  }
}

This works for most views.  However some style plugins may do fancy stuff that won't work with this technique (Calendar module I'm looking at you).

Used Global: PHP fields?  You can use them to duct tape together a View that combines the two.

Create a View of content with Content: Title and Content: Comments fields (Excluded from display).

Add a PHP field that calculates which is more recent, the date last updated, or the date of the last comment by the user, and set the field's value to be that date.  Add that field as a sort condition.

Add a similar field that outputs either a link to the comment or to the node.

It sounds good to me!


Duplicating drupal site without login info I'm a new Drupal user.

Someone gave me a backup of their Drupal and .mysql content.  I more or less followed these instructions: http://www.ostraining.com/blog/drupal/drupal-migrate/, except the site already had it's own settings.php, and so the site is now up and running.

The problem that I'm having now is that I can't log into the site to make any edits because I don't have a login.  I tried to create an active user in phpmyadmin with an md5 hash password, and changed the user to an administrator.  However I'm still not successfully logging in, the site says I'm still giving it the incorrect login info.  When I try to recover/reset my password by email I am not receiving any emails.  I am using Windows XP.

Is there any way I will be able to login to edit the site?

One way of solving your issue would be to update super admin (first user) password pragmatically, by creating a temporary php file under Drupal root folder and add the following code to it then access it from a browser.

<?php

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// load super admin user
$account = user_load(1);

// save user password
user_save($account, array('pass' => 'admin'));

echo "Super admin password has been changed";

Make sure to replace admin with desired password

drupal's admin uid is 1

in you phpmyadmin sql or mysql shell

view query to check admin record:
select * from users where uid=1;

update query:
UPDATE users SET pass = MD5('test') WHERE uid=1;


Is Migrate module supposed to be used for imports too? I am in need of an entity import functionality so I started to write my own. But then I started to think if I'm not reinventing the wheel and it occurred to me that maybe Migrate module will be used for this(beside it's main purpose)?

I mean, since all entity fields are objects with their own specifications regarding data they work with, Migrate will probably handle all of this. So am I correct to assume this or should I continue to work on my module? Because right now I started to think about the field objects(FieldDefinition for core fields and FieldInstanceConfig for field API fields) and I would need to write a lot of data handlers for each type of field and data-type it's working with(boolean, text, file/image, float,...) which will be a lot of work.

On the other hand Migrate would probably have all this data-handlers already in place so they could be reused?

By entity import I mean creating data from csv, xls, xml... files.

Of course! That's why we split migrate_drupal and migrate. The latter is the API, it has the destinations, like the entities you are asking for. Handbook page is at https://drupal.org/node/2127611 useful article at http://webikon.com/cases/migrating-to-drupal-8

Also github.com/larowlan/default_content for module provided entities


Add View To page.tpl I hope that you could help me out with this. After much time ive finally managed to work out how to takeover the space that my breadcrumb was taking up. With this bit of space i thought about adding a banner in there or a welcome message. I dont want my site to look 'tatty' so the banner idea was soon forgotten. A welcome message would be nice but it will be going through all my site and im sure that folks will get a bit sick of it.

I was hoping to add a View of random quotes in there. You can see the 'spot' i mean on my frontpage here-
http://onlinebanter.com/

As i type this though i'm a wondering if i could make that spot a block region? Then i could have a welcome message on the frontpage and then use it as a region to add helpfull advice for differant sections of my site. also i could add a random quote view for within nodes etc.

Could anyone offer me advice on either adding a view to a page.tpl or creating a block region in the wee spot ive found?

All help appreciated.

thanks

You can open your theme's .info file and add regions[my_region] = My region. Now open your page.tpl.php and do print $my_region (the name of the variable corresponds to the regions array index - see the first sentence) where the region should be rendered. After this make sure to clear your Drupal's cache so that it picks up the new region and the modified page.tpl.php.

Views can generate block displays. After you created the block display, you can use the Drupal's default blocks interface to put the Views block into the region you created, or better yet use a module like: Context which gives you more control over when to show which blocks in what region and when not to...

If you go for the view block directly in the template, you can use views_embed_view('yourview', 'yourblockdisplay') in your block's block--id-of-block.tpl.php (name depends on your drupal version).

If you want to create a region (which is probably overkill here), you have to add it to your theme.info in this form regions[quotes_region] = Region name and add the relevant variable in yourtheme_preprocess_block, then add the block to the region.


List items of a certain content type in another content type For college we have to create a website with drupal. This website has to be for a travel agency that does surf vacations. We already have the  basic website up and running but are kinda stuck with the destinations.

I will quickly explain how the website should be set up and our problem.

So bassicly a customer should be able to go to the page called "Destinations" and have a list of the 4 available countries where they could book a vacation. Like for example you have Australia and Costa Rica. However when a user clicks on for example Australia he should get a new list of possible locations within this country where he wants to go surf.

We have tried with many different ways to get this to work the problem however is that both the countries and local destinations should have a picture and a short description. Also the user should be able to select their "level" on the specific location.

What we have tried:

Taxonomy: We have tried using taxonomy but it doesn't allow us to give the right design to the website. It will list the countries but without any description or picture.

Ubercart: I wish this would have worked but somehow you can't create subclasses in ubercart or just only show a list of classes with views.

Thank you for taking your time and we hope to find a solution soon.

Kind regards.

A general out line is given below,

Create a content type for country, add your available
countries with images and description
Create a destination content type, with necessary fields like
image,description etc: (If you want process booking with payment, use
Ubercart and create a product class Destination, modify the required
fields)
Add a country field to destination contenttype of 'fieldtype' - Node Reference, choose widget as select list. This allows choose country on creation of a new destination
Use Views to list the destinations page, by selecting necessary fields,
Use views to create the list of related destinations based on the
country name and save it as a block. So based on the country
selection the destinations can be list in this block
If you are using online payment for booking use ubercart, otherwise
on booking you can send an enquiry to admin.

Hope you got an idea on how to proceed.

UPDATE
To get list of the destinations on clicking the country do the following

In your destination listing view, Add a 'Contextual filters'(
Arguments in D6) and choose the 'country nodereference field'.
In your four country listing view, in fields choose Nid (Nid)  also
and choose 'Exclude from display ' option for that field.
Then in the 'Country name field' - click 'Rewrite results' and choose
'Output this field as a link' checkbox. In link path give path like
below
eg: destinations/[nid]  ie: where destinations is the path of the
your destination page and [nid] is the token for the node id.
Probably you have to just change 'destinations' only with your path.

Thats it, now on clicking the country it will goto destinations page which shows all destinations belongs to the particular country

If you want a ajax work it should be done by your own code.

If you don't care about load new pages then you can try with views.

Is this a drupal 6 project?

Oscar?


Getting 443 Forbidden Error on my custom module I am learning drupal 8 and creating my own custom module. I have a clean localhost installation and was following some tutorials online to create a very basic "hello" for my first attempt.

The issue I am running into is when I attempt to go to my routing area, I get the following error:

Forbidden
You don't have permission to access /tag on this server.

Here is my code. Can someone tell me why this isn't working? If I followed the online tutorials right, I should have access.

tagnbag.info.yml file:

name: Tag N Bag
description: 'Create a custom grocery list.'
type: module
package: Custom
version: 1.0
core: 8.x

tagnbag.routing.yml:

tagnbag:
  path: '/tag'
  defaults:
    _controller: 'Drupal\tagnbag\Controller\TagBagController::welcome'
    _title: 'Hello Tag N Bag!'
    requirements:
      _permission: 'TRUE'

TagBagController.php:

<?php
/**
 * @file
 * Contains \Drupal\tagnbag\Controller\TagBagController.
 */

namespace Drupal\tagnbag\Controller;
use Drupal\Core\Controller\ControllerBase;

class TagBagController extends ControllerBase {
    public function welcome() {
        return array(
            '#type' => 'markup',
            '#markup' => 'Content for Tag N Bag.'
        );
    }
}

_permission: 'TRUE' is not a thing unless you've defined a custom permission TRUE (and if you did, I'd advise you to change that). What you have is looking to see if a user has the permission TRUE - which I doubt any user has, and correctly denying access. If you want to grant access to the route for everyone, in all contexts, use _access: 'TRUE'. See Structure of Routes on d.o for more info.

You missing \ in 'Drupal\tagnbag\Controller\TagBagController::welcome' change tagnbag.routing.yml  by:

tagnbag.tagnbag:
  path: '/tag'
  defaults:
    _controller: '\Drupal\tagnbag\Controller\TagBagController::welcome'
    _title: 'Hello Tag N Bag!'
  requirements:
    _access: 'TRUE'


Permission page broken All other pages are being loaded fine but when I go to permissions page it comes like this. What may be the reason for this ? Please help.

I had exactly the same problem few days ago.
Do you have the devel module install?

For me it was the problem, i can't explain why but when i desintalled it, all worked fine.

So maybe, try to desactivate and unistall it and maybe your page permission will work again.

PS: i just re-install the devel module to make a test and i have exatly the same permission page than you. For me it's the devel module the problem. (I'm new in Drupal so i had certainly make a mistake somewhere)

May be the permission listing makes the memory problem.You have to update the permission listing page to a simple one.

Try the Filter permissions module


how do I get the user ID other than the one for the current logged in user? How do I the user ID of the account profile that an administrator user is currently viewing/editin? I can't use \Drupal::currentUser() as it always returns the administrator details.

I tried \Drupal::routeMatch()->getParameter('node') and \Drupal::request()->attributes->get('node'), but it returns this error:

  Call to a member function id() on null...(file path)

Assuming that you're viewing a page at a path like /user/42, then you can use the RouteMatch class. Your example is close, but you need to change the parameter passed to the getParameter() method. The parameter in this case is named 'user' not 'node'. You can determine the parameter name from the route definition. Not all routes have parameters, but when they do, they are specific to the route in question.

In this case the route (entity.user.canonical) is defined by \Drupal\user\Entity\UserRouteProvider::getRoutes. And the 'user' parameter is the UID of the user entity in question. Given that, you can use RouteMatch to get the ID in one of two ways.

Load the $user object specified by the user parameter. Which is probably more common. I'm guessing if you're trying to get the UID it's so you can load the user object. With this method parameters are processed by the parameter conversion system, which does operations such as converting entity ID parameters to fully-loaded entities

$user = \Drupal::routeMatch()->getParameter('user');
$uid = $user->id();

Or access the parameter value directly:

$uid = \Drupal::routeMatch()->getRawParameter('user');

This change record provides a bit more information https://www.drupal.org/node/2295317

If you are talking about in the admin section, as in /user/42 - the user ID is the last fragment of the URL - take a look at drupal_parse_url to break your URL into components.

Once you know what the user id is (42 in the case above), you can use user_load function to load the profile of user 42


Boost + Domain Access + flushing cache I have the Boost and Domain Access modules working correctly. But I've found that if the cache is flushed for one domain it doesn't clear for the others. So if content is added to one, it won't show for others until cron has been run.

Any way to fix this at all?

Saw your post on d.o.: https://www.drupal.org/project/domain/issues/1673650
The suggested fix looks good and should still run:
function MODULENAME_domain_cron($domain) {
  global $base_root;
  if (isset($domain['path'])) {
    $base_root = $domain['path'];
  }
  boost_cron();
}

The error you have there seems strange. The argument should be passed to the hook_domain_cron method ?!?
UPDATE: You still can try to make the argument optional:
function MODULENAME_domain_cron($domain=[])

But I would debug that to find out the real reason ..
How does your code look for mymodule_hook_domain_cron?

I would use use Elysia Cron module.

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

That way I could leave regular CRON jobs just like they are (or tune them, but this is out of the scope of this question).

I would then set up Boost cron job to run every 5 minutes. There are 2 advantages to that:

You avoid heavy IO hit on your HDD, spreading it all over the day
Your original problem is pretty much solved - 5 minutes cache lag is something you probably can work with all right.


How can I use my table for Views 3 sort criteria? I am trying to create a special sort criterium.
I have a table with 2 cols: nid, and count.

How can I use this table to sort the view by count?

You can let Views know about your data using hook_views_data.

The function documentation itself contains all the information you need to use the data for sorting and other Views functions, so I'm not repeating them here.

You need to create a module and implement hook_views_query_alter()

Check this for details.


How do I use a field summary in a view? I'd like to make a Drupal 7 view which displays nodes using the following behavior:

1) Show the body summary if it is populated.
2) Never show a trimmed version of anything.
3) If the body summary is empty, show the actual body.
4) If the body summary is not empty, display a "read more" link.
5) If the full body was displayed, don't display a "read more" link.

I've got this entirely working using a separate field for the summary (which may be what I end up with) but I'd hoped to use the body summary instead.  As far as I can tell the only way to access the body summary in a view is to use the "summary or trimmed" formatter in the field display, which violates #2.

I looked for modules, and all I found was "Smart Trim" which appears to do the opposite of what I want.

Suggestions?

I think this is a good example for using custom formatters.

I Recommend you to use the custom formatters module as you cant get a fast result, but if you think this is useful, you should check the Field Formatter API to make more complex sollutions.

Install the module, and import this example:

$formatter = new stdClass();
$formatter->disabled = FALSE; /* Edit this to true to make a default formatter disabled initially */
$formatter->api_version = 2;
$formatter->name = 'test_body';
$formatter->label = 'test body';
$formatter->description = '';
$formatter->mode = 'php';
$formatter->field_types = 'text_with_summary';
$formatter->code = '$output = "";
foreach ($variables[\'#items\'] as $item) {
  if ( $item[\'summary\']) {
    $output = $item[\'summary\'];
  }else{
     $output = $item[\'value\'];
  }
}
return $output;';
$formatter->fapi = '';

it doesn't do all the job, but i think it can be enough for you to complete it.

Then go to your view and select the formatter for the body field.

The easiest way is to add the field, select "Rewrite results" and add the token [body-summary]


Taxonomy hierarchy in filter block of views isotope? How can I set the filter block to show a hierarchical taxonomy? As far as I can see there is only a flat list being built by default. How can I change this and apply the hierarchy of a taxonomy?

This is the link of the module, of course do not answer if you do not know what is views isotope Module.

First, I'm confused about what you mean by views isotope?

But if you're asking to build a hierarchical taxonomy in view select, there's Simple hierarchical select module.

  Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Try the Views Term Hierarchy Weight Field module

  This module allows you to display, filter or sort terms according to their hierarchical order or hierarchical depth.


How can I programmatically create products via REST? I have a module of rest service api, that is used to receive users upload products. Here is my code...

function commerce_services_product_create($data, $flatten_fields) {
    $status =1;
    $commerce_price = array();

    $sku = $data['sku'];
    $title = $data['title'];
    $type = $data['type'];
    $commerce_price = $data['commerce_price'];
    $price = $commerce_price['amount'];

    $cp = commerce_product_new('product');
    $cp->uid = 1;
    $cp->sku = $sku;
    $cp->title = $title;
    $cp->language = LANGUAGE_NONE;

    $cp->commerce_price = array(
        LANGUAGE_NONE => array(
            0 => array(
                'amount' => $price ,
                'currency_code' => 'MMK',
     )));

    // for store
    $cp -> cmp_store = array(LANGUAGE_NONE => $data["cmp_store"]);
    // for category
    $cp->field_category[LANGUAGE_NONE][0]['value'] = 137;

    try{
        commerce_product_save($cp);
        $result = "success!";
    }catch(Exception $ex){
        $result = "not success!, error -> ". $ex;
    }
}

When I pass the following json string to the function, this function create a product but not include cmp_store, mean cmp_store is null.

{
  "sku": "saa_prduct120",
  "title": "saa_prduct",
  "type": "product",
  "commerce_price": {
    "amount": "150000",
    "currency_code": "USD"
  },
 "cmp_store": 2
}

And when I check store drop down button with themer info module, it shows #name as like this, "field_product[und][form][cmp_store][und]".

Above my code I use this code for adding store, mean when users upload their product, they have to choose store. User choose store is passed by json.

 // for adding store
 $cp -> cmp_store = array(LANGUAGE_NONE => $data["cmp_store"]);

And I also try like this,

$new_product ->field_data_cmp_store[LANGUAGE_NONE]['cmp_store']['und'] = $data["cmp_store"];
$new_product -> field_product[cmp_store][und] = $data["cmp_store"];
$new_product -> cmp_store = $data["cmp_store"];
$form_state['values']['cmp_store']['und'] =   $data["cmp_store"];

not ok yet!

This might need to work around as below

['field_store']['und']['#options'] = Store_array


How to take a site offline using Drush? How can I take a site offline using Drush?

Drupal 8: drush sset system.maintenance_mode TRUE

Drupal 7: drush vset maintenance_mode 1

Drupal 6: drush vset site_offline 1

This is controlled by a variable, site_offline.

$ drush vset --always-set site_offline 1

You could also set the offline message this way.

$ drush vset --always-set site_offline_message 'Please try again later!'