Which table contains all of the module permission data?

To modify the permission data via drush command line. I first had to find the permission name by right click the checkbox on the module page and inspect element, in my case it was 3[view any office office]

The table responsible for permissions is: role_permission

I then goto the terminal and insert the following query:

drush sqlq 'insert into role_permission values(3,"view any office office", "office")'

3 is the role number then the name of the permission (view any office office) and then the module name (office).


Change value of user reference based on node reference

If what you are asking is can you change the user reference field to something based upon a node reference field, sure, not a problem.  But what do you want to change it to?  If it's the user id of the creator of the node referenced, that's easy:

// load node in question
$node=node_load($nid);
// load node referenced in that node
$node_referenced=node_load($node->field_node_reference[$node->language][0]['nid']);
// set user referenced in node to the uid of the node referenced in it
$node->field_user_reference[$node->language][0]['uid']=$node_referenced->uid;
// save the node
node_save($node);

If you want to do this automagically, you can look at hook_node_presave() and have this done every time a node type is saved.


How can I let users rate content with half stars in Fivestar?

I've written a module that alters the fivestar module to allow halfstar voting:

Halfstar

After installing the module an option is added to the field instance setting form allowing half star voting:

Which then allows voting with half stars:

There is a rounding bug that occurs occasionally at the moment when using the Stars (rated while editing) widget. If you have 9 stars and then vote 5.5 is display as 5.6.


This image is set in function views_data_export_views_plugins(), in views_data_export.views

Implement your own hook_views_plugins() and override ['style']['views_data_export_xls']['export feed icon'] with your own value. Just make sure your module fires after Views Data Export.


Control Visibility of Paragraph Without Fields

Implement hook_field_widget_alter

It will give control of paragraph fields.

function hook_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'xyz') {
    $element['subform']['field_name']['#access'] = FALSE;
  }
}


how to delete width and height attributes from image field for particular nodes

You may be able to accomplish this with view modes.

Make some new image styles for these particular images.  Implement a theme_image_style(), which checks for this new style name and unsets width and height as needed.

If you install/enable Entity View Modes you can create new view modes for your nodes.  Clone what you have for node/teaser to your additional layouts.  For the images, change the display settings to use your new styles.

Next is the part I am not sure what the best solution is.  One way to use the view mode is to use a Panel page for each individual node.  When you add the content, you can set the view mode to one of your new ones.   Otherwise, I would try @PierreBuyle's solution at Using a different view mode with a node.  This essentially overrides the menu page for node/nid to add some additional intermediate logic to set the view mode.


Why are store translation files stored in the database?

It's not likely that loading the translation files from disk would result in a faster page load time than it does from the database -- in fact I would expect it to be much slower. This is essentially the job of a database: store and organize a large amount of data on disk and provide other programs the parts they need quickly. Drupal (and all similar CMS's) are built on the assumption that for processing the content you are better off pulling from the database, and translations are basically just content. Disk-based optimizations usually help when you are trying to deliver unprocessed data as quickly as possible i.e. it's often faster to have the web server pull an image file off a disk instead of loading a script that loads a binary field from a database, and then streams it down.

There are several reasons that the database is likely faster for most use cases:

To keep translations flexible and manageable there are actually many files that go into translating the back-end (each module can have its own PO file for each language). For a production site you'd then also be looking for a place to store all the translated content so we aren't looking at loading one file, but tens or hundreds of files to process.
Each file has to loaded, parsed into useful structures, and then matched to the default (English) text. Yes, the site could cache a unified file, but that file could become massive and cause trouble on its own for some OSes and file systems.
The site content is already stored in the database so overriding displayed text would have to come from two systems (either you'd have some in file and some in database, or you'd have all the default language in database and the translations in files), which adds complexity an likely processing time as Drupal determines where to pull the data from next.

Now think about what happens with the translations in the database:

Since nodes (and other fielded objects) store all the languages in the same tables, most of the time Drupal doesn't have to do anything extra. All the translations for a given field get loaded with the object and then Drupal picks which to display at render time. When Drupal does need to load a translation specifically, Drupal is able to re-write the queries used so it again has the data on hand at the same time it would have had the default language (that rewrite time should be trivial since it had a write a query in the first place). So almost nothing extra needs to be added to the load time to load the needed translated text.

Finally you have to keep in mind that good page load speed is mostly driven by caching, which Drupal does in the database by default, it does not load even the full node objects whenever it can avoid it.

Disclaimer: I don't know that anyone checked a file-based system when the translation system was initially written and I've never seen actual numbers run, so this is mostly speculation.


you can use cache_clear_all() to clear the caches after you write the new value to the database. it will be best if you can find out the comment's cache id and clear only that one. Unfortunately I don't have any D6 databases on my server to look into the database


Instead use Auto Expire module, Using this module you can set the node to unpublish after 30 days.

For your case set zero in purge field, otherwise it will automatically delete from database.

  This module allows site administrators to set expiration times for
  content types.

  End users creating content that has auto expiry set cannot control the
  expiry time. They could be allowed to renew the content for one or
  more cycles.


No route found for GET /block-render?_format=xml

I have installed RestUI module and configured the REST resources for Block Render

admin -> config -> SERVICES WEB -> Rest

and it works now !


Resetting a configuration object to "factory settings"

Core does not provide such an API, not in a way that is easy to use.

There is a contrib module that provides this, but it's probably too complicated to rely on for a specific use case.


How to deal with /system/files references when upgrading to D7?

Why it happens

In D6, the system module provides the following menu entry that ties system/files to the file_download callback:

In system_menu() function:

  $items['system/files'] = array(
    'title' => 'File download',
    'page callback' => 'file_download',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

Then in file_download(), if the file exists and no hook_file_download() objects to the download, it gets served.

On the other hand, D7 expands on that with a page argument set to private:

  $items['system/files'] = array(
    'title' => 'File download',
    'page callback' => 'file_download',
    'page arguments' => array('private'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

It has the effect of preprending the private:// scheme to the filename, which file_download processes by requesting the registered file stream wrapper for  it.
By default (no private path set in /admin/config/media/file-system), this scheme is not registered, and that's why GET /system/files/logo.png finally fails with a 404 status.

How to fix

Setting the private file system path to sites/default/files (the same as the public path) makes it work.

However it's not a good long term fix, both because routing public static files through Drupal is much heavier than direct access by httpd, and because it precludes the use of a real private space should the site need it in the future.

The long term fix is to hunt for these /system/files/xyz references and replace them by /sites/default/files/xyz.


You can check the rules that change the order state into: 'pre-order'.
This would be my first guess that the rules are not configured ok.
Hope that i helped.


Link by internal path in *.links.menu.yml not visible in admin menu

It seems to be necessary to use a route_name for this. Then you can control permissions and the internal link is visible for the editor role too:

1 – Change my_module.links.menu.yml to use a route_name instead of the url:

my_module.test_link:
  title: 'TEST LINK internal'
  route_name: my_module.test_route
  description: 'TEST internal'
  parent: system.admin_content
  weight: 99

2 – Add the route with  permission to my routing file my_module.routing.yml:

my_module.test_route:
  path: '/node/add'
  requirements:
    _permission: 'access content'


Is there a way to send an email to a mailchimp list on the event of a content type being published?

I don't think you can do that directly from the interface. You need to create a hook function hook_rules_action_info in your custom module's .rules.inc file which will describe what the action actually does. See the link http://www.drupalcontrib.org/api/drupal/contributions!rules!rules.api.php/function/hook_rules_action_info/7
Even I'm looking for some good example or tutorial for this. Cheers!


Internal/External JS don't work with Drupal, but works fine in static HTML/JSFiddle

I've rebuilt the scenario and my guess now is that you don't want the value of the select field but the option text for your parsing purpose. Thus, the script should probably be something like this:

(function ($) {
Drupal.behaviors.totalAmount = {
attach: function(context, settings) {

    /*Add your js code here */
    var selects = $("select").change(function (e) {
        var total = 0;
        selects.each(function() {
          var val = $("#"+this.id+"  option[value='"+this.value+"']").text().match(/\$(\d+)/);
          total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });
}
};
})(jQuery);

This is how it looks like working:

This is how the first select's options are setup as a webform component

To retrieve prices, one would need to change the regex line to

var val = $("#"+this.id+" option[value='"+this.value+"']").text().match(/\$(\d+(\.\d{2})?)/);

Working example:

To have the total always be display with trailing zeros, replace the last script line with

$(".total").val(total.toFixed(2));

To make the script also work with thousands separator, change the script into

(function ($) {
Drupal.behaviors.totalAmount = {
attach: function(context, settings) {

/*Add your js code here */
    var selects = $("select").change(function (e) {
        var total = 0;
        selects.each(function() {
                var val = $("#"+this.id+" option[value='"+this.value+"']").text().match(/\$(\d{1,3}(,\d{3})*(\.\d{2})?)/);
                        total += val ? +parseFloat(val[1].replace(/,/g,'')) : 0;
        });
        $(".total").val('$'+total.toFixed(2));
    });
}
};
})(jQuery);


How to add another filter to TVI default page view?

You're most of the way there by the look of things, change your page settings -> path to taxonomy/term/%/%

The second % will provide your second contextual filter.


How do I create a url for views that displays values using exposed filter?

I think you want to use a contextual filter, not an exposed filter. The contextual filter will take an argument (such as the category term id or node id, depending on whether it's a taxonomy term or a node) and filter out all other nodes.


Drush finding 3rd party module but can't install

Please see --lock, described in drush help pm-update:

--lock

     Add a persistent lock to remove the
     specified projects from
     consideration during updates.  Locks
     may be removed with the --unlock
     parameter, or overridden by
     specifically naming the project as a
     parameter to pm-update or
     pm-updatecode.  The lock does not
     affect pm-download.  See also the
     update-advanced project for similar
     and improved functionality.


Eliminate the square brackets from the query and it should work:

$weight = db_select('system', 's')
  ->fields('s', array('weight'))
  ->condition('name', 'commerce_checkout_redirect', '=')
  ->execute()
  ->fetchField();

// Set our module to a weight 1 heavier, so ours moves lower in execution order

 db_update('system')
    ->fields(array('weight' => $weight + 1))
    ->condition('name', 'redirect_after_login', '=')
    ->execute();


Drupal 8: Performance Impact of frequently clearing all caches

You can clear the cache tags of a specific view whenever a term is created.

function hook_taxonomy_term_insert(EntityInterface $term) {
  if ($term->bundle() == 'VOCABULARY_ID') {
    Cache::invalidateTags(Views::load('view_name')->getCacheTags());
  }
}


Views-overriden taxonomy/term page returns not found

I was able to solve this only by duplicating the "taxonomy" view. This view's argument configuration makes it a viable solution.

After configuring/enabling this view, you can set the taxonomy url aliases to work in the same way.

A working example: http://www.indice.gr/portfolio/all shows "all" projects, wheras http://www.indice.gr/portfolio/mobile-application shows projects under the mobile-application term. Yay!


Showing icons to represent content types

This is set up by the node.module via preprocess()ing in variables:

// Display post information only on certain node types.
if (variable_get('node_submitted_' . $node->type, TRUE)) {
  $variables['display_submitted'] = TRUE;
  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
  $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
}
else {
  $variables['display_submitted'] = FALSE;
  $variables['submitted'] = '';
  $variables['user_picture'] = '';
}

These are then used like this in (the standard core) node.tpl.php:

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>

<?php endif; ?>

So, it would be pretty easy to do something along these lines in your theme's template.php file:

function YOURTHEME_preprocess_node(&$variables) {

  if ($variables['display_submitted']) {
    $variables['submitted']='type . '.jpg">' . $variables['submitted']; // or whatever/however you want to do this
  }

  // any other preprocessing goes here

}


How do i change the visibility of an existing block programmatically?

You can load the block and modify the visibility settings:

$block = \Drupal\block\Entity\Block::load('openidconnectlogin');
$visibility = $block->getVisibility();
if (isset($visibility['request_path']['pages'])) {
  $visibility['request_path']['pages'] = '/new/path';
  $block->setVisibilityConfig('request_path', $visibility['request_path']);
  $block->save();
}


Drupal 7 - Node specific template not working

If you haven't already done so, I'd recommend enabling theme debugging feature of Drupal 7.

In the settings.php file, or preferably in settings.local.php file if you have one, add the following line, and clear the cache once more.

$conf['theme_debug'] = TRUE;

  When debugging is enabled:
  - The markup of each template is surrounded by HTML comments that contain
    theming information, such as template file name suggestions.
  - Note that this debugging markup will cause automated tests that directly
    check rendered HTML to fail.

  For more information about debugging theme templates, see
  https://www.drupal.org/node/223440#theme-debug.

  Not recommended in production environments.

This should give you the available template name suggestions in the generated HTML.


Change the description for username field in user registration

Another couple of options using string translation techniques:

Contrib module: String Overrides
settings.php snippet insert

The string overrides module lets you do the string translation via the UI.
Otherwise, you can set the override in settings.php - the search string needs to match exactly.

/**
 * String overrides:
 *
 * To override specific strings on your site with or without enabling locale
 * module, add an entry to this list. This functionality allows you to change
 * a small number of your site's default English language interface strings.
 */
$conf['locale_custom_strings_en'][''] = array(
  'Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.' => 'Spaces and punctuation are not allowed except for periods, hyphens, apostrophes, and underscores.',
);


menu_masks is a Drupal variable used to find the possible ancestors of a menu item. It contains an array of values that are calculated from the paths defined from modules; each values is essentially a binary number where the digit is 1 when the path part doesn't contain a placeholder, and 0 when it contains a placeholder. For example, the number for node/%node/edit is 9 (101 in base 2), while the number for admin/structure/types/manage/%comment_node_type/comment/fields is 123 (1111011 in base 2).
The reason why numbers are used is avoid comparing strings; plus those numbers are easily sorted in a way that a number matching a path without placeholders is placed before a number matching a path with one or more placeholders. (The number for %/%/% would be 0, while the number for admin/appearance/list is 13.)

Notice that menu_get_ancestors() doesn't return the ancestors of the path passed as argument, but the possible ancestors. Passing array('node', '12', 'edit') to the function, I would get the an array containing the following values, as result.

node/12/edit
node/12/%
node/%/edit
node/12
node/%
node

In my test site, only the third, the fifth, and the sixth are paths defined by the modules I installed.

You don't need to export the menu_masks variable: Its content is very specific for the site and it is re-calculated when menu_rebuild() is called.
Drupal is still able to work correctly even in the case menu_rebuild() is not yet called, and that Drupal variable has not been set. You should not notice any performance issue, but if that would be the case, you can call menu_rebuild() or force Drupal to call that function; if you have the Devel module installed, you can easily force Drupal to rebuild its menus.


You can use The Block languages module, part of the Internationalization (i18n) package allows you to configure for which languages each block is visible. The settings for visibility per language are provided under Visibility Settings via the Languages tab when configuring a block.


How can I modify a user's last access date using Rules?

Two options:

Just as you said, a custom rules action:

function MY_MODULE_rules_action_info() {
  return array(
    'MYMODULE_action_update_last_access' => array(
      'label' => t('Update last accessed timestamp'),
      'group' => t('Custom'),
      'access callback' => 'rules_user_integration_access',
      'parameter' => array(
        'account' => array(
          'type' => 'user',
          'label' => t('User'),
          'description' => t('User account whose last accessed timestamp will be updated.'),
        ),
      ),
    ),
  );
}

function MYMODULE_action_update_last_access($account) {
  // There might be another way to update the last accessed date, but you can
  // also do it directly in the database.
  //
  // NOTE: the code below will update the last access to current timestamp.
  // You could also do something like this, to get a random value in the last
  // 24 hours:
  //    $timestamp = rand(REQUEST_TIME - 24 * 60 * 60, REQUEST_TIME);
  $timestamp = REQUEST_TIME;
  // Update the data in database.
  db_update('users')
    ->fields(array('access' => $timestamp))
    ->condition('uid', $account->uid)
    ->execute();
}

Use hook_cron() implementation in a custom module. This can be cleaner if you don't need to configure this more than once.

function MYMODULE_cron() {
  // Decide how often you want to do this, e.g. daily, weekly, etc.
  // Below is an example for daily trigger.
  $last_updated = variable_get('MYMODULE_var_last_time_access_updated', NULL);
  if (!$last_updated || $last_updated != format_date(REQUEST_TIME, 'custom', 'z')) {
    // Define user IDs which need to be updated.
    $accounts_to_update = array(1, 2, 3);
    // Update them.
    foreach ($accounts_to_update as $account_to_update) {
      // See #1 above; I'll use a random timestamp in last 12 hours this time.
      $timestamp = rand(REQUEST_TIME - 12 * 60 * 60, REQUEST_TIME);
      // Execute the query.
      db_update('users')
        ->fields(array('access' => $timestamp))
        ->condition('uid', $account_to_update)
        ->execute();
    }
  }
}


Drush by default is using wget to download project (if available), otherwise curl. This can be change by --package-handler. You can check which package handler is in place by running your command with debug parameter (-d).

So you configure proxy the same way as you would configure this for wget or curl.

For wget, you can configure these lines in ~/.wgetrc:

use_proxy = on
https_proxy = http://proxy-host:8080
http_proxy = http://proxy-host:8080

Note: Please check /usr/local/etc/wgetrc for some examples.

For curl this line should in your ~/.curlrc:

proxy=http://username:password@proxy-host:port

For both I think you can try to export http_proxy/https_proxy as a system variable.


How to call function after submit button clicked

If you want to call the function after submit of the form.

Add this part in hook_menu:

function MYMODULE_menu(){

    $items['project'] = array(
    'title' => 'Project List' ,
    'page callback' => 'project_list1',
    'access callback' => TRUE,
    'menu_name' => 'devel',
    'type' => MENU_CALLBACK,
    );

 return $items;

}

If you want the menu to appear in main menu you can make these changes:

     'menu_name' => 'main-menu',
     'type' => MENU_NORMAL_ITEM,

Your  function here:

  function project_list1(){
     /////code
    }

And then in your submit function, you can directly add:

  //Add this in the last line of your submit function
   drupal_goto('project');

This will directly go to the path 'project' and call your function

  project_list1()


update a module in the front page after adding new content into another page

Sounds like you should be using Views.

Create a new view
Create a page display and configure it to output the content you want.
Create a block display and configure it to output the content you want.
Add the block to your homepage

Now when you add new news it will show up on both the page and the block.


Render an image that is located inside a Paragraph that is inside an Entity Reference

Assumming a firm content type has field_paragraph which holds field_image of 1 image

for comparison to get firm name in twig file you will use

{{node.field_firm.entity.title.value}}

for firm paragraph image field value

{{node.field_firm.entity.field_paragraph.entity.field_image.entity.uri.value}}

To get the rendered image

{%
  set firm_image = {
    '#theme':      'image_style',
    '#style_name': 'thumbnail',
    '#uri':        node.field_firm.entity.field_paragraph.entity.field_image.entity.uri.value,
    '#attributes': { class: 'yourclass' },
  }
%}
{{firm_image}}

Alternative way to get referenced entity fields


Not sure if it would help or not, but if your looking for trying to tell the user nothing exists in the database, you can always add logic to the autocomplete that will return something to the field that indicates no results are found.


How to change the value of a user field through Restfull?

Assuming the user rest resource is enabled and PATCH requests are configured, also that the requesting user is authenticated to update the user, then:
send a PATCH request to: https://example.com/user/$uid?_format=json
Where $uid is the user id to update (e.g 12)
The request body should look something like this (json format):
{ "field_motherid":
  [
    {"value": "new_value"}
  ]
}


Find and display lowest value from one field in a node type

It is not clear from your question if your 'aggregated uses' and 'available uses' are CCK fields already. If they are, I hope this helps... You can access each of the fields available $a and aggregated $b with this code:

$items = field_get_items('node', $node, 'field_YOUR_FIELDNAME');
$first_item = array_shift($items);
$YOUR_VAR = $first_item['value'];

then deduct $a-$b=$c and store $c in another CCK field using the node_load and node_save:

 $node = node_load($nid = YOUR_NID);
 $node->field_YOUR_FIELDNAME[$node->language] = array(
    0 => array('value' => $c)
 );

once $c field is stored in your node, you will be able to access and display it from Views.


There are actually quite a few methods on how to do this. The method here is quick and easy to do.

Install the devel module (you will uninstall it when your site goes live).

Make sure the block visibility settings is set up to only show on product-page.

Then add this code to your theme's template.php file.

function MYTHEME_block_view_alter(&$data, $block) {
  dpm($block);
  if ($block->module == 'views' && $block->delta == "BLOCK_DELTA") {
    //hide the block
    $params = drupal_get_query_parameters();
    if(count($params) > 0) {
      $data["content"] = FALSE;
    }
  }
}

Change MYTHEME to your theme's name, and clear your cache.

Now you need to change BLOCK_DELTA with the delta of your block. To do that you will need to inspect the dpm output, and find your block, then find the delta of your block.

To further assist you in finding your block delta, you can inspect the block in question in your browser, and look at the id of the block. It will contain the delta as a substring with just the hyphens altered.

My delta is block_content-block so my line of code will be:

if ($block->module == 'views' && $block->delta == "block_content-block") {

When you are done remove the line dpm($block);. You may then uninstall devel module if you wish. This code is a primer and you can adjust it if you need, but as is it will work.


In D6, any custom templates (from core, such as node or page) must be in the same folder as the base tpl file in order to use the auto-recognition of theme files.

You may be able to specify additional template files (in D7 they're called theme hook suggestions) in a preprocess function in your theme's template.php. See the first code example at http://drupal.org/node/249726 to get you started.


Multiple copies of Views filter form (exposed filters)

This hack works very well but there's no need for a hack if you have seperate displays from your view. My search results were displayed as a "Page" display and you also have the "Default" display.

On the page you would click "Exposed form in a block" then click "Override" on the right hand side. Set this to "No" (so the form now displays on the search page). In the "Default" display, have "Exposed form in a block" set to "Yes" - so by default it produces a block, but you also get the form to appear on the search page as well.

Thanks guys,
Garry.


Use
parent.jQuery.fn.colorbox.close();

for closing colorbox, when submitting form.

like,  add the onClick event inside the submit button code:

<input type='submit' value="Submit' onClick='parent.jQuery.fn.colorbox.close();'>


Are there alternatives to using URL to Image Formatter?

Background Image Formatter provides a new formatter that can do this. You will probably want a unique identifier on your target div, but this module should do the trick otherwise. There's a responsive_bg_image_formatter submodule for using responsive image styles for your bg image.


The same rules, only one being triggered

That is a weird one.

I don't know what caused the problem but the fix was to export and import the rule.

The interesting part is that cloning the rule did not work, even when I simplified/changed the cloned rule to

{ "rules_tc_admin_review_cloned_" : {
    "LABEL" : "TC: admin review (cloned)",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "DO" : []
  }
}

The rule was never checked.
There seems to be a bug. Possibly in the rule cloning function.


Question about views (related to page specific blocks)?

This is a response to the part:  Is it possible to make it so that when you click....

If the page regions don't change and all you are really checking for is the blocks that should show depending on the referer, you could do something in your blocks where they check $_SERVER['HTTP_REFERER'].

You could breakdown the HTTP_REFERER so you could get /sectionA/article or /sectionB/article or /sectionC/article.

Then you would have your sectionA/B/C that you could then pass into your blocks.

You might use something like this below in your block and selecting the PHP evaluation method.

If user comes from sectionA/article your block might look like the below and it would show up.

if (isset($_SERVER['HTTP_REFERER']) {
  $referer = $_SERVER['HTTP_REFERER'];
  switch ($referer) {
    case 'pageA':
      return TRUE;

    case 'pageB':
      return FALSE;

    case 'pageC':
      return FALSE;

  }
}


Get the default image for a profile2 image field with code

You don't need to bother with the field_get_default_value function, you can use the field_info_field function. For image fields, it will provide the fid for the default image in ['settings']['default_image'].

Suppose your field is "field_picture", then this will get you the fid and file:

$info = field_info_field('field_picture');
if (!empty($info) && $info['settings']['default_image'] > 0) {
    $default_img_fid  = $info['settings']['default_image'];
    $default_img_file = file_load($default_img_fid);
}


For multilingual sites, do I set up a separate taxonomy?

The I18N project gives you multiple ways to deal with multi-language taxonomies:

Assign a vocabulary a language, making it specific for that language only
Translate Terms into different languages
Assign each term a language, so that you can have different terms based on the chosen language, but still a common vocabulary.


Leaflet - Possible to go straight to node instead of popup on click?

The easier way is to use the IP Geolocation Views & Maps module, which works a treat! Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).


If you want to set a variable with the URI returned from the query, you just execute code similar to the following one:

variable_set('variable name', $result->uri);

Replace "variable name" with the name you want to give to the Drupal variable, which is the same one you pass to variable_get().


Integrating html code into existing Drupal 6 webform

The submission made might be reaching client's side as POST variables, can you try to alter your form's submission method to "GET" instead of "POST".

From

$form['#method'] = 'post';

to

$form['#method'] = 'get';


Drupal 7 Rules - Grant access to node - pick username from node field

Take a look at the Node access user reference module which is meant for this sort of thing (giving access permissions based on a user reference value in the content).

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

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


First, you start with defining what are the rules of showing this content to the user. There are many ways how to deal with such a thing, but it all depends on the rules. I do recommend to create such rules, otherwise you will run into unmaintanable mess.

If you have less than 10 or so occurences

You can use the bean module (http://drupal.org/project/bean) to create specific block types with fields (similar way like creating content types). These blocks you can then expose via the default blocks UI and set the visibility there or you can use context.

If you have more than 10 occurences

You better define rules (logic), when such special content should appear. This way you can have just one logic easily maintainable (which is your goal).

Reference on node?

One way could be, that you create a content type for this content, and add any of the node reference fields (references, relations modules,...) (in case you want to display the content on specific nodes). This way you can always assign a content to another content and then create a block view that will take the argument from current nid and pass it over so you can display all content that has a reference with the same nid or you can attach the view to the entity via eva view.

Path?

I am not seeing any module available so you will have to create your own solution. This might help to get you started

Add a long text field to the content type - this field will allow you to enter path or multiple paths, one path per line
Create a custom module that will be using that field to match the path by using the function drupal_match_path. You can for example create a block, that will output matched content
You can place this block where you want the linked content appear (main content region, sidebar,...) via Drupal blocks UI, or context,... depends what you are using.

This could be a performance killer, if you will have a lot of content that Drupal will need to run through and see if it matches the content visibility, so you should think about some sort of caching, etc...


You can, at least in D8 use "reverse entity references" in contextual filters and relationships, so what you propose should work.

Have a contextual reference grabbing the node id of the Basic page from the URL. A relationship from the page to the school comes next, then a reverse relationship looking for items that have a relationship to the School. You'll also add a filter on that second relationship, limiting it to Events.


To achieve this I wrote a module, which creates a node on user create. The node has an alias, which is the username. Code below:

function mymodule_user_insert(&$edit, $account, $category) {
    $node = new stdClass();
    $node->type = 'article';
    node_object_prepare($node);

    $node->title = $edit['name'];
    $node->path = array(
        'alias' => $edit['name'],
    );
    $node->uid = $account->uid;
    $node->language = LANGUAGE_NONE;
    node_save($node);
}

Additionally I used MENU_TOKEN module, which allows to input tokens into title and path of menu links. So my new navigation link path is [current-user:name], which links user's article to his profile.

EDIT: Of course in the example I used 'article' as content type, but in practice I use a custom content type. So if you want to use this code, make sure this line:

$node->type = 'article';

is adjusted as per requirements.


How to embed images in MIME mail system?

With the help of Rules module and filtered HTML text format allowing img tag in the format you could send HTML emails with images.

Here is a summary of the required steps:

Enable the required modules, eg using Drush like so: drush dl rules entity mimemail mailsystem
Configure the MAIL SYSTEM SETTINGS choosing MimeMailSystem the Site-wide default and Mime Mail module class from admin/config/system/mailsystem
Set the text format to be filtered html or the format that allows img tag from admin/config/system/mimemail
Use Rules to send html e-mails.

For a more detailed tutorial, refer to How to Send HTML Emails in Drupal 7 using Rules.


The syntax for entity_generate is:

field_regio2:
    plugin: entity_generate
    source: rid22
    entity_type: taxonomy_term
    # This is where migration breaks. It need to know which key to look for.
    value_key: name
    bundle_key: vid
    bundle: YOUR_VOCABULARY_MACHINE_NAME


how to send multiple attachments with drupal_mail_system

You're using $messages['attachments'] as an array, so presumably just add another item to the array:

$message['attachments'][] = drupal_realpath($attachment_path);
$message['attachments'][] = drupal_realpath($another_path);
$message['attachments'][] = drupal_realpath($yet_another_path);


How to do an EntityQuery on a custom User field?

I think you might be missing a line:

$ids = \Drupal::entityQuery('user')
  ->condition('field_country', 'Canada')
  ->execute(); // This returns the user ids

// Load the users
$users = User::loadMultiple($ids);
foreach ($users as $uid => $user) {
    // $user contains the $user entity
}

More examples are located on the docs page.


Refer to the answer to How to configure webform with smtp , which includes:

  If you have SMTP module installed in your drupal site than you would have to configure the SMTP settings (/admin/config/system/smtp) for sending the email ...

It also includes an example for configuring SMTP.


Maybe starting from https://www.drupal.org/project/link_attributes and contributing a dir attribute patch (this way you have a UI for non tech users that will maintain the site)


Sending Auto-filled Email from Content Type Profiles

I use Webform for this kind of thing, as long as the values being passed to the form aren't too extensive.

On the Resource page template, create links to the webform, with field values in the the URL.

Webform 4 can then use tokens to place those values from the URL into fields.

You can then use Webform Rules to send an email.

The same thing can be accomplished with Entity Form, Entity Reference, Prepopulate, and Rules.


Complex SelectQuery with multiple left joins and conditions with OR

It seems that the problem was $field->field. For example if I have a field called field_book_author in database the $field->table would be field_data_field_book_author and the value of the field would be in field_book_author_value.

So the correct code is:

$or = db_or();
foreach ($fields as $field) {
    $query->leftJoin($field->table, $field->table, '(node.nid = ' . $field->table . '.entity_id)');

    if (property_exists($field, 'additional_fields') && (count($field->additional_fields) > 3)) {
        $field_name = $field->additional_fields[3];
    }else {
        $field_name = $field->field;
    }
    $or->condition($field->table . '.' . $field_name, '%' . $string . '%', 'LIKE');
}

$query->condition($or);


OK, I've just figured out how to achieve this. I'm using Display suite and I've created a custom field like this: Send a text message SPORT[node:nid] to number 2xxx .... The key was the token [node:nid]. It's working great.


Control display of post date as standard field?

display suite creates a "virtual" field for the post date and also for other properties of the node (submitted by, author,..). You can also set a date format for the post date.

To use it, enable ds and ds_ui, go to Manage display of a content type and choose a layout. You will see the mentioned fields.


MTA's can usually handle complex routing, such as handling multiple domains. Your specific rub will be the connection and routing to the MTA with the appropriate credentials to send the email.

You will need to setup a custom SMTP table where each role can setup their details, then within rules (or a custom module) create the logic to connect to the MTA with the appropriate credentials.

I hope this helps, or at least provides a gateway to an exact answer.


Get selected item in hook_form_alter in D8

I am just giving you the example because your scope is not clear to me,in my case i am taking node edit form where i am having a field which is select box.

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == "node_page_edit_form"){

    $v=$form[field_select_field][widget]['#default_value'][0];

    //dpm($form[field_select_field]);

    dpm($form[field_select_field][widget]['#options'][$v]);
  }
}


Query parameters from $_GET vs. using the Drupal menu path

There's a page with a logic that puts it together and that is determined by path. Core never bypasses the menu router. Parameters are somewhat orthogonal to this. For example, a page doesn't change in itself just because there's a form in it that uses a destination to redirect to said page so we do not add it to the clean URL. Pager is a little different because you could argue that path/to/some/view could become path/to/some/view/1 path/to/some/view/2 as it is paged but how do you differentiate real arguments (like a node id) from a pager? It's better to use a query parameter.


Register only via a specific e-mail domain

the "user restrictions module" is supposed to offer that feature. But it doesn't seem ready for production yet. However you could use the code to write your own.

I also tried to do it with the rules module and setup a rule for the "event" "user: before saving account" with a condition "data comparison" on field "account:mail".
Add "value contains" and use "@whatever.com" and then check the "negate" box. That will basically trigger the rule for all emails that don't contain @whatever.com.

However I couldn't find a way to stop the username from getting saved. If you use the event "user: after saving account" you can show an error to the user and block the account. It prevents the registration but shows a second message to your user "you'll get notified by the administrator". Not a great experience for your customers.


Getting the available template variables in a custom module

According to your code, you are creating a custom template for a paragraph.

As you are trying to access variables, that will be added by the paragraph module, you'll have to tell the theming system that it is a paragraph.

You can do so by adding the 'paragraph' base hook. This way the template will get the variables provided by the paragraph (pre-)processing:

/**
 * Implements hook_theme()
 */
function episode_data_theme($existing, $type, $theme, $path) {
  return [
    'paragraph__episode_content_question_slider' => [
      'base hook' => 'paragraph',
    ],
  ];
}


How to force users to logout after X minutes of inactivity using Rules, Views?

Drupalmodules.com shows two potential modules:

Session Expire - "Expires rows from the session table older than a certain time."

Automated Logout - "This module provides a site administrator the ability to log users out after a specified time of inactivity."

Either module would probably be able to give you the functionality you want. The automated logout module looks like it could give you a timer to show how much longer a user has before being logged out.


How restrict a constraints to a content type?

No, it's not directly possibly when adding the constraint.

But you can always check the bundle or existence of certain fields (in some places preferable, if you ever need another node type with those fields and the same logic) within your constraint when it is run.


Views query alter add orderby function FIELD()

There is a similar answer here: https://drupal.stackexchange.com/a/200662/79998

You should either use $query->addField() to add the expression and then append or unshift in $query->orderby array,
or you can use directly $query->addOrderBy() to add the expression and order, if it's ok to be added last.

$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,3,2,1,4)', 'ASC', 'order_field');


How to attach css classes to the  title attributes if node_is_page() dynamically?

Okay, as commented under the question, I've tried out another idea: a little bit dirty since this is far away from the way it is supposed to be, but hiding '$title' in page.tpl.php and removing the IF NOT PAGE condition from the standart node.tpl.php (like in Bartik) makes it possible to access the title-attributes array, since node.tpl.php seems to know title-attributes, but page.tpl.php not...

But in this case I have to reimplement the programmatically "node is page OR node list switch" toggling of h1 and h2 again, since if-page $title in page.tpl.php did this before:

After removing the complete if-title-title part (in Bartik it looks like this, near the $content) from page.tpl.php,

<?php print render($title_prefix); ?>
  <?php if ($title): ?>

      <?php print $title; ?>

  <?php endif; ?>
<?php print render($title_suffix); ?>

... I have added (exchanged) this in the node.tpl.php:

//node.tpl.php

// usually we have something like the following here
/*
<?php if (!$page): ?>
   <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>
*/

// but we exchange it with this ...

<?php print render($title_prefix); ?>

  <?php if ($page): ?>
    <h1<?php print $title_attributes; ?>>
       <a href="<?php print $node_url; ?>">
          <?php print $title; ?>

  <?php endif; ?>

  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>">
         <?php print $title; ?>

  <?php endif; ?>

<?php print render($title_suffix); ?>

Now I do have my title inside of my wanted scope, where I can theme it programmatically inside the main content container. Thanks to Clive for his support on my question, and special thanks to Digidog from drupal.org, who gave me the final hint per mail.


Contextual filters in Views - Filter by taxonomy

Retrieving the term ID by name has one considerable downside: If term names change, links may become invalid.

A safer option would be the use of aliases. For each of your terms, generate a URL alias per language that points to the internal view path (containing the term IDs). That way your view won't require custom logic to retrieve the term ID.

You could then expand on that approach and use e.g. the Redirect module to keep track of alias changes.

If you still want to stick to your approach, keep in mind that Drupal provides various functions to deal with paths and arguments. In your case, that one-liner can be simplified to:

$url_arr = arg();


How to fetch nearest node based on geofield?

Something like this should do the trick to implement haversine :

/**
 * Implements hook_views_pre_execute().
 */
function YOURMODULE_views_pre_execute(\Drupal\views\ViewExecutable $view) {
//...
    $view->build_info['query']->join('YOUR_FIELD_LATLNG', '...', '...');
    $view->build_info['query']->addExpression(sprintf('3956 * 2 *
                                            ASIN(
                                                SQRT(
                                                    POWER(
                                                        SIN((%s - TABLE.YOUR_FIELD_LATLNG_LAT)*pi()/180/2)
                                                    ,2)
                                                    +COS(
                                                        %s*pi()/180
                                                    )
                                                    *COS(
                                                        TABLE.YOUR_FIELD_LATLNG_LAT*pi()/180
                                                    )
                                                    *POWER(
                                                        SIN((%s-TABLE.YOUR_FIELD_LATLNG_LNG)*pi()/180/2)
                                                    ,2)
                                                )
                                            ) * 1.60934', $lat, $lat, $lon), 'kilometers');
}

edit nearest :

$view->build_info['query']->orderBy('kilometers', 'ASC');
$view->build_info['query']->range(0, 1);

Note there is a contribution with views on geofield : https://www.drupal.org/project/geofield/issues/3012750


Well, I found a solution, however, I'd be amazed if there isn't a better way to do it, and in fact I'm pretty sure it's bypassing the placeholder API, so it's likely the wrong way to do it. But until someone gives me a better solution, it's a working one.

The solution is to generate the token manually, then set it as a GET query on the URL when generating the URL.

When generating the token however, you need the internal path for the route, which is used as a basis for generating the token.

$url = Url::fromRoute('mp.ajax.authorized');
$token = \Drupal::csrfToken()->get($url->getInternalPath());
$url->setOptions(['absolute' => TRUE, 'query' => ['token' => $token]]);
$absolute_url = $url->toString()

Note that I've already found this method doesn't work on routes with optional parameters, so if someone comes across this, you'll have to find another method in such a case.


Solved the issue.
In my case, after debugging the value, I guessed the right code could be:

$date = date('Y-m-d\T00:00:00', time());

And it is. I'm not sure what the date format depends on. For sure it doesn't depends on the form display format since in the I'm using the Italian one (d/m/Y).


Taken from Bala's answer.  I had to do a great deal of work on the code before it worked so I thought I'd paste my corrected code here:

Copy sites/all/modules/webform/templates/webform-form.tpl.php to your sites/all/themes/ folder so that you don't hack the original tpl.

In the sites/all/themes//webform-form.tpl.php copy add the code:

<?php
    if($form['details']['page_count']['#value'] > 1){
        $output_pagenum = '
Page '
            . '' . $form['details']['page_num']['#value'] . '' . ' of '
            . '' . $form['details']['page_count']['#value'] . '';
        echo $output_pagenum . '
';
        // End of custom code
    }

  // Print out the main part of the form.
  // Feel free to break this up and move the pieces within the array.
  print drupal_render($form['submitted']);

  // Always print out the entire $form. This renders the remaining pieces of the
  // form that haven't yet been rendered above.
  print drupal_render($form);

Then in your js file:

//Progress bar for webforms.
    var actual = $('.actual').text(); //Get the value of the actual page.
    var total = $('.total').text(); //Get the value of the total of pages.

    if(total > 1) { // check if is a single page form and the webform has no breaks
        var percentage = (actual/total)*100; //Divides the actual value between all the pages.
        percentage = percentage + '%';
        var progressbar = '
'
         + '

';

        $('.page-count').append(progressbar);
        $('#progressbar').css('width', percentage); //Depending on which page break youre on modifies the width of the progress bar.
    }

    //End of Progress Bar


migrating from multiple csv files in one migration class

I have solved it.
Just place the following line after the field mappings if it is the import process.

$this->processImport();


PDOException: SQLSTATE[HY000] [2002] No such file or directory in _registry_check_code()

For simplicity check drush status with verbose and debug parameters:

drush -vd status

If you're using different profile, don't forget to include it as -l http://foo.

If you still have a problem, it's an issue with bootstrapping your Drupal.

First check your SQL connection if it's working:

drush sql-cli

If it does not, check your db credentials in your Drupal settings file.

If it does, there is a problem with SQL connection through the socket.

So in MAMP you've to do:

Check value of socket in my.cnf (menu: File/Edit Template), it's usually set as:

socket      = /Applications/MAMP/tmp/mysql/mysql.sock

Double check if your MySQL can find this file:

$ mysql_config --socket
/Applications/MAMP/tmp/mysql/mysql.sock

Double check if your PHP has the right mysql.sock set-up:

$ php -i | grep mysql.default_socket

Link the socket into your /tmp and see if that helps:

sudo ln -s /Applications/MAMP/tmp/mysql /var/mysql

Test the socket file:

mysql --socket=/var/mysql/mysql.sock

Still the problem? Add the following setting into your $databases:

$databases['default']['default'] = array(
  // ...
  'unix_socket' => '/var/mysql/mysql.sock',

Troubleshooting

Try: drush sqlq "SELECT @@version_comment LIMIT 1"
Try: drush ev "Database::getConnection('default', 'default');"
Try: mysql --socket=$(php -r 'echo ini_get("mysql.default_socket");')
Check permissions on Unix socket: stat $(mysql_config --socket)
Debug: on OS X with sudo dtruss -fn mysqld, on Linux with strace
Debug with XDebug:

echo '<?php xdebug_start_trace("/tmp/foo.log");' > init.php
drush -c init.php ev 'Database::getConnection("default", "default");'
or set xdebug.show_exception_trace=1 in your xdebug.ini

Check MySQL settings:

echo '<?php phpinfo();' > init.php
drush -c init.php  ev 'Database::getConnection("default", "default");' | grep mysql

Run: php -r "new PDO('mysql:host=localhost;port=3306;charset=utf8;dbname=dbname', 'root', 'root');"
Try to rebuilt your registry


There is a module to do what monymirza suggested - http://drupal.org/project/rename_admin_paths

  The purpose of this module is to secure drupal backend by overriding
  admin path.


I resolved it by changing the custom display settings from teaser to full content. Once the image appeared on the front page, I changed it back to teaser and the image now displays correctly on the front page.

I'm guessing it's some bug or conflict with some modules that was causing this.


Suggestion for "Convert line breaks into HTML" and text editor for corporate website

You can use Wysiwyg (or CKEditor) along with most editors and use Wysiwyg Linebreaks to make the editor work great with existing content, or when switching between editors, and in other circumstances.

Also, Wysiwyg should be pretty stable (I've been using it on a ton of different sites), especially when using it with CKEditor, TinyMCE, or most other editors.

For most of my sites, I have the Convert line breaks into HTML option checked no matter what, mostly because I like being able to see/edit content without extraneous paragraph and line break tags all over the place, and so paragraphs don't get run together.


How to only allow a node to be viewed in its assigned language?

i18n_redirect module has simple code, so turn it off, and add next code to custom module:

/**
 * Implements hook_init()
 */
function CUSTOMMODULE_init() {

    $path = $_GET['q'];
    $language = i18n_language_interface();
    // Not for logged in users nor for home page
    if (!$path || drupal_is_front_page() || !empty($GLOBALS['user']->uid)) {
        return;
    }
    elseif ($translations = i18n_get_path_translations($path)) {
        if (isset($translations[$language->language]) && $translations[$language->language]['href'] != $path) {
            drupal_goto($translations[$language->language]['href'], array('language' => $language), 301);
        }
        else {
            // Here we working with node, since question about node redirections
            $node = menu_get_object();
            if ($node && $node->language && ($node->language != $language->language)) {
                $languages = language_list();
                if (isset($languages[$node->language])) {
                    $language = $languages[$node->language];
                    drupal_goto('node/' . $node->nid, array('language' => $language), 301);
                }
            }
        }
    }
}


How to detect same user when they submit two webforms?

Another less obvious solution if using the rules module already is https://www.drupal.org/project/rules_session_vars

Set the variable when the first form is submitted and check for it when the second is submitted. The use rules to do whatever is needed.

Your own prepopulate solution is perfectly fine however. This one just stops someone from hacking the url.


(nginx) File field upload progress not working, but upload progress in FileField Sources works

Nginx doesn't support upload progress in core, you will need to install - http://wiki.nginx.org/HttpUploadProgressModule

To show upload progress a webserver should implement - RFC1867


Do you have the Theme Developer module enabled? I had the same problem (disappearing contextual links menu for blocks) and disabling the Theme Developer module resolved the issue. Likely something to do with the z-order being utilized by Theme Developer.


Webform Module or hook_form_alter() - What is right for me?

Webforms generally are best as contact/survey forms or some variant of them.

For an application like this, in my opinion it is just easier to implement your own form and do your own validation and submission. The validate handler could evaluate if the data is valid, and then the submit handler could create a new Node, set values, and save it.

Technically, you could do that submit Node creation handler with Webform, but it isn't as practical to me. Plus, if you haven't learned the Form API, this is a good opportunity to do so!

If this is Drupal 7, you could also take a look at Entity Forms and Rules, but again in my experience, getting to the goal is just faster with your own form or two and coding in what you want.


You can always use the  Views: Filter by an entity reference view  option from Entity selection mode and then create a view as per your sorting options and filters and select the view in the select box which shows up.


Enable the Kint module (comes with devel) then do

kint($result->__toString()); or kint($result->arguments());


Allowing users to create calculated views

You are right, you shouldn't allow people to change php code on your site.

I would allow a lot of customization to the data that is returned via views filters.

You can return the data in a table format and allow this table to be exported to excel or csv (there are views modules for both of these). Then people can create whatever they want.

There are a few js libraries which can give you spreadsheet like functionality in the browser with an HTML table, that may be an option too.


Users can post new node but ONLY Unpublished status

The obvious thing is that the "published" option is unticked on the content type. So if you go to "structure > content types > question" (/admin/structure/types/manage/question) and then click "Publishing option" is the published ticked? That controls the default status

If its not that then you must have some other module/code doing it. Without knowing your sites setup I dont think people can help much further


How to add a "company name" as a user value for permissions and a data variable

This article can be helpful for you: https://www.drupal.org/node/200631, and you can try Taxonomy Access Control module to implement it.
Or another way you can try Organic groups - its more powerful.


How do I find which file contains a function?

You can find it at includes/database/database.inc, line 2342.

Your editor may be providing a similar feature like the one implemented in Zend studio: When you press control while you click on the function name, it will take you to the file containing the implementation of that function.


How to send a Group email based on date field using Rules?

This is typically something you can get to work using the Rules module, together with Rules Scheduler (a sub-module of it), as explained in the steps below.

Step 1: Enable the Rules Scheduler

Enable the Rules Scheduler (a sub-module of Rules). And make sure your cron jobs are running (to ensure that scheduled rules actually start executing.

Step 2: Create a Rules "Component"

Create a Rules Component labeled something like Notify all members of a Group, which looks like so (in Rules export format):

{ "rules_notify_all_members_of_a_group" : {
    "LABEL" : "Notify all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "group" : { "label" : "Group", "type" : "group" },
      "event_node" : { "label" : "Event node", "type" : "node" }
    },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail Id \u0022[member-of-group:user:mail]\u0022 is a member of the \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and group id \u0022[group:gid]\u0022, related to the node with id [event-node:nid] and title [event-node:title] (and date [event-node:field-expiration-date])." } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail as a friendly reminder related to the node with id [event-node:nid] and title [event-node:title] (and date [event-node:field-expiration-date]).\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some more details about this Rules Component:

The type of this Rules Component is an "Action Set" (no need for any conditions).
Action 1 is to build a list of all the members of the group. It uses "Fetch entity by property", with these additional specs:

Entity type value = Group Membership.
Property value = Group.
Value of the data selector = Group.
Limit result count = blank (we do not want to limit the nr of results).
Provided variables = "Group members" (variable label) and "group_members" (variable name).

Action 2 is to iterate (= loop) over each of the members of the group. It uses "Add a (Rules) loop", with these additional specs:

The list to loop over = group-members
Current list item = "Member of group" (variable label) and "member_of_group" (variable name).
Sub-action (i) of this Action 2 is to just "Show a message on the site" (while QA-testing this Rules Component), with message type = Status and with an appropriate message using various tokens which might be interesting.
Sub-action (ii) of this Action 2 is to actually send an eMail to the "member_of_group" being processed in the loop, using various tokens similar to those in Sub-action (i).

If you have the Rules UI enabled , as well as the Group module, you can simply import the above rule in your own site, no need to tweak anything in it. Though you may want to tune the Subject and Message content of the actual eMail (just remember the various tokens you may want to use), while you might also want to use some other From eMail ID. And after QA-testing it, you probably want to remove the Rules Action "Show a message on the site".

Step 3: Create a "Rule" using the Rules Component

Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste):

{ "rules_schedule_group_notification" : {
    "LABEL" : "Schedule Group notification",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_event_date" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_notify_all_members_of_a_group",
          "task" : "[node:nid]"
        }
      },
      { "schedule" : {
          "component" : "rules_notify_all_members_of_a_group",
          "date" : [ "node:field-event-date" ],
          "identifier" : "[node:nid]",
          "param_group" : [ "node:group" ],
          "param_event_node" : [ "node" ]
        }
      }
    ]
  }
}

The above rule refers to the Rules Component from the previous step. And is based on these assumptions:

The content type of the event node is has machine name article (adapt prior to import to fit your case).
The field "Event date" has machine name field_event_date (adapt prior to import to fit your case).

The schedule_delete that is part of this rule is to ensure that previously "scheduled" notifications will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recently entered date).

Attention: whatever gets updated in such node, will each time trigger this rule. Even if the actual date itself is not updated. If that's not what you want, just add additional Rules Conditions so that the rules Actions are only performed if the date is updated.

PS: I'm assuming this question is about D7.


Show all children of a specific taxonomy term using Views exposed filters

Contextual filters (in the Advanced section) has a parent filter.

Also if you add a Relationship to parent you can make use of that within normal filters.


How do I use an HTML5 element for my field widget?

Your question is not clear please explain what HTML5 element you want to add to the form field. If you want to add placeholder or any other element you can pass them in #attributes, like this:

$form['name'] = array(
  '#type' => 'textfield',
  '#title' => t('First Name'),
  '#attributes' => array('placeholder' => 'First Name'),
);


Have you tried accessing the values with entity_metadata_wrapper?

$entityform_id = 12; // entity form id
$entityform = entityform_load($entityform_id);
$entityform_wrapper = entity_metadata_wrapper('entityform', $entityform);
// Access fields with $entityform_wrapper->field_name->value() or ->field_name->raw()
drupal_set_message($entityform_wrapper->field_my_field->value()); // for example


Easy way to create author account on node creation?

You can do this easily using Rules Module. Just trigger a rule that whenever you create a node of the particular type, the Rule checks the entered email-id in the field and creates a new account using that email-id if it doesn't already exist.


In the end I created a custom module with a Views Sort handler to write the custom ORDER sql.

function custom_module_views_query_alter(&$view, &$query) {
  if($view->name === 'viewname') {
    /**
     * Order = (rating * 10) – (hours old / 2)
     * Note: the rating field is divided by 2 because in the DB the rating is out of 100
     */
    $view->query->orderby[0]['field'] = "(if(field_data_field_rating.field_rating_rating, field_data_field_rating.field_rating_rating,0) / 2) - ROUND((UNIX_TIMESTAMP(NOW())-created)/60/60/2)";
    $view->query->orderby[0]['direction'] = "DESC";

    $view->query->orderby[1]['field'] = "created";
    $view->query->orderby[1]['direction'] = "DESC";
  }
}

For this to work you either have to add the SQL JOINS in this module or add the rating and posted date fields as a 'sort' in your view.


In short, unless you are the only person with physical access to the server, you are not safe, there is no way you can do this with reasonable effort, a VPS makes no difference.

If you could deploy something like full disc encryption which was only unlocked when you logged in to the system, your provider could still have virtualized the entire server, and not encrypt it anyway, only tell you they have.

Even if you somehow managed to safely encrypt the database, it needs to become readable at the server side at some point, or your server couldn't possibly serve the data.

Either this means that your webserver actually holds the decryption key, making it at most moderately complicated to copy it. You could require the key to be entered every time your http-deamon starts and store it only in RAM, but again, if your host is in a virtual machine you are immediately screwed, and a determined attacker could steal the key from RAM even from physical ram.

I could go on, but the gist is, you can't do what you want without a lot of resources, mainly physical servers in a locked serverrack.


Try this on your code:  taxonomy_get_tree(1,0,NULL,TRUE)

Syntax:

taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE)

  Parameters

  $vid: Which vocabulary to generate the tree for.

  $parent: The term ID under which to generate the tree. If 0, generate
  the tree for the entire vocabulary.

  $max_depth: The number of levels of the tree to return. Leave NULL to
  return all levels.

  $load_entities: If TRUE, a full entity load will occur on the term
  objects. Otherwise they are partial objects queried directly from the
  {taxonomy_term_data} table to save execution time and memory
  consumption when listing large numbers of terms. Defaults to FALSE.


I think you will have to do this at the CKEditor level.  See:

https://ckeditor.com/docs/ckeditor4/latest/guide/dev_configuration.html#defining-configuration-in-page

On the Drupal side, this JS could be added by altering the content type edit form to add the JS.


You can use the Views module to do this.

Create a new view, remove sort options, fields and other default settings
Add a field for "Content: Type"
Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
Add yet another field for "Content: Type"
On the second "Content: Type" field, click "Aggregation settings"
Set the aggregation type to "count"
The second "Content: Type" should now look like "COUNT(Content: Type)"

That should be it! If needed, adjust some more settings like field labels and row style settings.

Here is an export of such a view, so you can easily import it and try it out:

$view = new view;
$view->name = 'nodecounts';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Node counts';
$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'] = 'Node counts';
$handler->display->display_options['group_by'] = TRUE;
$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['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'type_1' => 'type_1',
  'type' => 'type',
);
$handler->display->display_options['row_options']['separator'] = ': ';
$handler->display->display_options['row_options']['hide_empty'] = 0;
$handler->display->display_options['row_options']['default_field_elements'] = 1;
/* Field: Content: Type */
$handler->display->display_options['fields']['type_1']['id'] = 'type_1';
$handler->display->display_options['fields']['type_1']['table'] = 'node';
$handler->display->display_options['fields']['type_1']['field'] = 'type';
$handler->display->display_options['fields']['type_1']['label'] = '';
$handler->display->display_options['fields']['type_1']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['external'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['html'] = 0;
$handler->display->display_options['fields']['type_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type_1']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type_1']['hide_empty'] = 0;
$handler->display->display_options['fields']['type_1']['empty_zero'] = 0;
$handler->display->display_options['fields']['type_1']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type_1']['link_to_node'] = 0;
$handler->display->display_options['fields']['type_1']['machine_name'] = 0;
/* Field: COUNT(Content: Type) */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
$handler->display->display_options['fields']['type']['group_type'] = 'count';
$handler->display->display_options['fields']['type']['label'] = '';
$handler->display->display_options['fields']['type']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type']['alter']['external'] = 0;
$handler->display->display_options['fields']['type']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type']['alter']['html'] = 0;
$handler->display->display_options['fields']['type']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type']['hide_empty'] = 0;
$handler->display->display_options['fields']['type']['empty_zero'] = 0;
$handler->display->display_options['fields']['type']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type']['separator'] = '';
$handler->display->display_options['fields']['type']['format_plural'] = 0;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');


How to get entity Translation's title in Twig

Normally you filter rows having all the same language, but you don't have to. So rows can have different languages.

The code in the question seems to get the entity from the wrong place. See this topic for examples of different kind of rows: How to access raw data in twig template using views table format

A normal views row is a ResultRow object having the property _entity, which then should return the translated entity:

$entity = $row->_entity;

See ResultRow::$_entity

But it doesn't. Tested it with the pre-installed view Content and I had to get the entity translation of the row language stored in node_field_data_langcode before I could get the translated title:

foreach (views_get_view_result('content') as $row) {
  $entity = $row->_entity;
  $langcode = $row->node_field_data_langcode;
  $entity = $entity->getTranslation($langcode);
  $translated_title = $entity->label();
}


Term reference field: Checkboxes with add new textfield

http://drupal.org/node/1208512#comment-5605324

It has been adapted from Select or other to support taxonomy term references.

It is a non-contrib module and you may need to tweak it to your taste, especially as it adds Other: to the term you have added. I just tried it out and that part needs to be fixed, but it shouldn't be difficult.


You could get the node values from: $element['#object']: The entity to which the field is attached.

So in this case if the field is a node field the $element['#object'] is the node object.

print $element['#object']->title;

Documentation: https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7


How to print a block inside the node body?

Try to use Insert Block module. It has Drupal 8 version


First, if you want to get an argument from the URL, you should declare it in hook_menu, as such:

$items['items_form/%'] = array(
  'title' => 'Item Form',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('get_item_form', 1),
  'access arguments' => array('access items_form content'),
  'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
);

Drupal's menu system will then pass in the itemid to drupal_get_form(), which will then pass it along to your form declaration function. You will need to add an argument to your function definition to access it, suggest something like this:

function get_item_form($form, $form_state, $itemid = NULL){
  $form = array();
    ...
}

Please look at the documentation for hook_menu for more information about how to handle URL arguments. I would caution against using arg() in your code.

The reason this is important is what happens when you submit your form with a URL argument. By default, if you do not override with the #action parameter in your form, it submits a POST request to the present URL. By not declaring that your URL has an argument in it, Drupal actually doesn't know how to handle a request to *items_form/123*. The only reason you see anything but a 404 when you go to *items_form/123* is that Drupal attempts to find the nearest path. I suspect that since it doesn't know explicitly what to do when a request is made to *items_form/123* it breaks the form submission handling.

I should also mention that you'll need to declare both *items_form* and *items_form/%* menu paths if you wish them both to work. They're distinct paths in the eyes of Drupal's menu system.


I have also create custom resource using services module like:

function vintervals_resource() {
  $api = array(
'registration' => array( // Resource name
'operations' => array(
    'create' => array(
    'help' => 'Ticket System',
    'file' => array(
        'type' => 'inc',
        'module' => 'My_module_name',
        'name' => 'includes/My_module_name.services',
    ),
    'callback' => 'My_custom_callback', // callback
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'access arguments append' => FALSE,
    'args' => array(
        array(
        'name' => 'body', // parameter name in callback
        'type' => 'string',
        'description' => 'Function to perform',
        'source' => 'data',
        'optional' => FALSE,
        'default' => '0',
        ),
    ),
    ),
    ),
)
);
return $api;
}
   // callback
 function My_custom_callback($body)
 {
      // Your work here..
      $json_array = array($body);
      $json = json_encode($json_array);
      $body_Array = json_decode($json);
      $applicationId = $body_Array[0]->appno;
      $emailid = $body_Array[0]->emailid;
      $mobileNo = $body_Array[0]->mobno;
      $password = $body_Array[0]->userpwd;
      $returnArray = array('status'=>FALSE,'application_status'=>-1);
      return $returnArray;
 }

URL of my web service call is :

My domain + My endpoint + resourcename

"mydomain.com"+"api/ticketsystem"+"registration"

But it will not working directly in the browser.
For this I have sent post request to server with parameters and receive it in my callback then it's working perfectly.


Which hooks can I use in profile development?

I can't find a documented list anywhere, but a quick look at the code suggests these are the available hooks:

hook_install_tasks()
hook_install_tasks_alter()
hook_install()
hook_form_alter()
hook_form_FORM_ID_alter()


How to add the node settings "Exclude node title" to a field group?

In the form_alter function:

  if (isset($form['exclude_node_title']) && isset($form['title']) && isset($form['#group_children']['title'])) {
    $form['#group_children']['exclude_node_title'] = $form['#group_children']['title'];
  }

this will move the exclude title into the same group as title is in


Get a message if insert into table works

You can use drupal_set_message() to display a message in the browser, this can be marked as a status', 'warning' or 'error' message.

If you want to debug your code, the Devel module is recommended and provides the dpm() function. Besides being able to print a simple message, dpm() also allows to display an array or object quite easy.


How do you load a select field with pre-selected items when the Chosen module is installed/enabled?

Your select field is currently only accepting one selected option. This is why it won't allow an array as a default value. (It expects a string or an integer).
The following select field allows more than a selected option.
$form['list_info']['my_list'] = array(
  '#title' => t('Select a list to manage:'),
  '#type' => 'select',
  '#options' => $my_list,
  '#default_value' => $my_list,
  '#multiple' => TRUE,
);


One way would be to set a minimum height on #banner. That way when #banner is empty of content, there will still be a space between #menu and the border. This solution does not require you to involve PHP at all.

#banner {
  min-height: 10px;
}


The WYSIWYG module allows embedding any supported WYSIWYG editor to a field via a hook_form_alter()/hook_form_FORM_ID_alter() invocation. Here's a link to its documentation page. You can alter your custom node type form by altering the its body field #type & #format elements.

Note: To do this it also requires:

The WYSIWYG libraries pre-installed to the sites/all/libraries directory.
A pre-existing WYSIWYG profile created.

As such, you'll need to have add a wysiwyg dependency in your module's .info file and some how do the above work in #1/#2 inside your  hook_install invocation.


I'm afraid you can't, no, it has to be in a module.

The array of blocks is built up in _block_render_blocks() using the module_invoke() function which, as its name suggests, only invoke hooks for modules and not themes.

If you haven't written a custom module before don't be afraid to get stuck in its pretty easy. I'd highly recommend the Module Developer's Guide which will tell you everything you need to know.


How to hide non-editable profile fields in DrupalGap?

During hook_form_alter() implementations in DrupalGap, the form hasn't yet been rendered into the DOM, so at that point it is not yet possible to use jQuery selectors on the form.

Instead use an inline JS event (attach it to the form's prefix or suffix during the form alter). Your inline JS page event handler can have a custom function, and that custom function can do the custom jQuery selectors. Also, that appears to be the incorrect usage of the access property. Try this instead:

// During hook_form_alter()...
form.elements['field_points'].access = false;
form.suffix += drupalgap_jqm_page_event_script_code({
    page_id: drupalgap_get_page_id(),
    jqm_page_event: 'pageshow',
    jqm_page_event_callback: 'my_user_profile_form_pageshow',
    jqm_page_event_args: JSON.stringify({
        hello: 'Hi!'
    })
});

Then make a custom function:

function my_user_profile_form_pageshow(options) {
  $('#edit-user-profile-form-field-points-und-0-value').css("background-color","yellow");
  $('#edit-user-profile-form-field-points').css("background-color","yellow");
  $('#edit-user-profile-form-field-points-und-0-value').hide();
}


how to show the foreign characters in tpl.php file

Make sure that your theme is using the utf-8 character set.  You can see this in the headers of the page:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

You'll also want to make sure that the web server you are using to serve the page is sending the correct HTTP header as the response (you can use the web developer inspector tool in either Firefox or Chrome to see this).  It should be:

Content Type: "text/html; charset=utf-8"

If your browser is set to use a different content-type encoding this might also explain the difference.


how to create a link to mysite/user and how to theme mysite/user?

Like Stan Ascher posted the simplest and quickest way would probably be to create a block with the links and set it to appear where you want on the front page. With a wysiwyg editor it should be fairly easy to get the output themed to your liking as well.

If adding a block is not suitable for one reason or another there's also the option to manually add the necessary code in your theme's page--front.tpl.php file or if it doesn't exist then page.tpl.php. The code could look like this:

<?php if ($is_front): ?>
<div class="user_links">
  <?php print l(t('login'), 'user', array('attributes' => array('class' => array('login')))); ?>
  <span> | </span>
  <?php print l(t('register'), 'user/register', array('attributes' => array('class' => array('register')))); ?>
</div>
<?php endif; ?>

If the code is going into page--front.tpl.php then remove the first and last line. Basic HTML, CSS knowledge would probably be necessary with this approach though.

You can add fields for users on the 'admin/config/people/accounts/fields' page or select Configuration -> Account settings then the manage fields tab. These can be set to appear on user registration and users can edit them later with their other profile information.


Is there a way to automatically cancel an account after 14 days?

Sure you can do this, using the Rules module (and the Webform module for your form). Here is a blueprint about how to do so:

1. Rules Component to block a user

Create a (rather basic) Rules Component to "block" a user, whereas you use a "User" entity as parameter for it.

2. Rule to cancel an account

Create a (rather basic) rule like so:

Rules Event: Before saving a user account
Rules Conditions: None (feel free to add whatever fits)
Rules Action: Schedule the execution of the Rules Component (from step 1), to be executed after 14 days. For this you need to have the "Rules Scheduler" (a sub-module of Rules) enabled. Make sure to use an "id" for this scheduled task that includes the user's uid (you'll need it in Step 3).

Refer to my answer to "How to send an email notification reminder based on a user's date of entry field?" for a sample of a rule that is pretty close to what your rule should look like (especially Step 3 of it).

3. Rule to delete the scheduled rule

Use the Webform Rules module to create a rule like so:

Rules Event: After a webform has been submitted
Rules Conditions: Check the webform Id (to ensure it's the form you want to consider).
Rules Action: Delete the Scheduled rule from Step 2, and Reschedule it to be executed 21 days after there account activation date. For this you'll need the id of the Scheduled task, but if you used the user's uid for that, this should be no problem.

PS: I'm assuming this is about D7 ...


Regcode/OG Issue - Need D7 Equivalent of og_all_groups_options()

The closest one seems to be og_get_all_group() in og.module.


There may be better routes out there, but I am going to suggest the one I have in mind right now.

You could create your own custom block - that wraps around the Views block display that you already created. Why? Because that way you have full control of the arguments.

Wrapping a Views block display with your own custom block:

Implement hook_block_info() and hook_block_view().
Inside your hook_block_view() call the View display programatically. The View display should be a block (it looks like you got it already configured).
While instantiating the View display, you can grab the arguments from the URL using the arg() function. Since this is your own code, you can do anything that you want with those arguments. For example, you could load a term using an nid-based argument, get the term's proper name, URL-decode it if needed, and then feed it to your display.
Execute the View display, retrieve the results, and return them as the output of your block.

Then instead of embedding in the panel the block that was provided by your View, you embed the one that you created in your custom module. Again, since you called the View programatically, you had full control of the arguments that were passed to it.

It sounds complex, but it's really easier than you think. Here's a plain example of how to call the View (you could modify it for your needs):

$view = views_get_view('my_foobar_view');
$result = $view->execute_display('block_display_baz');
$term_id = arg(2); // Get the term from my-panel/foo/<term id>
$view->set_arguments(array($term_id));
$view->execute();
if(!empty($view->result)) {
  foreach($view->result as $result) {
    // Do something with $result...
  }
}

This G.D.O. document can provide you with more examples on how to programatically embed Views.


You need to include the file itself, module_load_include can help you with that. Then you need to instantiate the class, you should read the docs about jcart to figure out how to do that, but something like

 $jcart = new jCart($args);

This can be done in your theme, or ever better create block in your module than will display the cart and that will invoke display_cart.

Note I don't know anything about jcart, and as such the code is just an illustration.


How to get rid of text box artifact with Fivestar module?

Can't you get rid of it with CSS? display: none;


Alternative, more secure user registration process wanted

If you want to change the way a user can register on a Drupal site, I would rather implement hook_menu_alter() to alter the menu callback called when a user access user/register.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_register_form');
  }
}

If you are going to allow users to enter an email that is already used from another account, then you should alter also the menu callback associated with user/register, as Drupal allows users to reset a password by entering their username or their email address.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_register_form');
  }
  if (isset($items['user/password'])) {
    $items['user/password']['page arguments'] = array('mymodule_user_pass');
  }
}

The functions Drupal uses as form builders for those menus are user_register_form(), and user_pass(). You can use them as guideline for the code you implement.

Keep in mind the following points, though:

The unique email is necessary because Drupal allows users to request a new password by entering the email associated with their account. This is also helpful for who simply forgot their username, as the email sent from Drupal contains a link that redirects them to their account, where they will eventually change their password (or just enter their previous password to keep it).
There isn't any security involved, as that doesn't allow a user to know all the emails used in a Drupal site, nor any email matching a partial email address. The users need to enter a complete email, and at that point there is few they can do; even in the case they try resetting a password, Drupal would sent an email to that email address, to which that user needs to have access. If that user can change the password of that email address, or can obtain it, that is not a Drupal security issue, but eventually with how that email address is handled, or who knows the password used for an email address.
If there is a security issue with allowing to use an email address to reset a password, then there would be a security issue even in the case the user is able to enter a username to request a new password, because somebody could find out a username already in use on a Drupal site.
Allowing to have not unique emails can create problems with modules such as the LoginToboggan module that allows users to log in entering their email address when logging in. There are probably other modules that assume there aren't two user accounts using the same email.
Enforce unique email addresses for users is a Drupal issue report related to what you are trying to achieve. If this patch is going to be applied, it will be possible to allow users not to have unique emails by setting the user_mail_unique Drupal variable.


You should include it with composer to your Drupal project. That is step one. You don't need to consider package management - composer will do this for you.

How you wire it up from there is basically up to you and your use case. I assume first you start with a basic controller and go from there in a custom module.


Boost won't work after configuration of .HTaccess

You can verify Boost is working by browsing a page as an anonymous user (e.g. using your browser's Incognito/Private Browsing mode) and looking at the source code of the page. If Boost is working you should see a HTML comment at the bottom of the document that looks like this:

<!-- Page cached by Boost @ YYYY-MM-DD HH:MM:SS, expires @ YYYY-MM-DD HH:MM:SS, lifetime X hours -->


We can style that with simple css,

.node--view-mode-teaser .node__content p {
  /* write you style */
}

I think, you don't need to add separate class in P tag for that. and it would also affect only the teaser mode content :)


How do I free the memory used from node_load()?

It happens because node_load(), as every Drupal function that loads entities from the database, stores in memory the loaded entity. If you want to avoid that happens, you can use code similar to the following one.

for ($i = 0; $i < 1000000; $i++) {
  $nid = get_node_id($i);
  $node = entity_load('node', array($nid), array(), TRUE);
  $data = [
    $node->field_1,
    $node->field_3,
  ];
  save_to_database($data);
}

The last argument of entity_load() is telling Drupal not to store in memory cache the previously loaded entity.

This is what happens with the default entity controller implemented from Drupal, DrupalDefaultEntityController, which uses the following code for DrupalDefaultEntityController::resetCache().

public function resetCache(array $ids = NULL) {
  if (isset($ids)) {
    foreach ($ids as $id) {
      unset($this->entityCache[$id]);
    }
  }
  else {
    $this->entityCache = array();
  }
}


What does "Argument #1 is not an array in _form_set_class()" mean?

For me it happened; when I used

$form['field']['#attributes'] = array('class' => 'myclass');

While it should be

$form['field']['#attributes'] = array('class' => array('myclass'));


How to create a Gmap view that can be filtered?

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
Specific to the "filter" part of your question, here is a quote (also from the project page):

For those using the Commerce module a ready-to-use Order Locations map is provided (3rd screenshot). For each order placed at your store it outputs a marker on the map with its location details retrieved by IPGV&M. The view comes with filters to zoom in on country, time frame and order status. Each order location marker, when clicked, reveals in a text balloon details of the order, e.g number, date placed and order status as well as street address.

Note: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.
PS: I'm assuming this question is about D7 ...