How do you convert an existing order into a shopping cart order?

As you mentioned a shopping cart is nothing more than an order with the state of cart.

So all you need to do is to update the state of $order to cart using commerce_order_status_update() function:

<?php
$log = t('Reverting back to Cart state so the customer can modify items.');
commerce_order_status_update($order, 'cart', $skip_save = FALSE, $revision = TRUE, $log);

Alternatively if you are using rules, you can use the rule: "Set order status : Cart" which comes with commerce module out of the box.


You need to supply the tag the full URL to the image. If you install the Metatag module not only can you have full control over keyword, description, etc. but also all the og tags too per node.


How can I do a custom form redirect on the user registration form?

Login Toboggan has an option for this whereby you can use %uid as an argument for the redirect URL.

Literally a text box where you'd type /user/!uid/edit

It's also got a whole host of awesome features that are worth checking out :)


Devel query log not showing module enabling queries?

I found the answer: enable/disable module calls are ajax requests and the devel display query log doesn't show queries from the ajax request.

BTW, if you want to use hook_exit() you will notice it is not fired for ajax calls that use exit() and not drupal_exit(). However, if you need something to be run at runtime end, you can use PHP register_shutdown_function() in your module (in your hook_init() for instance).


How to make node hierarchy with siblings and child pages

You will need to create a entity reference field to find the parent node. On each child select the parent it belongs with.

In Views you can then create a "menu" by using views field views and passing the parent (content ID) argument into the child view.

In your parent view filter, make sure and filter by Parent is Empty to show only parents if there are no children.

On your child view, make sure Context has the entity reference to the parent.


Field collection fields are empty in edit mode

I've experienced this a while ago with field collections and paragraphs but can't remember the exact cause.  Suggestions for troubleshooting:

Check to make sure there's no updates available for the field collection module, Drupal Core, or any other modules that may be impacting the types of fields you're trying to assign in your field collection.
If your field collection involves an entity reference to either:

another node and allows creation of said node within the edit form, make sure to click save on the embedded node creation form before saving the overarching node.
a file upload, make sure to upload the file before clicking save on the overarching node.

If this still doesn't work, try creating the field collection from scratch, adding one field at a time to determine which one is causing the issue.


Insert an article and fields with db_insert function or SQL

If you need to save a node without invoking any hook, then use the same code node_save() uses, excluding the part invoking hooks.

  $transaction = db_transaction();

  try {
    if (!empty($node->nid) && !isset($node->original)) {
      $node->original = entity_load_unchanged('node', $node->nid);
    }

    field_attach_presave('node', $node);
    global $user;

    if (!isset($node->is_new)) {
      $node->is_new = empty($node->nid);
    }

    if (empty($node->created)) {
      $node->created = REQUEST_TIME;
    }
    $node->changed = REQUEST_TIME;
    $node->timestamp = REQUEST_TIME;
    $update_node = TRUE;

    if ($node->is_new || !empty($node->revision)) {
      if (!isset($node->log)) {
        $node->log = '';
      }
    }
    elseif (!isset($node->log) || $node->log === '') {
      unset($node->log);
    }

    if (!$node->is_new && !empty($node->revision) && $node->vid) {
      $node->old_vid = $node->vid;
      unset($node->vid);
    }

    if ($node->is_new) {
      drupal_write_record('node', $node);
      _node_save_revision($node, $user->uid);
      $op = 'insert';
    }
    else {
      drupal_write_record('node', $node, 'nid');
      if (!empty($node->revision)) {
        _node_save_revision($node, $user->uid);
      }
      else {
        _node_save_revision($node, $user->uid, 'vid');
        $update_node = FALSE;
      }
      $op = 'update';
    }
    if ($update_node) {
      db_update('node')->fields(array('vid' => $node->vid))->condition('nid', $node->nid)->execute();
    }

    // Call the node specific callback (if any). This can be
    // node_invoke($node, 'insert') or
    // node_invoke($node, 'update').
    node_invoke($node, $op);

    // Save fields.
    $function = "field_attach_$op";
    $function('node', $node);

    $delete = $op == 'update';
    node_access_acquire_grants($node, $delete);

    unset($node->is_new);
    unset($node->original);
    entity_get_controller('node')->resetCache(array($node->nid));

    db_ignore_slave();
  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('node', $e);
    throw $e;
  }

I didn't remove the call to node_invoke(), since that calls the hooks implemented by the module implementing the content type, and those hooks are necessary for the content type to work correctly.
I also left the call to db_transaction() because, in the case one of the operations fails, all the operations are rolled back, and the database is left in a consistent state, which means (for example) that every table will refer to the same node version ID.


If you use the Pathauto module, you can set an automatic alias for the user profiles using a token that is replaced with the username. In Pathauto for Drupal 7, the default pattern for user paths is /users/[user:name], which is the pattern I would suggest to use to avoid conflict with path defined from other module. As you don't control the username chosen from a user, it could happen the username is admin, which conflict with the path used from system.module for its own menu callback.

If you want to use a different token, the list of available tokens is available right after the text field used for the pattern to use.

What I reported is still valid for Drupal 6; the difference is that the token for the username is [user].


Is it possible to install new module without ftp in drupal 6?

If all directories are writable, you should be able to enable PHP module, create a node with PHP filter, and in that node use:

