Why isn't my integer value processed correctly with PHP in Rules? My articles have a field collection field and one of the fields is an integer. Users can add as many fields as they want. I'd like to reward them some userpoints, equal to the total value in their saved fields, but with an overall maximum of 5.

e.g. A user saves a first field with a value of 3. Therefore, he's awarded 3 points. When he saves another field with a value of 4 afterwards, he must be rewarded 5-3=2 points.

I wrote a rule that sums all the old and new values in the integer fields via a loop (the results are saved as variables 'Old total' and 'New total') when a new field collection is saved. Before I can grant userpoints to the user, I have to do some calculations to prevent the total amount of earned points to be larger than 5. I tried doing that by adding the following PHP code in the 'Process value' box of a 'Grant points to user' action:

if (old-total > 5) {$value = 0;}
elseif (new-total > 5) {$value = 5 - old-total;}
else {$value = [field-collection-item:field-my-integer];}
return $value;

However, when the action runs, the code seems to be ignored, because the value doesn't change at all. I don't get any errors.

What did I do wrong? How can I solve this?

I was able to solve this problem after finding the answer on my question 'How to use variables in a PHP evaluation in a rule?'.

Instead of activating the Rule when an event "After saving a new field collection item" occured, rather use "After updating existing content" and grant the Userpoints for the first Field Collection item in a different Rule. Afterwards, follow the instructions in the referenced answer and use the code underneath.

<?php
if ($old_total > 5) {return 0;}
elseif ($new_total > 5) {return 5 - $old_total;}
elseif ($new_total == $old_total) {return 0;}
else {return $new_total;}
?>


In sent message, the user name is not displaying I am using the Privatemsg module, version 6.x-1.x.

If my username is "TEST" and I am sending the email to myself, the sent messages doesn't show "TEST." The "From" field is empty.

If I send the email to other users their names is displaying fine.

What is the reason of this, and what should I do to display my name there?

This is currently working as designed. The message listings do not show your own username as you obviously are a recipient as it is displayed for you. It is however a limitation of the current system that when you send a message to yourself, no recipient is shown.

You can alter the sql query and remove the exclusion of the current user for the sent list, but then it will always show the current user there.

There are some ideas on how to make the whole listings more flexible but that's quite a bit of work and needs time that I currently don't have.


Get path of Page Manager page Basically I have created a page and it shows up fine.

When I do a arg or current_path on that page it shows as a 404 path, not the one defined in the page.

current_path() => error-404
$_GET[q] => error-404
arg() => array(0 => error-404)

Is there a function that returns the path/URL that is set in the Page?

Node that current_path() returns the URL path of the current page, not the URL. So on the http://www.example.com/latest-deals page it will return just latest-deals.

If you need to convert that to an actual URL, use url(current_path()), which will return /latest-deals. Or url(current_path(), array('absolute' => TRUE)) if you need the absolute URL.


What's the alternative to using the Conditional Rules module? The Conditional Rules module allows for including Rules Conditions within Rules Actions (using its If/Else constructs), something you cannot do by only using the Rules module. Here are just a few (out of many) typical questions that can be solved by using Conditional Rules:

How to create a rule to assign roles to users based on some checkbox items in their profile?
How to use Rules to email users when any field(s) is changed in a node (and include the unchanged/changed values for that field)?

However, there are some issues with the Conditional Rules module, such as:

It does not have an official release for D7 yet.
There is not a lot of documentation about it (and no Community documentation).
There are some scenarios for which this module produces incorrect results.

Is there any alternative solution for building equivalent Rules logic, and which doesn't require using the Conditional Rules module?

For any custom rule where you are tempted to use the Conditional Rules module, you can always create corresponding Rules Components, with similar Rules Actions to be performed, but also with additional Rules Conditions equivalent to any Rules Conditions you'd want to include by using the Conditional Rules module. And then perform that Rules Component inside your Rules Actions of your original rule.

Consider this prototype-example (just assume it's a simplified version of a more complicated rule with preceding Rules Actions like "Fetch entity by ID", "Set a variable", etc):

{ "rules_show_a_message_using_conditional_rules" : {
    "LABEL" : "Show a message using Conditional Rules",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_delete--page" : { "bundle" : "page" } },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "node:promote" ], "value" : "1" } },
            "DO" : [
              { "drupal_message" : { "message" : "Bingo ... using \u0022Conditional Rules\u0022 ..." } }
            ]
          }
        ]
      }
    ]
  }
}

Here is its equivalent using Rules Components:

{ "rules_show_a_message_using_a_rules_component" : {
    "LABEL" : "Show a message using a Rules Component",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_delete--page" : { "bundle" : "page" } },
    "DO" : [ { "component_rules_say_bingo" : { "current_node" : [ "node" ] } } ]
  }
}

And the related Rules Component looks like so:

{ "rules_say_bingo" : {
    "LABEL" : "Say bingo",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "current_node" : { "label" : "Current node", "type" : "node" } },
    "IF" : [
      { "NOT data_is" : { "data" : [ "current-node:promote" ], "value" : "1" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Bingo ... using a Rules Component instead of \u0022Conditional Rules\u0022 ..." } }
    ]
  }
}

Some details about the alternative using a Rules Component:

The Rules Condition within the Conditional Rules construct, has become a Rules Condition of the Rules Component.
The actual Rules Action to be performed, was moved to a Rules Action of the Rules Component.
The original rule simply calls the Rules Component, thereby passing the node to be processed as a parameter of the Rules Component.
The Rules Event in the original rule is unchanged, and if there would have been any additional Rules Conditions in the original rule, those would have remained unchanged also.

Note: the above is just a "concept", to illustrate the key-part of the solution. Because this prototype did not require any previous "Fetch entity by ID" (or "Set a variable", or "load current user points") as a previous action.


Display entity images with thumbnails and 1 large image I want to attach multiple images to custom entity (commerce product),
and display them as follow: 1 large image, and list of thumbnails, user can click on thumbnail thus changing large image.

I found and plan to use the library http://www.elevateweb.co.uk/image-zoom/examples#gallery-lightbox

So my steps:

create subtheme of bootstrap theme
add field "images" to the commerce product entity
write twig file to display images

Is it correct path? or maybe there is better solution? better library?

With image zoom, I need to get output like this

<?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Field\FieldFormatter\SlickMyentityGalleryFormatter.
 */

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Html;

/**
 * @FieldFormatter(
 *   id = "slick_myentity_gallery",
 *   label = @Translation("Slick Myentity Gallery"),
 *   field_types = {
 *     "image"
 *   }
 * )
 */
class SlickMyentityGalleryFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'visible_slides' => 3,
      'image_style' => 'thumbnail',
      'arrows' => TRUE,
      'dots' => TRUE,
      'fade' => FALSE,
      'standalone_image' => TRUE,
      'standalone_location' => 'above',
      'standalone_style' => 'xlarge',
      'vertical' => FALSE,
      'lazy_load' => 'ondemand',
      'hide_single_navigator' => TRUE
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = parent::settingsForm($form, $form_state);
    $field_name = $this->fieldDefinition->getName();

    $image_style_entities = \Drupal::entityManager()
      ->getStorage('image_style')
      ->loadMultiple();

    $image_styles = array_map(function($image_style) {
      return $image_style->label();
    }, $image_style_entities);

    $image_styles = ['_original' => '- ' . $this->t('Original') . ' -'] + $image_styles;

    $element['visible_slides'] = [
      '#type' => 'number',
      '#title' => $this->t('Number of visible slides'),
      '#default_value' => $this->getSetting('visible_slides'),
      '#min' => 1,
      '#max' => 10,
      '#description' => $this->t('Number of images visible at once.')
    ];

    $element['image_style'] = [
      '#type' => 'select',
      '#title' => $this->t('Image style'),
      '#default_value' => $this->getSetting('image_style'),
      '#options' => $image_styles,
      '#description' => $this->t('Image style to display the images with.')
    ];

    $element['arrows'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Show arrows'),
      '#default_value' => $this->getSetting('arrows'),
      '#description' => $this->t('Display the navigation arrows.')
    ];

    $element['dots'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Paging'),
      '#default_value' => $this->getSetting('dots'),
      '#description' => $this->t('Display the paging dots.')
    ];

    $element['fade'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Fade'),
      '#default_value' => $this->getSetting('fade'),
      '#description' => $this->t('Fade between transitions.')
    ];

    $element['vertical'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Vertical slider'),
      '#default_value' => $this->getSetting('vertical'),
      '#description' => $this->t('Display slider vertically instead of horizontally.')
    ];

    $element['lazy_load'] = [
      '#type' => 'select',
      '#title' => $this->t('Lazy load'),
      '#options' => [
        'none' => '- ' . $this->t('None') . ' -',
        'ondemand' => $this->t('On demand'),
        'progressive' => $this->t('Progressive')
      ],
      '#default_value' => $this->getSetting('lazy_load'),
      '#description' => $this->t('Lazy load the images to increase page performance.')
    ];

    $element['standalone_image'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Standalone active image'),
      '#default_value' => $this->getSetting('standalone_image'),
      '#description' => $this->t('Display the active image separately.')
    ];

    $element['standalone_style'] = [
      '#type' => 'select',
      '#title' => $this->t('Standalone image style'),
      '#default_value' => $this->getSetting('standalone_style'),
      '#options' => $image_styles,
      '#description' => $this->t('Image style to display the standalone image with.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    $element['standalone_location'] = [
      '#type' => 'select',
      '#title' => $this->t('Standalone image location'),
      '#default_value' => $this->getSetting('standalone_location'),
      '#options' => [
        'above' => $this->t('Above'),
        'below' => $this->t('Below'),
        'left' => $this->t('Left'),
        'right' => $this->t('Right')
      ],
      '#description' => $this->t('Display slider vertically instead of horizontally.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    $element['hide_single_navigator'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Hide single item carousel'),
      '#default_value' => $this->getSetting('hide_single_navigator'),
      '#description' => $this->t('If standalone image is displayed and there is only one image, the carousel will be hidden.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = parent::settingsSummary();

    if ($this->getSetting('standalone_image')) {
      $standalone_style = $this->getSetting('standalone_style');
      if ($standalone_style == '_original') {
        $summary[] = $this->t('Display standalone image without image style.');
      } else {
        $style = \Drupal::entityManager()->getStorage('image_style')->load($standalone_style);
        $summary[] = $this->t('Display standalone image with %style image style.', [
          '%style' => $style ? $style->label() : 'original'
        ]);
      }

      $location = $this->getSetting('standalone_location');
      $location_labels = [
        'above' => $this->t('above'),
        'below' => $this->t('below'),
        'left' => $this->t('left'),
        'right' => $this->t('right')
      ];
      $summary[] = $this->t('Standalone image position: %position.', [
        '%position' => $location_labels[$location]
      ]);

      if ($this->getSetting('hide_single_navigator')) {
        $summary[] = $this->t('Hide carousel with single image.');
      }
    }

    $image_style = $this->getSetting('image_style');
    if ($image_style == '_original') {
      $summary[] = $this->t('Display images without image style.');
    } else {
      $style = \Drupal::entityManager()->getStorage('image_style')->load($image_style);
      $summary[] = $this->t('Display images with %style image style.', [
        '%style' => $style ? $style->label() : 'original'
      ]);
    }

    if ($this->getSetting('vertical')) {
      $summary[] = $this->t('Display slider vertically.');
    }

    switch ($this->getSetting('lazy_load')) {
      case 'ondemand':  $summary[] = $this->t('Use on demand lazy loading.'); break;
      case 'progressive':  $summary[] = $this->t('Use progressive lazy loading.'); break;
    }

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    // Skip if there are no items to display.
    if ($items->isEmpty()) {
      return [];
    }

    $standalone_html_id = Html::getUniqueId($items->getName() . '-standalone');
    $carousel_id = Html::getUniqueId($items->getName() . '-nav');
    $lazy_load = $this->getSetting('lazy_load');
    $use_lazy_load = $lazy_load != 'none';

    // Retrieve file IDs.
    $fids = [];
    foreach ($items->getIterator() AS $item) {
      $fids[] = $item->get('target_id')->getValue();
    }

    // Load files so we can get their URIs.
    $files = \Drupal::entityManager()->getStorage('file')->loadMultiple($fids);

    // Make a list of all URIs.
    $uris = array_map(function($file) {
      return $file->getFileUri();
    }, $files);

    // Set up the render element.
    $element = [
      '#attached' => [
        'library' => [
          'mymodule/slick_myentity_gallery'
        ]
      ]
    ];

    // Create carousel for the standalone image if needed.
    if ($this->getSetting('standalone_image')) {
      $element['#attributes']['class'][] = 'with-standalone';

      $element['standalone'] = [
        '#theme' => 'item_list',
        '#items' => [],
        '#weight' => 0,
        '#attributes' => [
          'id' => $standalone_html_id,
          'class' => [
            'slick-myentity-gallery',
            'slider-standalone',
            'location-' . $this->getSetting('standalone_location')
          ],
          'data-slick-settings' => json_encode([
            'slidesToShow' => 1,
            'slidesToScroll' => 1,
            'arrows' => FALSE,
            'fade' =>  TRUE,
            'asNavFor' => '#' . $carousel_id,
            'lazyLoad' => $lazy_load,
            'mobileFirst' => TRUE
          ])
        ]
      ];

      foreach ($uris AS $uri) {
        $element['standalone']['#items'][] = $this->getImageItem($uri, $this->getSetting('standalone_style'), $use_lazy_load);
      }
    }

    // Create the main image carousel.
    $element['carousel'] = [
      '#theme' => 'item_list',
      '#items' => [],
      '#weight' => 1,
      '#attributes' => [
        'id' => $carousel_id,
        'class' => [
          'slick-myentity-gallery',
          'slider-navigation',
          $this->getSetting('vertical') ? 'vertical' : 'horizontal'
        ],
        'data-slick-settings' => json_encode([
          'slidesToShow' => (int) $this->getSetting('visible_slides'),
          'slidesToScroll' => 1,
          'asNavFor' => '#' . $standalone_html_id,
          'dots' => (bool) $this->getSetting('dots'),
          'arrows' => (bool) $this->getSetting('arrows'),
          'fade' => (bool) $this->getSetting('fade'),
          'vertical' => (bool) $this->getSetting('vertical'),
          'verticalSwiping' => (bool) $this->getSetting('vertical'),
          'focusOnSelect' => TRUE,
          'lazyLoad' => $lazy_load,
          'mobileFirst' => TRUE,
          'rtl' => \Drupal::languageManager()->getCurrentLanguage()->getDirection() == 'rtl',
          'infinite' => FALSE
        ])
      ]
    ];

    foreach ($uris AS $uri) {
      $element['carousel']['#items'][] = $this->getImageItem($uri, $this->getSetting('image_style'), $use_lazy_load);
    }

    // Display the carouse first if the standalone image is visible and
    // is positioned below the carousel or to the right next to it.
    if ($this->getSetting('standalone_image') && in_array($this->getSetting('standalone_location'), ['below', 'right'])) {
      $element['carousel']['#weight'] = -1;
    }

    // Hide navigator if standalone image is displayed and there is only
    // one image.
    if ($this->getSetting('standalone_image') && $this->getSetting('hide_single_navigator') && $items->count() == 1) {
      unset($element['carousel']);
    }

    return [$element];
  }

  /**
   * Helper method to generate image for provided style
   * that takes the lazy load setting into account.
   *
   * @param string $uri
   *   The original image uri.
   * @param string $image_style
   *   The image style name.
   * @param bool $lazy_load
   *   If TRUE the lazy slick load image will be returned.
   *
   * @return array
   *   Renderable array for a single image.
   */
  function getImageItem($uri, $image_style, $lazy_load = FALSE) {
    if ($lazy_load) {
      $style = \Drupal::entityManager()
        ->getStorage('image_style')
        ->load($image_style);

      return [
        '#type' => 'inline_template',
        '#template' => '',
        '#context' => [
          'path' => $style ? $style->buildUrl($uri) : file_create_url($uri)
        ]
      ];
    } else {
      return [
        '#theme' => 'image_style',
        '#uri' => $uri,
        '#style_name' => $image_style
      ];
    }
  }

}

(function($) {

  Drupal.behaviors.slickMyentityGallery = {
    attach: function(context) {
      // Initialize the Slick Carousel on all appropriate elements.
      $('.slick-myentity-gallery[data-slick-settings]', context).once('slick-myentity-gallery-init').each(function() {
        var $this = $(this);
        var settings = $this.data('slick-settings');

        // Adjust behavior if this is a Field API field.
        var $fapi_items = $this.find('.field__item');
        if ($fapi_items.length != 0) {
          $fapi_items.parent().slick( settings );
        } else {
          $this.slick( settings );
        }
      });
    }
  }

})(jQuery);


Does the Transliteration module alter the existing URLs? I want to install the Transliteration module for a site on Drupal.

If I install this module, would it also change existing URLs (if I enabled it in the Pathauto module settings), or would it change just the new urls? I don't to alter the existing URLs.

The Transliteration module doesn't update anything on its own. It's the Pathauto that controls that. Just enabling the Transliteration won't do anything.

Pathauto module has a setting for what happens when an entity is updated (/admin/config/search/path/settings). This means that when you edit existing content Pathauto may change the alias depending on your settings.

You can set it to Do nothing. Leave the old alias intact. This way you'll be able to edit old content without the alias being automatically changed.

If you need to use some other Update action setting you'll have to remember each time when editing an "old" node to untick the option Generate automatic URL alias and use the "old" alias manually.


ajax callback on form element checkboxes I am having some troubles with ajax on form element checkboxes, in ajax callback form_state is without values and triggering element etc .. why is that?

The form is called with drupal_get_form and this is my element

$form['select_options'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'ajax_options_callback',
    'wrapper' => 'options-form',
    'event' => 'change',
    'method' => 'replace',
  ),
);

When you use a callback $forms and $form_state is available for use in your callback. But you should call them as parameters in your callback definition.
So:

public function ajax_option_callback(array $form, FormStateInterface $form_state) {
  // get the id of the form
  $value = $form_state->getFormObject()->getFormId();
  // create a response object and return it
}

public function ajax_option_callback() {
  // $form and $form_state not available
}

Note that &form_state->getTriggeringElement() contains nothing as the form is not submitted.

I realize now the question is for D7. Maybe my answer is usefull for someone within the D8 context.


Migrate Module and AddressField Locality/City Lookup in PrepareRow Fails I'm running a migration to move volunteers from a csv file to drupal.  I have written the following code.

<?php
/**
    * @file
    * Migration for Volunteer File
*/

ini_set('auto_detect_line_endings', TRUE);

class VolunteerMigration extends Migration {

public function __construct($arguments) {
    parent::__construct($arguments);

    $this->description = t('Imports Volunteers from CSV file ');

    // Create a source object
    $columns = array(
        0 => array('pkid', 'PKID'),
        1 => array('fname', 'First Name'),
        2 => array('lname', 'Last Name'),
        3 => array('email','Email'),
        5 => array('dayphone','DayPhone'),
        6 => array('eveningphone','EveningPhone'),
        7 => array('address','Address'),
        8 => array('city', 'City'),
        9 => array('state','State'),
        10 => array('postalcode','zip'),
        11 => array('occupation','Occupation'),
        12 => array('interests','Interests'),
        13 => array('created','Timestamp'),
    );
    $address_arguments = array(
        'first_name' => array('source_field' => 'fname'),
        'last_name' => array('source_field' => 'lname'),
        'thoroughfare' => array('source_field' => 'address'),
        'locality' => array('source_field' => 'city'),
        'administrative_area' => array('source_field'=>'state'),
        'postal_code' => array('source_field' => 'postalcode'),
    );
    $this->source = new MigrateSourceCSV('/mnt/www/cylindrical/theoregonproject.com/data/drvollist.csv', $columns, array('header_rows' => 1));

    // Create a destination object
    $this->destination = new MigrateDestinationNode('volunteers');

    // Create a map
    $this->map = new MigrateSQLMap(
        $this->machineName,
        array(
            'pkid' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
        ),
        MigrateDestinationNode::getKeySchema(),
        'campaign_migration'
    );

    // Create Mappings
    $this->addFieldMapping('title', NULL)->DefaultValue('Volunteer');
    $this->addFieldMapping('field_volunteer_address')
        ->arguments($address_arguments);
    $this->addFieldMapping('field_volunteer_id', 'pkid');
    $this->addFieldMapping('field_email', 'email');
    $this->addFieldMapping('field_dayphone', 'dayphone');
    $this->addFieldMapping('field_eveningphone', 'eveningphone');
    $this->addFieldMapping('field_occupation', 'occupation');
    $this->addFieldMapping('field_interests', 'interests')
            ->separator(',');
    $this->addFieldMapping('created','created');

}

public function prepareRow($row) {

    if ( $row->zip ) {
        $row->city = zipcity($row->zip);
    }
}

public function zipcity($zip) {
    $ch = curl_init('http://ziptasticapi.com/' . $zip);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    $result = curl_exec($ch);
    curl_close($ch);

    $json = json_decode($result,true);

    return $json['city'];
}
}
?>

I'm am using the ziptastic api to fill in the cities using the zipcode.  Running the migration returns all except the address portion of the migration.  The zipcity function works as expected (returns city given a zipcode) but none of the address arguments are migrated.

I have adapted this code from a previous and successful migration minus the preparerow / zipcity additions.

Mark

Found the issue.  When using the addressfield module, you should have field mappings that allow for preparerow to work.  I thought that the address_arguments array was enough to create the field maps.  Also I was using the csv column title 'Zip' instead of the the mapped field title 'postalcode'

Under my address field mapping I added the following code.

    $this->addFieldMapping(NULL, 'fname');
    $this->addFieldMapping(NULL, 'lname');
    $this->addFieldMapping(NULL, 'address');
    $this->addFieldMapping(NULL, 'city');
    $this->addFieldMapping(NULL, 'state');
    $this->addFieldMapping(NULL, 'postalcode');

I also moved the function zipcity to my helper function file to allow other migrations to use it if needed.

This post https://drupal.org/node/1326044 was key into figuring out the missing link.


Use user/register instead of default login page for anonymous users This sounds simple enough but I can't make it work.

Only registered users can view the site content, but instead of the login block, I want users to go to the user/register page (with the 'login' and 'request new password' tabs also there), and after registering then be taken to the frontpage.

I've tried the login redirect and login destination modules, but they don't help setting user/register as the defult page for anonymous users. I tried setting 'user/register' as the homepage in config/system/site-information and force logged-in users to the actual frontpage, but not surprisingly that didn't work. I tried disabling 'view published content' permission for anonymous users, and then set the 403 page to user/register, but nothing. I tried creating a rule (first time using rules) as follows:

Event: drupal is initializing

Condition: user has anonymous role

Page redirect: user/register

And other variations I could think of, but to no avail.

I don't think it's that difficult and I'm probably missing something. Can someone please advise?

Solved it. In case someone looks for something similar, to the rule above I added another condition:

NOT Text comparison - Parameter: Text: [site:current-page:url], Matching text: user


If Profile2 fields are empty, problem in accessing data I just found out that if ALL fields of certain Profile2 profile ie. main are empty, I am not able to access data inside main profile. For example I want to do a check if a field is empty but can not access it using

global $user;
$account = user_load($user->uid);
$data = profile2_load_by_user($account);

How can I access the fields? thank you.

I would suspect that profiles only get created when needed, hence when it is saved with field values.

You most probably then are trying to look at a profile of a user who does not yet have a profile. You should do a test on $data. If it is null or false, then you should assume that the user has no profile and that the fields are in effect empty. If you want to alter the fields then you must set up a profile object and save it after validation.

The docs for profile2_load_by_user is misleading as it indicates that there will always be a profile returned, but looking through the source code I can see a return value of FALSE.

If there is a profile then return value is either a single profile or an array of profiles, so you must test $data for 3 things: false, object, or array of objects.


#states attribute of FORM API? Currently I am using states attribute in my form to show/hide a drodown having days as its value on selecting a parent dropdown value. My working scenerio is that I want to show a dropdown having 31 days if january,march,may.... is selected and to show another dropdown having 30 days as its value when febraury,april,june .... is selected , can some one suggest me how its could be achieved because in usage of #states attribute only one value could be selected.

function sandbox_ajax_dropdown($form, &$form_state) {

$options = array(1 => t('1 月'), 2 => t('2 月'), 3 => t('3 月'), 4 => t('4 月'), 5 => t('5 月'), 6 => t('6 月'), 7 => t('7 月'), 8 => t('8 月'), 9 => t('9 月'), 10 => t('10 月'), 11 => t('11 月'), 12 => t('12 月'),);

$form['state_list'] = array(
    '#type' => 'select',
    '#title' => 'Choose A Day First',
    '#options' => $options
);
$form['illinois_cities'] = array(
    '#type' => 'select',
    '#description' => t("Thirty-One Days."),
    '#states' => array(
        'visible' => array(
            ':input[name="state_list"]' => array('value' => '5'),
        ),
    ),
    '#options' => array(1 => t('1'), 2 => t('2'), 3 => t('3'), 4 => t('4'), 5 => t('5'), 6 => t('6'), 7 => t('7'), 8 => t('8'), 9 => t('9'), 10 => t('10'), 11 => t('11'), 12 => t('12'),
        13 => t('13'), 14 => t('14'), 15 => t('15'), 16 => t('16'), 17 => t('17'), 18 => t('18'), 19 => t('19'), 20 => t('20'), 21 => t('21'), 22 => t('22'), 23 => t('23'), 24 => t('24'),
        25 => t('25'), 26 => t('26'), 27 => t('27'), 28 => t('28'), 29 => t('29'), 30 => t('30'), 31 => t('31')),
);

$form['ohio_cities'] = array(
    '#type' => 'select',
    '#description' => t("Thirty Days."),
    '#states' => array(
        'visible' => array(
            ':input[name="state_list"]' => array('value' => '1', '2'),
        ),
    ),
    '#options' => array(1 => t('1'), 2 => t('2'), 3 => t('3'), 4 => t('4'), 5 => t('5'), 6 => t('6'), 7 => t('7'), 8 => t('8'), 9 => t('9'), 10 => t('10'), 11 => t('11'), 12 => t('12'),
        13 => t('13'), 14 => t('14'), 15 => t('15'), 16 => t('16'), 17 => t('17'), 18 => t('18'), 19 => t('19'), 20 => t('20'), 21 => t('21'), 22 => t('22'), 23 => t('23'), 24 => t('24'),
        25 => t('25'), 26 => t('26'), 27 => t('27'), 28 => t('28'), 29 => t('29'), 30 => t('30'))
);

return $form;

}


Code in the template or in a module? Is it better to write hook functions in template.php (or a .inc in my theme folder) or is it better to put them in custom modules?  Or, does it matter?  Is it just a matter of organizational preference?  Does it depend?

Id say its simple case of organisation and relevance. Hooks fit into three different categories, alter, process and theme so probably best to organise these into separate include files.

inc/
template.alter.inc
template.process.inc
template.theme.inc

If your going to add a class to a button in a certain contrib module or similar then obviously creating a custom module is overkill.

Probably the best strategy to have is to work on the theme layer and it will soon be apparent if its worth putting the relevant code into its own module. Either way, you have achieved what you wanted.

Does it matter where the code is? Probably not, it's a few checks or calls wherever it is. Your probably get many an argument on best practices from various developers on this.


Creating a custom login system by developing a new module I've created 2 files:

login_process.info
login_process.module

I've created the table "user" in the database that Drupal is using. I want to display a custom login form with fields "Username" and "Password".

Assuming the data from Username and Password fields are in the correct format(proper validations), when the submit button is pressed, a query is done and data to check if the values matches that found in the table.

If no result is found, it displays an error message

else it redirects to to the welcome page.

Here are the codes:

login_process.info

name = "My login process module"
description = "Performs login process"
core = "7.x"
version ="7.x.1.0"
package = "Login/Register"`

login_process.module

<?php

/*
*Implements hook permission
*/

function login_process_hook_permission()
{
 return array(
    'submit login_process' => array(
      'title' => t('Submit login form'),
      'description' => t('Submit the login form')
    ),
  );
}

/*
* Implements hook menu
*/

function login_process_hook_menu() {
  $items = array();
    $items['login-process'] = array(
  'title' => 'login',
  'type' => 'MENU_NORMAL_ITEM',
  'access arguments' => array('submit login_process'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('login_process_form')
    );
    return $items;
}

/*
* The login form
*/

function login_process_form($form,&$form_state)
{
  $form['Username'] = array(
  '#type' => 'textfield',
  '#title' => t('Username'),
  '#size' => 20,
  '#maxlength' => 20,
  '#required' => TRUE,
  '#description' => t('Please enter a valid username'),
  );

  $form['Password'] = array(
  '#type' => 'textfield',
  '#title' => t('Password'),
  '#size' => 20,
  '#maxlength' => 20,
  '#required' => TRUE,
  '#description' => t('Please enter a valid password'),
  );
  $form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Add item')

  );
  return $form;
}
/*
* Validation handler for the login_process_form
*/

function login_process_form_validate($form,&$form_state)
{
  print('
'.print_r($form_state['values'],1).'
'); die();
  if (!preg_match("/[a-zA-Z]/",$form_state['values']['Username']))
  {
    form_set_error('Username', t('Username must contain only alphabets'));
    return FALSE;
  }
  return TRUE;
  //add more validations for Username and Password
}

/*
*Submit handler for the login form
*/

function login_process_form_submit($form,&$form_states)
{

  $username = $form_state['values']['Username'];
  $password =  $form_state['values']['Password'];
  $results = db_query("SELECT Username,Password FROM user WHERE Username='".$username."' AND Password='".$password."'"));
  if(is_null($results))
  {
    form_set_error('Username', t('Wrong username or password. Try again!!!!'));
    return FALSE;
  }
  else
  {
  echo "Welcome".$form_state['values']['Username']."Logout" // it will be better if it is displayed in a block
  }
}

It neither display errors nor the login form created from the module. Can anyone help me here? Do I have to install additional modules to make it work?

Most of the codes are based from Daily dose of Drupal episode 16 to 22.

You don't need any other modules, to just show a form. Your code is not correct in some points, though, and that needs to be corrected.

A form validation handler doesn't return TRUE nor FALSE; it just calls form_set_error() in case the submitted data doesn't pass the validation.

A form submission handler doesn't validate the submitted data; that is the task of the form validation handlers. The purpose of the form submission handlers is to take the necessary actions (e.g. loading data from the database, saving data to the database), but they don't return anything.

You don't inject values entered from user directly in the query, as you do with db_query(). That is the perfect way of given a malicious user access to the user #1 access, for example, and without the user knowing the user #1 account.
Always use placeholders for input obtained from users, when you are using it in a query. See what user_login_authenticate_validate() does.

$account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();

The correct way to show a message to the user is using drupal_set_message(). In the specific case, showing a message with a logout link is not much helpful, since the users will not see it anymore after moving to a different page. In any case, you don't use echo() to print anything on a Drupal page from a form submission (or validation) handler.


Check if certain line item type exists I am using Commerce Userpoints to award points based on purchases and then customers can use those rewards on future purchases for a discount.

I'd like to customize the checkout pane if the user has already applied a discount. Commerce Userpoints Discount creates a line item type of userpoints. My initial idea was to check if the current order contains a line item of type userpoints, but I'm not sure how to do that. Any help would be appreciated!

You can check for a certain type of line item on an order using one of the two following methods.

Given an order, let's look for a shipping line item.

// Load your order.
$order = commerce_order_load(/* Order ID */);

Without Metadata Wrappers

if (!empty($order->commerce_line_items)) {
  // Iterate over the line items.
  foreach ($order->commerce_line_items[LANGUAGE_NONE] as $line_item_data) {
    $line_item = commerce_line_item_load($line_item_data['line_item_id']);
    // Check the type.
    if ($line_item->type == 'shipping') {
      // Shipping line item found. Do the things.
    }
  }
}

With Wrappers

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
// Iteration is a bit simpler here.
foreach ($order_wrapper->commerce_line_items as $line_item) {
  // We have to access it using ->value().
  if ($line_item->type->value() == 'shipping') {
    // Shipping line item found. Do the things.
  }
}


How to return all the tags from a specific vocabulary for the current node I am trying to return all tags from a vocabulary but the code below keeps giving me error.

$vid = 1;
$nid = arg(1);

$getterms = db_query('SELECT t.tid, t.* FROM {taxonomy_term_data} t INNER JOIN {taxonomy_index} r ON r.tid = t.tid WHERE t.vid = :vid AND r.nid = :node_nid ORDER BY weight', array(':vid' => $vid, ':node_nid' => $nid->nid));

I am getting 2 errors:

Notice: Trying to get property of non-object in eval() ...
Recoverable fatal error: Object of class DatabaseStatementBase could not be converted to string in eval() ...

arg() returns a string so $nid is not an object. You're currently adding your :node_nid database condition with a value of $nid->nid, when you should just be using $nid:

$vid = 1;
$nid = arg(1);

// Updated as per comments below
$sql = 'SELECT t.name FROM {taxonomy_term_data} t INNER JOIN {taxonomy_index} r ON r.tid = t.tid WHERE t.vid = :vid AND r.nid = :node_nid ORDER BY weight';
$args = array(':vid' => $vid, ':node_nid' => $nid);

$terms = db_query($sql, $args)->fetchCol();
$comma_separated = implode(', ', $terms);

If you want to load the node object related to the current path then you can use menu_get_object(); then you can access the nid as part of the object:

$node = menu_get_object();
$nid = $node->nid;

But I suspect that will be overkill as you only really need the $nid, and not the full node object for your query.


How do I move a site to a new server? How do I move a site to a new server?

I have a backup file for the database content and all the files. I uploaded it using cPanel to the new server, imported the database, and updated the username and password as well.

For some reason, the website is just showing this message.

  The website encountered an unexpected error. Please try again later.

The content of the error log provided by my hosting provider is the following.

How can I fix this?

It seems that you may forgot to move the vendor directory to the new location. Also you may need to run composer dump-autoload to update the autoloader with your new vendor's path. Though may be obvious to many, you need to clear the Drupal cache, in this case I prefer do a truncate over the cache bins (assuming you're using the default cache backend).

Update

Also worth checking the autoload.php file in your Drupal root, this file includes the actual autoloader generated by Composer.


Best Method to Separate Drupal Website from Customized Scripts I currently have 2 small cloud servers: (1) database server; (2) web server.

The web server hosts my Drupal 7 website plus a lot of continually running scripts that process data and hook into Drupal's API functions (e.g. node_save, taxonomy_term_save).

I would like to split up my web server into two servers so that now I have 3 servers: (1) database server; (2) Drupal website server; (3) data processing server.

Since my custom scripts tie into Drupal's API functions, I am not sure how to actually run these scripts from a completely separate server without essentially cloning the web server and just blocking public access to the website on the data processing server.

Any ideas would be greatly appreciated! Thanks!

There's no way to use Drupal Apis from a separate server. Your best bet would be to use the web service module and process your request via json.

You'll have to do more work but on second hand, you'll end up with a nifty setup that'll allow you to leverage many other frameworks such as angularjs, backbone, and even mobile development.


Add another button removes the default values from my fields on node form I have a node form on which two fields are displaying.
One is a list of radio buttons which is required field.

I am getting a value from url using arg(3) and setting the default value of that field

$form['field_test'][LANGUAGE_NONE]['#default_value'] = arg(3);

I have a link field which is a multi valued field. It means this field as add another button.

When I click on this add another button and then submit the form, I see an error of Test field is required, and that default value of test field gone.

Without clicking the add another button everything works fine.

How can I set a default value of the test field in this case?

Code:

if (!$form['nid']['#value']) {
  if (arg(3)) {
    // Select the default value.
    $tg = arg(3);
    $form['field_test'][LANGUAGE_NONE]['#default_value'] = $tg;
  }
}

  // Make the field readonly.
  $form['field_test'][LANGUAGE_NONE]['#attributes']['disabled'] = 'disabled';

Ok. I found the solution. Let me share my code here.

I stored the argument in the $form_state['storage] so that it can be preserved during the ajax call.

if (arg(0) == 'node' && arg(3)) {
    $form_state['storage']['field_test_value'] = arg(3);
}

// Only on node creation.
if (!$form['nid']['#value'] && isset($form_state['storage'])) {
    $form['field_test'][LANGUAGE_NONE]['#default_value'] = $form_state['storage']['field_test_value'];
}

$form['field_test'][LANGUAGE_NONE]['#attributes']['disabled'] = 'disabled';

Hope this will help someone.


How do I add a media image field? I have installed these modules:

Media Entity
Media Entity Image
Entity Browser

When I try to add an image field, I have no widget for Media like there was in Drupal 7.
I also tried to add a reference to a media, but it doesn't seem to work.

What am I doing wrong?

What you got can do what you want, but it requires configuration and without a UI it's quite hard.

You might want to try adding the file browser module, which uses Dropszonejs to create a nice file browser widget. I have tested it out and it seemed to work just fine, but it wasn't quite mature enough for what we wanted to do at the time.


Multiple aliases, context and menu items (Drupal 7) I have a site with 2 sections of content, A and B. I have a node, 'Z' that needs to appear in each area. I also have a different menu for each area, e.g.

Section 'A'
link 1
link 2
link Z -> should show menu 'A'

Section 'B'
link 3
link 4
link Z -> should show menu 'B'

I am using context to load the correct menu block, depending on which section a user is viewing (each node is either in an Organic Group, or the Group has a taxonomy term identifying the section which is the ultimate source of the section).

How can I display the content in node Z and also show the correct menu?

I've tried Node Hierarchy and it doesn't appear to be able to do what I'm looking for (it's also left some menu entries I can't delete).

Update: taking a step back and looking fit aaa simple solution, I think that the patch here will allow me to append a simple query string to my URL and thus avoid having the appearance of duplicated content. Assuming of course that I can add the query string to the menu item.

I was able to create an acceptable solution by adding a query string to my menu links and adding an additional test to my PHP conditions. Now I've got something like:

return $_SERVER["QUERY_STRING"] == 's=pt';

and I get the context I'm looking for. The actual implementation is a little more complicated (due to having taxonomy also defining context, but needing to override it when a query string is passed so as to avoid ending up displaying both menus) but that should give you the idea in case anyone else is looking to solve the same problem.

I'd like to see the patch in http://drupal.org/node/904416 make it's way into the official context release. For me, maintaining a custom PHP condition is much easier than remembering I need to patch a module every time I update it if it doesn't get in there.


How to use drupal_http_request for send data? I need some help in sending data in an array (POST) to a webservice (REST). I need some examples in how to use the function drupal_http_request().

Now, I'm using cURL with PHP but I need to replace it with drupal_http_request(). And I see that it's easier to use in Drupal.

If my first page is the login (http://[ip]/users/sign_in) and I'm using "User:Pass" to enter to main page(http://[ip]/event). Then, I select the menu for view the data that I send from my form in Drupal (http://[ip]/event/mobile/management).

How to do this with drupal_http_request()?

UPDATE:

function send_data_form_submit($form, &$form_state) {

    $name = $form_state['values']['name'];
    $email = $form_state['values']['email'];

    $attendee = array(
        'name' => urlencode($name),
        'email' => urlencode($email)
    );

    $attendee = http_build_query($attendee, '', '&');

    $url_login = 'http://[ip]/eventmobile/users/sign_in';
    $url_target = 'http://[ip]/eventmobile/attendee_management/attendee';

    $use  = array(
      'email' => 'root@root.com',
      'password' => '123456'
    );
    $user = http_build_query($use, '', '&');

    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');

    $method = 'POST';

    $result_1 = drupal_http_request(url($url_login, array(absolute => true)), $headers, $method, $user); //I get a http_code = 200. OK
    $result_2 = drupal_http_request(url($url_target,array(absolute => true)), $headers, $method, $attendee); // I get a http_code = 500. Internal Server Error

}

UPDATE 2 (Using cURL):

$attendee = array(
        'name' => urlencode($name),
        'email' => urlencode($email)
);
$userpwd = "root@root.com:123456"
   $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url_target);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
        curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE); //I get http_code=200

        if(preg_match('#Location: (.*)#', $result, $r))
                $url_redirect = trim($r[1]); //The URL of LOGIN

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url_redirect);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_USERPWD, $userpwd);
        curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $page = curl_exec($ch); // Return string: Evaluating...
        $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE); //I get http_code=200

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);
        curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
        $result = curl_exec($ch); // Return string: Evaluating...
        $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE);// I get http_code=200

    curl_close($ch);

Your $url_login looks like the default URL scheme for a Ruby on Rails website that uses the devise login system. Here is a function I've used to login to a rails/devise backed web site.

/** Authenticate via Rails/Devise site */
function devise_login($email, $pass) {
   //Build up data to send to devise
   $data = array('user' => array('email' => $email, 'password'=>$pass));
   //Pull the url out of the drupal settings
   $url = variable_get('devise_authentication_url', '');
   if ($url != '') {
     $response = drupal_http_request($url, array(
       'method' => 'POST',
       'data' => json_encode($data),
       'max_redirects' => 0,
       'headers' => array('Content-Type' => 'application/json', 'Accept' => 'application/json'))
     );

     return = json_decode($response->data);
   }

   return FALSE;
}


Is there a process to run a task daily I have business logic that interfaces with Drupal entities (in this case, users), and we need to generate reports off these records daily at a preset time. It would be easy for me to generate this data on-demand, but the requirements ask for a daily report.

I'm wondering if its possible in D7 to have the system schedule a specific cron task to run at a preset task over the time cron is expected to run (which right now, is every 3 hours). Another option I am considering is to have a Contrib Drush script that simply runs using the OS'es crontab/launchd. Which one makes the most sense?

I had to do something similar recently. The extremely simple answer I came up with was to simply keep track of the last time the function was run with a db variable.

So, in psudo code, I ended up doing something like this:

function hook_cron(){
  $now = new DateTime(date(DATE_ISO8601));
  $last_checked = new DateTime(variable_get('last_checkedvar', date(DATE_ISO8601, '0')));
  $diff = $now->diff( $last_checked );

  if ($diff->days >= 1){
    //do your stuff
  }
}

Works well for me. And it also doesn't interfere with any of the other cron tasks I have running on my site.


How to programmatically reset user password I'm trying to create a custom module for resetting the user's password.

In the following block of code I'm attempting to get the password in hash form:

$pass='User123@';

$autoloader =require_once(\Drupal::service('file_system')->realpath('autoload.php'));
//echo $autoloader; exit;
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod', FALSE);
$kernel->boot();
$password_hasher = $kernel->getContainer()->get('password');
$newhash =  $password_hasher->hash($pass);

//echo  $newhash ; exit;

This is my db update code:

 $updatepass = \Drupal::database()->update('users_field_data')
      ->fields(array(
        'pass' => $newhash,
      ))
      ->condition('name', "$id",'=')
      ->execute();

Please help me understand what mistake I've made.

Just use the setPassword() method to update the user's password:

// Get user storage object.
$user_storage = \Drupal::entityManager()->getStorage('user');

// Load user by their user ID
$user = $user_storage->load($id);

// Set the new password
$user->setPassword('User123@');

// Save the user
$user->save();

This will take care of all the hashing for you and will trigger all the appropriate hooks for saving a user.


How to remove author name from blog post url? When a user publishes a blog post the user's name is included as part of
the blog link or url:

  www.example.com/blogs/author/post-name

What I want is that:

  www.example.com/blogs/post-name

How can I remove that author name from the url?

For Drupal 6; you can go to admin/build/path/pathauto page and change URL alias pattern for Blog content type (under Node paths settings).

You can make it blogs/[title-raw] or anything else you want.

Note: The picture above shows how to do change URL pattern. But, the URL pattern isn't what you want. The URL here something like that: term/blog-post-13.html.


Get terms from node? I need to get the terms a node has. I found out that you can use this:

$result = field_view_field('node', $node, 'field_tags', array('default'));

But this prints a rendered list. I need the names, or tids.

How do I separate them?

with taxonomy_node_get_terms() function (D6) you can get 'terms from node'. one example:

<?php
$terms = taxonomy_node_get_terms($node);// get term from nodes
rsort($terms); //rsort() just sort an array in reverse order
$myterm = $terms[0]->name; //get a value
echo $myterm; //show value
?>


User profile picture - avatar uploader on all pages I am trying to change my profile picture via ajax.

I used views to display my user profile picture in a block. This works Perfect.
I am then using the avatar uploader module to change my user profile picture.  This module is exactly what I want because it also crops my photos.  The problem is, this works, but only if I am on the user edit page.  I get the ajax uploader if I click on my profile picture that is displayed using views, but only on the user edit page.

Is there any way to get this module to work regardless of what page I am on?

Thanks.

Firstly,
Check avatar_uploader.js file, the default selector is '.profile .user-picture a', if you want to use this for other profile img, please change the selector
Drupal.settings.avatar_selector

Drupal.behaviors.avatar_uploader = {
    attach: function(context) {
        if (Drupal.settings.avatar_uid) {
            Drupal.settings.avatar_selector = Drupal.settings.avatar_selector || '.profile .user-picture a';
        var el = jQuery(Drupal.settings.avatar_selector);
        au.attach(el, Drupal.settings.avatar_uid, Drupal.t('Change avatar'));
         }
     }
}

Second, Check "avatar_uploader.module".

These code is to use uploader only in 'user' page in order to reduce js for browser, so you can change here

hook_init

$params = array('avatar_panel_id' => UPLOADER_PANEL_ID);
    if ($user->uid) {
        if (arg(0) == 'user' || (arg(0) == 'user' && arg(1) == $user->uid)) {
           $params['avatar_uid'] = $user->uid;
        }
    }

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


Write a module to replace jquery with another js library jQuery is great. But sometimes it's not exactly what I want. What would it take to write a module that could enitrely replace jquery with something like mootools or closure? Would this even be possible without hacking core modules?

Theoretically you could use hook_js_alter() to remove all traces of jQuery (and any JS files that rely on jQuery) from the page build, and drupal_add_js() to add your replacement library/code.

Bear in mind that you would have to re-implement a lot of system/contributed javascript in your library of choice to maintain the same UI experience for your admins/users.

Also remember you'll lose access to jQuery UI so none of those widgets will be available until you provide an alternative in your new library.

All in all, it would be a lot of work to do this.


search result not in prioritize order drupal 7 Hi i am new to drupal 7 and also to sql query builder format.i have a requirement to search the string. in that i hav to display exact matched string at the top followed by related matches. i explode a string with space and searched a each word exist or not.the code as follows.

$keys -> contain the search term

 $keys = preg_replace('!\*+!', '%', $keys);

$keys = explode(' ', trim(str_replace(array( '\'', '"', ',' , ';', '<', '>','!','_','-','+','@','#','$','%','^','&','.'), ' ', $keys)));;

 $query = db_select('file')->extend('PagerDefault');
 $query->fields('file', array('fid','filename'))
  ->fields('fs', array('e_id','f_subtitle_value'));

 $subquery = db_select('field_data_sub','fs');
 $subquery->Fields('fs', array('e_id','f_subtitle_value'));
 $subquery->condition('fs.e_type', 'node','!=');

 $query->leftjoin($subquery,'fs','file.fid = fs.e_id');
 $db_or = db_or();
foreach ($keys as $key) {
if(!(empty($key))) {
 $db_or->condition('filename', "%$key%", 'LIKE');
 }
}

$query->condition($db_or);
  $query->condition(db_and()->
          condition('filemime', 'image/jpeg', '!=')->
           condition('filemime', 'image/png', '!='));

i tried union all - wrote two query and combine it.. it fetches output but the exact searched result came twice . is that a gud way or else is there any other way.. please suggest the best way :)

You can use default drupal's search from admin/config/search/settings and se Views module for searching specific fields. You need not write any code or Query to search in a Drupal site unless it is needed.


What is the fastest way to convert a large volume of documents (.html) to drupal nodes How would you go about creating a large number of nodes from a large number of html documents?

I am trying to create something similar to a book and have a lot of .docx files on my computer. I am aware I should use a wysiwyg editor to clean up the formatting and make it look like I want saving it as HTML.
However there is the issue of getting all the .html files uploaded as nodes without having to copy-paste 200+ times.

Any ideas?

The module that appears as most suitable for you is called HTML import. This module will divide one single large HTML document into a structured Drupal book where the heading level hierarchy is respected. This module works with HTML exported from Word; HTML document converted from PDF as well as HTML document exported from Adobe InDesign.

This makes it possible to use a single HTML page, created in a word processing program and saved as HTML, or other structured HTML, to create a multipage Drupal book in a single step.  You actually need to collate the output from all your .docx files into a single HTML-file before converting to HTML to use HTML import in a single step.

In case your requirements are beyond what HTML import is capable of, below is a list of all the (usable) Drupal modules I am aware of that can be used to bulk import HTML (and some other formats) into a Drupal site:

HTML import  - Import a single HTML page created from MS Word and split it up into an hierarchical Drupal book structure consisting of a set of interlinked Drupal nodes.
HTML2Book - This also imports a single HTML page and split it up into an hierarchical Drupal book structure consisting of a set of interlinked Drupal nodes, but requires you to clean up the tagsoup created by MS Word first.
Import HTML - Import all of an existing, static HTML-site into a Drupal site as nodes.
Feeds - Import or aggregate data as nodes, users, taxonomy terms or simple database records.
Migrate - Provides a flexible framework for migrating content into Drupal from other sources, including HTML.
Node import - Allows users to import content (node, user, taxonomy) from CSV or TSV files. Requires you to convert from HTML to CSV. (no Drupal 7 version)

Of these, the simplest to use are HTML import and HTML2Book. However, both can only handle a single HTML page. For more complex conversion tasks, where you need to convert a large static HTML-site made up of several interlinked pages, one of the other modules may be more suitable.

Also: Whatever tool you use, never experiment with bulk import on a production site. Unless you're a lot more clever than me, there are going to be false starts and botched imports. Cleaning up thousands of nodes damaged by an import gone wrong is not fun.  Always experiment with bulk import on a throwaway staging site that just can be discarded wholesale when things go wrong. Transfer the settings and do the import on the production site when you're sure you have a working set-up.


how to render links as menu tabs I have created a block that generates some links. I want to display these links as menu tabs in my website. This is the php code I have written inside block.

<?php
  $current_url = current_path();
  $param = explode("/", $current_url);
  $nid = $param[1];

  $type = db_select("node", "n")
            ->fields("n", array("type"))
            ->condition("nid", $nid, "=")
            ->execute()
            ->fetchAssoc();

  switch($type['type']) {
    case "description":
      $current_desc_link = $current_url;
      $current_demo_link = db_select("field_data_field_desc_demolink", "fddd")
                          ->fields("fddd", array("field_desc_demolink_url"))
                          ->condition("entity_id", $nid, "=")
                          ->execute()
                          ->fetchAssoc();

      $howto_entityid = db_select("field_data_field_howto_demolink", "fdhd")
                          ->fields("fdhd", array("entity_id"))
                          ->condition("field_howto_demolink_url", $current_demo_link['field_desc_demolink_url'], "=")
                          ->execute()
                          ->fetchAssoc();

      $current_howto_link = "node/" . $howto_entityid;

      break;

    case "how_to":
      $current_howto_link = $current_url;
      $current_demo_link = db_select("field_data_field_howto_demolink", "fdhd")
                          ->fields("fdhd", array("field_howto_demolink_url"))
                          ->condition("entity_id", $nid, "=")
                          ->execute()
                          ->fetchAssoc();

      $desc_entityid = db_select("field_data_field_desc_demolink", "fddd")
                          ->fields("fddd", array("entity_id"))
                          ->condition("field_desc_demolink_url", $current_demo_link['field_howto_demolink_url'], "=")
                          ->execute()
                          ->fetchAssoc();

      $current_desc_link = "node/" . $desc_entityid;

      break;

    default:
      $desc_entityid = db_select("field_data_field_desc_demolink", "fddd")
                          ->fields("fddd", array("entity_id"))
                          ->condition("field_desc_demolink_url", $current_url, "=")
                          ->execute()
                          ->fetchAssoc();

      $howto_entityid = db_select("field_data_field_howto_demolink", "fdhd")
                          ->fields("fdhd", array("entity_id"))
                          ->condition("field_howto_demolink_url", $current_url, "=")
                          ->execute()
                          ->fetchAssoc();

      $current_demo_link = current_url;
      $current_desc_link = "node/" . $desc_entityid;
      $current_howto_link = "node/" . $howto_entityid;

      break;
}
?>

I want to render $current_demo_link, $current_desc_link, $current_howto_link as menu tabs in drupal webiste. I have tried menu_tree_output but I have to create menu links in Db. Is there any other way to render the links as menu without converting this as menu links.

Maybe try something like this?

$output = '
';
$output .= '
demo link title';
$output .= '
desc link title'
$output .= '
hot to link title'
$output .= '
';


programmatically disable menu based on user taxonomy reference fields I am trying to programmatically disable menu based on account settings/user taxonomy term field, is there a better way to do it? do I need to use hook menu? to disable already built menu, as I have a lot of users in department that needs to get filtered to only show the menu they can edit

UPDATE :

I wanted to hook the permisssion of user so not all can edit the menu structure, like edit links and so on, like example I allowed permissions manage menu 1, manage menu 2, for role a, then I wanted to hook that menu 1 is only available for user with term reference 1. something like that

thank you!

The answer will depend on what your created menu items route to (hook_menu() is for defining new menus so it won't help you here).

Generically, hook_menu_alter() allows you to alter the access callback so that you can override access with your own logic. If the path you're overriding is specific to a special module route (e.g. admin/dashboard), then it would make sense to use this hook.

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['admin/dashboard']['access callback'] = 'MYMODULE_access';
}

/**
 * Access callback function
 */
function MYMODULE_access() {
  global $user;
  $user_entity = user_load($user->uid);

  // @TODO: Check your user entity's taxonomy field for access and return
  // TRUE | FALSE

  // EXAMPLE: Allow access for USER #123
  // return ($user_entity->uid == 123);
}

If your created menu items link to content nodes then you should look at hook_node_access(). This hook is specifically designed for controlling access to nodes so you'll have access to the node/user object from the hook's arguments.

/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access($node, $op, $account) {
  $user_entity = user_load($account->uid);

  // @TODO: Check your user entity's taxonomy field for access and return
  // NODE_ACCESS_ALLOW | NODE_ACCESS_DENY | NODE_ACCESS_IGNORE
  // depending on your logic
}


Make my session non persistent I created a function to save the location (city, lat, long) of the user. So when he change the page, I don't need to convert his location again. So I've a problem. The session might be saved because when I close my computer, go to another place and reopen the page, my old location is still saved. How I can forget the location of the user when he leave my website ?

Here is a code example for how I store the user location :

function user_location_update($args) {
    drupal_session_start();
    if (isset($_GET['lat']) && isset($_GET['lng'])) {
        $_SESSION['user-location'] = array(
            'lat' => $_GET['lat'],
            'lng' => $_GET['lng'],
            'city' => $_GET['city'],
        );
    } else {
        $_SESSION['user-location'] = array(
            'city' => $_GET['city'],
        );
    }
}

Then here is an example how I use my data (I send them to JS by settings) :

drupal_add_js(array('userlocation' => (isset($_SESSION['user-location']) ? $_SESSION['user-location'] : array())), 'setting');

This is the best advice:
https://stackoverflow.com/questions/8311320/how-to-change-the-session-timeout-in-php

To put it in a Drupal context, you'd have to add a new column to the user table that tracked the last time a user was active and check that on a user hook.


Hide price and add to cart form for purchased product I'm using Drupal 7 and Drupal Commerce.

I need to hide the price and the add to cart form when a product was bought by the current user.

I found the solution for the add to cart form, but not for the price.

I imagine that it is necessary to use the function hook_entity_view_alter, but my code doesn't work. Here he is :

function mymodule_entity_view_alter(&$build, $type) {
  $purchased_product = mymodule_get_users_purchased_products();

  $line_item = commerce_unit_price[LANGUAGE_NONE]['0']['amount'];
  $product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);

      if (in_array($product->product_id, $purchased_product)) {
        $build['product:commerce_price']['#access']=FALSE;
      }
    }

Function for load the purchased product :

mymodule_get_users_purchased_products() {
      $purchased_products = &drupal_static(__FUNCTION__);

      if (!isset($purchased_products)) {
        global $user;
        $query = db_select('commerce_order', 'corder');
        $query->join('commerce_line_item', 'li', 'corder.order_id = li.order_id');
        $query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
        $query->condition('corder.uid', $user->uid, '=')
              ->condition('corder.status', 'completed', '=')
              ->fields('prod', array('commerce_product_product_id'));
        $result = $query->execute();

        $purchased_products = array_unique($result->fetchCol());
      }

      return $purchased_products;
    }

Do you know where from comes the problem?

Thanks for your help

Here's a function that you can use to accomplish your goals. I tested it with Commerce Kickstart 2.

function MYMODULE_entity_view_alter(&$build, $type) {
  if ($build['#view_mode'] != 'full' && $build['#entity_type'] != 'node' || empty($build['field_product'])) {
    return;
  }

  // Load your purchased products.
  $purchased_products = array('HAT2-BLK-OS');

  foreach ($build['#node']->field_product[LANGUAGE_NONE] as $product_data) {
    $products[] = $product_data['product_id'];
  }

  $all_products = commerce_product_load_multiple($products);
  if (count($all_products) == 1) {
    $product = reset($all_products);
    if (in_array($product->sku, $purchased_products)) {
      $build['product:sku']['#access'] = FALSE;
      $build['field_product']['#access'] = FALSE;
    }
  }
}

Let's step through it. The first thing that happens is that you need to get your SKUs that you'll base your hiding off of. Just replace this line with a line that loads the products that the current user has purchased.

  $purchased_products = array('HAT2-BLK-OS');

Then, you load the products:

  foreach ($build['#node']->field_product[LANGUAGE_NONE] as $product_data) {
    $products[] = $product_data['product_id'];
  }

If you just have a single product per page, you could grab a single product_id.

Then you need to load your products.

  $all_products = commerce_product_load_multiple($products);

I'm assuming a single SKU per product here, so it does reset($all_products) to grab the first one. Then, just do a check to see if that product's SKU is in the array of SKUs that were already purchased:

    if (in_array($product->sku, $purchased_products)) {
      $build['product:sku']['#access'] = FALSE;
      $build['field_product']['#access'] = FALSE;
    }

If it, then hide the sku (in product:sku) and the add to cart form (in field_product). The result will then be this:

As opposed to this:


What are some benchmarks with Mysql vs MariaDB while on Drupal 7? I was wondering how much faster is MariaDB vs Mysql in a Drupal 7 setup.

When you have applied full due diligence, the difference between MariaDB and MySQL should be virtually negligible. Why would I say this?

MariaDB has done some benchmarking with some settings that give all MySQL processes the same level playing field : See Sysbench OLTP: MySQL-5.6 vs. MariaDB-10.0.  In fact, here were the setting used in the benckmark.

[mysqld]
sql-mode="NO_ENGINE_SUBSTITUTION"
back_log=500
user=root
port=3306
max_connections=4096
max_connect_errors=5000
max_prepared_stmt_count=50000
table_cache=2048
transaction_isolation=REPEATABLE-READ
loose-skip-external-locking
innodb_status_file=0
innodb_data_file_path=ibdata1:200M:autoextend
innodb_buffer_pool_size=1G
innodb_additional_mem_pool_size=20M
innodb_log_file_size=650M
innodb_log_buffer_size=100M
innodb_support_xa=0
innodb_doublewrite=0
innodb_flush_log_at_trx_commit=0
query-cache-size=0
query-cache-type=0
symbolic-links=0
skip-grant-tables

Please note

the settings do not accommodate use of more read and write I/O threads.
double write buffer disabled, good for speed, bad for data consistency in case of a crash

The key to really deciding which version of MySQL to choose is to effectively tune all the versions  under test and then benchmarking with actual Drupal data. I would look into getting all MyISAM converted to InnoDB as much as possible (If you are using FULLTEXT indexes, you must go with MySQL 5.6).

Here are some of my past posts from the DBA StackExchange on what settings to look for when tuning InnoDB and why:

Jun 19, 2011 : How do I properly perform a MySQL bake-off?
Nov 24, 2011 : Why mysql 5.5 slower than 5.1 (linux,using mysqlslap)
Oct 05, 2011 : Query runs a long time in some newer MySQL versions


Send node as HTML formatted email to all users of a role I have a RULE that works well:

After saving a new content of type DEMO
Send node as HTML formatted email
Parameter: Send email to:doe@example.com,jane@test.com

What I need is to send the same Action but to a "users of a role", something like

After saving a new content of type DEMO
Send node as HTML formatted email
Parameter: Send email to: Roles: Editor ---Rules does not allow to add roles here---

Is there any module that can expand this function in RULES? Or is there some way to achieve this directly within RULES?
Thanks

It may depend on your config. Here's a solution relying on Mime Mail and Mail System, as Mime Mail integrates smoothly with Rules.

Download and enable these 2 modules. Then you'll have a few steps configuring it :

Mail System: select MimeMailSystem in both "Site-wide default MailSystemInterface class" and "Mime Mail module class" drop-down list.
Mime Mail: change it from "Plain text" to "Filter HTML".

Now when you edit your rule, you'll see an action "Send HTML mail to all users of a role". Select editor role. You're done :)

Find even more details in this step by step tutorial: How to Send HTML Emails in D7 using Rules

EDIT : Alternative solution.

Download simplenews and enable both simplenews and simplenews rules. Set up the module.
Create a editors newsletter. Deactivate Subscription block
Enable "Use as simplenews newsletter" in the content type options you wish to send as HTML formatted email.
Create a rule : after editing a user account, condition user has role editor, subscribe user to newsletter editors  (and reverse rule to unsubscribe)
Create a rule : after saving a node, condition content-type is..., send newsletter :The newsletter node to be sent.: [node]


How to restrict users to certain Content Types? A site that I'm working on will have lots of users managing the content. Unfortunately their workflow dictates that certain people only have access to certain content types. There isn't a method to their madness, so using roles to do this will result in a nightmare to maintain really fast.

The Content Access module will not work for this. It mentions Authors, but there doesn't seem to be any configuration for this. And managing on a per node basis won't cut it.

I'm thinking the most logical way would be checkboxes on the edit user account page for admins to set. This should limit them to creating and updating content that they have been explicitly allowed to. And the admin menu should only show the content types they were assigned to.

Is there a way to implement this? Or any pointers in the right direction for the appropriate hooks?

It looks like you should give it a try to use the Group module.
You'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types.

From the details included in your question, it seems that possibly you'd only need 1 group type. And if you then would create 1 group for each of the Content Types involved, you might be close to a working solution.

More info: What's the purpose of the Group module and how to get started with it?


Integration of Microsoft Exchange server with Drupal I am using Drupal 7.

I would like to integrate Microsoft Exchange server with my Drupal site, so that I can login with the credentials of Exchange server and can also integrate with other features of Exchange server like Events, Calenders etc.

I checked one module called LDAP(Light Weight Directory Access Protocol), and it is working with other servers, But i don't know whether I can use this integration with Microsoft Exchange server.

All recent version of Exchange (2000+) require and Active directory for the authentication and authorization.  Active Directory is integrated via LDAP.


colorbox on a external link I have create a little fotogallery where I display only the first 3 images, the first "big" on the left side and the other two (small, width / 2 of the big one) on the right side. All images are "linked" to colorbox.
If I click on one of these 3 images colorbox "run" (ok, perfect).

Via a div in a absolute position style I have added this phrase "See all NUMBER images". Now I need to link this "phrase" to the event that run colorbox from the first image (the big).

How can i do this ?

This can be achieved with jQuery .trigger() event.

jQuery('#id-of-your-phrase').click(function (e) {
 e.preventDefault();
 jQuery('#id-or-class-of-first-image-YouCanAlsoUse-first-child').trigger('click');
});

This code will open the colorbox from First Image (the Big).


Can I simply delete the File Entity folder from Modules if I am using Media 7.x-1.3 When I try to create new content with a linked YouTube video I am getting the following error:

  Fatal error: Call to undefined function file_info_file_types() in /home/setstart/public_html/sites/all/modules/media/media.module on line 1084

I have inherited a site that use Media 7.x-1.3

I see that the following Module is also installed - File Entity 7.x-2.0-unstable7

I see from the following threads that the file entity submodule within Media should be used not the standalone one.

http://drupal.org/node/1516804

http://drupal.org/node/1850324

So it looks like File Entity 7.x-2.0-unstable7 should never have been installed.

Can I simply remove the independent File entity module? I see a lot of other modules state they depend on it (so I can't disable it from admin screen)

If not what is my best option? Upgrade to Media 2.x?

Do you have backups from before the 2.x version of File entity was installed? That would be the ideal solution because frankly, things are bad. You can't just remove the File entity 2.x module directory, because at this point the module has been installed and your data is at quite a dirty state. The only real solution is to try an in-UI disable/uninstall of File entity and any Media related modules to try and get your site to a more clean state before again installing and enabling the proper versions you need/want.


Drupal 8 Looking for an elegant alternative of rowCount in a query In Drupal 8 we can not use the rowCount property anymore in case of a select statement. Is there an elegant alternative?

I can use a foreach, but when converting from Drupal 7 I would like to replace the result->rowCount() more elegantly

According to the Drupal API, "in D8 rowCount() is the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed or throws \Drupal\Core\Database\RowCountException if the last executed statement was SELECT."

If you need to select count of rows you can use $query->addExpression('COUNT(*)');

   $query = \Drupal::database()->select('table', 't');
   $query->addExpression('COUNT(*)');
   $count = $query->execute()->fetchField();


Trying to render a custom date format with Twig I'm in the process of porting one of my contrib themes to Drupal 8. For custom date formats on nodes, I have something like this in a node_preprocess function in the theme's template.php file in the Drupal 7 version:

$vars['thedate'] = format_date($node->created, "custom", "j");
$vars['themonth'] = format_date($node->created, "custom", "M");
$vars['theyear'] = format_date($node->created, "custom", "Y");

I render it with the following code.

  <?php print $thedate; ?> / <?php print $themonth; ?> / <?php print $theyear; ?>

In my Drupal 8 port, I've tried a similar approach in the theme's .theme file and then try to render them in node.html.twig as {{{ thedate }} / {{ themonth }} / {{ theyear }}}, but I'm getting a nasty error.

  Twig_Error_Runtime: An exception has been thrown during the rendering of a template ("The timestamp must be numeric.") in themes/mytheme/templates/page.html.twig
          at line 210. in Twig_Template->displayWithErrorHandling()
          (line 279 of /site/core/vendor/twig/twig/lib/Twig/Template.php).

I looked to Twig date formats, and it seems you should simply attach a variable, such as {{ display_submitted |date("m/d/Y") }}. I tried that without a preprocess function but what outputs is 12/31/1969, which is not the date the node was created so I'm a bit lost here.

Here is an approach that uses just Twig (no preprocess functions needed):

<p>{{ node.createdtime | date("d F Y") }}</p>


How do I filter only the root terms in a vocabulary in a view? I have have a vocabulary structured as so:

Root Alpha

Term Alpha 1
Term Alpha 2

Subterm Alpha 1

Root Beta
Root Gamma

Term Gamma 1
Term Gamma 2

How do I filter the view to show only the root terms of the vocabulary?
Currently my view is displaying the root terms as well as the children (Term * *)

Going forward from that I would like to pass the argument 'Root Alpha' (or its tid, or whatever from a context) and then have it filter to only 'Root Alpha's direct children. (Term Alpha *). Filtering to a depth any further than that would be a bonus.

I can get it to work if I put all my terms in one root term so that the vocab becomes:

True Root

Root Alpha

Term Alpha 1
Term Alpha 2

Subterm Alpha 1

Root Beta
Root Gamma

Term Gamma 1
Term Gamma 2

I'm not sure which vocab structure is more correct, writing this made me realise I have some reading to do apart from figuring this out with views.

For displaying only the root terms, I have a solution which surely will make someone facepalm (at least I did that):

Add a contextual filter to your taxonomy view
Select Taxonomy term: parent term.

Set it up like this: When a filter value is not available: Provide default value - Fixed value. Set the value to 0.

Yeah, that's all. Terms without parent have 0 here. See the description of the parent field of the taxonomy_term_hierarchy table:

  Primary Key: The {taxonomy_term_data}.tid of the term's parent. 0
  indicates no parent.


How to Create a Table of PDFs with Views? I've been tasked to develop my company's intranet with Drupal. One of the key items is to allow our HR department to upload job openings (PDF's) to display on site. I'm envisioning having this table output using Views but I'm not sure how to set up the front end for the Department to publish the files.

They need to be able to upload a file, give it a name (Job title) & date of upload. Table will then populate with them.

Any guidance would be greatly appreciated, I'm new to Drupal.

Regards
Tony

Generally there would be two steps to this in Drupal 7.

Create a content type with the fields you need
Create a view to pull in that content

In your content type settings, manage the fields, and you can add a file attachment field (for uploading the PDF) and a text field for entering the job title. Date of upload is automatically created in the sense that your HR people will create a new piece of content (of this new type) when they want to upload a new job opening, and you can use that piece of content's date last edited data for that field. You can enable display of that info in the view settings under Fields.

Once you get your view correctly displaying all the content from your new content type, you can work on styling it as a table with CSS.


How to configure paragraphs module for multilingual I try to configure the Paragraphs drupal module for a multilingual website.

I have :

set the content type translatable with field translation
enable translation on the paragraphs field
enable translation for the field in the paragraph bundle (or not)

However, when I create some content and translate it, the existing paragraphs are not displaying in the other language.

What's the correct/working way?

From the community documentation about Field Translation:

  Note: The Field Translation module does not provide content translation for fields. This functionality is provided by the Entity Translation (ET) module.

So could it be that the Entity Translation module is what is missing?


How to correct my Rules Component to perform VBO operations for the Group module? I followed the instructions included in the answer to the question "How to implement the mass operations on the Group's members page using Views?". The 2 Rules Components in it (to either block or unblock a member), work fine (and my VBO view shows the mass operations that use those 2 Rules Components).

Now I want to create a similar Rules Component for one of the other typical mass update operations (as used in the context of the Group module).

Below is the Rules Components (in Rules export format) I created for this so far, to "Delete selected members":

{ "rules_remove_a_group_membership" : {
    "LABEL" : "Remove a group membership",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "DO" : []
  }
}

This Rules Component should implement the equivalent of the Update option "Remove selected members" (as shown on group/gid/member, with gid=group id).

My question:

Something seems wrong in the Rule Component shown above, since I can't get it to do the equivalent of the Update option of the Group module (using VBO, similar to the answer in the question I mentioned above).

So how to correct this Rules Component to perform the equivalent operation using a custom VBO action created using a Rules Component, so that with the addition of this component, my custom VBO page should be equivalent to the default page of the Group module?

Part 1: Create a Rules Component

Have a look at this Rules Component (in Rules export format):

{ "rules_remove_selected_group_members" : {
    "LABEL" : "Remove selected group members",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "DO" : [ { "entity_delete" : { "data" : [ "group-mbrship" ] } } ]
  }
}

Some more details to further explain the above Rules Component:

It uses a "Group membership" (which is an entity, remember!) as a parameter.
All it does is to perform an Action "Delete entity", for the entity specified as parameter.

By deleting such entity, you do the same as what happens when using the "Remove selected members" (for 1 specific Group membership, entered as parameter).

If you want, just copy the exported Rules Component above, and import it in your own environment. Then navigate to admin/config/workflow/rules/components in your own site and use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Group membership identifier and hit the Execute button. The Group membership for the id you specified will be deleted then.

Tip: (temporary) improve your Group Membership view to also include the field "Group Membership Id" (=mid). This makes it easy to know which ID to use when testing this Rules Component.

After you're confident this Rules Component works perfect for all variations of your nodes, it's time to move on to Part 2 below.

Part 2: Extend your VBO view

The typical next step when creating custom VBO oprations, is to edit the VBO field in your view, and enable the additional VBO operation that corresponds to the Rules Component as in Part 1.

In my case, with the VBO view I'm using, I ran into some AJAX error which I could not resolve right away. I was pretty sure it is NOT a bug, but rather something I'm doing wrong. Head over to Part 4 for more details on that.

However while further investigating this error, I realized that there is no need at all for a Rules Component to implement that VBO action "Remove selected members". Head over to Part 3 for more details on that (sometimes the solution to a problem, is to prevent the problem from happening ...).

Part 3: Enable a standard VBO action

Head back to your VBO field in your view, and enable "Delete item" (within Selected Bulk Operations). I suggest to use the "Override label"-option for it, and give that VBO action a label like "Remove selected members".

QA-test this VBO action to confirm it does exactly the same as:

what you try to achieve with the custom Rules Component in bullet 1 of your question.
what I try to achieve with my Rules Component in Part 1 of this answer.

Part 4: Heading for the golden cradle (= Solve the AJAX error)

The AJAX error as in Part 2 is resolved by using this variation of the Rules Component from Part 1:

{ "rules_remove_selected_group_members" : {
    "LABEL" : "Remove selected group members",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "DO" : [
      { "entity_delete" : { "data" : [ "group-mbrship" ] } },
      { "drupal_message" : { "message" : "Membership of group [group-mbrship:group:title] removed for user [group-mbrship:user]." } }
    ]
  }
}

Note the "ACCESS_EXPOSED" : "1" added here now (apart from the extra "drupal_message" Action, which has nothing to do with the AJAX error). That turns out to be the clue to solve the AJAX error. For (way) more details on this, refer to Comment nr 13 in Support issue # 2530000. My understanding about that comment is that something in Entity API or Rules is what causes the AJAX error, and by using this access setting you prevent the issue.

With that, you now have 2 solutions/answers to solve your question ... i.e. to Remove selected members. My preference is using the Rules Component from Part 4, because:

The messages you get after executing it are more detailed as compared to Part 3.
If you want, you can add any additional Rules Action or Rules Condition in the Rules Component.

Voilà!


How to set default value for route parameter based on configured value? I have a route with optional parameter that has some default value:

# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
    name: 'there'
  requirements:
    _permission: 'access content'

I'd like to make there value for {name} parameter configurable. Let's assume that this default value for {name} is available in simple config variable.

You must implement a route alter. In the alter code, extract the setting and set the value on the route definition.


How can I add text in my theme? Drupal is a complex CMS but all I need is simply a text on my page in the specific region of the page ( that will be rarely changed ) that can be changed by an admin.

Here's my theme mockup.

The text is going to be in the red square area as seen above. That text is going to be rarely changed. I was trying to do this with 'Basic page' content type block but It isn't showing me what I want it creates some text showing up

"No front page content has been created yet. Add new content"

and when I create new content It shows up Read more and then redirects me to node/1 URL If I click it.

There must be some other simpler way of doing this. I mean all I want is text that is editable by admin in control panel not some fancy blog posts. Also please notice that I am still learning Drupal and any answer would be great!

By Default Drupal front page shows the list of Contents you create, the number of contents you can list is controlled in Site Configuration. To answer you particular scenario would be too much of an answer here, I'd recommend you to read some Beginner Documents or watch some Videos in the net. Good place to Start is Drupal documentation

To displaying content in front page go-to UR-URL/admin/config/system/site-information and change the default front page to node/1 (in your case). This will display static front-page when your created the Basic page.

Be aware this is not the best bet, so, I'd suggest you to explore Drupal bit more before actually starting the site building.


How to programmatically set role based permissions on a field? How do I programmatically set role based permissions on a field?

For example, I have field_my_field, for which I want the following permissions:

Owner can view and edit
Role X can view and edit
Role Y can view only

Looking in the database, the role_permissions table looks like it's what contains the data, but I'm confused about the actual permissions, as they're very close to natural language. e.g. 'access site in maintenance mode' although field ones make more sense:

Edit own field_my_field (owner can edit)
View own field_my_field (owner can view)
Edit field_my_field (can edit any)

I guess it's something along the lines of granting the permission to a RID, and identifying the module which interprets the permission.

Note: I'm trying to do this in another module with PHP - not in the UI. The Field Permissions module is great, but I need to do this in my code.

Ok, worked this one out...

I created my own function to do this, which I have called in the MY_MODULE.install file, as I'm creating the fields there, and as I understand, you can't set permissions in the install file.

Note, this is just a custom function name, not a hook - you could call it anything.

function MY_MODULE_assign_field_permissions($role_name, $permission, $field_name) {
    $permissions = array($permission.' '.$field_name)
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
}

$role_name is the name of your role, $permission is the natural language permission, like 'view own', 'create', 'edit', etc. and finally $field_name is the name you gave your field.

Here's how I would call it in my MY_MODULE.install file to allow the role type my_role view their own entries for field_my_field:

MY_MODULE_assign_field_permissions('my_role', 'view own', 'field_my_field');


How to change upload destination from private to public? On a Drupal 7 installation I have an image gallery (set up with the media gallery module). I set the upload destination to private to protect those images for anonymous users. Unfortunately it turned out, that the performance of private images is that poor, that the gallery became quit unusable.

So I decided to switch the destination to public for the node type. But as there already exist nodes of the mentioned type (I assume that my be the reason), the options of the node type's filed, where to set the destination is greyed out:

Is there any way to change the destination for existing nodes?

You could accomplish this by moving the files out of the private directory and into the public directory (make sure the paths stay the same!). Then you would need to update the 'file_managed' table. The 'uri' table will list the files as either private or public. The mySQL would be similar to:

UPDATE file_managed SET uri = REPLACE(uri, 'private://', 'public://') where instr(uri, 'private') > 0;

NOTE Please make sure to test this on a dev site before doing in production.


Views page showing a user's content I have created a image gallery on Drupal 7 users' profiles, which I would like to present as a separate page, linked to their profiles using views.

so, there would be a page at mysite.com/typical-user/gallery

I am at a loss on how to use the contextual filters to achieve this.

If you want to filter gallery images by user id try "provide default value" and than use arg(1) which is user id in your URL, More on this here : http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7


I want to customze menu_tree output I found a code in drupal page in this url http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_tree/6#comment-1073

code is

<?php
function phptemplate_menu_tree($tree,$menu_name="") {
     return '
'. $tree .'
';
}
?>

it is written that we can customize every menu by css and also adding $menu_name.

but even though that I have added this function into my template.php and it is working , $menu_name variable is always empty

really the target that I am following is :
I want to modify the css class of the ROOT us base on menu name.

for example for primary links , i want to have this return out put

'
'. $tree .'
'

or for secondary links i want to have this return output

'
'. $tree .'
'

$tree includes all nested li items from the selected menu.

please help me

page.tpl.php

for admin menu

    <?php print '
'.menu_tree($menu_name = 'navigation').'
';?>

//for primary menu
 <?php print  '
'.menu_tree($menu_name = 'primary-links').'
'; ?>
//for secondary menu
 <?php print  '
'.menu_tree($menu_name = 'secondry-links').'
'; ?>

template.php

  function menu_tree($tree}{return $tree;}


Check if block is visible I'm on Drupal 8,

I'm using \Drupal::entityQuery('block') to get the list of blocks.

Now I want to determine if the block is visible for:

Current Page (Content Type)
Current User (Role)
Current Path

I want this information according to visibility settings configured in block's configuration.

I can use $block->getVisibility() method when I load the block and there I can iterate through visibility settings and find out if the block is visible or not.

I wander if there is a better and easier way to do this??

Checking view access to a block includes visibility checks. so you can just do this: if ($block->access('view')).

Why do you want this information? block.module has a block.repository service with a getVisibleBlocksPerRegion() which gives you exactly that. a list of visible blocks, grouped by region.