How can I use feeds tamper to remove currency ($) sign when importing prices?

This is pretty easy.  You can use the "Find replace" tamper under "Text", and then user "$" as the search and "$ " as the replace.  If you want to be fancy you can use the "Find replace REGEX" tamper to make sure you only get the leading $.  IIRC, this needs to include the delimiters.  Using "/^\$/" as the search and "$ " as the replace should work (you need the ^ to anchor to the beginning and then escape the $.  Both of these plugins are part of the base feeds_tamper module.


Control Webform's date field (datepicker) from JS

You can override it with js .. the trick is when it is when your js is attached.

so in your module you need ....
<?php
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id){
  if ($form_id === 'webform_submission_YOURFORMID') {
    $form['#attached']['library'][] = 'YOURMODULE/mymodule.fix-datepicker';
  }
}

then in your js please try some thing like..

(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.fixMyDatepicker = {
attach: function (context) {

  var dateElement = $('#edit-1'); // id of your date picker
  var dateData = dateElement.data();
  if (dateData.datepicker) {
    makeChangesToDatePicker();
  }
  else {
    var myInterv = setInterval(function() {
      if (dateData.datepicker) {
        makeChangesToDatePicker();
        clearInterval(myInterv);
      }
    }, 100);
  }

    function makeChangesToDatePicker() {
      //@TODO here check if mobile .
      var settings = dateData.datepicker.settings;
      settings.maxDate = '2019-03-11';
    }
   }
  };
 })(jQuery, Drupal, drupalSettings);

the above worked for me. remember datepicker is just: https://jqueryui.com/datepicker/


Remove array keys starting with '#':

{% for key, block in page.footer if key|first != '#' %}
    <div class="col col-4">
        {{ block }}
    </div>
{% endfor %}


I need a starting pointo to write a Views Form handler to show a Bulk Operation view field in each row instead of a single button?

VBO doesn't support that.
Furthermore, in that case you probably don't even need VBO, just write a custom Views Form handler that shows the button in each row.


I am managing a site that gets about 1000 unique visitors a day. Not sure how big your application is, but 1000 is enough to cripple a default drupal install.

I added the standard performance optizations, apc, etc, but found that memcache by far had the best result. My pages used to take 20 seconds to load. Now pages load instantaneously. If you have not tried that, I would see if that helped first before investing in the SSDs.


How do I get rid of "Body:" as highlighted bellow?

Login as Administrator
Go to admin/structure/types
Click on Manage Fields next to above content content type..

Click on Mange Display
Hide Body label like shown below..


How to programmatically know a required select list has no value on node add/edit form page?

It will depend on the field type. For a list field with text/numeric values, the output of the field API function field_info_field() contains allowed values within its settings element. This field data can be fed into list_allowed_values() to retrieve either the static or dynamic list of allowed values for the field.
For example:
$field = field_info_field('field_myfield');
$values = list_allowed_values($field);
if (count($values) > 0) {
  // There are allow values
}
else {
  // There are no allowed values
}


Drupal 8 views slideshow not displaying images

Views > Select Settings next to format > selected Slide(image) in Image drop down list. I am not sure this is a best solution. At least I can see the image now.

 field to display.


Override Profile2 with account fields and values

Profile2 modules gives profile entity apart from we have in default as user.I am not putting the codes , but here is my idea,

manually add those three fields to the profile you have created.
loop through all users, load their profile, I guess you can use profile2_load_by_user() to load the profile inside the loop
Check if you are getting the added fields in the loaded profile object.
Map the fields on user entity to profile entity.
save the profile using profile2_save() 5.
Delete the fields from user entity, once you ensure mapping is in the way you want.

NOTE: function listed may need a replacement,as I have not tested the workflow.


How to create a block with CCK dropdown lists and some values in it?

This is something you can do in Drupal 7 easily as they now use enititys. However in Drupal 6 you will need to use a custom module like Node Blocks


Access current node in an existing block

Enable debug
by going in sites/default/ and copying the file default.services.yml to services.yml  and modifying the following lines
cache: false
debug: true

Turn browser comments on
make sure your browser has Comments enabled (some browsers have them disabled by default for example in chrome in inspector on the 3 dot menu click settings and preferences find Show HTML comments
Find out which twig template is used
after that inspect the code in near the block that you want to override and you should see something similar to this

you can get the twig block template from the location in comment BEGIN OUTPUT
Use and modify template
Copy this twig file into your theme templates folder and rename to any name above.  Modify the code and add something similar to the twig block template you just created
{% if nid %}
    nid:{{nid}}

    title:{{node_title}}

    body:{{body}}

    text:{{field_text}}

{% endif %}

Expose node variable to block templates
Add into your THEMENAME.theme the following code or similar
function THEMENAME_preprocess_block(&$vars){
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      // You can get nid and anything else you need from the node object.
      $vars["nid"] = $node->id();
      $vars["node_title"] = $node->getTitle();
      $vars["body"] = $node->body->value;
      $vars["field_text"] = $node->field_text->value;

      //following did not work ?!
      //$vars["field_text"] = $node->get('field_text')->getValue();
      //$vars["field_text"] = $node->field_text->getValue();
    }
}

Clear cache
with the above you are making the node fields available to block templates


How can I create a web form automatically when an organic group is created?

There is probably multiple was to this.  The way I see it is a custom module.

You want to use hook_nodeapi(&$node, $op) in Drupal 6,  hook_node_insert($node) in Drupal 7.

You code would look like something like this

CUSTOM_MODULE_NAME_nodeapi(&node, $op) {
  switch ($op) {
    case 'insert':
       if ($node->type == 'group') {
         global $user;

         // Create new object.
         $node = new stdClass();

         // Set desired data and metadata as members in object.
         $node->type = 'predefine_webform_with_predefine_fields';
         $node->uid = $user->uid;
         $node->title = 'node title';
         $node->body = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...';
         //... prefill other cck fields

         // Save the node
         node_save($node);

       }
       break;
     }
   }
}

(Code should look the same for Drupal 7, minus the switch case)


Add this code to your custom module:

function my_module_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['menu_link_image'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Menu link image'))
      ->setDescription(t('Upload the image related to this menu item'))
      ->setDisplayOptions('form', array('type' => 'string', 'weight' => 0));

    return $fields;
  }
}

Then use hook_update_n to update the schema of the menu_link_content_data table. Run update.php, flush caches and the new field should appear on all the Add/Edit menu item form.

In case someone wants to simply add a text field, boolean etc, simply edit BaseFieldDefinition::create('image') and change it to BaseFieldDefinition::create('string') or BaseFieldDefinition::create('boolean') etc


You could achieve this by either one of the following:

By using db_query():

function custom_get_user_account_id() {
    global $user;
    return db_query('SELECT field_account_target_id FROM {field_data_field_account} WHERE entity_id = :user_id AND bundle = :bundle', [
        ':user_id' => $user->uid,
        ':bundle' => 'user',
    ])->fetchField();
}

Or by using db_select():

function custom_get_user_account_id() {
    global $user;
    return db_select('field_data_field_account', 'fa')
        ->fields('fa', ['field_account_target_id'])
        ->condition('entity_id', $user->uid)
        ->condition('bundle', 'user')
        ->execute()->fetchField();
}


EntityFieldQuery BETWEEN condition is not working

I had the same problem than you, and was able to fix it. The real problem here is that the documentation does not provide any example.

As it was already mentioned, the BETWEEN will only work if you are using the same data types that are being stored.

In my case, the field i was searching was a date field that has a specific format. So instead of passing a timestamp i had to format that date and then pass it.

//something like
start_date = (isset($_GET['startDate'])) ?  date('Y-m-d/T00:00:00',strtotime($_GET['startDate'])) : null;
        $end_date = (isset($_GET['endDate'])) ? date('Y-m-d/T00:00:00',strtotime($_GET['endDate'])) : null;

        if (isset($start_date) && isset($end_date)) {
           $query->fieldCondition('field_publication_date', 'value', array($start_date,$end_date), 'BETWEEN');
        }

Hope this helps you!


Alphabetical case insensitive grouping of results

To group all of your results by Last initial, capitalized:
First, under Format > Settings > Grouping field X, make sure you check the box to "Use rendered output to group rows".
Second, update the field settings for the field you're using to group the results - under Rewrite Results, check "Trim this field to a maximum number of characters," and enter 1 for the length.
Finally, again under Rewrite Results, check the box to "Override the output of this field with custom text". You can use twig in the custom text field and leverage twig's upper filter to convert the entire string to uppercase. You'll have to check the Replacement Patterns for the correct field name to use in your case, but the end result should look something like:
{{ field_last_name|upper }}

The result is your view results grouped by last initial, capitalized (whether they actually start with a capital letter or not).


how to give path to custom page tpl for content type

If I understood your question correctly, you are looking for hook_menu. You can find the API here.

An Example:

function mymodule_menu() {
    $items['test_insights'] = array(
      'page callback' => 'mymodule_test_insights',
      'page arguments' => array(),
    );
    return $items;
  }

//The callback function
function mymodule_test_insights(){
    //Do the necessary actions
    return $something;
}

Note: After implementing the hook_menu you have to clear the drupal cache to access the URL.

To add content type specific page tpl you have to use theme_hook_suggestions by implementing template_preprocess_page. You can add the below code in the template.php file of your theme

Example:

function themeName_preprocess_page(&$vars, $hook) { //themeName change to your theme name
  if (isset($vars['node'])) {
  // If the node type is "test_insights" the template suggestion will be "page--test--insights.tpl.php".
   $vars['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $vars['node']->type);
  }
}


Event:  adding product to the cart.
Conditions:
1. Entity has field (the featured field).
2. Data comparison:  (is that field "on"?)
Action: add amount to the unit price.

I'm not looking directly at the Rules interface, but that should get you well on the correct path.


Is it possible customize user login page on Adaptive Theme?

If you wish to hide blocks, go to the block configuration page (/admin/structure/block), celect 'configure' for the blocks you wish to hide, and under 'Block Visibility Settings' on the 'Page' tab select 'All pages except those listed '. Then if your login url is '/user/login', enter 'user/login' in the box. If you enter 'user/*' it will exclude the block from all pages matching the pattern.


Install a custom empty module break my custom style

Is your custom theme called nature?

That's not allowed, you can't have modules and themes with the same name.


How to hide input from user inside a textfield

You can add a CSS style to implement this.

However, currently, only Chrome supplies "-webkit-text-security" could do this. I find someone has some sample code:   https://jsfiddle.net/estelle/8WpNg/


Export news items (including pictures etc.) from Drupal to SQL

Try Node Export.

  This module allows users to export nodes and then import it into
  another Drupal installation, or on the same site.

  Using this module you can save yourself a lot of time setting up new
  websites that have similar nodes to websites you've already made,
  migrating nodes to new Drupal versions, or between
  development/staging/production sites.

  You will need the same content types for the imports to work (unless
  using Feeds to import), and ideally relevant compatibility with
  fields, and modules.

Node export formats

The format to export with is configurable, and the Node export package comes with the following formats:

  JSON - JavaScript Object Notation code which is known for being
  security friendly. (Drupal 7 only)

  Drupal var export - A Drupalized PHP array which is similar to
  var_export(). (Drupal 7 only)

  Node code - A customized PHP array which is similar to var_export().
  (Drupal 6 only) CSV - RFC4180 compliant CSV code. Ideal for viewing in
  Windows software, and editing data as spreadsheets.

  Serialize - Very robust, though not human readable, representation
  through Serialization using the PHP serialize function.

  XML - XML 1.0 representation which is good for machine-readability and
  human-readability.


CSS not loading on Chrome for drupal site after moving to https

The warning which you see is because some of the contents are not secure, which means they are fetched using http instead of https.
As per the limited information provided by you, I'd suggest you to follow the following steps:

Inspect the source code of the page, by pressing CTRL + U, in Chrome.
Check to see if there are links present in the content(specially the <head> section) are using the pattern http://... instead of https.
Find the resources (css/js/images) which are loaded using http.
Identify which part of the site (module or a theme function) adds that resource.
Make the necessary changes to make sure the resources are loaded securely i.e. via https.


Optimize CSS & JS breaks IE & FireFox (All Themes)

One possibility is that one or more CSS files have a Unicode BOM at the beginning.  The CSS optimizer that Drupal uses (at least the one in 6) doesn't work properly with these.  IIRC, the first rule gets mangled if it is the very first line in the file.

Switching the encoding with Notepad++ is the easiest way to fix this in you are on a PC.


How do I add CSS files only to the front page?

You can find exactly what you want under the topic Adding Libraries to Specific Pages at this tutorial Drupal 8 Theming Fundamentals, Part 1

To give you a real example, I am going to explain with the Bartik theme, so you can change easily.

I have created a css file cssfile.css under the path css/cssfile.css. Now this CSS file I want to use on only front page.

Step 1: Add the library to the theme: Add the following code in the bartik.libraries.yml

css-filling:
  css:
    theme:
      css/cssfile.css: {}

Note: Here I have given the name css-filling to this library but you can give any other name. We will use this name in path
Step 2: Setting the code in bartik.theme so above perticular library(ultimately css) will only be added to front-page,

function bartik_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    $variables['#attached']['library'][] = 'bartik/css-filling';
  }
}

Note: Now in the above code the important thing is path, bartik part comes form the themename and css-filling comes from the step-1.

This code I have tested in my test site and it is working on front-page only.


How to consume custom fields in RSS feeds

For this situation I prefer using the Services module, then enable a rest server and using the index. Here is an excerpt about it from the module's project page:

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.


Clicking any administration menu link results in empty overlay screen

The issue turned out to be caused by me including jQuery via the following line in my theme's info file:

scripts[] = js/jquery-3.1.1.min.js

Removing this line and using the jQuery version included by default (1.4.4) will return the $ is not a function error when using $() syntax, which can be resolved by wrapping existing jQuery code in the following:

jQuery(function ($) {
  // ...
});


How do I pass variables to a view builder's renderer?

This is not possible to add parameters to renderPlain(). What you can do depends. If you want to use a variable inside of the node, then do this in a node preprocess hook. But more likely you want to add additional elements to the build array before you render it, for example:

$build = [];
$build['top'] = ['#markup' => 'abc'];
$build['node'] = $view_builder->view($node, 'cnas_pdf');
$build['footer'] = ['#markup' => 'xyz'];


I imagine you could try and override the setting in a local

php.ini

file.

For example.

/var/www/my-site/php.ini

disable_functions = system

Adding a single function instead of the list your host is using by default.

If that works, you could add other functions there, e.g

disable_functions = exec,shell_exec,popen,passthru,proc_open,system,pcntl_exec

Otherwise, you'll need to hack Drupal to remove those ini_set declarations and move them to the local php.ini file. ( not recommended )

You could also ask your webhost for help ( recommended )

Alternatively, find a new webhost.


how do I get my module to install a view?

Create the MODULENAME.views_default.inc file (replace MODULENAME with the name of your module), and copy the exported code in the implementation of hook_views_default_views() you write in that file.

For example, the Views module implements node_views_default_views() for the Node module. The relevant parts for the front page view are the following ones.

  $views = array();

  // Omissis

  $view = new view;
  $view->name = 'frontpage';
  $view->description = 'Emulates the default Drupal front page; you may set the default home page path to this view to make it your front page.';
  $view->tag = 'default';
  $view->base_table = 'node';
  $view->human_name = 'Front page';
  $view->core = 0;
  $view->api_version = '3.0';
  $view->disabled = TRUE; /* Edit this to true to make a default view disabled initially */

  // Omissis

  $views['frontpage'] = $view;

The hook then returns the content of $views.

If the view has not been overwritten by a user, it should not be shown in the view list, once the module implementing the hook is uninstalled.


You need to check values of checkbox field in $form_state while setting it "checked" in line

$form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = 'checked';

This would be something like

$form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = isset($form_state['values']['field_show_end_date'][LANGUAGE_NONE][0]['value']) ? $form_state['values']['field_show_end_date'][LANGUAGE_NONE][0]['value'] : 'checked';

I haven't tested this code, but it should work just fine or it will give you idea about how to fix your problem. Hope it helps...cheers!


Pass offset and limit in Drupal embed view

| skip first 1 sometime or first 3 some other time.

Is there a reason you can't do this in the view? If you use a pager you can specify an on offset in pager options.

If you need to do this in code, you do something like:

$view=views_get_view('questions');
$view->display['block']->display_options['pager']['options']['offset'] = 'OFFSET NUMBER';
$view->execute_display('block'));


Can I check a file's properties before saving it with system_retrieve_file?

It depends on what the file "properties" you're wanting to check here.

The file contents? Sure. You can invoke $result = drupal_http_request($url);(7) or \Drupal::httpClient()->get($url)->getBody();(8) ahead of time to inspect the HTTP contents before calling system_retrieve_file().

The file entity properties (or the temporary file created before moving to $destination)? No (without replicating/modifying some core functionality). There are no open hooks to that before system_retrieve_file() commits to saving that data to filesystem/DB.


Workflow, Workflows, Workspace, and State Machine-- what is the difference?

There are also content moderation module which aims to define content states.
From my understanding, core Workflows is API and UI to utilize the moderation states and transition. I am not sure if core Workflows could work with states machine, but logically it should.

Core Workflows and contributed core Workflow must be similar in their general goal, but provides different widgets, and architecture.

It is very interesting question and I would be happy to hear some clarification.