file_put_contents ( 'path_to_modules/mymodule/mymodule.info', 'name = example
description = Demonstrates how to write info file.
core = 6.x');

The same for module file.

Preferably do that with rudimentary module that will allow you to upload and extract zip / tar.gz module files as provided by Drupal.org, and then remove PHP filtered node and disable PHP module.


How to give access custom module to individual users?

The correct approach here would be to implement hook_permission to define permissions/a set of permissions to give your user roles specific access.

The Example module has some good info on how to use and validate permissions with hook_permission in your code.

If you want to restrict certain users, the easiest approach is to create an additional role with those specific things and assign the desired users to that role.


Bootstrap: Responsive tables with WYSIWYG text format

Option 1: Use Responsive Tables
To have more control over table columns, use the Responsive Tables module. Some details about it (rom its project page):

Adds a library to allow tables to function better in responsive layouts.
You can manually add the library to any table on the site. You also have the option of using the Better Views Tables module to configure the responsive table controls through the Views UI.

Option 2: Use a responsive theme
You should consider using a responsive theme, such as (popular) Omega or Zen themes. There is also the Beep Edition "theme", which (quote from project page) "is designed from the ground up as a mobile-first responsive theme". However that has like 5 module dependencies ...
For a list of way more (less known) responsive themes, refer to 26 More of the Best Responsive Drupal Themes. Quote from that link:

All of these free Drupal themes have responsive layouts, and they include great features like Bootstrap frameworks, Google Fonts, sliders, Font Awesome icons, Facebook integration, social networking icons, and more.


"Undefined index: und" Error fetching array in node form

To get usable markup of the field in template you need to render it before print.

print drupal_render_children($form['title']);

As explained here Theming Node Forms in Drupal 7

Additionally make sure you also render the hidden parts of the form to keep track of form identity related to system. If you wish to exlude some parts of the form, do something like this.

hide($form['field_body']);
print drupal_render_children($form);

This way drupal "render api?" can be aware of what has allready been rendered, what needs to be hidden and finally push out all required parts to make form functional.


If you develop your site in a sub folder, rather than a subdomain, you are going to be in for a bad time. All of your image paths and links are going to be incorrect. You are better of moving to a subdomain instead. If its already too late then use the Pathologic module to clean them up.

  Pathologic is an input filter which can correct paths in links and
  images in your Drupal content in situations which would otherwise
  cause them to “break;” for example, if the URL of the site changes, or
  the content was moved to a different server. Pathologic can also solve
  the problem of missing images and broken links in your site’s RSS
  feeds.


use the super fish module. http://www.drupal.org/project/superfish that should do what you need.


How to force entity translations to load in a certain language with user_view() or entity_view()

So one workaround is to force it manually like this:

$agegroup = $user_profile['field_acc_age_group']['#items'][1]['taxonomy_term']->name_field[$lang][0]['value'];


Installed base them NineSixty - where is it?

If you have access to the database, check the "system" table of your drupal database and look for a record with the "name" ninesixty. That row will also tell you the path to the theme.

If you have phpmyadmin via cpanel or something similar you can just browse the system table.

Otherwise you could use this SQL (if your database is using a prefix it will be slightly different a the prefix will be appended to the table name "system"):

SELECT * FROM system WHERE name = 'ninesixty';

and that will give you all the info about your ninesixty theme.

Another way is to search your file system for the word ninesixty, which I imagine won't be anywhere except for the theme and maybe your base theme.


How to add more image styles to an image element in a content type

Instead of altering the default field widget of the image fields, you should create an own custom field widget.

You may either extend the existing widget, or create it from the scratch by copying the image field widget's code to your own widget.

Then you will be able to just select that widget for your images that require two image styles to be selected, while other image fields can still use the default widget.

Edit:

For defining the different image styles for output to the end user (within your slider), you will be better off to creating a custom field formatter with according settings and output and choosing this formatter in "Manage display" of your content type. A good starting point once again is the existing field formatter.


Enable PHP Filter module comes with Drupal core

  The PHP filter core module adds the ability to include PHP code in
  posts. PHP is a general-purpose scripting language widely-used for web
  development; the content management system used by this website has
  been developed using PHP.

The following is a guide to add a new text format filter in Drupal 7:

Navigate to the Text formats page Administer » Configuration » Content authoring » Text formats (/admin/config/content/formats).
Click Add Text Format (admin/config/content/formats/add).
Enter the following information:
Name: The name of the filter as it will appear in the administration interface.
Roles: Select one or more roles that will be able to use the format.
Enabled filters: Enable one or more filters.  Note: As filters are selected, items are added to the Filter Processing Order and Filter Settings sections.
In the Filter processing order section, drag the four-headed arrow to rearrange the order in which the filters will be applied.
In the Filter settings section, specify the settings for the selected filters. Some filters do not have settings.

Click Save Changes
WARNING: Some HTML markup should only be available to authenticated and trusted users. The PHP option should not be enabled unless it is necessary and care should be taken to limit access to a role representing trusted and knowledgeable users.


Setting up a date field to require an end date

I believe you would need to setup the requirement on the form you are building for the custom content type so you would add this to the date_end form entry:

$form['CUSTOM_CONTENT_TYPE']['DATE_END'] = array(
...
  '#required' => TRUE,
...
),


Remove it unless you have an automatically loaded node associated with it.


Fixing Notice: Undefined variable: content_share in include() (line 39....node.tpl.php)?

Regions are only available in page.tpl.php, not node.tpl.php.

In page.tpl.php you can use

print render($page['content_share']);


Drupal db_or() only returning one result

It's, because you are calling fetch(). That method fetches a single result.

If you want all, you can simply loop over the return value of $query->execute() or use fetchAll() or one of the many related helper functions.


RuntimeException when patch submission. Module Webform Rest

Ok mate if you open up
webform_rest\Plugin\rest\resource\WebformSubmissionResource.php
and find the patch method you will see
public function patch($webform_id, $uuid, array $webform_data) { ...

looks like Webform Rest 4.0.0-beta1 is now using the submission uuid
so
/webform_rest/{webform_id}/submission/{sid}

"sid" should now be Webform Submission UUID
for the body field or the $webform_data
the module is looking for
  foreach ($webform_data as $field => $value) {
      $webform_submission->setElementData($field, $value);
    }

so your json should look like:
   {
    "filed_name": "value"
   }

because json_decode($json_string, true) will return an array.
if that does not work then file a bug ticket


an error occurred while installing jplayer and audiofield module on server in drupal 7

Try to create a temp directory and give 777 permission and change file system's temporary directory from 'admin/config/media/file-system' to that temp directory. Because C:/xampp/tmp/ doesn't exist on your server.


Allow the node preprocess function to be called after setting the theme function in hook_node_view()

With that line, you set the theme function for all the content shown for the node. Your code should be similar to the following one, taken from the documentation for hook_node_view().

function mymodule_node_view($node, $view_mode, $langcode) {
  $node->content['mymodule_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_custom',
  );
}

As to why your code is setting the theme function for all the node content, see the code executed by node_view(). (The comments are mine.)

  // This is the function that invokes hook_node_view().
  node_build_content($node, $view_mode, $langcode);

  $build = $node->content;

  // $node->content['#theme'], the value you set, becomes $build['#theme'].

  unset($node->content);

  // The following lines don't set anymore $build['#theme'], since you have already set it.
  // It is similar to executing the following code:
  //   $a = array('first' => "I am the first");
  //   $a += array('first' => "The array will never get this value");
  //
  // If you print the value of $a, you will see it is as it was first set.

  $build += array(
    '#theme' => 'node',
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  // Now the code is going to use your theme function, which means that not even
  // the node preprocess function is executed.

Normally, what you want to do is adding a new content to the render array for the node. That is what the code I show in the first snippet does.

If you really wanted to change the theme function used for the node, then you should simply implement hook_theme_registry_alter(), and redefine the function associated with the node theme function.

Keep in mind that once you change the used theme function, also the preprocess function changes; in your case, if theme_my_custom_theme_function() is your theme function, then the preprocess function is mymodule_preprocess_my_custom_theme_function().


How to display only the first value in Views, by overriding TPL.PHP?

You can do this on the View edit page using the UI without editing the template.

Go to admin/structure/views
Edit the view in question
Under Fields, select the field in question
Expand the section 'Multiple field settings'
Set as: 'Display 1 value(s) starting from 0 (first item is 0)
Save your view and that's it.


How can I use NID Token with the Insert Module?

You want to use the filefields_path module to add node tokens to your imagefield (or any other file fields):

  The File (Field) Paths module extends the default functionality of
  Drupal's core Upload module, the FileField module and many other File
  Upload modules by adding the ability to use node tokens in destination
  paths and filenames.

In my test environment with the insert module and this module enabled, I now have the capacity to use node:nid in the filefield path as well as a number of other useful tokens:


I understand that modules in Drupal aren't classes

Yes, however Drupal modules can certainly make use of classes, and many do.

You can use as many classes as you like.

Put your private functions in class definitions and access them that way.

Include the class file in your module.info file:

files[] = includes/MyModuleClass.class.php

You can use public and private variables in your class

public $public_var;
private $private_var;

Add private methods to your class

// Public
public function myPublicFunction(){
  $this->public_var = 'Public';
}

// Private
private function myPrivateFunction(){
  $this->private_var = 'Private';
}

Instantiate an object with

$options = array(); // example constructor params
$object = new MyModuleClass($options);

echo $object->public_var; // OK
echo $object->private_var; // Error

$object->myPublicFunction(); // OK
$object->myPrivateFunction(); // Error

More info in the PHP OO docs

http://php.net/manual/en/language.oop5.visibility.php
http://php.net/manual/en/language.oop5.php


Converted CSS/HTML theme to D7, .js files ignores integrated jQuery and works only with jQuery imported via .info

add a anther js file via theme's .info;

scripts[] = js/mycustomscript.js

dont add your inline script in html.tpl.php , add it in mycustomscript.js file like

(function ($) {

  Drupal.behaviors.exampletheme = {
    attach: function (context, settings) {
      $(".carousel").jCarouselLite({
                btnNext: ".next",
                btnPrev: ".prev"
     });
    }
  };

})(jQuery);


Allow a user to flag the same node/user multiple times

How about using the Five Star module and incrementing the rating each time?  Eg, first reply, rate the message 1.  Next reply, re-rate the message 2.  When you get to 3 (or 4 or 5) don't allow more. You could implement this directly with the Voting API if you wanted to, too, I'd imagine, if you needed higher than 5.


How cache tables are different from other normal tables in database?

Cache tables contain the results of expensive queries. Often more than one query in a single cache row.

As a contrived example, take a node. When you load a node, you have to join in all of the single field tables containing it's data, plus make a bunch of separate queries for extra data. That's a lot of db load.

Wouldn't it be quicker if you could make just one, single, light query and get all of that information in one go?

That's what cache bins are for. There may well be scenarios where querying from cache is as/more expensive than the original operation, but they'd be rare.

Also don't forget your cache doesn't have to be in the database, you can get considerable improvements moving it into memory.


addTranslation takes a second parameter, $values:

  An array of initial values to be assigned to the translatable fields. Defaults to none.

So in theory you should just need to make use of that parameter, and pass the node's current field values:

$node->addTranslation('de', $node->toArray());


How do I filter a view within a view based on an Enity Reference field when NID is not in the URL of the container view's page?

You can use myexhibit/NID url for this view page and then set up an alias (for example myexhibit/TITLE). If you want to make this page only for certain artists you can filter them by node ID.


Add body classes to 404 and 403 error pages

For anyone working with Drupal 7, the function names and the way you pass variables are a bit different. The D7 solution for a 404 would look like this:

function MYMODULE_preprocess_html(&$variables) {
  $headers = drupal_get_http_header();

  if (isset($headers['status']) && $headers['status'] == '404 Not Found') {
    $variables['classes_array'][] = 'page-404';
  }
}

The drupal_get_headers() function from D6 is now drupal_get_http_header() in D7. The values returned are structured a bit differently. You can view the contents of the array with "dpm($headers);" if you're using the devel module.

Finally, additional class variables can be added as elements of the $variables['classes_array'] by assigning them to an empty index, which will then be added to the html body tag via the template_process() function.


Aliases are alternative paths to the node. They require the canonical path, so that there is a path to be an alternative of. The canonical path requires the Node ID (Entity ID) as node paths are /node/[NODE ID]. The Node ID doesn't exist until the node has been saved, as it comes from the database upon save. So the path does not exist until the node has been saved, meaning there is nothing to alias.

So the answer is that no, it's impossible to create an alias before a node has been saved, as the canonical path does not and cannot exist until the node has been saved.


To get your NID back (after it has been aliased) one of the solutions here is for you:

Drupal 7 Contextual Filter on URL Alias

But first I'd make sure your view is set up correctly with a contextual filter that has a relationship to the entity reference field ...

On your "view" click "Advanced". Click the "Add" button to the right of Relationships.

Find the "Entity Reference: Referenced Entity" relationship and check the box. Click "Apply". On the next screen, click "Apply" right away unless you want to change the identifier or make the relationship required.

Once you are back to your view's 'advanced options' Click the "Add" button to the right of Contextual filter and select "Content: Nid".

Under "Relationship", ensure that the entity reference relationship you added previously is selected. Next, select "Provide default value" and then set the type to "Content ID from URL". Click "Apply".

Stolen from here: https://www.drupal.org/node/1841004


Menu does not translate on second language

Your menu link translations are likely not published. Check the translation details element on the translate form and make sure the published checkbox is checked.

The default behavior around that is a bit weird, especially if you create the menu links before enabling translations, there is an issue that should improve that, might already be better in 8.4


Can't you just add your own submit handler to the form you're talking about rather than trying to override an existing one?


Sounds like some simple Javascript. E.g. by the help of JQuery you could bind a click/submit function on the login-form, show a confirm-window ("Would you really like to log in?") and if this is confirmed, submit login-data (or not).

Such a function could(!) look similar to this:

$('#user-login-form').submit(function(){
 var r = confirm("Would you really like to login?");

 if (r == true) {
    return true; // submit form-data
 } else {
    return false; // stay on page
 }
});


On Rules Event Present Splash Screen To Flagged User

One possible way is define your own Rules action against on that event.

Check the api: (assuming you are using D7)

http://drupalcontrib.org/api/drupal/contributions!rules!rules.api.php/function/hook_rules_action_info/7

Use jQuery to pop up an alert or whatever you like.


Would I be in "Blacklist" to send bulk mail by Simplenews?

As far as I'm aware, your ip gets blacklisted if a couple of people click 'report spam' in the email browser.  Consider setting the SMTP on your server to use a web service such as MailJet who have all kinds of advice on what to do and what not to do.


How can I avoid to return HTML markup for access denied?

If you look into ParagraphAccessControlHandler you will find something similar.
Implement something similar in your Access callback.
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {

// Allow paragraph entities to be created in the context of entity forms.
  if (\Drupal::requestStack()
    ->getCurrentRequest()
    ->getRequestFormat() === 'html') {
    return AccessResult::allowed()
      ->addCacheContexts([
      'request_format',
    ]);
  }
  return AccessResult::neutral()
    ->addCacheContexts([
    'request_format',
  ]);
}


How do I refresh a view (or a page) after a new comment has been posted?

Try using Views Auto-Refresh module.

  A module to refresh a view after a specified time interval. Includes
  advanced options to avoid reloading the whole view, and to avoid
  causing a full Drupal bootstrap at each refresh.

If you are looking for REAL realtime update you should use some server side javascript like nodejs, to push event to the dom.

also there is nodejs module for Drupal.

A great tutorial


Hide tab created by views if user has a specific role

Finally it worked for me using hook_menu_local_tasks_alter(), thanks to drupal developers community.

function hide_tabs_menu_local_tasks_alter(&$data) {
  if (arg(0) == 'user' && is_numeric(arg(1))) {
    $uid = arg(1);
    $account = user_load($uid);
    if (in_array('gerant', array_values($account->roles))) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == "user/%/infos") {
          unset($data['tabs'][0]['output'][$key]);
        }
      }

    }
  }
}


MachineName field element: How do I use the source and exists properties?

We can look at Drupal\node\NodeTypeForm.php for an example.

We see the name and type fields defined like:

$form['name'] = array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  // ...
);
$form['type'] = array(
  '#type' => 'machine_name',
  // ...
  '#machine_name' => array(
    'exists' => [
      'Drupal\node\Entity\NodeType',
      'load',
    ],
    'source' => array(
      'name',
    ),
  ),
  // ...
);

This shows us how to define the special machine_name type properties in the array. We can see that both exists and source are defined inside #machine_name. Additionally, we see that the exists callback is just calling the NodeType::load() (which is actually inherited straight from Drupal\Core\Entity\Entity::load()).

For our exists callback, given this example, we'll want to use the equivalent method for whatever kind of entity we're creating a machine name for. Given your example, we're creating webforms, so we'd use the Drupal\webform\Entity\Webform::load() method for the exists callback.

We also see, from the machine_name element documentation, that the source property needs to be the #array_parents of the source field. Since your fields are nested inside settings, you'll need to include it in the source property.

Given the above, your updated code should be:

$form['settings'] = [
  'label' => [
    '#type' => 'textfield',
    '#title' => 'Form Title'
  ],
  'id'=> [
    '#type' => 'machine_name',
    'label' => 'hh',
    '#maxlength' => 64,
    '#description' => $this->t('A unique name for this item. It must only contain lowercase letters, numbers, and underscores.'),
    '#machine_name' => [
      'exists' => [
        'Drupal\webform\Entity\Webform',
        'load',
      ],
      'source' => [
        'settings',
        'label',
      ],
    ],
  ],
];


Here is the answer to my question by using the chaos tools:

// this creates the url that can be entered to reach this form
function ctools_ajax_sample_menu() {
  $items['ctools_ajax_sample/simple_form'] = array(
    'title' => 'Simple Form',
    'page callback' => 'regone_form',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  return $items;
}

function regone_form() {
  global $user;

  ctools_include('ajax');
  ctools_include('modal');

  // Add Ctools' JavaScript to the page.
  ctools_modal_add_js();

  $sample_style = array(
    'ctools-sample-style' => array(
      'modalSize' => array(
        'type' => 'fixed',
        'width' => 500,
        'height' => 400,
        'addWidth' => 20,
        'addHeight' => 15
      ),
      'modalOptions' => array(
        'opacity' => .5,
        'background-color' => '#246'
      ),
      'animation' => 'fadeIn',
      'modalTheme' => 'CToolsSampleModal',
      'throbber' => theme('image', array(
        'path' => ctools_image_path('ajax-loader.gif', 'ctools_ajax_sample'),
        'alt' => t('Loading...'),
        'title' => t('Loading')
      )),
    ),
  );

  drupal_add_js($sample_style, 'setting');

  ctools_add_js('ctools-ajax-sample', 'ctools_ajax_sample');
  ctools_add_css('ctools-ajax-sample', 'ctools_ajax_sample');

  $links = array();
  $links[] = ctools_modal_text_button(t('Wizard (custom alex modal)'), 'ctools_ajax_sample/nojs/animal', t('Pick an animal'), 'ctools-modal-ctools-sample-style');

  $output  = theme('item_list', array('items' => $links, 'title' => t('Actions')));

  // This deals with theming of the modal box.
  $output .= theme('ctools_ajax_sample_container', array('content' => '<h1>' . t('Sample Content') . '</h1>'));

  return array('markup' => array('#markup' => $output));
}


When using the Omega Responsive theme, IE7 and IE8 load all stylesheets

Omega does not support responsive layouts for IE 8 & below. You will need to add respond.js or a similar javascript to your theme in order to make up for IE 8 & below's lack of support for CSS media queries.

There is an Omega issue on drupal.org related to this topic with more detailed information.


The answer is the same as in Drupal 7, because there is no API to return multiple aliases for a single source path, so your only option, if you really need that (I guess there is a reason that you are not using redirects), is a custom query, which is the same as in 7.x, with the only difference that it has a leading /.

So, copied from the other issue:

$aliases = \Drupal::database()->query('
  SELECT alias
  FROM {url_alias}
  WHERE source = :source
', array(':source' => '/node/' . $nid))->fetchAll();


Why there is not loadData() method in FileSystem?

To answer your questions in respective order:

Sure. If there's no built-in API function to make it easier, there's nothing wrong with using file_get_contents since the function can use Drupal's file stream protocols.
The core test,
FileSaveDataTest::testFileSaveData(), is doing this to confirm that saveData() works.
One can only guess about the requirements as the class was composed. saveData() is a wrapper around a file_put_contents() op so that logging can take place when Drupal writes to a temp file. Perhaps there was no need to wrap file_get_contents in the same way?
Drupal has a StreamWrapperManager service class that registered different custom myscheme:// streams with PHP. This manager makes use of core PHP function stream_wrapper_register() to register any injected class that has the tags: { name: stream_wrapper, scheme: myscheme }. For example, look at CoreServiceProvider::register() which registers the private:// scheme when it detects file_private_path settings has been set.


Automatically fill in the subject line of contact form

There isn't a built-in way to do this with the contact entity form. The prepopulate module looks like it would be covered under this scenario, but it doesn't work on contact forms.

As an alternative, a simple form alter with a custom module could do this on the back end, or front end, with a hook_form_alter() invocation.

The backend solution could alter the default form value:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  // Set the default subject based off the subject query param.
  $default_subject = \Drupal::request()->query->get('subject');
  $form['subject']['widget'][0]['value']['#default_value'] = $default_subject;
}

Or the frontend solution can attach a custom JS file:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  // Assuming mymodule has defined a drupal.mymodule library
  // within mymodule.libraries.yml
  $form['#attached']['library'][] = 'mymodule/drupal.mymodule';
}