Please try to locate another relationship named "File Usage: File"
After that you should be able to add a field type "File: Path". In the field options you can decide how the output is formatted: as server-path (public://yourpath) or as download path.


How to render html tags in field collection items?

When you use Field Collection you get nested templates. So start with the outer div container in the node template:

  {{ content.field_cv }}

This produces a new set of templates, which you can see when you switch on Twig Debug. The next level is the field template:

field--field-cv.html.twig

{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

and inside you'll find the field collection templates:

field.collection.html.twig

{%
  set classes = [
    'field-collection-item',
    'field-collection-item--name-' ~ field_collection_item.name|clean_class,
    'field-collection-item--view-mode-' ~ field_collection_item.view_mode|clean_class,
  ]
%}

    {{ content }}

Which you all can use for the custom html markup.


Check required directory structure on module install/enable

The Drupal API function drupal_load() will let you preload your .module file so you can make its constants/functions available during your hook_requirements() invocation:

/**
 * Implements hook_requirements().
 */
function MYMODULE_requirements($phase) {

  // @TODO: misc code.

  drupal_load('module', 'MYMODULE');

  // @TODO: code that requires MYMODULE_CONST_DEFINITION
}


Two different front pages with different themes

Have you tried the ThemeKey module?

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules.


Why is INPUT field size different across platforms? OS X vs Windows?

Size is the char amount that goes into the input field. If you want to style it, use CSS.

.inputbox{
  border: 1px solid #666;
  width: 210px;
  height: 30px;
  font-size: 1em;
}


or you can simply add a views field 'Node:Link' - you can set the text in the options of that field.

If you want to add this field to other fields, choose the 'rewrite output' option of those fields, and place the token of that current field + the token of the 'node:link' field in the output area.

Make sure you check the 'exclude from display' option for the 'node:link' field and set the field first in the field order, so the token is made available


Wrapping fields together in a Views Exposed Filter

I solved it by using a fieldset to group my fields.

  // Create a fieldset to group related fields.
  $form['my_group'] = array(
    '#type' => 'fieldset',
    '#attributes' => array(
      'class' => array('my-group')
    ),
  );

  // Move the desired fields in it.
  $form['my_group']['field_one'] = $form['field_one'];
  $form['my_group']['field_two'] = $form['field_two'];

  // Unset the original fields, so they don't show up in the form anymore.
  unset($form['field_one']);
  unset($form['field_two']);


How can I find a module or activity that is excessively writing to the database?

I recommend turning on mysql query log and examining types of queries flooding your server.

Or, pay for a product like New Relic or AppDynamics which provide per-url PHP performance metrics (including DB usage) of your application on web servers.


You can define custom tokens such that they can be replaced by pathauto.

See Implementation with a custom Module

The idea is to define tokens such that they get displayed in pathauto's admin page. and we manage the token from our code; after checking conditions.

AS OP's request here's my D6 code that i've implemented.

function MODULENAME_token_list($type = 'all') {
  $tokens['MODULENAME']['fullname'] = 'The Use\'r Display Name';
  return $tokens;
}

function MODULENAME_token_values($type, $object = NULL, $options = array()) {
  $tokens['fullname'] = _MODULENAME_get_display_name($object->uid);
  return $tokens;
}

function _MODULENAME_get_display_name($uid) {
  //load corresponding user and  get $displayname
  return $displayname;
}


How to apply image style to image field in view based on the sort position of that image field?

You can add a field of the type "Global: View result counter"

This will add a number depending on the position of the result.

You can use this to add a class using token to the image.


#block-system-main with no content interrupting my layout

I dont know where it comes from. Probably best would be if you can find that. But if you want to quick fix it. You could unset it in page preprocess

function YOURTHEME_preprocess_page (&$variables, $hook) {
  unset($variables['page']['some_region']['block_id']);


Adding View to Content Type already existing to combine fields

To do what you want, one way is to create a new view, something like this should work I think:

Create a new view of the content type you wish to include
Set display format to Table
Add the fields you want combined to the Fields section
Arrange them in the order in which you want them displayed
Under format: Table | Settings, choose which column you want ALL of these fields to appear in and select that for each

This should present a new view with all of those fields in one column, and any other data as you see fit in other columns. You may need to adjust some styling to get them to format properly - for example, text is inline, so to have it appear on a separate line, you will need to wrap it a DIV or something like.


The block "Recent blog posts" is in blog.module.

/**
 * Implements hook_block_view().
 *
 * Displays the most recent 10 blog titles.
 */
function blog_block_view($delta = '') {
  global $user;

  if (user_access('access content')) {
    $result = db_select('node', 'n')
      ->fields('n', array('nid', 'title', 'created'))
      ->condition('type', 'blog')
      ->condition('status', 1)
      ->orderBy('created', 'DESC')
      ->range(0, variable_get('blog_block_count', 10))
      ->addTag('node_access')
      ->execute();

    if ($node_title_list = node_title_list($result)) {
      $block['subject'] = t('Recent blog posts');
      $block['content']['blog_list'] = $node_title_list;
      $block['content']['blog_more'] = array(
        '#theme' => 'more_link',
        '#url' => 'blog',
        '#title' => t('Read the latest blog entries.'),
      );

      return $block;
    }
  }
}

So there is no .tpl.php to customize.
Using Views module to create a block which lists out recent blog posts would be a solution for you.

Hope this help,


Check to determine if user is member of any group of specific type

I don't think Rules alone will do what you want. You'll want something like

// This hook fires whenever a user account is saved.
// If you want to do it at other times, you'll want another hook.
function mymodule_user_presave(&$edit, $account, $category) {
    // This is an organic groups API function for finding out what group a user is in.
    $user_groups = og_get_groups_by_user($account, 'my_group_type');
    if ( [check for group membership] ) { ... }
}


How do I avoid mydomain.com/node/1 or mydomain.com/node/4 is used?

You need to create patterns for pathauto and go back to those nodes and save them, ensuring “generate new alias” is checked off on the node form.


You can make the address field not-required and write a custom validate function to check for the postal code. Like this:

<?php
function my_form_user_profile_form_alter(&$form, $form_state,  $form_id) {
  if ($form_id == 'user_profile_form') {
      $form['field_adress']['und'][0]['#required'] = FALSE;
      array_unshift($form['#validate'], '_my_postal_validate');
  }
}

function _my_postal_validate(&$form, &$form_state) {
    if (strlen($form_state['values']['field_adress']['und'][0]['postal_code']) < 2) {
        form_set_error('field_address', t('You must enter a postal code'));
    }
}
?>

See form_set_error to set better form errors.

If you support non US addresses (without a postal code), make sure the postal_code is available or you'll get warnings.


how to include globals.php in template.php file

1.in order to include entire file into some other file,we have 2 functions in php:-

a) include('filename'):this function will include the file and if any error occurs during the importing of the file,then the script will not stop and will continue with its execution.

b) require('filename'):this function will include the file and if any error occurs during the importing of the file,then the script will stop.

include() function is recommended for including files.


Best way to get current user purchased products

One one thing that I can think of to change. Make sure you only get a single result.

$query = db_select('commerce_order', 'corder');
$query->join('commerce_line_item', 'li', 'corder.order_id = li.order_id');
$query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
$query->condition('corder.uid', $user->uid, '=')
      ->condition('corder.status', 'completed', '=')
      ->addExpression('DISTINCT prod.commerce_product_product_id', 'product_id');

Using this line:

->addExpression('DISTINCT prod.commerce_product_product_id', 'product_id');

instead of:

->fields('prod', array('commerce_product_product_id'));

will insure that you only get one product_id per row in your result. By using the DISTINCT SQL Keyword, it will only allow distinct values to be returned.


For those who need to implement this as well. I solved this by the following code. However in this code $tid_to_remove is not a view but generated on the view itself.

function MODULENAME_views_post_execute(&$view){

  switch ($view->name){
  case "VIEW_MACHINE_NAAM";

    GLOBAL $user;

    // Go through the view and build a list of items which should be removed
    $data = $view->result;
    $tid_to_remove = array();
    foreach ($data as $row => $rowinfo) {
      if ($rowinfo->users_node_uid == $user->uid ){     // if the current row belongs to the current user
        $tid_to_remove[] = $rowinfo->tid;  // added to the array
      }
    }

    // Optimize the array to unique values
    $tid_to_remove = array_unique($tid_to_remove);

    // Go through the view again en remove all values which are stored in $tid_to_remove
    $data = $view->result;
    foreach ($data as $row => $rowinfo) {
      if (in_array($rowinfo->tid,$tid_to_remove)){
        unset ($data[$row]);
      }
    }

    // place the values back into the view
    $view->result = $data;

  break;
  }
}


How to show friendly url when using Facets search?

I was looking for the same thing yesterday and came across Facet API Pretty Paths

  Enables pretty paths for searches with Facet API. You will likely use this module in combination with either Search API or Apache Solr Search Integration.

I haven't had a chance to try it yet but looks promising...


Try the Themekey module which allows content, user, or role -specific themes.


You will need to create the message yourself, since the url is not available as a parameter in the string, like the type and title is via @type and %title.

To do this, you can add a custom submit function with hook_form_alter and delete the message created by the node module. This would look like this:

module_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'node_form') !== FALSE) {
    $form['#submit'][] 'my_custom_submit_handler';
  }
}

function my_custom_submit_handler(&$form, &$form_state) {
  // Unset previous set messages.
  drupal_get_messages('status');
  drupal_set_message(t('Your custom string', array('@with' => 'params')));
}


A simpler way can be:

Current Setup:

View A (show content)
View B (show orders)

Steps:

Create a new "page display" of the View A and set the path and menu if you have to.

2 a. Then on the view header or footer (depending if you want the View B before or after View A) add a global view area that will show the View B when viewing View A page.

2 b. Select from your existing views the View B

2 c. Apply the change to the current display and you are done.


You may want to simply make use of the existing field available in views called:

  Content: Has new content  values
  Add that as a field or use it to customize another field, it is pretty handy.

Some more information on what constitutes as NEW or UPDATED:
for how long is Content considered "new" by the filter criteria "Content: has new content"?


How do you override page.tpl.php in Omega 4?

Omega 4 includes a few changes.  From the project page (emphasis mine):

  The Omega theme provides layouts as a method of managing page
  templates along with layout specific stylesheets and regions. This
  allows you to write highly customized layouts that can be contextually
  switched. You can disable this feature to use the plain page.tpl.php
  or even use Omega 4.x together with Panels and Panels Everywhere to
  gain even more control over your pages if required.

If you want to use the new layout system, clone sites/all/themes/omega/layouts/simple into your theme, rename the files, edit the layout include, and clear caches.

The goto admin/appearance/settings/mytheme, and click on the Layouts tab.  If you did everything correctly, you can select the layout you just created, and then save your configuration.

If you don't want to use the layout system, and just want to use page.tpl.php, then untick Enable Layouts extension, and save your configuration.


Creating specific taxonomy terms the Drush way

Try the taxonomy manager module.

https://www.drupal.org/project/taxonomy_manager

It allows for mass insertion of terms.