Then have the attached JS attach to a Drupal behavior:

(function ($, Drupal, drupalSettings) {

  // Attach a drupal behavior that uses jQuery to alter the form value.
  Drupal.behaviors.mymodule = {
    attach: function () {
      var subject = '';
      // @TODO: parse location.search for the subject query param.
      $('#edit-subject-0-value').val(subject);
    }
  };

})(jQuery, Drupal, drupalSettings);


How do I change the date format depending on Start and End date in Drupal 7

Enable the Date Views module

In views, click on your field and change Date Format to Custom

For Custom Date Format: you can put something like this m/d/y  or M d, Y

You can format it however you want by using the format characters from the PHP manual


Inline Javascript throws an error on drupal_add_js() within an AJAX callback

Quick written code:
      <?php

      /**
        * Form.
        */
      function sample_luhn_form($form, &$form_state) {
        // I don't recommend inline js, prefer usual module js file, attach via $form['#attached'] or in module info file
        // Also I am use jQuery instead of $, but your shown (function ($) { }jQuery)); is preferred, I don't know why it's show errors, try inspect on dev.tools
        drupal_add_js('jQuery(document).ready(function () { jQuery(".luhn-nums").keydown(function() { if (jQuery(this).val().length >= 5) { jQuery(".luhn-check").mousedown(); } }); });', 'inline');

        // text field that should be checked for Luhn
        $form['luhn_nums'] = array(
          '#type' => 'textfield',
          '#title' => t('Luhn numbers'),
          '#prefix' => '
',
          '#suffix' => '
',
          '#attributes' => array(
            'class' => array('luhn-nums'),
          ),
        );
        // hidden ajax button
        $form['luhn_check'] = array(
          '#type' => 'submit',
          '#ajax' => array(
            'callback' => 'sample_luhn_form_ajax_submit',
            'wrapper' => 'luhn-nums-wrapper',
          ),
          '#attributes' => array(
            'class' => array('luhn-check', 'element-invisible', 'hidden'), // set class, that hide this ajax submit button or hide via CSS styles
          ),
        );

        // here goes another form elements
        // ...
        $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
        );
      }

      /**
       * Ajax callback function.
       */
      function sample_luhn_form_ajax_submit($form, &$form_state) {
        if (_sample_luhn_check($form_state['values']['luhn_nums'])) {
          // If luhn not passed
          form_set_message('luhn_nums', t('Luhn error, please fix numbers'));
        }
        // here you can alter luhn_nums textfield value
        return $form['luhn_nums'];
      }

      /**
       * Validate form.
       */
      function sample_luhn_form_validate($form, &$form_state) {
        // Don't allow pass to submit untill luhn will passed
        if (_sample_luhn_check($form_state['values']['luhn_nums'])) {
          // If luhn not passed
          form_set_message('luhn_nums', t('Luhn error, please fix numbers'));
        }
      }

      /**
       * Form submit.
       */
      function sample_luhn_form_submit($form, &$form_state) {
        // save data
      }

      /**
       * Private function that check luhn algorithms.
       */
      function _sample_luhn_check($nums) {
        $result = FALSE;

        // check numns by luhn algorithms
        // lot of code that alter $result

        return $result;
      }


How to exclude views fields from display when a node is flagged

General approach:

Use the Rules module (which does not yet have a stable release for Drupal 8, but does have the capability in its current state to implement the recipe below) to detect the content is flagged, then do a Rules action which will result in those fields being hidden.

Here is one specific example, but there are many ways, and likely simpler ways to do it than my recipe. I wanted to give you an example that doesn't require coding or extra modules besides the Rules module:

Drupal automatically includes a body class with the content type of the node. So make a rule that will evaluate that a node has been flagged, and if it is, change that node's content-type via the action "Data => set a data value." Now you can easily create the css to hide the fields that you want hidden by using the body class for the content type assigned flagged nodes.

Make sure the two content types use the same fields and have all the same settings for those fields.

Also make sure to set up a second rule which does the opposite so that the content type is returned to the original when the flag is removed.


Search API and Facets API with multilingual taxonomy

To localize FacetAPI you should install FacetAPI i18n.

  The Facet API Translation module integrates the Facet API and
  Internationalization projects allowing site builders to translate
  configuration settings. This module also overrides common mapping
  callbacks, such as the content type mapping callback, to translate the
  display name of facets.


How do I re-run updates (change module schema version)?

While accessing state directly works, you can also just use the API: drupal_set_installed_schema_version(). Which actually exists unchanged at least since 4.7, as visible on the linked documentation page. Probably one of the few API functions that existed for so long ;)

To set it from drush:

drush ev "drupal_set_installed_schema_version('fillpdf', 8012)"

Note: In Drupal 7 you need to add extra include 'includes/install.inc';.


How can I create Rules condition for event when 404 error generated?

Navigate to this path admin/config/system/site-information, which will look like www.example.com/admin/config/system/site-information.

Enter the page URL(your page for 404) in the 'Default 404 (not found) page', where you want to navigate your user when 404 happens.

Note - I don't think you can detect 404 from rules. May be somebody can answer about that but not me. Though I have experience with rules but never seen this kind of thing.


How can I see all the places an asset or entity is referenced?

Have you looked at /admin/structure/views/view/files? Is that what you need?

Otherwise, you might try your creating your own view of files at /admin/structure/views/add.

No matter the view, you will need to check the file before deletion as there will be no functionality to warn admins.

Then for content, I think it would just be a view of content focused on adding the Content Reference field (or whatever you content reference field_name is), which can show where references are coming from.

langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_content_reference
  module:
    - node
    - user
id: content_references
label: 'Content References'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: full
        options:
          items_per_page: 50
          offset: 0
          id: 0
          total_pages: null
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          tags:
            previous: '‹ Previous'
            next: 'Next ›'
            first: '« First'
            last: 'Last »'
          quantity: 9
      style:
        type: table
      row:
        type: fields
      fields:
        field_content_reference:
          id: field_content_reference
          table: node__field_content_reference
          field: field_content_reference
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Referenced Content'
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: entity_reference_label
          settings:
            link: true
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          plugin_id: field
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Referenced By'
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
      filters:
        status:
          value: '1'
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
        field_content_reference_target_id:
          id: field_content_reference_target_id
          table: node__field_content_reference
          field: field_content_reference_target_id
          relationship: none
          group_type: group
          admin_label: ''
          operator: 'not empty'
          value:
            min: ''
            max: ''
            value: ''
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            placeholder: ''
            min_placeholder: ''
            max_placeholder: ''
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: numeric
      sorts: {  }
      title: 'Content References'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.node.field_content_reference'
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.node.field_content_reference'

I am not sure about an all in one solution...


Show block for specific content type programmatically

If you look at the node_module file it controls the node type visibility using the hook_block_list_alter.

So basically it might looks something like this.
NOTE: This is a non tested version.

function hook_block_list_alter(&$blocks) {
  $node = menu_get_object();
  // list of all block deltas u want to apply this
  $block_delta = array('deltas');
  foreach ($blocks as $key => $block) {
     if (!empty($node) && $node->type == 'page' && in_array($key, $block_delta)) {
       unset($blocks[$key]);
       continue;
     }
  }
}


Render arrays are trees. If you hide() the subtree P1.P2.P3.P4, it's stil possible for a supertree (P1.P2 or P1.P2.P3) to have caching enabled (i.e. have #cache set).

Also note that just having #cache set does not mean that the subtree with that element as a root does not get cached per se. Only when #cache[keys] is set is render caching triggered. #cache can also just contain cacheability metadata (tags, contexts, max-age) describing the cacheability of that subtree.

See https://www.drupal.org/developing/api/8/render/arrays/cacheability.


The object/array is too big for your server resources to handle the default kint settings.
Edit modules/devel/kint/kint/config.default.php and set $_kintSettings['maxLevels'] to a lower number to reduce recursion and the memory needed for dumping variables. The default is 7, I have mine set to 4. If 4 still doesn't work for you, keep lowering the number.


How to convert taxonomy term name to term id at time of importing and create custom node from csv in drupal?

This function will return the term object if you pass it the term name:
https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_get_term_by_name/7

There is an example at the bottom of that link


Passing a single two word value into contextual filter that allows multiple values

in your case I think you need to separate values with plus-characters. so it would be:

views_embed_view('places_to_stay', 'block', "new york+chattanoog");

Because you have a single argument expecting multiple inputs.

in some other cases you might use the comma separator if you have multiple arguments each expecting a single inputs.


dl.example.com/file1.zip instead of example.com/sites/default/files/file1.zip

In my opinion if you can create a subdomain dl.example.com then you can also redirect all requests to default/files subfolder using symbolic link in /home/domains/dl.example.com/ linking to /home/domains/example.com/sites/default/files/
depending on your .htaccess or httpd.conf setup.

Please note I don't think this is a Drupal-specific question, I am not an expert on this and you'd better asked on https://serverfault.com/

I think using this method will be faster then creating a custom module to do this for you because the method I explained doesn't even require loading Drupal for the request handling.


Read and write files from external FTP server

I think you better face this problem using system commands that adding FTP support to the Drupal stack.

For this you can use:

1) standard FTP. You can read here how to automate FTP commands from a bash script:
http://www.stratigery.com/scripting.ftp.html

2) SFTP, FTP over SSH. If you can use SSH public key authentication this is the best way as you only will have to exec this command every day:

scp your-remote-user@your-remote-server:/path/to/files/* /local/dir/for/files

Once your files are copied locally you only have to process them with Feeds.

You can even use PHP exec and launch the script that retrieves your data from the Drupal Cron.


What happened to the edit links in the Page Manager UI?

Found the problem-- I had been lazy and replaced the "Edit" translation string with a space to remove it from some of the pages on the site, forgetting that it would remove "Edit" from all pages on the site.  Restoring the string fixed the problem.


The MigrateFileUri destination has a class property which indicates what to do when collisions are encountered.

  /**
   * How to handle destination filename collisions.
   *
   * @var int
   */
  protected $fileReplace = FILE_EXISTS_RENAME;

What you want to do is, extend MigrateFileUri override $fileReplace to be FILE_EXISTS_REPLACE and then use that as your destination.

example:

class MigrateFileUriReplace extends MigrateFileUri {
  protected $fileReplace = FILE_EXISTS_REPLACE;
}

Don't forget to update your migration code.

$this->addFieldMapping('field_image:file_class')
     ->defaultValue('MigrateFileUriReplace');


Why date field is picking the user's timezone?

In Drupal, dates stored in the DB do not have any timezone fixed to them; it presumes all date fields are consistent in timezone and relies on the system's timezone setting to offset everything to its correct date for displaying.

There are two different offset settings: the field's timezone settings (which adjust from user's timezone input to the site's timezone) & the user's timezone setting which adjust display from the site's timezone to the user's timezone.

Needless to say, the various offset settings can make for a confusing situation to adjust to your needs.

If you want to keep the field adjusted to the site's settings and have the users still adjust for their own time zone, you should customize the display of your field so the time zone is presented in an unambiguous format.


A quick fix is to use a bit of custom code to save the profile fields in the time of user creation as empty. Say you have a profile of type of "main". This have to be done while creating the users, find the appropriate hooks here.

Now just create the user's profile with empty values.

// create profile object
  $profile = profile_create(array('user' => $account, 'type' => 'main'));
  // populate profile fields
  $profile->field_firstname[LANGUAGE_NONE][0]['value'] = '';
  $profile->field_lastname[LANGUAGE_NONE][0]['value'] = '';
  $profile->field_gender[LANGUAGE_NONE][0]['value'] = '';
  // save profile
  profile2_save($profile);

Ref: here and here

This may solve your problem. if now then let me know.


The short answer here is to disable & uninstall the Views Data Export module. Once you uninstall it, all the tables should be wiped out. The longer answer is why worry so much about so much size? The views_data_export_object_cache seems like it should contain large chunks of data that can be cached from previous exports.


How to use Rules to disable access to selected fields while editing an existing node?

You're right, there is no such event like "While editing an existing node". Probably because an event is something that takes like a fraction of a second, while editing may take minutes (hopefully not hours!).

However, you might get it to work by implementing an "edit-in-progress" (= EIP) feature using the Flag module, combined with using the Rules module. Similar to what I described in my answer to "Can the Flag module be used to lock content while editing to prevent concurrent edits?" (BTW, that question is a variation of yours, I don't think it's a duplicate though ...).

After you'd have such EIP-flag available, it should be straight forward to use it in appropriate Rules to "restrict/disable access to certain fields" (eg based on a data comparison to validate selected field values (using their before and after save values).


Modules only appear listed on the uninstall tab if they have been enabled and then disabled at some point in the past, AND if they actually installed something in the database that can be uninstalled (i.e. custom tables, variables, etc.) OR they implement hook_uninstall, even if they don't install anything in the database.


How to unflag/reset a flag again, when matching some conditions in onFlag event?

I'm guessing the problem is that in the onFlag event, the flag is still being created, so it can't be unflagged because it hasn't been fully saved yet.
But I think the bigger problem is that your code has a logic error-- validation should happen before the action, not after the action.
It looks like you are trying to do this:

When a user is flagged,
check if the flag meets certain "unflag" conditions,
if the conditions are met, unflag the user.

However, validation in Drupal usually is applied before something happens, not after.  Validation is not supposed to be a kill switch to stop a problem; you should stop the problem before it happens.
One reason to stop the problem before it happens is that you later may add code that does something when a node is flagged (for example, in hook_entity_insert()); in such a case, you would also have to undo the code in your flag event subscriber.
So, what you probably want to do is apply the validation login in hook_form_alter() so you can stop the flagging before it happens.


Didn't realize that I need to upgrade my drush to 8.0.1 as drush 6.7 won't work with drupal 8.


List related nodes through the same referenced node?

I can't believe I just did it myself, though not sure if it's the best way.

First add a relationship, Content: Author (field_reference_author), give it a name: field_reference_author

Then add a relationship, Content: Author (field_reference_author) - reverse, set RELATIONSHIP to the field_reference_author, give it a name: field_reference_author_reverse

Set each displaying field to use relationship: field_reference_author_reverse

Add contextual filter, Content: Nid , without any relationship, Provide default value :content ID from url.

To exclude the node that is containing the related nodes list, from the list, just add contextual filter:  Content: Nid , with relationship: field_reference_author_reverse, Provide default value :content ID from url.

And it's done!


modifying results displayed for Search API Live results module

for(key in matches){
   var endOfUrl = matches[key].search('>')+1;
   var url = matches[key].substring(0,endOfUrl);
   var rest = matches[key].substring(endOfUrl);
   var regex = new RegExp( '(' + searchString + ')', 'gi' );
   bolded= rest.replace( regex, "<b>$1</b>" );
   matches[key]= url+bolded;
}

right before the line

db.cache[searchString] = matches;

This bolds all occurrences of the word in the Title and makes sure the bolding goes into the cache for when it's pulled up again.

Another update:
I was able to get my results grouped by content type by installing and enabling Search API grouping and modifying my index's filter (admin/config/search/search_api/index/node_index/workflow) so that under "enabled processors" i checked grouping.

Once I did that, I also modified my search page so that my view mode was Live Result Search. This gave me access to the node content type in the js file I was modifying so that I could then parse the html string for the node-type and add an element to the live results list that was the content type label. Comment if my JS file interests you.


How to track popular categories (taxonomy terms)

I don't know of a module which does this but you may be able to do it via google analyitics

token array will allow you to put all taxonomy terms into a custom variable

google analytics reports allows drupal to create reports from GA

So in theory you should be able to do this, I'm not sure how GA handles multiple values for the taxonomy


CronJobs - I have two cron jobs but only one works

The URL of the cron.php page requires a "cron key" to protect against
unauthorized access. Your site's cron key is automatically generated during
installation and is specific to your site. The full URL of the page, with the
cron key, is available in the "Cron maintenance tasks" section of the Status
report page at Administration > Reports > Status report.

As an example for how to set up this automated process, you can use the
crontab utility on Unix/Linux systems. The following crontab line uses the
wget command to visit the cron.php page, and runs each hour, on the hour:

0 * * * * wget -O - -q -t 1 http://example.com/cron.php?cron_key=YOURKEY

Replace the text "http://example.com/cron.php?cron_key=YOURKEY" in the
example with the full URL displayed under "Cron maintenance tasks" on the
"Status report" page.


Create content after editing other content-type

How can I find out the ID of the content-type A node?

You should use devel module's kint function to get all available methods of an object, and you could easy find out, that it's: $node_object->id();

how can I find out if a B-type content already exists referencing the A-type node I'm working with?

You will write a Database service query (not pure sql query), where you will have two important condition:

the node type must be B
it's reference field contains the id of the A content.

You will of course have to use table joins. To better understand the schema representation of your content types, I suggest you do use phpmyadmin parallel.


Why can anonymous users see my block, whose visibility is set to hide it for anonymous users?

The strangest thing fixed my issue.  I'm still not sure why.

I was placing the block in a certain region with the 'Context' module.  When I removed the block placement from that context and set it directly in the block's configuration page, the block stopped being visible to anonymous users.

Not sure why that would matter!  Placing blocks generated by views with the 'Context' module is not interfering with their visibility settings, but for some reason it was interfering with this one.  It's just a regular block with text, nothing funky.

In any case, that's what solved my problem...


Anonymous user's can't views/download files uploaded via file field

Figured out! I have uploaded a .rar file, so drupal wouldn't recognize this as existed file types e.g. audio, image, document. I had to go in admin/structure/file-types/manage/document

And add mimetypes for .rar and .zip extension:

application/rar
application/zip

Then just reuploaded file and gave anonymous user's permission:

Document: Download any files


Views RSS channel properties added with hook_views_query_alter() disappear

You can do this with Views RSS 2 and hook_views_rss_item_elements().

As we can see in the documentation for Views RSS API views_rss_get it can :

  Fetch item elements provided by other modules.

So to create your own item element do the following :