There's also a taxonomy csv module which allows for import/export of taxonomies to file. That might be worth a try too:
https://www.drupal.org/project/taxonomy_csv

Else you can try and write your own module... But that's a rather tougher route.


JS error when using AddThis field displayed in a view

AddThis includes it's javascript in the footer. It could be possible that, in your case, you have to add addThis in the header.

You can do this by changing this line of code in the addthis.php:

AddThis.php line 274 comment:

'scope' => 'footer’,

Hopes this help you out!


How can I be sure configuration is never changed on live system?

One option is to use https://www.drupal.org/project/config_readonly, it enforces that config writes can not happen on production.

So far, I haven't built/maintained a D8 site where that approach was practical. Most of our sites rely quite heavily on contact forms for example, with workflows where content managers create contact forms as well. And sometimes quick changes are necessary, e.g. for services and integrations.

One option to deal with that is to use a project like https://www.drupal.org/project/config_split, which allows to keep a part of configuration outside of git and not have it overwritten by deployments. So far, we just do a config export on production, commit that to the production branch and then merge the feature branches that we want to deploy. There's some risk for conflicts, but that doesn't happen often.

But sure, there are sites where it is critical that every change is reviewed and approved first, before it can be deployed, then something like config_readonly is useful. I wouldn't enforce it just because some d.o page says so, you need to figure out what works best for your site and workflows.


Adding link with image in the .tpl.php file

I think what you want is something to link to that will execute your PHP "callback". Have a look at hook_menu() in the Drupal API.

Here's an example:

/**
 * Implements hook_menu().
 */