First thing, revert your hack, it won't be needed.
Download and install the module Views RSS (and Core Elements, DC Elements)
Create a default view for content and fields
Add a feed to it
Style it as RSS Feed - Fields
In the settings pubDate is avaible alerady so we don't have to worry about that.

Create a tiny module and enter the following

/**
 * Implements hook_views_rss_namespaces().
 */
function MY_MODULE_views_rss_item_elements() {
  $elements['dc:lastBuildDate'] = array(
    'description' => t('My custom lastBuildDate field.'),
    'help' => '',
  );
  return $elements;
}

Then install it and clear your cache.

Now, in the Views RSS field settings there should be a new field for your custom field (see image)

And when you view your feed it should be included (see image - last line)

Note: if you look at the snippet, it adds the field to the dc namespace. If you want to use another or provide your own namespaces have a look at the API and hooks.


First of all, you can prepare a SelectQuery object using db_select(), then use it in place of a table in another db_select(). Example (off-the-cuff, not tested):

$inner_query = db_select('comment', 'c')
  ->fields('c');
$outer_query = db_select($inner_query, 'sub');

Second of all, you can UNION two prepared SelectQuery objects with the SelectQuery::union() method.

$some_query = db_select('comment_table', c)->fields('c');
$union_query = db_select('other_comment_table', o)->fields('o')->union($some_query, 'ALL');

So all the tools you need are there; it'll just take some trial and error to put them all together.


Is it properly to include a third-party php library via composer without creating drupal module for it?

Sure, you can do that on a project.

But you're probably going to write code somewhere to actually integrate that into Drupal and expose it somehow, and that will be in a module (or theme). But especially if that's a custom module that is just used for that site, you kind of have to add it to the project composer.json as composer doesn't include composer.json of moules that aren't actually added themself with composer (excluding solutions like merge plugin)


Embedding the s3slider jQuery plugin in a block

I would use in D7 the Fields Slideshow module.

If you still want to use the s3 slider, these are some general steps to make.

Make a content type with an imagefield.
Add nodes for each slide in your slider.
Create a view that has the fields you need.
Set the field stye of the imagefield to none for all the items (label and wrapper too).
Set the body field style to span and set none to label and wrapper. Trim the field to your desired length and remove any html.
Go to 'Theme information' in your view. You need to copy the name of the templates of the views you will be replacing. You need to get the list template (views-view-list--MYVIEWNAME.tpl.php).
Go to the themes folder in the views module and copy the views-view-list.tpl.php into your theme and rename it to what you figured out in the first step.
Change the content of the template with something like this, remember to change MYTHEMENAME to the name of your theme and remember to flush your theme registry so it recognizes the new template file.

I couldn't add the code successfully so I made a Drupalbin: http://drupalbin.com/20119


How to use the Rules module to attribute a new user role after a product was bought?

Refer to the tutorial Selling Content with Drupal Commerce using Content Access and Roles for granting access to premium content to users who have a "premium" role.

Here is a summary of the steps required (= quote from that link):

Enable Content Access and the ACL (optional) module.
Create a role called "premium".
Create a content type called "Premium Content" and put some great content in it.
Verify that users can only access the premium content if they have the premium role.
Create a product representing the premium role.
Create a rule that grants the premium role on order completion:

After updating an order.
If the order state is Completed.
And the order contains our premium product.
Add a role to the user who is the owner of the order.


I'm using Mobile Navigation but does not load the dropdown menu after installing jQuery Update

You have to set the correct Default jQuery Version in configuration. May be that causes this problem..


Added the following code

'#tree' => TRUE,

working charm!!

added after:

'#title' => t('Image'),
'#type' => 'media',
'#description' => t('...'),


Starts with a larger ubercart order number

Run this query against your database:

ALTER TABLE uc_orders AUTO_INCREMENT = 100001;

The next record added will use 100001 as the ID.

Or for Postgres (Thanks @Mołot for the heads up):

SELECT setval('SEQUENCE_ID', 100001, FALSE);

You'll need to replace SEQUENCE_ID with the appropriate sequence id for the uc_orders table.

For sequence-enabled databases that lack setval (like Oracle, at least in some versions), you can:

ALTER SEQUENCE schema.sequence_id INCREMENT BY 1000;
SELECT schema.sequence_id.NEXTVAL FROM dual;
ALTER SEQUENCE schema.sequence_id INCREMENT BY 1;


Getting average of a numerical field across multiple nodes

Follow these instructions:

Open your view in edit mode.
Open the Advanced tab.
Find the section named Other
Enable the Use aggregation option
Click on the Aggregation settings option for your desired field
Select Average from Aggregation type select list


Have you tried Views Arguments? Parts of your URL (eg. volume/1) can be passed to the View as arguments to control the content displayed (eg. arg '1' tells View to display volume num 1).

Here's a solid tutorial video:
http://mustardseedmedia.com/podcast/episode39

And a more detailed explanation on Drupal.org:
"Arguments are parts of the URL of a view that can be used to reduce the result-set. A classic example of an argument would be in the case of taxonomy/term/TID or tracker/UID. In the former case, the view is restricted to posts tagged with the associated taxonomy ID; in the latter case, the view becomes restricted to posts by the specified user.

There is also a special case where arguments can be embedded into a View's URL. For example, the URL /user/$arg/track would be valid on any /user/WHATEVER/track URL, and the WHATEVER would be passed into the view as the first argument.

A given view can have multiple arguments. For example, you might have blogs as a view, and provide UID, Year, Month, and Day as arguments in that order. Thus the URL might look like blogs/1/2006/3/15 which would display all blog posts written by user id #1 on March 15th, 2006. Arguments can also be specified as , which will be interpreted as 'all values'; so in this case, blogs//2006/3/15 would show blog posts by ALL users on that date."

http://drupal.org/node/54455


How to remove 'destination' query paramater from link URLs in Drupal 8

Before proceeding, realize that although this might be better for SEO; it might be negative for user experience. Personally I'd hate it if I were to comment on a node and after the login I have to navigate back to that node. You might want to perform some session magic to redirect the user back to where he came from.

The answer to your question involves a custom module, with a Path Processor service. In addition to the default module files (mymodule.module and mymodule.info.yml), you'll need mymodule.services.yml and src/PathProcessor/MyModulePathProcessor.php.

The services file will expose your path processor to Drupal with this code:

services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\MyModulePathProcessor
    # Optionally provide arguments.
    #arguments: ['@config.factory', '@entity_type.manager', '@current_user']
    tags:
      - { name: path_processor_outbound, priority: -10} # Low priority acts last.

This 'subscribes' the class to the path_processor_outbound event.

The Outbound path processor should look something like this:

<?php

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MyModulePathProcessor.
 */
class MyModulePathProcessor implements OutboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($path == 'user/login') {
      unset( $options['query']['destination'] );
    }
    return $path;
  }

}


Insert JavaScripts into head of only one page

Drupal provides theme suggestion for html.tpl.php

you can put html.tpl.php in templates folder inside you theme directory

html--node--id.tpl.php

id will be your page id
e.g. ID = 123, then file name will be html--node--123.tpl.php

Hope this will help.

===================================================================

For particular block you can use hook_block_view_MODULE_DELTA_alter

@see https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_view_MODULE_DELTA_alter/7.x

like,

function module_name_hook_view_MODULE_DELTA_alter(&$data, $block) {
  drupal_add_js();
}


How to progragrammatically get NodeType translated value in D8?

You need to set the config override language to the desired language:

  $language = $language_manager->getLanguage('es');
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);

  // Load the node type here.

  $language_manager->setConfigOverrideLanguage($original_language);

Taken from user_mail()


Exporting the entire website, except users and content?

I would suggest to put your code in a version control like Git. There are many free services you can use like Github and Bitbucket. With Git you can easily ship your code from one server to another.

  I need to export the modules, views, blocks, everything BUT the
  content and the users. I don't want the content as I made dummy
  content, and the user is a dummy user as well.

You can use Features to export your views, blocks, content types, permission and roles, configuration, and even settings stored in variable table (Strongarm).

With everything in Features you can then run a normal installation in production then enable the features one by one. Here are some execellent tuts about using Feature.

http://mustardseedmedia.com/podcast/episode43
http://sf2010.drupal.org/conference/sessions/managing-and-deploying-configuration-exportables-and-features-module.html
http://www.drupalatlanta.com/event/drupal/april-13-2010

Related modules:

Migrate - Documentation

  My other solution is to build everything on production again, which is
  going to be draining.

One of the great things in Drupal is making the development easier and simple. With Features module, or hook like hook_update_N you will never do the same task on every environment you have. Development must only be done in local machine.

  I would also use a Dev -> Stage -> Prod workflow, but this will be a
  one time thing.

That is what Pantheon and Acquia are doing. You can build your own infra but that's another story.


Hide user pictures from guests and web crawlers

None of the core themes have all the preprocess functions or template file in use. The best way to find what's available to use is with the devel_themer module.

Here's what devel_themer gave me:

This says we can use template_preprocess_user_image() or user-picture.tpl.php. When doing logic such as this, it's standard to use preprocess functions. When you're changing HTML structure you use template files.