function MODULENAME_menu() {
  $items = array();
  $items['mymodule/callback'] = array(
    'page callback' => 'MODULENAME_do_callback',
    'access arguments' => array('access content'), // You can specify a permission here.
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function MODULENAME_do_callback() {
  // your php here
}

With that you should be able to link your image (just with standard HTML) to yourdomain.com/mymodule/callback and it will execute your code.

Note: Be sure to clear all caches after adding your hook_menu() implementation.


In general to get the value of field if the entity type is a node

$node = node_load($nid);
echo $node->field_image_url['und'][0]['value'];

or try to print the $node to figure out how to get it

echo '<pre>'; var_dump($node); var_dump($node->field_image_url); die;

in your situation try the next to figure out what is happen there

<?php
$node_type = "slider_image";
$sql = db_query("SELECT nid FROM node WHERE type = $node_type");
$results = db_query($sql);
foreach($results as $row){
   $node = node_load($row->nid);
   echo $node->field_image_url['und'][0]['value'];
   echo '<br>';
}
?>


How do I override the date filter to filter by years instead of exact date?

I contribute a module for this check it out here:

  This module add views filter by year exact, instead of full date like mm-dd-yyyy you can use date year like yyyy.

https://www.drupal.org/project/views_year_filter


I'm assuming your parent-child relationships are done through an Entity reference field on the child node pointing to a parent.
As always there is more than one way of solving it in Drupal but one popular way is to use the Views Bulk Operations (VBO) module.
The module Views Bulk Edit helps to speed it up by showing the field options to update.
The procedure is to create Views where you can see all the child nodes among the results. It can be all nodes of that type, or you can even create it specifically for one parent node where its children nodes are automatically filtered.
VBO allows you to add a Field to your Views that shows up as a checkbox next to each result row. It also adds an Action you can trigger on the chosen rows.
With that configured you will be able to choose nodes from your results and edit them in bulk.


Menu access callback function called multiple times

Drupal forms are clever enough to know whether or not they've been submitted in the current page call and can react accordingly. Your best bet would be to move your code logic to inside the form function, where I think you can check for $form_state['#submitted'] to decide whether this code runs or not.

Alternatively you could check for the existence of $_POST variables in the MYMODULE_menu() function.

  Check and read it out $form_state['cache'] = true; from here.

Hope that helps.


Hi you have to remove the row from field_data_comment_body table where entity id is 28 ..


How to get the first non-empty field value of a referenced entity in views?

From Everything is OK but there is a problem I couldn't solve I supposed you successfully create a view of issues and their related magazine and I focus on the problem.

There are two cases,

at least one of the issues has an image
non of them has an image

In order to create a view for case 1, you need to modify your existing view to have sort criteria on image_field:fid (Issue image field, using relationships you can have this)

and sort it descending

and set the Pager to:

Use pager:
Display a specified number of items| 1 item

in this way, if there is any issue with an image, the first one that has image is displayed.

Lets handle the case where there is no issue with image. The image field is displayed in here, it can be in a

, but it is empty. We have to insert a default image in it. Simply add css like this to your theme

.views-field-field-image{
       width: ...px;// you standard display of width
       height: ...px;// you standard display of height
       display: inline-block;
       background-image: url('');

Now if there is an image, the

 layer will go behind the image and it will not be shown and if there is no image, we have set the
 dimension and also an image for it to be displayed.


Return 'tokens' if you want to add new/custom to the existing list.

return [
  'tokens' => ['commerce_product' => $tokens],
];


How to place an Ubercart order on behalf of another user?

If you'd like to change ownership during checkout, probably not, or not without reworking some core UC code; there are likely to be permission problems if you switch the user owner before order completion.

Changing the ownership of a UC order is a trivial change.

$order = uc_order_load($order_id);
$order->uid = 1234;
uc_order_save($order);

But, the core Ubercart rules integration do not support a rules action that changes order ownership.  So in order to use rules you'd need to build a custom action there. Also, because aforementioned permission problems, you'd likely need to use an event that occurs when the purchasing user no longer needs to own the order.

In summary, the above code is somewhat of a starting point, but you're looking at tripping over UC's order ownership enforcement if you go down this route.


Made a local copy of live-site: all paths generate error 404

Fixed. It appeared that I installed the mod rewrite module, but didn't activate it in my default site profile (as per these instructions: http://www.seangw.com/wordpress/2012/01/how-to-enable-mod_rewrite-in-apache2-ubuntu/). Did that and everything works fine now. Woops, feel kind of stupid now.


The problem seems to be the key of the nested array, where you are using 'VAR', you are repeating this key and that makes PHP to override the value on the array (or on the object on Js).

I think you would have to use the 'VAR' key on a slightly different way:

drupal_add_js(array('THINGS' => array(
    'ONE' => array(
      'VAR' => 'blah blah blah',
      'VAR_ONE' => 'blah blah blah one'
    ),
    'TWO' => array(
      'VAR' => 'blah blah blah two',
      'VAR_ONE' => 'blah blah blah two'
    ),
    'THREE' => array(
      'VAR' => 'blah blah blah three',
      'VAR_ONE' => 'blah blah blah three three'
    )
  )
));

to get what you are looking:

"THINGS":{"ONE":{"VAR":"blah blah blah", "VAR":"blah blah blah one"},"TWO":{"VAR":"blah blah blah two","VAR":"blah blah blah two two"},"THREE":{"VAR":"blah blah blah three","VAR":"blah blah blah three three"}}


$this->t() assumes object context. $this isn't available in the static context of the create method above.

The ControllerBase provides access to t() via a protected function (see below from docs) to it is also not available from the public context.
setStringTranslation however is a publicly available method.

StringTranslationTrait::t   protected   function    Translates a string to the current language or to a given language.
...
StringTranslationTrait::setStringTranslation    public  function    Sets the string translation service to use.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Controller%21ControllerBase.php/class/ControllerBase/8.2.x


Is $site_name , $logo ,$site_slogan are part of render array $page?

The variables you use in templates aren't really part of the render arrays themselves.  They are created by the various preprocess and process functions and added to the $variables array.  By default, those you list are added in either a template_preprocess_page() or template_preprocess_html(), which your theme can have, too.  Look at the source to see what is going on.  For example, the stock template_preprocess_page sets $site_slogan like

$variables['site_slogan'] = (theme_get_setting('toggle_slogan') ?
                            filter_xss_admin(variable_get('site_slogan', '')) : '');

To aid in figuring this out, I suggest installing the Devel module, and looking at the functions that it provides.  For example, you can do

dpr($variables);

to get a dump of everything in the $variables array, or you can do

kpr($page);

to poke through the $page object via Krumo, which is included in Devel.


Content Access for not showing specific Content types on Add Content page


How to display a block if a user does NOT have a selected role?

In global variable $user are stored all roles that current user has. So in template.php or template suggestion files you can check if your targeted role is in $user->roles and display block if not.


How do I create content of the day/week/month?

Using the Flag module seems like a no brainer to me to get this to work: introduce a global flag that is allowed to be used by your editors to flag relevant articles. Since Flags are fieldable, you could add extra field(s) to such flags to let the flagging user indicate an appropriate start date and end date.

With the above in place, you've reduced your question to creating an appropriate view (using Views) which shows the flagged article(s) for which their flag fields (start / end dates) have appropriate values as compared to the current date.

This solution is "without programming" (as in your question) ...

Ps: I'm assuming this is about D7.


Moving File Directory to Other Partition

It's probably easier to simply use symlinks to point to the new folder. That way, you can leave the default settings as they are. In addition, Windows will deal with the change instead of Drupal. Move the files folder to D:/files, open a command prompt (cmd), and run the following:

C:\> mklink /j "C:\xampp\htdocs\www\proyects\sites\FirstProject\files" d:\files\

Are you sure its proyects and not projects?


Strict warning: Only variables should be passed by reference in Open Restaurant

drupal_render takes reference. taxonomy_term_view($term, $view_mode) is not a variable, so you shouldn't use it in places where reference is needed - because if something takes reference, it will try to update what it got, and it's impossible with a function. So to fix this, you need to create variable, then store result of taxonomy_term_view in it, and pass that variable to drupal_render.

Then, create patch file nd post it in their issue queue for everybody to see.


How do you reorder the shipping services for drupal commerce?

You can use a custom hook to reorder services:

<?php
/**
 * Implements hook_commerce_shipping_service_info_alter().
 */
function mymodule_commerce_shipping_service_info_alter(&$shipping_services) {
  if (isset($shipping_services['my_flat_rate'])) {
    $shipping_services['my_flat_rate']['weight'] = -10;
  }
}
?>

See discussion here: https://drupal.org/node/1537394#comment-7003814

Steps would be create a custom module or add this hook to existing module for your site, set the weight as code above ranging from -10 to 10 and you should be all set till there is a patch or update to overall Shipping module.


How to see an overview of the download statistics of all modules on drupal.org?

You can get information about a particular module in both XML and JSON format by accessing URL:

Eg: (For Views Module) :

XML format:

https://www.drupal.org/api-d7/node.xml?field_project_machine_name=views

JSON format:

https://www.drupal.org/api-d7/node.json?field_project_machine_name=views

Reference: https://www.drupal.org/api


Manual ajax callback on saved dropdown value

If I understand correctly, anything that can query a URL would do, for example Curl.


Let me explain you the template order

In this, you can alter the header and footer if you wanted it to be different than normal page layout that is set in the page.tpl.php

page--[content-type name].tpl.php = page--lab.tpl.php
It will be used to theme all contents of type lab including header and footer

page--node--[content-id].tpl.php = page--node--12.tpl.php
It will be used to theme  content with 12 including header and footer

Secondly,

node.tpl.php Will work for all type of content on the site
node--[content-type name].tpl.php (node--lab.tpl.php) will used to alter the content part only of lab type content excluding header and footer
node--[node-id].tpl.php(node--10.tpl.php) will use to alter the content part of node 10 only excluding header and footer

Including and excluding meand control over header and footer.

Hope it will help you!


Customizing the register form with a new class: Why do I get this error?

It seems like you could reduce complexity with hook_form_alter, and manipulate the options on the reference field.


Remove case sensitivity from username when logging in

Using hook_user_insert, you can convert every letter of username to lower case once a user is being created. Then when a user is submitting the login form, you can convert its username field to lower case. So from now on all of the usernames will be in lower case it is no longer case sensitive


Can Location Modules Geo Code on node save?

I figured out the problem. I have to set a Service for each country I want to use in the Geo Coding Settings: admin/config/content/location/geocoding


Using Entity metadata wrappers to change field value under hook_node_insert()

The method you are using the save the field isn't ideal.
For setting the field values you should use the set() function provided by the EntityMetadataWrapper class.

function mymodule_node_insert($node) {
  if (!_is_dynamic_type($node->type))
    return;

  $messagew = entity_metadata_wrapper('message', message_create('post', array('uid' => $node->uid)));

  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //below loads a full taxonomy term
  $nodew->field_hidden_type = taxonomy_term_machine_name_load('event', 'hidden_type');

  $messagew->field_hidden_type->set($nodew->field_hidden_type->value());
  $messagew->save();
}

On a side note, I see that there is not check on the node type, or any other parameters in the implementation of  hook_node_insert. Note that it will get triggered every time a node of any content type is created.


That’s the browser validation message appearing. If you want to show Drupal messages only, you need to set the no-validate attribute on the form tag itself so browsers ignore it. Drupal will still run validation on submission.


Change User Profile Fields from modules - $form fields not available - Ubercart Roles

I figured it out! My module name was alphabetically before the other modules..."A" (admin_dasboard) comes before "U" (ubercart_roles). I was able to go into the drupal_system table and set my modules weight to 1, where before it was set to 0, the same as Ubercart. Hope this helps someone.


If I download a sub-theme do I install it under the main theme's directory?

Yes, you should install it under main themes directory i.e. sites/all/themes.

Download Nucleus Base theme and put it inside sites/all/themes/ folder
Download TB Purity theme and put it inside sites/all/themes/ folder.
Go to Appearance and enable TB Purity theme.

The concept of base theme is it provides code base to its sub-theme, so, you don't really need to enable Base theme, just keep it there for your Sub-theme to find the codes that it needs to run.


Commerce + Views: Distinct on Referenced Product not working

Just use this in filter.

Content: Product Reference:delta (= 0)

which will show only one variation of your product.


Add value to field using hook_webform_submission_presave()

flag_get_user_flags will return an array. so you have to handle it as an array not like a value.


Connect to Salesforce using wsdl in Drupal 8

It seems the problem you are facing is due to the way you are referring the library; please refer the following question; they have explained how you should be using external libraries in Drupal 8 custom modules.


Use DRUPAL_ROOT.

It is defined in index.php as:

define('DRUPAL_ROOT', getcwd());


Drupal 7: How to use CKeditor with Rules email

I know this is an old issue but i had the same problem and could not find any answer so i figured it out myself.I thought i will put my findings here maybe it will help others.

Most important is that you should use text_formatted not text_format otherwise rules cannot render the field correct. Second is that you should use a different hook "mymodule_rules_action_info_alter" to change the type of the field. See in the example code how i changed the html body field for the mime mail rule "html email"

function mymodule_rules_action_info_alter(&$actions) {
  $actions['mimemail']['parameter']['body']['type'] = 'text_formatted';
  $actions['mimemail_to_users_of_role']['parameter']['body']['type'] = 'text_formatted';
}


Remove jQuery and find out what is asking it to be included

I think that it is pretty safe to assume that any module using JS is going to assume that jQuery is present.  Yes they should feature detect this, but its availability in Drupal is pretty much assumed by everyone.  There is no real way to get a list of all of the jQuery dependencies.

CSS can be aggregated and minified if the worry is file count.

If you truly want to manage these yourself, your best bet is to remove the $scripts and $styles variables from html.tpl.php and manage your own, eg $myscripts and $mystyles.  You could also unset/reset them in your own template_process_html.

Drupal is built on hooks.  Don't think of it as having to add code to remove something.  You add code (implement hooks) as a way to modify or extend the default behavior.

Now that I have answered your question, you are really going out of your way to bypass a lot of the power of Drupal.  You should start by looking into what Drupal calls starter themes or base themes.  The Omega and Zen themes are two popular ones.


How does the mapping of the Feeds module work?

You can import as few or as many source fields as you want.  You do not have to include all of them!  The source table or cvs row or whatever does not have to match your destination entity exactly.  It's OK to just take the parts you need.  I frequently use the feeds module with csv files, and import just a portion of the columns that are actually present in the file.

Naturally, just make sure none of those missing fields are marked as required on the destination entity...


Calculate shipping based on square meters (m2)

I'm struggling with a a similar problem.

From what I can see, the only way to do it with Ubercart is to connect to the API of an appropriate shipping company that supports volumetric shipping calculations. The availability of this (in terms of an existing module) will depend on which country you're working in, plus it will depend on whether there is an existing module that supports the specific carrier you've chosen.

The US is obviously well-served in this regard. Outside the US, support can be patchy, to say the least.


Simple drop-down "list" items (inside a html "body") --- content (un)hiding upon click --- Not a navigation bar, no redirect, no menu, no forms

@Wtower's help above makes this pretty straightforward. Drupal (I am using 7) can use these jQuery codes without any additional install.

One can just put the following right inside a drupal "node", such as a standard article. This solution works for list items; the following is to be implemented [I used ordered lists (ol) in my example]:

List tem 1.

Content of list item 1.

List item 2.

Content of list item 2.

I haven't looked at triangular (changing upon revealing or hiding content) list bullets yet.

If you want other items than list items, look here:

http://renaudjoubert.com/fr/node/56
http://triq.net/articles/hide-and-slide-drupal-content-jquery


How do I migrate while content is still created on production site?

Migrate, as shipped with Drupal 8, has two components:

The migrate module. This provides a very flexible API.
The migrate_drupal module. This provides Drupal 6 / 7 to 8 migrations (the migrations themselves has been scattered into the modules). This is the part which keeps IDs and the motivation for this was very simple: there's just no way to tell where those IDs might lurk. Say, one of the old nodes has a http://example.com/node/12345 link in the body text and we changed the node id to 67890 during migration? Then that link breaks. It also made for more rapid development which is not a bad side effect either. It is arguable whether for example file IDs deserved such treatment or not.

As @berdir comments, if you remove the nid: nid process definition from a node migration then it will happily generate new node IDs for you, no sweat but you need to look everywhere for the same to make sure that any references are changed to a migration_lookup process definition. Some of it is already done for you, some of it is not.

For example, comment/migration_templates/d6_comment.yml has:

# If you are using this file to build a custom migration consider removing
# the cid field to allow incremental migrations.
cid: cid
pid:
  plugin: migration_lookup
  migration: d6_comment
  source: pid

For core, pid: pid would work just as well but instead, this migration is already prepared for this migration creating new IDs. But then it continues with

entity_id: nid

Now the corresponding node/migration_templates/d6_node.yml has

# If you are using this file to build a custom migration consider removing
# the nid and vid fields to allow incremental migrations.
nid: tnid
vid: vid

If you actually do that then you need to circle back to comment/migration_templates/d6_comment.yml  and write

entity_id:
  plugin: migration_lookup
  migration:
    - d6_node:article
    - d6_node:page
  source: nid

Because the actual migration is not d6_node but rather d6_node:nodetype.


The way I would do this is with a Notification module.  There is a page at Drupal.org that lists the notification modules that exist.  You may want to look at that page to find a module that suits you.

One particular module I would like to suggest (since I maintain it :-) is the one named Notify.

  The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily news letters sent by some websites.

You can set it up so that users become automatically subscribed to notifications when they register at the site.  You may notify about all new content or only specific content types.  I.e. you can create a special content type named "Site updates" and use that to post site updates about your alpha site. Then, all your subscribed users will receive an e-mail update update whenever you post new content of the type "Site updates".


Why Cant add a class to an element by jquery

Going on little information provided its probably because you cannot access jQuery with the $ by default in drupal.  This is to prevent other library conflicts (see jQuery.noConflict())  If this is the case you will probably be getting an undefined function error in your console.  To fix this you can either use jQuery or wrap it in a function like this:

(function($){
  $(".play").attr("id", "myID");
})(jQuery);

or can do this:

jQuery(".play").attr("id", "myID");

By default the version of jQuery that is used on drupal is 1.5.  You may consider using jQuery Update module for a newer version.

"Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them."


How to hide language switcher block if node has no translation?

In template.php add:

/**
 * hide language switcher if en-gb is not set
 */
function MYTHEME_links__locale_block(&$vars) {
  // made conditional if other languages are added later
  if(!isset($vars['links']['en-gb']['href'])) {
    unset($vars['links']['en-gb']);
  }
  // here is the condition
  if(count($vars['links']) <= 1) {
    return '';
  } else {
    return theme_links($vars);
  }
}


Restrict a users node posting total dependent on a paid subscription role

In my opinion the best solution would be Ubercart for selling roles to users
 and Node Limit module to set a block on how many nodes can be created by certain roles (in a given period, optionally).

You should set up different roles, one for every different amount of nodes a user can create. Then with Ubercart you have configure a product for every role to be sold.

Then with Node Limit module you can configure the restrictions for every role.


How to inject a fake class into container when running WebTestBase tests?

Here's the solution.

Let's say your module A defines a new service.

In order to alter that service, you need to create a separate module B and follow the steps outlined in Overriding the default service class section on https://api.drupal.org/api/drupal/core%21core.api.php/group/container/8.

Make sure to list module A as a dependency in module B info.yml file.

Add both modules to the $modules array in your test class, and everything will work. $this->container->set() is no longer needed.

That issue on drupal.org: https://www.drupal.org/node/2700739


How to add custom entities to group types?

Here's how I've solved it in the end. Although in my example I'm adding user entities, you can add whatever custom-entity you want, the approach is the same. What I needed was to add users to a group not as members (as already provided by the group module), but as pure user entities (group content). My answer is a basic example. See /group/src/Plugin/GroupContentEnablerInterface.php for a detailed description what methods etc. are available to refine the whole thing. You basically need 2 files

module_name\src\Plugin\GroupContentEnabler\UserEntity.php

<?php

namespace Drupal\module_name\Plugin\GroupContentEnabler;

use Drupal\group\Plugin\GroupContentEnablerBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a content enabler for user entities.
 *
 * @GroupContentEnabler(
 *   id = "group_entity_user",
 *   label = @Translation("User"),
 *   description = @Translation("Adds users to groups as pure entities and not as members."),
 *   entity_type_id = "user",
 *   entity_access = TRUE,
 *   pretty_path_key = "user",
 *   reference_label = @Translation("Username"),
 *   reference_description = @Translation("The name of the user (entity) to add to the group (not as a member)"),
 *   deriver = "Drupal\module_name\Plugin\GroupContentEnabler\UserEntityDeriver"
 * )
 */
class UserEntity extends GroupContentEnablerBase {

/**
 * {@inheritdoc}
 *
 */
 public function defaultConfiguration() {
   $config = parent::defaultConfiguration();
   $config['entity_cardinality'] = 1;
   return $config;
 }

 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
   $form = parent::buildConfigurationForm($form, $form_state);
   // Disable the entity cardinality field as the functionality of this module
   // relies on a cardinality of 1. We don't just hide it, though, to keep a UI
   // that's consistent with other content enabler plugins.
   $info = $this->t("This field has been disabled by the plugin to guarantee the functionality that's expected of it.");
   $form['entity_cardinality']['#disabled'] = TRUE;
   $form['entity_cardinality']['#description'] .= '
' . $info . '';

   return $form;
 }

 /**
  * {@inheritdoc}
  */
  public function calculateDependencies() {
   return ['module' => ['user']];
  }

}

and the second file module_name\src\Plugin\GroupContentEnabler\UserEntityDeriver.php

<?php

namespace Drupal\module_name\Plugin\GroupContentEnabler;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class UserEntityDeriver extends DeriverBase {

  /**
   * {@inheritdoc}.
   */
   public function getDerivativeDefinitions($base_plugin_definition) {
     // I used to set 'entity_bundle' to 'user' and the autocomplete for the user name never worked.
     // Checking a user with devel, the bundle is  always empty.
     // So leave it empty and specify the entity_type_id = "user" in the docblock
     // of UserEntity.php
     $this->derivatives['user'] = [
       'entity_bundle' => '',
       'label' => t('Group entity (user)'),
       'description' => t('Adds users to groups as pure entities and not as members.'),
     ] + $base_plugin_definition;
     return $this->derivatives;
    }
}

This can now be installed just like all the other group-content types. The plugin_id of this user-entity group content type is group_entity_user:user. Again, see the group module's source code, as the documentation is good and lot's of additional methods can be used to refine this approach.

As a warning, be very careful when creating these custom plugins as it can cause a lot of trouble when not propery configured/tested. (see my previous question)


How can I transfer node and comment records from Drupal 6 to Drupal 7?

You could look into using the Migrate module. Although I haven't used it myself, I know that many have been using it to move content from a Drupal 6 website into a Drupal 7 website. Be aware that it is an advanced module that has no UI (that I'm aware of). It integrates with Drush and allows you to create migration scripts and run them from the command line.


Ajax button strange behaviour when clicked twice

Problem solved!
The button must be of type "submit" instead of "button"! So the correct code is:

$form['auctionpersons']['add_person_btn'] = array(
  '#type' => 'submit',
  '#value' => 'Add person',
  '#description' => 'Click button to add person',
  '#ajax' => array(
      'callback' => 'add_auction_person_ajax_callback',
      'effect' => 'fade',
  ),
);

Thx for viewing this question :-)