So you can add the following function to your theme and it should hide all user pictures for anonymous users (web scrapers are considered anonymous users).

function YOURTHEME_preprocess_user_picture(&$variables) {
  // this is the currently logged in user
  $user = $variables['user'];

  // this is the user the picture belongs to
  $account = $variables['account'];

  // If the current user is anonymous don't show the user picture
  if ($user->uid == 0) {
    $variables['user_picture'] = NULL;
  }
}


How to create Facebook style user notifications?

Approach 1: Menu Badges
Use the Menu Badges module to add such notifications to any menu item and/or menu tab of your choice. Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Adding Badges to Menus
Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
Adding Badges to Tabs
For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
Badge Types
The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".
Video tutorials:

Defining Menu Badges with Views in Drupal (from the module maintainer).
Drupal 7 Menu Badges Module.

Approach 2: Message stack
Use the Message Stack, which consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium.
If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.
And the Message Stack will make you well positioned for Drupal 8 also (because of he modules' object orientated architecture). Even though there is no such a thing as 8.x-dev yet, the Message code repository already does contain something already (not yet for the 2 other modules though). I assume the wip part of the branch name stands for 'Work In Progress'.


How to display body content in custom text?

Under the custom text box, if you click on "Replacement Patterns" it will show you all the patterns you can use.

Should be [body]

Also, make sure all the other fields are arranged above the Global: Custom text or else the pattern will not work.


I usually don't throw the (array)$file line because really the only thing the field data needs is the fid, description and display. So I usually do the following:

$node->field_image[LANGUAGE_NONE][] = array(
  'fid' => $file->fid,
  'display' => 1,
  'description' => '',
);
node_save( $node );

This way if the display is required, I don't get an error. But that's just me...


How to set different form displays for creating and editing an entity?

The media entity has already specific form handlers add and edit, so you can configure them right away.

Add both form modes to the media entity at /admin/structure/display-modes/form and enable them for the media type at /admin/structure/media/manage/image/form-display in CUSTOM DISPLAY SETTINGS.


How to update from Drupal core 8.5.0 to 8.5.5?

It's all here Update core via Composer.

Short version, turn on maintenance mode

drush sset system.maintenance_mode 1

then run

composer update drupal/core --with-dependencies
drush updatedb
drush cr

Turn off maintenance mode

drush sset system.maintenance_mode 0

  If you run the composer update command above but drupal/core is not
  updated, there might be another dependency holding back the Drupal
  upgrade. You can check for blocking dependencies using the command
  composer prohibits. For example, if you are trying to upgrade from
  8.4.5 to 8.5.0, you can run composer prohibits drupal/core:8.5.0, and it should give a list of dependencies blocking the upgrade. Update
  those dependencies along with drupal/core and it should work (e.g.
  composer update drupal/core symfony/* --with-dependencies).


Focus problem when Ajax call for multiple fields calling the same callback function

Enable disable-refocus when adding the ajax callback:

'#ajax' => [
  'callback' => [$this, 'friends_advance_search_results'],
  'disable-refocus' => TRUE,
],

See https://www.drupal.org/project/drupal/issues/2627788


You can do it in a preprocess template function.
e.g.

/**
 * Implements template_preprocess_views_view_table()
 * @param $variables
 */
function TEMPLATE_preprocess_views_view_table(&$variables){
  /** @var ViewExecutable $view */
  $view = $variables['view'];

  //Do no alter other views
  if ($view->id() !== 'YOUR_VIEW_ID') return;

  $rows = $variables['rows'];
  foreach ($rows as $key => $row){
    if (empty($row['columns']['VIEWS_FIELD_VIEW_FIELD_NAME']['content'])){
      unset($variables['rows'][$key]);
    }
  }
}

Replace
TEMPLATE with your module name or theme name.
YOUR_VIEW_ID with your view id
VIEWS_FIELD_VIEW_FIELD_NAME with the name of your field

Hope that helps


How to summarise different date ranges using this week, last week, etc?

"Date Views" (date_views) sub-module of the Date module extends the "Configure filter criterion" used in Views. It allows for using "Relative dates" that are computed when the view is displayed.

Some examples are:

now
now + 1 days
-2 months
Monday next week
...


Is it possible for the front page view to use a different image style for each teaser item?

First, you need to go one level up, don't think about image styles, think about enity view modes. Then you can control which image style is used for each view mode.

The reason for that is that entity output is cached by view mode. You could theoretically alter each entity and switch out the view mode, the data might actually even be available there, but it will fall apart when the same entity is suddenly in a different position but still cached.

You could try to implement preprocess or another views hook to change the view modes programatically in the render array. That will however not be configurable if that is a requirement.

What we build for our project is a views display plugin that allows to not select a single view mode but one for each entity that is being displayed.


Drush to get and print single node data in terminal?

Install this set of Drush tools to either your $HOME/.drush directory or within your project.

Drush Entity

Brief examples from the project page are:

drush entity-read node 3  |  less

#read in json format
drush entity-read node 3 --format=json

drush entity-type-read user

drush entity-type-read node --fields=label

drush entity-type-read user node --fields=label,bundles/*/label,drush/count

EDIT

For legacy Drupal6 support of viewing what a Node contains consider using Node Export via the command line and drush, possibly using the --pipe command to Linux Less command.


Show block content inside custom node template

First, you have to make your block available inside your node.tpl.php, so edit template.php and add the following:

function YOURTHEME_preprocess_node($variables) {
  $YOURBLOCK = block_load('MODULENAME', 'BLOCKDELTA');
  $variables['YOURBLOCK'] = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
}

Then, on your node.tpl.php you can print $YOURBLOCK; anywhere you want.

And yes, you have to call two "private" functions from block module, see http://api.drupal.org/api/drupal/includes%21module.inc/function/module_invoke/7#comment-15884


How to create a pie chart using the chart module in Drupal 7?

Yes it is possible to do so. Use the google chart tools to achieve that. This module also integrates with the views module nicely.


Heres an example using theme_image_style()

$mypath = (file_load(theme_get_setting('heroImage'))->uri);
print theme_image_style(
  array(
    'style_name' => 'heroimage',
    'path' => $mypath,
    'attributes' => array(
    'class' => 'YOUR_IMAGE_CLASS'
    ),
    'width' => NULL,
    'height' => NULL,
   )
 );
}

I'll be honest, I cant remember why I set height and width to NULL, off the top of my head it helped fix some bug! Hope it helps!


How to plot a chart from CSV uploaded in a content type?

The Easychart module may be close to what you're looking for. It comes with these facilities:

Pasting of CSV data to create charts from it.
Entering an URL pointing to a CSV file containing the data to be charted.

For an extremely short demo of these facilities, have a look at this video.

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

It defines a new content type (= Chart) used to add charts to your site.
It creates a chart widget that can be used in your own content types.
It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (CKeditor and TinyMCE are supported).
It provides an intuitive interface to configure charts through the Easychart plugin.
The Government of Flanders contains some real world examples of a Drupal website with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

If you're using an URL pointing to a CSV file with data to be charted, then be aware of what's mentioned in comment nr 5 of the issue about "EasyChart data doesn't update unless I edit and save the chart node", i.e.:

  For performance reasons, the external csv data is only updated when cron runs.

Resources:

Module documentation.
Video demonstrations:

Easychart (quick) demo
Easychart - visual editor for Highcharts (Drupal demo).
Easychart powered dashboard (proof of concept)

Notes:

(1): To resolve an error like "Highcharts not defined" (as per your comment below this answer, you may want to have a look at the issue titled "Highcharts is not defined". Comment # 2 in it includes a possible explanation for that error, ie:

  It was a permissions issue on the library. For some reason the highcharts library had permissions set to: drwx------@

  This worked fine on my local machine, but not on shared hosting. I changed them to: drwxr-xr-x to match all the other libraries.

(2): From the Easychart project page:

  Make sure to clear the website's css-js cache after installing the javascript dependencies

(3): The Highcharts library needs to be placed in /sites/all/libraries/highcharts (as mentioned also in the README.txt)


In views, how do I show posts from this calendar day, ten years ago?

Like you did, create two filters for the date range and then use the following values

-10 years midnight
-10 years +1 day midnight

Remember to select

An offset from the current time such as "+1 day" or "-2 hours -30 minutes"

If you want to do this programmatically you can create a date filter and set the actual date values from code for the filter range.

You can create the date filter and set the filter value programmatically like the following

How do I programmatically render a view that has exposed filters?


Since your contextual filter is expecting an nid (you said your contextual filter is set up as 'Content: Nid') - you really have to provide it with an nid even when that filter is not present in the URL.  You can't give it 'seller' as an argument or anything like that because that's not an nid, so it won't help it pull up the correct node.

So to get it to work in those cases, what you really want for your view to do is grab the nid of the current node it appears on.  It's OK if that page has a custom URL, the nid can still be gotten.

Just select 'Content ID from URL' as the default value when an URL argument doesn't exist!  That'll work even if it has a custom alias for the URL.


Moving nodes from dev to production (a simple use case)

From my experience, I use Node Export to export some nodes and import in other Drupal site (same versions). To export/import a node, the respective Content type must have been created with his respective fields.

Also, this page Comparison of Content and User Import and Export Modules have information about some import/export modules alternatives (also I suggest see comments). Could be suitable for your needs.

I hope information be useful.


How to open a node edit form in an overlay (modal window) in Drupal 8

You can do that by constructing special links with the help of Colorbox and Colorbox Inline. You'll probably have to create your own style for the "minimized" overlay.

There are other libraries that do the same or similar thing as Colorbox, also integrated into Drupal through a module, so you might want to search and investigate others too (Shadowbox, for example).

These modules are also worth checking out: Modal Configuration, Simple Modal Entity Form, Entity Overlay.


Your query is a bit different compared to a regular query. A regular query is constructed like this (source):

$query = db_select('users', 'u');
$query->join('domain_editor', 'de', 'u.uid = de.uid');
$query->fields('u', array('name'))
  ->condition('u.name', '%' . db_like('john') . '%', 'LIKE')
  ->condition('de.domain_id', 25, '=')
  ->range(0, 20);
$result = $query->execute();

You have the base query:

$query = db_select('users', 'u');
$query = db_select($table, $alias);

Then the join:

$query->join('domain_editor', 'de', 'u.uid = de.uid');
$query->join($table, $alias, $condistion);

The fields to select:

$query->fields('u', array('name'))
$query->fields($table, array $fields)

And the conditions:

  ->condition('u.name', '%' . db_like('john') . '%', 'LIKE')
  ->condition($field, $value, $operator)

In your code it seems you did not take the table aliases into account. So you might want to try something like:

function mymodule_search_query_search_node_alter(QueryAlterableInterface &$query) {
    $u_alias = $query->join('field_data_field_date', 'fd', 'search.date = fd.field_date_value'); // No idea what the field is called, assuming 'search.date'.
    $query->fields('fd', array('field_date_value2'));
}

(You'll need to figure out what the name is of the field you want to join with, and substitute 'search.date' with that value.)


Blanket CCK Field Permissions for Specific Content Type?

"Editing a field" can mean a lot of things because a field has many properties for input ('widget'), storage and output ('formatter'). That's why I was trying to figure out what you're after.

If you can write PHP, anything is possible, but I think that introducing a way for content creators to edit (a limited set of) field settings, would require a lot of custom code. However I assume that you're looking for a solution that requires no (or a little) custom coding. In order to achieve that, you may need to choose an alternative solution, like a custom compound field, CCK Multigroup or Webform. However I cannot advice you about that because I don't know which problem you're trying to solve.

On a more theoretical level, I think you have to be careful not to get content and configuration mixed up. Drupal stores both configuration (like field settings) and content (the information in a node) in the database. What you're asking sounds as if editing the field settings would in fact become another way to enter information. That may not be a problem now, but it can become a problem later because other modules are not prepared to access field settings as if they are part of the content.


do some work when user login or register in drupal6

In drupal 6, there is a function named hook_user.

By using this hook in your custom module. You can do watever you want. Remember to put condition in this by '$op' like

function hook_user($op, &$edit, &$account, $category = NULL) {
  if($op == 'login') {
    //do watever you want
  }
}


How to access fields attached to taxonomy term in views-view-field.tpl.php?

Puh, finally I found a way.
This is my template file views-view-field.tpl.php (instead of a custom field I used the description field, but that doesn't matter in this case):

<?php
if (isset($row->_field_data['nid']['entity']->field_myfiled['und'][0]['tid'])) {
  $tid = $row->_field_data['nid']['entity']->field_myfield['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  $output = $term->description_field['und'][0]['value'];
} else {
  $output = $output;
};
?>

<?php print $output; ?>


I think it's because the not-super-admin users don't have permission to edit unpublished content that they didn't create.

If you want to alter this behavior you can add a new permission "edit any unpublished content" and use hook_node_access to allow editing unpublished nodes (if they have that permission)


Avoid sql-drop or sql-sync drush commands in a particular environment

This is best done with a policy file.  See policy.drush.inc, which has an example policy prohibiting overwriting a production server.

The example could be expanded to perhaps check for patterns in the destination parameter (any alias containing 'prod'), etc.


First, you need a png image (my case 17x17 px whatsapp.png), place it under sub-theme/images folder, then, place this css under sub-theme/css/custom.css file

.whatsappwrapper {background-
 image:url("../images/whatsapp.png");background-repeat:no-repeat;}
.whatsapplabel {display: none;}
.whatsappnumber {margin-left: 20px;}

then, set your views field styles as shown in picture
first part of image is the result of this settings. note: telephone icon is a html symbol.


Fetch Link field Label and Link separately in views-view-fields template

Just edit the Link field and select these two options (highlighted in screenshot)


How to track and report which data is used or accessed the most for a site on an internal network?

Have a look at the Visitors module. Here are some reports you get from it:

  View pages that have recently been visited.
  View pages that have been hit frequently.
  View pages count per month, day of month, day of week, hour.
  ...

Especially these reports should be what you're looking for, which also includes hits for paths corresponding to a view, such as the one with path charts/examples/views:

Top pages (table with columns Title, Path and nr of Hits). Here is an example of this report:

Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor). Here is an example of this report:

If you follow any of the "details" links in the example above, you'll get something that looks as in this example:

Checkout the above (source) links to get an idea of which data are available.

The demo site contains some sample reports (charts) available to anonymous users also. Any visits to a Views related path will be reported in the Recent hits module. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.


Even if Clean URLs are successfully enabled at install-time, if you have a dedicated server you may still want to follow the steps (below) to enable the more efficient httpd.conf rewrite method for clean URLs. If you choose to do that, you might want to turn off Clean URLs while you are working on the server.
    Server configuration for Clean URLs on a dedicated server, with httpd.conf


Change the index structure of fields in a table in database? Wise thing to do?

If you are even thinking about doing this I have two big key phrases

BACKUPS
DEV SERVER

Here is what you should do

Install MySQL on a DevServer
mysqldump the database and load it on the DevServer
Point your Drupal App at the DevServer and bang on it, and kick the tires

Once you got a good dev environment, now do this on the DevServer

SELECT mail,COUNT(1) MailCount FROM users
GROUP BY mail HAVING COUNT(1) > 1;

If you get any rows coming back, there are multiple users using the same mail value

If nothing comes back, you can proceed as follows:

CREATE TABLE users_new LIKE users;
ALTER TABLE users_new DROP INDEX `name`;
ALTER TABLE users_new DROP INDEX `mail`;
ALTER TABLE users_new ADD INDEX `name`;
ALTER TABLE users_new ADD UNIQUE INDEX `mail`;
INSERT INTO users_new SELECT * FROM users;
SELECT COUNT(1) UsersCount FROM users;
SELECT COUNT(1) UsersNewCount FROM users_new;

If UsersCount = UsersNewCount, CONGRATULATIONS, you can continue.

ALTER TABLE users RENAME users_old;
ALTER TABLE users_new RENAME users;

You drop users_old if you are sure you no longer need.

Give it a Try !!!


Not able to save the selected custom populated option list

List fields are tied to their allowed values and they make sure all the values in the database align with what is in the allowed values.

To programatically populate list fields, there is a lesser known feature, which is that you can set the 'allowed_values_function' setting of your field instance.

If you are programatically creating your field you just add it in the settings.
If not you could do one of these things:

Form alter the field settings form to make the allowed_values_function field a visible text field you can enter a function name into.
Implement hook_enable() in your custom module to load the fields in question and set the allowed_values_function and then save the fields. Then use hook_disable() to reverse the cahnge when you disable the module.
Go in the database directly and set the value in the field settings.

Your allowed value function should be of the form:

function function_name($field, $instance, $entity_type, $entity, $cacheable) {
  // return an array of values.
  $values = array(
    'val1' => t('Value 1'),
    'val2' => t('Value 2'),
    'val3' => t('Value 3'),
  );

  return $values;
}

There is another module though that makes things a little nicer: List field predefined options

It allows you to implement it's hook to define allowed value functions, which you can then select from in the field UI.

For example:

/**
 * Provide information about available predefined list options.
 *
 * @return
 *   An associative array whose keys define the machine name for each
 *   predefined list options and whose values contain the list options
 *   descriptions. Each list options description is itself an associative
 *   array, with the following key-value pairs:
 *   - 'label': (required) The human-readable name of the list options.
 *   - 'callback': (required) The name of the function that will return the
 *     list options.
 *
 * @see hook_list_option_info_alter()
 */
function MYMODULE_list_option_info() {
  $info['FIELD_NAME'] = array(
    'label' => t('Name that describes the values this callback will return'),
    'callback' => 'mymodule_function_that_returns_allowed_values',
  );

  $info['ANOTHER_FIELD_NAME'] = array(
    'label' => t('Name that describes the values this callback will return'),
    'callback' => 'mymodule_another_function_that_returns_allowed_values',
  );

  return $info;
}

Then you can implement the functions you defined in the above hook to return the allowed values and in the field UI you can select to use the function by its label.
Much more user friendly.