Entity Reference - show link on referenced node

I found the solution! I just went to "Manage display" of the content type and I checked "Link label to the referenced entity" in the "Entity Reference" field.


Creating nodes from json including image field upload

The best way to achieve that is through Services module

In your case you have to post the image itself and use the file data in node object as a value for the field see that snippet:

  //$file_array is the result from saving the file
  //assuming you have the field name is image
  $file_array = api_save_file($_POST['image'], $title);
  $node->field_image[LANGUAGE_NONE][0]['value'] = $file_array

Note that you have to save the image base64 encoded like

//save base64 images as files
//@return object file object

 function api_save_file($file, $name, $entity_type = 'node', $entity_id = 0){
$data = base64_decode($file);

$finfo = finfo_open();
$mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
finfo_close($finfo);
// get file type png. jpg
$ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
$file_name = str_replace(' ', '-', $name);

$file = file_save_data($data, 'public://'.$entity.'/'.$file_name.'.'.$ext, FILE_EXISTS_REPLACE);
file_usage_add($file, 'file', $entity_type, $entity_id);

return array(
    'fid' => $file->fid,
    'width' => 800,
    'height' => 600,
    'display' => 1,
    'alt' => $name,
    'title' => $name
);

}


Drupal 8 Accessing Menu Tree in a Block's JS

The documentation is inevitably focused on PHP, since Drupal is written in PHP and server-side renders.  And the answer to getting info from PHP/server side to JS/client side is not really Drupal specific.  Like any other situation of this ilk in web development, you have two basic choices.  Either annotate your HTML with enough elements, IDs and classes that you can pull the necessary info out of the DOM, or expose an endpoint containing the info in a convenient-for-JS-consumption format like JSON for your javascript to fetch.

As for the latter, if you don't feel like rolling your own endpoint, there seem to be one, two three and maybe more modules, although I cannot vouch for any of them.


UbertCart Cart does not follow my cart count

The Ubercart block probably defaults to having DRUPAL_NO_CACHE set, while the view may have a different cache setting per default. Check the cache settings on the view?

May help for you to say whether this behaviour differs for logged-in and anonymous users.


Using views to display content based on taxonomy terms?

Drupal Views can easily do this :)

Create your view and call it "example", and for this example, put Node Title in the Fields.
Add in an argument.  Here select Taxonomy: Term ID.
In "Action to take if argument is not present:" select "Provide Default Argument"
There, select "Taxonomy Term ID from URL" and then click "Load default argument from node page, thats good for related taxonomy blocks" and if you want, you can also limit it to specific vocabulary(ies) by clicking "Limit terms by vocabulary" and clicking on the one(s) you want.
Create a "Block Display" and save everything.
Goto your Site Building/Block Admin Page and look for "Views: example" and put it in a region of your theme.

Now, if all is well in the world, that block will appear and will display the titles of all nodes that also have the same taxonomy term as the node it is displayed on.  Of course, you will probably want this block displayed only on certain pages, but you can do that in your block UI as well.  And of course you'll also probably want to be fancier than just the node title, etc, but there you would include the fields in the specific nodes, etc.

ADDITION:

This is what I see here for a taxonomy term id argument with D6 and Views3:

UGLY SOLUTION:

I was sure there would be a solution to this using just Views, but I can't figure it out for the life of me.  Grrrr, I hope someone out there says Duh, this is how you do it. But, if you have the PHP Input Filter enabled, you can create a block that will do this instead of creating a custom module.  The PHP Input Filter is UGLY.  It should be killed with that dull ax I often use, but here goes:

Add a new block via the blocks UI with this as the block body:

<?php

$node=menu_get_object();

if (isset($node->type) && $node->type=='Faculty') {

  $vid = db_result(db_query('SELECT vid FROM {vocabulary} WHERE name = "Expertise"'));

  if (!empty($node->taxonomy)) {
    foreach($node->taxonomy as $term) {
      if ($term->vid == $vid) {
         print '
' . $term->name . '
';
         print '
' . views_embed_view('faculty_expertise_test2', 'default', $term->tid) . '
';
      }
    }
  }

}

?>

Make sure you select PHP Code as the Input Filter.  Select a Block description and title and save the block.  Place it in whatever region you want.  Cross fingers and see what happens :) Basically all this does is loop through all taxonomy terms of your Expertise vocabulary in the node shown and then calls the view with that argument. I think I have everything capitalized correctly from your examples, but the key things to customize about are Faculty, Expertise and faculty_expertise_test2, which are your node type, vocabulary and view.  If all works, then it's up to you to CSS things to your liking.  Hope this helps!

PS
I just realized that the view will most probably return the faculty member her/himself but that can be dealt with another day :)


How can I quickly check Drupal 7 porting status of the contributed projects?

There is the Drupal 7 contributed project porting status website that uses data from the Upgrade Status module to show Drupal 7 porting status of the top 61 contributed projects.


Have you tried with an exposed Global Combine fields filter ? I'm not sure which Views version implemented that filter.

Alternatively, you may use the Views filters populate module :

Add the fields you want to search in a OR combination of filters, not exposed.
Add the Global : Populate filters provided by the module (exposed),  checking the filters you added in the Or group.


Create a block showing the latest of a certain content type

This definitely sounds like a job for views. I could explain how to do this exactly BUT for your own learning you should install views and go through the documentation also as you will thank me in the long run for not explaining exactly how to do it. You do not need to do it the way you have started doing it already, Views will manage everything you have already tried to accomplish with listing articles.

If you want a shortcut without going through the documentation, click this which will give you a thousand tutorials to do what you want to do.


To set the date format used when dates are displayed on your site, navigate to Home » Administration » Configuration » Regional and language, and set date format.


Can I attach a jquery.ui.datepicker widget to a form element using the form api?

You can use after_build in your form to call a function that contains drupal_add_js


How to pass a custom Form to a Twig template

This structure will not work with the autoloader right now - your namespaces and directory structure needs to follow these PSR-4 standards. (In particular, setting a namespace in your .module will cause Drupal to not find your hooks, which must be in the global namespace.)

I'm not sure I understand your use case fully, but it sounds like you want to:

Create a form.
Create a route that serves this form.
Render the form with a custom template.

For the first, your form class should be something like this (and must be saved in a file matching the class name under modulename/src/Form/{ClassName}.php):

namespace Drupal\modulename\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class MyModuleConfigForm extends ConfigFormBase {

  public function getFormId() {
    return 'modulename_settings';
  }

  public function getEditableConfigNames() {
    return ['modulename.settings'];
  }

  public function buildForm(array $form, FormStateInterface $formState) {
    // build the form
    $form['...'] = [
      //...
    ];

    parent::buildForm();
    return $form;
  }

  public function submitForm(array $form, FormStateInterface $formState) {
    $this->config('modulename.settings')
      // set the values from the form
      ->set('...', $formState->getValue('...'))
      ->save();

    parent::submitForm($form, $formState);
  }

}

For the second part, you need a modulename.routing.yml file that looks something like this:

modulename.settings:
  path: '/admin/config/mymodule'
  defaults:
    _form: '\Drupal\modulename\Form\MyModuleConfigForm'
  requirements:
    _permission: 'administer site configuration'

(This is for admin configuration forms, since you mentioned ConfigFormBase. If you want a more general form and open it to anonymous users, extend FormBase instead and put _access: 'TRUE' in the route requirements.)

Finally, for the third part, you need to create your theme hook in modulename_theme(). (Your code already works, although the template key is superfluous as it matches the default.)

Then, modify the buildForm() as follows:

  public function buildForm(array $form, FormStateInterface $formState) {
    // build the form
    $form['...'] = [
      //...
    ];

    parent::buildForm();

    // *After* parent call.
    $form['#theme'] = 'modulename_form';

    return $form;
  }


Which is the most performant way of overriding views field output

I would go for Template based solution for the sake of maintainability and flexibility. For example, if you are using the same field in two different views, you can use a .tpl file that applies to all views that have that field. But if you depend on Views UI, you will have to configure each field in every view separately which may complicate things in the long run. Also, the fewer access to database to retrieve configuration the better.


You should define hook_search_api_solr_query_alter and something like this:

/**
 * Implements hook_search_api_solr_query_alter().
 */
function MODULE_search_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  $call_args['params']['fq'][] = 'FACET_MACHINE_NAME:YOUR_VALUE';
}

I hope it helped you.

The other way to do this described here http://www.eilyin.name/note/how-set-value-facet-default-drupal-54


Error: Call to undefined function twig_render_template() when accessing website

Solved! Apparently core has been damaged, restored core everything is back to normal.


How to disable the "clear log messages" functionality for administrators?

You would have to use hook_form_alter, and either remove that form or put access control on it. This needs to happen in a custom module.


What services must I leave switched on in Elysia cron

Elysia cron is just an improved durpal cron service. You must have enabled the services you have enabled by deafualt in the standard Drupal cron. Some of them, for example, remove temporal data from the database (probably the reason your database is growing).

So, yes, you must have the services enabled, and those are the services enabled byu default by Drupal. Obviously the exact services that must be turned on depends on each installation.


ESIs with Varnish 2.1.5 for Anonymous Users

Try turning off Anonymous caching and see what results you get (caching should be handled by Varnish).

Go to admin/config/development/performance
Uncheck Cache pages for anonymous users


I think you're just looking for a standard page callback for your menu item. To extend the example from the hook_menu() docs slightly:

function mymodule_menu() {
  $items['abc/def'] = array(
    'page callback' => 'mymodule_abc_view',
  );
  return $items;
}

function mymodule_abc_view() {
  $text_content = 'Text to print to the page.';

  // You could just return the string itself here, that will also work fine,
  // but it's 'best-practice' to return a render array so other parts of the system
  // can alter the content if they so desire.
  return array(
    '#markup' => $text_content
  );
}

Remember to clear Drupal's caches after making the changes to hook_menu(), or they won't be picked up.


Yes, there are instructions for doing this on Drupal.org.

Also, here's a general article on organizing your theme files in Drupal.


How do I display serialized 'REST Export' with date format rather than timestamp?

Even with the rows being displayed as entities, you can have a hook_views_pre_render(&$views) invocation alter the entity field properties before they are used they are rendered out.

function MYMODULE_views_pre_render($view) {

  // Only alter my_view_machine_id view, rest_export display
  if ($view->id() == 'my_view_machine_id' &&
      $view->getDisplay()->definition['id'] == 'rest_export') {
    foreach ($view->result as $row) {
      if (isset($row->_entity->created)) {
        // Alter the entity created property to a readable ISO8601 date
        $row->_entity->created->setValue(date('c', $row->_entity->created->value));
      }
    }
  }
}

There might be a better part of Views rendering pipeline (e.g. REST views export has some templating system) to place this in, but it still renders out the altered serialized property.


If you want to inspect the values of a submitted form, I'm afraid you'll have to dig in to a nested array.

However, if you need to check if a file has been uploaded, why don't you make it a required field? And if you have a reason to write your own check, why don't you add a validation function instead of a submit handler?


Taxonomy page by views with two arguments?

Based upon my read of your question there may be several things to address here.

View is not overriding your URL.  The address you have in the URL should be unique and intended to call the view just as if it is any other piece of content.  Do not have more than one piece of content with the same address, can only confuse things. Ignoring aliases for a moment, that means you cannot create a view with the path of taxonomy/term/tid, but you can create one called taxonomy/term/tid/facts. adding the fourth level of the URL makes it a unique address.
You are not defining a taxonomy page with terms from two vocabularies. To provide the content you desire you should create a view with the desired URL name.
A taxonomy page has a URL of taxonomy/term/tid. You can provide it with an alias, but that can confuse your thinking.  The first thing Drupal always does with an alias is convert it back to the original path.  So anything that uses the URL, such as Views will not see the alias, it only sees the original path. That means that that if the paths you desire, such as red/gm are aliases, they will not be seen by the view.
A view can have multiple paths using the % wildcard.  If you created a view with a path of /cars/%/brand Then your view will be called by Drupal for any value placed in the % location of the path.
A view path should always have a static name for the first and last positions of the path.  In your examples above for red/GM you basically have an URL of %/%which would be assigned to just about everything.

To create your desired View content you may want to try the following:

Define two vocabularies for brand and color, and/or anything else you want in the categorization.
Create a content type that includes fields for these two vocabularies and give the content URLS following the formula similar to  `cars/%(color)/%(brand)/
Create a view with a path something like cars/%/%/view The word 'view, in the path can be anything you desire.
Define the view to display whatever content you want.
Create two contextual filters, the first defined to read a term from the color taxonomy and the second to read the brand.  Views will use the value of the first % for the first contextual filter and the second % for the second filter.

That should get you started, although I suspect you will have at least one more round of questions before it works for you (It always does.)  There are a lot of previous questions on this site whose answers will help solve the details for you.  There is also an excellent video series 'Taming the Beast' that can show you everything you need to know about views.


How do I change the layout of the fields used in a node?

Here is a great tutorial on how to theme a node edit/add form in Drupal 6: Theme a CCK input form for CCK2 & CCK3


Go to specific page in view using node id

You want to link to a node title thats in a view from another page, and not loose your pager ? (correct my summary if thats incorrect) ...

You can do this by using an ID anchor when building the link to the node.

If needed, use a Views field to output an html anchor per node title:

add field Node NID, exclude from View output
add field Node NID, rewrite HTML as <a name=[node:nid]>

Then build a link to your View including the anchor reference.

$vars['view-scroll-to-node'] = l('some node title', '/your/view/path#'.$nid);


How to use drupal_get_token() within custom user registration email

The reason this is failing is because drupal_get_token() and drupal_valid_token() use the value of session_id() to generate and validate the token.

The problem is that session_id() will return a different value for anonymous users on each page load. So the token generated by drupal_valid_token() is different from the one that is generated in drupal_get_token() because the input (sessoin_id()) is different.

For form submits where you want to compare a token on the next page load for anonymous users, you can call drupal_session_start() on the form page which will start a session and ensure that the results of session_id() are the same on the form page and the result page. But in your case, where the user is clicking on a link back to the site from an email, the value of session_id() will only be the same if it's the exact next page load. My tests indicate that Drupal destroys the session created by drupal_session_start() on the next page load.


How can I link the file name to the file?

You can solve by implementing a preprocess function
/themes/mytheme/mytheme.theme
<?php

/**
 * Implements hook_preprocess_HOOK().
 */
function mytheme_preprocess_file_link(&$variables) {
  $variables['link']['#title'] = t('Open Here'); // change title
  $variables['link']['#url']->setOption('attributes', ['target' => '_blank']); // open in a new browser tab
}

Rename mytheme to your actual theme name and clear/flush caches so hook gets picked up.


Pass hidden fields using drupalSettings to Twig template

Wish I could comment...

Are you sure your hook is running?  the instanceof operator is not implemented correctly so you should be seeing an error when the hook tries to run.

Also, you may not need to add 'drupalSettings' to the 'elements' key.  You should be able to put it on the top level of $variables.


According to the code example that you posted, you are using a relative path in your AJAX request. Maybe you should try anchoring your request to the base path by using /objnum_callback instead of just objnum_callback. This will ensure that your request is pointing to the same place regardless of the current page.


Getting the nodequeue id from the nodequeue name?

There is a function of the same name as in the excepted answer included in current versions of the nodequeue module.

$queue = nodequeue_load_queue_by_name($name);

It returns the queue definition, or an empty array if no queue was found with the given machine name. So the id would be found at:

$queue->qid;


Actually, what I would do is I would make my own sub-theme that uses Bartik as a base theme and add the additional css stylesheets to my sub-theme's .info file like this:

stylesheets[all][] = css/MY-CUSTOM-CSS-STYLESHEET.css

Just look at Bartik's own .info file to see how it adds stylesheets and javascript files as an example!

Here is some info on how to create a sub theme: http://drupal.org/node/225125.

The best thing about creating a sub-theme rather than adding these stylesheets using a custom module is that you'll be all set to do things like adding or overriding theme images, modifying template files and tackling a big array of potential customizations you may want to do in the future that you may not even be for-seeing now!  It'll just end up being more flexible in the long run.


Block loading behaviour in Drupal 8 in a performance sense through the visibility settings

The block is loaded (otherwise we could not check if he should be shown or not), but we do not call build() unless the block is visible and the user has access.

I'm pretty sure that was already the case in Drupal 7, it is only Drupal 6 AFAIK where it was building the blocks and then checking visiblity.


ajax form link how to call form function with parameters

There is no '#type' => 'link' form element, and markup does not have #ajax property. So you are down to buttons and images. You can style them to look like a links. Problem is, button will trigger form validation no matter you want it or no.


Is there a nodequeue module for ordering and selcting taxonomy terms instead of nodes for used in a view?

You can try out Flag module, which supports flagging entities, combined with flag_weights and draggableviews you can create ordered slideshows of flagged taxonomy terms.

  Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

If you want to use Flag-3.x with flag_weights you will have to apply this patch: https://drupal.org/node/1877304 works for me so far.


Skip payment method selection in Drupal Commerce

You would have to hide the payment method checkout pane via a form alteration, because the payment method still technically needs to be selected for the redirect page to show properly. However, if you just want to remove the "Review" page since you don't need it as an intermediate step for payment method selection, you could just move the payment method checkout pane to the "Checkout" page and disable the default review checkout pane.


How can I get a different version of a webform to show dynamically based on a selection value?

If I'm understanding correctly, you want to show/hide certain fields based on the value of the Subject field, and you also want this value to have the ability to be set via a URL parameter?
If that's the case, this can be done in a single form using conditional fields and form settings.
First, in your form Settings, under Form >> Form Behaviors >> Prepopulate, check Allow all elements to be populated using query string parameters.
If this is checked, all elements can be populated using query string parameters. For example, appending ?name=John+Smith to a webform's URL would set the 'name' element's default value to 'John Smith'. Please note that individual elements can also have prepopulation enabled, so you could skip this and allow only the Subject field to be prepopulated if desired.
Next, in "Build" screen, edit one of the conditional fields that depend on the Subject field value. In the "Conditions" tab, you can describe the logic to display or hide the field based on the value of another field, something like
Visible if All of the following is met:
Subject[Select] Value Is 'Some subject value'
I hope I've understood your question correctly! While it doesn't use 'variants', this approach can still help you show a variation of your form depending on how the "Subject" field is filled.


Webform Address Element and Canada provinces

You can alter the default state options via /admin/structure/webform/config/options/manage.

I recommend installing the Address module for substantially better international address support.


Custom content entity route or url alias

I think you can do this with the pathauto (path alias?) module.  Go to the Admin -> Config -> Search / Metadata -> URL Aliases.  In the settings tab, enable your custom entity type.

When you edit them, you should have a URL field added.  You can also use the patterns to define default paths if you want.

I did a quick test with an ECK custom entity and it worked.


Guidelines on customisation options when using hook_views_default_views?

There is one neat and simple way. Create view normally, using GUI. Then export it. I created view default-demo for demonstration purposes:

http://example.org/admin/structure/views/view/default_demo/export

gives:

$view = new view();
$view->name = 'default_demo';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'default demo';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially     */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'default demo';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'default-demo';
$translatables['default_demo'] = array(
  t('Master'),
  t('default demo'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Page'),
);

As you can see that's exactly what you would want to put into hook_views_default_views function. Simple as this :D

If you can't find export link, it's at top right, drop down edit view name/description to see it.

Everything available from code is supposed to be available from GUI too, with the notable exceptions of $view->core and $view->api_version that are always set by gui to the current release and must match what you set in hook_views_api() in your module.

For specific line you asked for:

$handler->display->display_options['access']['type'] = 'none';

You need to go to Page Settings > Access, set things as you want them, export view. Done. It seems that Views developers chooses to use their time to give us tools, not documentation, when their time is limited, but the tools they give us are comprehensive.


Why is Rules Action "Create Linked Drupal User Account" not working?

The explanation for the issue you're facing is within the comment lines of the Rules Action you included iin your question, i.e.:

  // @TODO What happens if they don't have an email at this point?

  // An email is a pre-requisite for a Drupal account, so the action
  // fails if they don't have an email.

The eMail ID for the CiviCRM contact you're using appears to be missing. So try again with a similar testcase, but make sure that for the CiviCRM contact some eMail Id is entered.

This probably also explains the "It was working some time ago": chances are that it was working, since you were using a CiviCRM contact for which an eMail ID was available.


Views: filter by the highest (max) field value of all items

I fear you will need a subquery for that. You can do that in a custom module.

/**
 * Implements hook_views_query_alter().
 */
function MODULE_NAME_views_query_alter(&$view, &$query) {
  $max = db_query('select max(YOUR_TABLE_COLUMN) from YOUR_TABLE')->fetchField();
  $query->add_where(0, db_and()->condition('TABLE.YOUR_FIELD_NAME', $max));
}

The tricky part here is to create your select query and find the correct field name/alias. Have a look at the query output of your view to find the correct parts.

Original answer (before clarification)

Instead of a contextual filter you can use a sort on the 'Volume' field. Sort descending. That way the articles with the highest 'volume' are at the top.

If you want to show only articles with a number higher than X you could add a regular filter for that.


is there anything like $view_mode in user-profile.tpl.php

I don't believe there is. There should be, and if I had to guess I'd say there will be in D8. Large parts of the entity api simply didn't get implemented in D7, and nodes were probably just considered a higher priority.

I believe the Profile2 modules work by extending the user entity, it may provide you with what you want.
Otherwise my suggestion is Panels, which can control the user view via something called "Selection rules", instead of view modes.


I suggest to clear cache, use jQuery update module to update the version of jQuery. This worked for me.

Wish it might help!!


How Do I Create a User Role that Can Only CRUD a Single Content-type?

The Permissions section is broken out across content types. You can create a new group, put that user into it, and give that group permission to CrUD one or more content types. Allow this user no other permission in any other content type (outside of calendar).

To overcome the 'overview' page problem, is View published content checked?


How to set a url in drupal database or settings.php?

In your settings file add

$settings['razorpayUrl'] = 'https://example.com';

Then in your module

use Drupal\Core\Site\Settings;
$url = Settings::get('razorpayUrl');


Have you tried "ImageField Extended"? Alternatively, you could create a new content type which consists of an image and any number of fields that you want.