Maisystem module not saving my custom class on production server

http://php.net/manual/en/features.safe-mode.php
notes

  This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

So in general it is not very useful feature and turns out to be causing issues with some applications when they try to write to the file system.


Dropping options of exposed filters breaks when user is logged

As Bala said, it is a CSS issue. I finally fixed it.
The problem comes from my <#section id="main">. It's a wrapper to all the main content area in my theme.
It has display:inline, but when I change it into display:inline-block or by deleting the display, the dropping options are working flawlessly.


Migrating nodes with image- and textfield to file-entity with image and description

Load an array of nodes, loop over the array and in this loop loop over the field collection items. For each item create a file-entity.

Something like this:

$nids = db_query("SELECT nid FROM node WHERE some condition is true")->fetchCol();
$nodes = node_load_multiple($nids);

foreach($nodes as $node) {

  foreach($node->field_collection_field[LANGUAGE_NONE] as $item) {
    $collection = field_collection_item_load($item);

    $values = array(
      'field keys' => 'field values',
      'field keys' => 'field values',
    );

    entity_create('file', $values);

  }

}

Note that is half PHP half pseudo code - copying and pasting it won't work but will guide you on the code structure and functions that you'll need.


the Private files folder outside of "sites/default/files"

TL;DR - It is okay even if you place the private files directory outside the sites/default/files directory. In fact, it is recommended that you keep it outside the Drupal root (source). This is hard to implement on shared hosting.

More explaination:
When you specify the path of the private files in Drupal's configuration, Drupal places a .htaccess file with Deny to All in it. Which means that Apache will not be able to serve any of the files inside that directory. The files inside the directory can only be served by Drupal and their paths are resolved as Drupal path.

Example: Let us compare how placing the same file in public and private directory changes the way Drupal handles it. Say the filename is brochure.pdf:

Public file path - If we place brochure.pdf in public directory with path sites/default/files. And in the browser you hit http://yoursite.com/sites/default/files/brochure.pdf.
This request goes to Apache (considering it as a server), Apache tries to resolve the type of request. It tries to go to the directory structure and see if it can fetch the file. In case of public files it has the permission to do so. It directly fetches the file and returns to the browser where it is presented or downloaded. In fact the request doesn't even need to go to Drupal or the PHP interpreter for that matter.
Private file path - If we place brochure.pdf in private directory with path sites/default/files/private. And in the browser you hit http://yoursite.com/sites/default/files/private/brochure.pdf.
Again, the request goes to Apache and it checks the directory to locate the file. It does not have permission to fetch the file from private directory due to Deny to All. It passes on the request to Drupal. Drupal then does the access checks as it does on all other menus (routes in D8), with access callback.

So, to summarize, it should be okay to place your private directory outside the public files.

Note: If you are hosting your site on other servers and not Apache, you might need to check if you need some extra settings as .htaccess restrictions might not work with them.


How does the tmp folder work? It stores lots of junk files and takes space

What does tmp mean?

Tmp is an abbreviation of temporary. So the tmp folder is a folder intended for temporary files. Every operating system uses such a folder, and in facts needs it. So does Drupal. Drupal by default attempts to store files in your operating system's tmp folder. On Linux this is /tmp, on Windows C:\Windows\Temp. You can check and change this setting in Configuration > Media > File System. If your temporary directory is set to one of these standard paths, you should assume it is not only Drupal's files, but files of the operating system and several other programs (Apache sessions, Drush downloads, installation packages).
If it is on a custom path, or in the case of the OP: /sites/default/files/tmp/ (Drupal's fallback path) it should contain only Drupal files.

So what kind of files does Drupal store there?

In general Drupal stores all uploaded files in the temporary folder first. If something goes wrong (eg. the connection with the client is interrupted) there is a corrupted file on the server. Keeping these files in a temporary folder and only moving them after the whole file was transferred, ensures there will be no damaged or unneeded files in your public files directory sites/default/files.

This also includes modules and translation downloads, some js files (probably used in aggregation) and several other files.

There is no real list of all files Drupal stores in tmp, because contributed modules might choose to store a file there as well. Possible use cases for this could be file generation on demand (eg. a module that packages a custom selection of files into a zip file and offers it as download. It is unlikely the same file will be used more than once and there is no real benefit in storing it).

Can I safely remove the files?

Well yes and no... The idea of temporary files is that they are, well... temporary. They are generally used directly after they are created and might no longer be needed. But since all programs can write to tmp, it is a reasonable assumption not all programmers played by the rules, or some files might in fact still be in use.

Should I remove the files?

Drupal performs several cleanups on its own during cron runs (assuming cron is set up and working). Uploaded files that were not saved permanently will be removed during system_cron().
Old modules downloads are handled by update_delete_file_if_stale() (via update_clear_update_disk_cache() and update_cron()).
These cleanups are set to clean up files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE (6 hours), but the actual time depends on the cron interval. (If cron only runs every 12 hours, it can take up to 12 hours before the files are removed).

In most cases there should be no need to remove the files manually. If in some cases cron doesn't remove (all) files, you might attempt to remove them by hand. But make a backup first!

If your folder is shared with your operating system's folder, you might want to use your operating system's tools for it (Windows users can clean the temporary files with the Disk Cleanup tool. (Some Linux distributions clean the folder during system reboot, some don't.)

When the tmp folder is on a custom (non-operating system) path, as is the case with the OP, it should be relatively save to empty the folder by hand. Make sure your webserver (Apache, Nginx) is stopped, so no user of cron task will be touching the files. Then delete the stale files (older than 6 hours) manually.

Conclusion

If your system is setup properly and cron is working, there should be no need to clean these files, as they are removed automatically. If it doesn't happen, you can remove them manually, but keep above conditions in mind. It might still go wrong, so always make a backup!


I came to know that it's by design but not a bug. We can do nothing with the uploaded images. The SimpleTest files will be deleted automatically after successful test suite run.


Use group filters

First views filters group

Type A AND taxonomy 1

Condition between groups

OR

Second views filters group

Type B AND taxonomy 2


How to select author/creator field of CRM-Core Contact and Activity in views?

From what I know, the permissions 'edit any contact' is designed on purpose...module maintaiers claim this allows for custom permissions to be set per your requirement.

As for author / creator field, you have to add a relationship first to your view
Try these -

CRM Core Activity: Author
Entity Reference: Participants

That should probably expose the field you are looking for.


How to remove width and height from image field images in Views?

It feels clumsier than I'd hoped and requires a module, but I found a solution:

Install image_url_formatter module, which creates an image field display that is just the url but still allows you to choose from available image styles
Change the image field in the view to use the new "Image URL" display.
Use the Views rewrite feature to rebuild the image (<img src="[field_image]" alt=... />).


Problems with moving my site to another server - WSOD with unfamiliar errors

When I'm migrating websites I use the Backup & Migrate module. You should give it a try.

If the problem persists, look for differences between the two servers: PHP version, Apache version, MySQL version, etc.
Also check your user permissions on the new server.


Contextual filters in taxonomy term ID (with depth)

This is similar to another request: Contextual filter in taxonomy- Drupal 7

I've customized my answer to your specific requirements:

First thing you need to do is install the References module

When setting up your project content type, create a category node reference field and a services node reference field. This will tie each project to one or more categories and one or more services.

When configuring your view, you will need to create relationships between the project and service/category.


Try with this code:

\Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);


How to output plain URL to the node in Views?

Content: Path works with Drupal 7. Select Use absolute link (begins with "http://") in Rewrite results section of the field settings.


How to send node as body content in email using Rules?

It depends on the Rules Event that your rules is using ... e.g.:

If Rules Event is something like "After updating existing content", then you'll be able to use token [node:body] within (eg) the message body of Rules action "send eMail".
If Rules Event is (eg) "After updating an existing user account" then token [node:body] is not available for using it within (eg) the message body of Rules action "send eMail".


How to set the default "Show as expanded" to true in a custom menu item

I couldn't find it anywhere on the Drupal documentation, but adding

expanded: TRUE

in the module.links.menu.yml file works.


How to remove ":" (colon) when displaying field name?

Note: The OP is not talking about Views. (In Views you can uncheck a box that says Place a colon after the label).

The accepted Drupal method is by copying the core field.tpl.php file into your theme directory and manually removing the colon from the file.

modules/field/theme/field.tpl.php
sites/all/themes/[mytheme]/field.tpl.php

In Drupal 7 this is on line 55:

from:

<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

to:

<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>&nbsp;

In order to do this in a specific content type you first copy field.tpl.php to your theme, then duplicate it, adding the machine name of your content type, and remove the colon from the content type specific version.

sites/all/themes/[mytheme]/field.tpl.php
sites/all/themes/[mytheme]/field--[content-type].tpl.php

Note: the double hyphen (--) is not a typ-oh.

Read up on theme suggestions for more. Using suggestions you can target just a specific field in this content type, just the field globally, all fields in the content type, or all fields in all content types. Or handle every combination differently.


Ubercart most selling product in drupal 7

Here is a view Export

$view = new view;
$view->name = 'best_sellers';
$view->description = 'Best Sellers';
$view->tag = 'Best Sellers';
$view->base_table = 'node';
$view->human_name = 'Best Sellers';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Fields: uc_product_image */
$handler->display->display_options['fields']['entity_id']['id'] = 'entity_id';
$handler->display->display_options['fields']['entity_id']['table'] = 'field_data_uc_product_image';
$handler->display->display_options['fields']['entity_id']['field'] = 'entity_id';
$handler->display->display_options['fields']['entity_id']['label'] = '';
$handler->display->display_options['fields']['entity_id']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['trim'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['entity_id']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['entity_id']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['html'] = 0;
$handler->display->display_options['fields']['entity_id']['element_label_colon'] = 1;
$handler->display->display_options['fields']['entity_id']['element_default_classes'] = 1;
$handler->display->display_options['fields']['entity_id']['hide_empty'] = 0;
$handler->display->display_options['fields']['entity_id']['empty_zero'] = 0;
$handler->display->display_options['fields']['entity_id']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['entity_id']['settings'] = array(
  'image_style' => 'thumbnail',
  'image_link' => 'content',
);
/* Field: Node: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['element_label_colon'] = 1;
$handler->display->display_options['fields']['title']['element_default_classes'] = 1;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Field: Product: Buy it now button */
$handler->display->display_options['fields']['buyitnowbutton']['id'] = 'buyitnowbutton';
$handler->display->display_options['fields']['buyitnowbutton']['table'] = 'uc_products';
$handler->display->display_options['fields']['buyitnowbutton']['field'] = 'buyitnowbutton';
$handler->display->display_options['fields']['buyitnowbutton']['label'] = '';
$handler->display->display_options['fields']['buyitnowbutton']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['trim'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['html'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['element_label_colon'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['element_default_classes'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['hide_empty'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['empty_zero'] = 0;
/* Field: Product: Sell price */
$handler->display->display_options['fields']['sell_price']['id'] = 'sell_price';
$handler->display->display_options['fields']['sell_price']['table'] = 'uc_products';
$handler->display->display_options['fields']['sell_price']['field'] = 'sell_price';
$handler->display->display_options['fields']['sell_price']['label'] = '';
$handler->display->display_options['fields']['sell_price']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['trim'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['sell_price']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['sell_price']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['html'] = 0;
$handler->display->display_options['fields']['sell_price']['element_label_colon'] = 1;
$handler->display->display_options['fields']['sell_price']['element_default_classes'] = 1;
$handler->display->display_options['fields']['sell_price']['hide_empty'] = 0;
$handler->display->display_options['fields']['sell_price']['empty_zero'] = 0;
$handler->display->display_options['fields']['sell_price']['set_precision'] = 0;
$handler->display->display_options['fields']['sell_price']['precision'] = '0';
$handler->display->display_options['fields']['sell_price']['format_plural'] = 0;
/* Sort criterion: Order product: Qty */
$handler->display->display_options['sorts']['qty']['id'] = 'qty';
$handler->display->display_options['sorts']['qty']['table'] = 'uc_order_products';
$handler->display->display_options['sorts']['qty']['field'] = 'qty';
$handler->display->display_options['sorts']['qty']['order'] = 'DESC';
/* Filter: Node: Is a product */
$handler->display->display_options['filters']['is_product']['id'] = 'is_product';
$handler->display->display_options['filters']['is_product']['table'] = 'uc_products';
$handler->display->display_options['filters']['is_product']['field'] = 'is_product';
$handler->display->display_options['filters']['is_product']['value'] = '1';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'best_sellers');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Best Sellers';
$handler->display->display_options['defaults']['css_class'] = FALSE;
$handler->display->display_options['css_class'] = 'new-product-block';
$handler->display->display_options['block_description'] = 'Best Sellers';
$translatables['best_sellers'] = array(
  t('Defaults'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort By'),
  t('Asc'),
  t('Desc'),
  t('.'),
  t(','),
  t('Block'),
  t('Best Sellers'),
);

How to

Login to Drupal as an administrator. Go to Structure > Views.
Click “Import View from Code”

Add "Popular Products" view


Why are available updates of CKeditor not visible in the update report in Drupal 7?

Drupal only check for drupal modules. The CKEditor module is https://www.drupal.org/project/ckeditor and the latest version is 7.x-1.16. This information should appear in admin/reports/updates.

I suppose you are talking about the CKEditor library which is not handled by the page admin/reports/updates.


How I can get nodes of type basic page of current month only in drupal views

Add 'Filter criteria' with the next settings


How do I redirect from an existing file?

The redirect rules in .htaccess that cause Drupal to be fired up only happen if/when an actual file doesn't exist. For example, if I have a file in my webroot named file.txt, and I go to example.com/file.txt, Drupal will not start, as the file exists. If that file does not exist, Drupal will be fired up, and show a 404 page (unless you have an alias in Drupal for the path /file.txt). You have said the file exists on your system, which means Drupal is not being started up when someone accesses that file, and therefore the redirect module will not work.

As for how to delete the file, you say the content item has been deleted. This should also result in the file being deleted, though it does not appear that it was. I'd do a search through the {file_managed} table in the database to make sure it's not still in there for some reason - maybe the file is still attached to a different piece of content or something. If you're absolutely sure the file does not exist in Drupal anymore, then you can log into your server (ftp, ssh etc) and manually delete the file.


All special characters get outputted as question marks

It turned out that the described problem was caused by the Backup and Migrate module. In fact it is a known bug. So, don't use this module for Drupal 8. It will destroy your entire site.


How can I implement user timezone & user's last login in this format?

You can use the global $user object to get user details, or load user details from a uid like this: $user = user_load($uid); From the $user->login property you can get last login timestamp.

Thanks


Migrating a forum created with Advanced Forum 1.x branch from Drupal 6 to a Drupal 7 site running Advanced Forum 2.x branch?

First, upgrade the site to Advanced Forum 6.2.x, then, after everything is correct, migrate to D7.

The upgrade to 6.2.x should be relatively smooth (there were no problems in my experience).

You might have to have several tries for the D6->D7 migation, depending on your site configuration. Always do it in a separate installation, and back up everything, step by step. If something does not go right, this will allow you to reset the site to a point where you can restart a step, rather than going back to a fresh install and starting from scratch.

Follow the Upgrading from previous versions on D.O. to the letter.


In Drupal 6 you would use code similar to the following.

db_query("INSERT INTO {mytable} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14);
$id = db_last_insert_id('mytable', 'id_fieldname');

The Drupal 7 equivalent code is the following.

$id = db_insert('mytable')
  ->fields(array(
    'intvar' => 5,
    'stringvar' => 'hello world',
    'floatvar' => 3.14,
  ))
  ->execute();


I usually do something like this:

<?php

use Drupal\taxonomy\Entity\Term;

function hook_preprocess_page(&$vars) {
  $route = \Drupal::routeMatch();
  if ($route->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term_id = $route->getRawParameter('taxonomy_term');
    $term = Term::load($term_id);
  }
}


How to handle Custom Validation in inline entity Form?

You have to use inline form alter for custom validation in module shown below

/**
 * {@inheritdoc}
 *
 * Implements hook_form_alter().
 */
function module_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {

  // Added custom validation
  if ($entity_form['#bundle'] == 'bundle_name') {
    $entity_form['#element_validate'][] = '_custom_validate_function';
  }
}

And implement that validation like below.

/**
 * Custom validation.
 */
function _custom_validate_function(&$form, FormStateInterface $form_state) {

 $triggering_element = $form_state->getTriggeringElement();
 $values = $form_state->getValues();
 // or you can use $form_state->getValue('field_name')
 // Validate your functionality

 // Set Error for form
 $form_state->setError($form, t("message"));
 // Note: $name may be unknown in $form_state and
 // $form_state->setErrorByName($name, $message) may suppress the error message.
 // hence use above $form_state->setError()
}


Fields for different languages on the same interface

You must repeat the fields, because the Entity Translation and the Internationalization (i18n) module don't provive the fields for each language in the same interface.


User registration form change Username to name

You can do that by implementing hook_form_alter() in your custom module:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    $form['account']['name']['#title'] = t('Name');
  }
}


It could be that you are using the incorrect argument. hook_ENTITY_TYPE_insert is a generic hook, it's not opinionated about what entity you are "inserting" (E.g. it could be a node, taxonomy, user...)

Try:

function weekly_digest_user_insert(\Drupal\Core\Entity\EntityInterface $entity) {
  // Do stuff.
}


Disable creation of a page for a content type and just use teasers?

As far as I'm aware, every Drupal node created has a "page" created for it, no matter what. You can disable the creation of a user-friendly URL, but all nodes have a node ID, and since the node/id URL path is in reality just a simple query, all nodes can have "pages" generated for them by querying against their node IDs in this way.

I would say as long as you just refrain from placing these content types into a menu, you won't need to worry about it. It's highly unlikely that a user would manipulate a URL on their own in order to find the content's page.


Can I control which database Drupal uses for certain data?

If it's not possible at the Drupal level, this might be possible at the MySQL level using the FEDERATED storage engine.  This is a thoroughly untested solution, however, and it might not play nice with Drupal.


Using a Views Output as Options in a Webform in Drupal 7?

I'm a big fan of webform, but in this use case, I would probably use Entity Form and References instead.

Install both modules, and create your entity form.

Add a node reference field. On the field settings, narrow the results by content type "article".

Note, this would show all articles. If you were hoping to narrow down your results using views filters, you might want to investigate the sandbox project that Volker suggested.

Update: The References module allows you to use a view as a list of referenced nodes. This is very useful for drilling your results down to the exact nodes you want to show.


When you give the focus to your field, it triggers an ajax call to the server. If you reload the page right away, it breaks the ajax call and throw this error in an alert.

This only happens as you reload the page during an ajax call. As far as i know you can't do anything about it, unless you modify the core I guess - which is "unclean".

You could use the classes added in css to display a loader while there is an ajax call to the server, and let the user know the page is working on something.

EDIT:

Thanks to clive's comment I actually got rid of this alert by overriding Drupal's Drupal.ajax.prototype.error function.

In a js file, you can add :

Drupal.ajax.prototype.error = function (response, uri) {
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  // Undo hide.
  $(this.wrapper).show();
  // Re-enable the element.
  $(this.element).removeClass('progress-disabled').removeAttr('disabled');
  // Reattach behaviors, if they were detached in beforeSerialize().
  if (this.form) {
    var settings = response.settings || this.settings || Drupal.settings;
    Drupal.attachBehaviors(this.form, settings);
  }
};

This is a copy of the original error handler callback without the alert() function. This will remove your message, but will also hide any error message returned by Drupal's Ajax.


Responsive Views-Slideshow Json Cycle working good in Chrome not in IE or mozilla

I use this code

     $(window).resize(function () {
          $('.views_slideshow_cycle_main').each(function(){
                var cycleMain = $(this);
                var img_width = 0,
                    img_height = 0;
                var clearCSS = {width: "auto", height: "auto"};
                var cycle = cycleMain.children('.views-slideshow-cycle-main-frame');
                cycleElements = cycle.data("cycle.opts");
                cycle.css(clearCSS);
                cycleMain.find('.views-slideshow-cycle-main-frame-row').each(function(i){
                  $(this).css(clearCSS);
                  var tmp_img_width = $(this).width();
                  var tmp_img_height = $(this).height();
                  if(tmp_img_width > img_width)
                    img_width = tmp_img_width;
                  if(tmp_img_height > img_height)
                    img_height = tmp_img_height;
                  cycleElements.elements[i].cycleW = tmp_img_width;
                  cycleElements.elements[i].cycleH = tmp_img_height;
                  $(this).css({width: tmp_img_width, height: tmp_img_height});
                });
                cycleMain.height(img_height);
                cycle.css({width: img_width, height: img_height});
                cycle.data("cycle.opts.elements", cycleElements);
              });

        });

and it works perfectly. you can also add some css to avoid too much high height like:

@media screen and (min-width: 980px){
 .al-slideshow img{
       height: 650px !important;
   }
}

The following css code is also needed

.views_slideshow_cycle_main { width: 100% !important; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame-row { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .field-content { max-width: 100%; width: 100%; }
.views_slideshow_cycle_main .field-content img { max-width: 100%; width: 100%; height: auto; margin: 0; padding: 0; }


Impossible to html_entity_decode the button title in a render array

As pointed out by Jaypan, it was due to a bug in the bootstrap_barrio theme.

I have posted a patch for it: https://www.drupal.org/project/bootstrap_barrio/issues/3083728#comment-13527917


How to remove default div wrappers from fields output via custom field formatter?

The div wrapper you are looking for is probably in field.html.twig. Drupal provides a theme name suggestion for a custom field type automatically, so you can override this template by placing field--myfieldtype.html.twig in the theme templates folder.

If you want you can deliver a default template with the custom field module, like the comment module does for the comment field:

core/modules/comment/templates/field--comment.html.twig

Then you need to define a theme hook in mymodule.module.

Example from the comment module:

/**
 * Implements hook_theme().
 */
function comment_theme() {
  return [
    // ...
    'field__comment' => [
      'base hook' => 'field',
    ],
  ];
}


Data not returned / rendered in simple module

The value returned from the page callback will be passed into the function stated in delivery callback.

The default value of delivery callback is drupal_deliver_html_page().

  "delivery callback": The function to call to package the result of the page callback function and send it to the browser. Defaults to drupal_deliver_html_page() unless a value is inherited from a parent menu item. Note that this function is called even if the access checks fail, so any custom delivery callback function should take that into account. See drupal_deliver_html_page() for an example.

So you cannot output the $files directly. You have to return a render array if you want to keep using the default delivery callback.


How to hide a field based on a specific condition?

I'm not sure I completely understand what you need. But if I'm correct and you just need to show / hide specific fields in a node based on some other field in that node the hook_field_access should help you.

 /**
 * Implements hook_field_access().
 */
function YOUR_MODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  switch ($field['field_name']) {
    case 'field_adding_make_vip':
      if ($node['isVIP'][value]) {  //Is the node VIP?
        return false;  //Show the field_adding_make_vip
      }
      else {
        return true; //Hide the field_adding_make_vip
      }
      break;
  }
    case 'field_adding_vip_image':
      if ($node['isVIP'][value]) {
        return true;
      }
      else {
        return false;
      }
      break;

}


Make sure you actually uninstall the module as opposed to just disabling it.

Uninstall is an additional tab on Admin > Modules page.

If that doesn't work, you could try calling node_type_delete($type) from somewhere.


It turns out Drupal will distinguish ajax for subforms automatically if you work within the system - which I was not.

Instead of calling the form builder function directly (bad), I use drupal_get_form() so the code above becomes:

foreach ($form_state['items'] as $key => $item) {

    $form['item_holder'][$key] = drupal_get_form('item_form_edit', $item);

}

I was previously loading the subitem's code with module_load_include(). I now load the sub-item's code with form_load_include() which should make a cached version of this form load correctly.

Since I am building a list of similar subforms, the subform needs to make sure it gets a unique wrapper:

function item_form_edit($form, &$form_state, $edit = NULL) {

    $id_string = 'sub-item-form';
    $unique_id = drupal_html_id($id_string);

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    ...

    return $form;
}

Now, an AJAX element on the subform can replace that subform with

    '#ajax' => array(
        'wrapper' => $unique_id,
        'callback' => 'subform_callback',
        ...

In this example, the entire subform is being replaced by the callback:

function subform_callback($form, &$form_state) {
    return $form;
}

My subform builder function is in a separate file, so hook_init() needs to make Drupal aware of the subform code during AJAX requests:

if ($_GET['q'] == 'system/ajax' || strstr($_GET['q'], 'file/ajax/')) {
    if (preg_match('/item_form_edit/', $_POST['form_id'])) {
        module_load_include('inc', 'mymodule', 'file_with_item_form');
    }
}


Tying together creation of multiple content types in a form

The Field Collection module is a quick and easy solution. It lets you nest entities within your content type as a field. So you could have a "Garage" Content Type which then has "Car" field of type (field collection) with "Number of values" set to unlimited.

At /admin/structure/field-collections you can add fields to this Car type.

On the Garage edit form you can add cars to your garage as shown below:

Then while viewing a Garage node, a user with sufficient permissions will see edit and add links which work just like you would expect. See below.

The downside with this approach is that since the Car's information is tied closely to a specific Garage, it's not easy to move a car from one garage to another or have one car in several garages, etc. Those use cases are possible, but you will have to write you own code however.


Receiving requests

With webform, you can create forms that allow you, or your site-admins, to create and maintain the form that site-visitors will fill out. When the form gets submitted, you can use Rules to send this information on as an e-mail. The module Webform Rules, provides the bridge between the two modules, allowing Rules to react to webform events.

Answering requests

Just turn the whole process around. Again, use webform to create a form for the request reciever to fill out. When this form gets submitted, send a mail to the requestee with the reply.

Custom work

You will most likely need to do some amount of custom coding to make this whole thing work. For example, in the mail to the sales rep, a link must be autogenerated to a form that gets prefilled with the requestee's e-mail. Auto-filling the form is likely best done as a hook_form_alter. There is a lenghty Rules video series that you can view to learn more about how to work with Rules and how to extend it to do what you need.


For the Entity base field update, You'll need to also add an update hook to apply it
For example:
Installing a new field storage definition
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Implements hook_update_N
 */
function example_update_8701() {
  $bundle = 'article';
  $field_storage_definition = BaseFieldDefinition::create('text_long')
  ->setLabel(t('New Name'))
  ->setDisplayOptions('form', [
    'type' => 'text_textarea',
  ])->setRevisionable(TRUE)
  ->setTargetBundle($bundle);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('new_name', 'node', 'EXAMPLE_MODULE', $field_storage_definition);
}

Documentation: https://www.drupal.org/node/3034742


It would probably be better to have that form coded by hand where you can turn your  list into a set of divs with a jQuery library, eg. http://designwithpc.com/Plugins/ddSlick

Or, you can set a background image to each option with CSS (which kinds of takes a bit of time depending on how much options you have in your select list):

select option[value="your_value"] {
  background-image: url(your_image.png);
}


Does Drupal automatically unlink() orphaned files?

The images will be automatically deleted if they were added through a regular image upload field. In that case Drupal understands that that image is related solely to that one node/entity.

In case you are using some other module for inserting the images, it depends and might not be deleted.


How to make changes to the database schema?

Your database schema literally just means the structure of your database. It sounds like you're being instructed to manually make a change to this e.g. to add a column, which you could do in something like PHPmyadmin.

Normally a module's database schema is managed in its .install file. The initial schema is defined in hook_schema() and any changes are automated with hook_update_N(), but it sounds like you're being asked to make manual changes instead. Be careful!


I would recommend reviewing the Drupal Contrib examples project:

  This project aims to provide high-quality, well-documented API
  examples for a broad range of Drupal core functionality.

It has an example in the form's submodule that provides you some working stub / skeleton code that you can learn, modify or apply to your own project.


How to implement a Drupal Commerce multi-select membership donation form?

I know you are asking about the form specifically, but it isn't clear to me how you are actually managing your 'memberships'. Something like CiviCRM that has full membership management tools can be integrated with both Drupal and with Commerce. There is a module for the latter, but we have found it problematic and have instead done the Commerce to CiviCRM integration using Drupal Rules and the CiviCRM Entities modules.


How to import an addressfield with Feeds?

Following the links you posted, it looks like it's all wrapped up. Yes, try the current dev releases for Feeds.


In your code the html of 'Default page' is never returned. I have refactored it a little bit to make it cleaner and easier to maintain.

/*
 * Taxonomy term callback page
 */
function taxonomy_taxonomy_term_page($term_id) {
  $term = taxonomy_term_load($term_id);
  $breadcrumb = array();
  $parents = taxonomy_get_parents($term->tid);
  // Vocabulary IDs
  $desired_vocab_1 = 1;
  $desired_vocab_2 = 2;
  $desired_vocab_3 = 3;

  if (count($parents) > 0) {
    $show_sub_cat = false;
    $list = get_legal_articles($term->tid);

    foreach ($parents as $item) {
      $_parent = $item;
    }

    $breadcrumb[] = l(t('Default page'), 'Default page');
    $breadcrumb[] = l($_parent->name, 'taxonomy/term/' . $_parent->tid);
    $html = theme('category_details', array('term' => $term, 'list' => $list, 'is_sub_cat' => $show_sub_cat));
  }
  else if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));

    switch ($term->vid) {
      case $desired_vocab_1:
        $breadcrumb[] = l(t('Page 1'), 'Page 1');
        break;
      case $desired_vocab_2:
        $breadcrumb[] = l(t('Page 2'), 'Page 2');
        $breadcrumb[] = l(t('Page 2.1'), 'Page 2.1');
        break;
      case $desired_vocab_3:
        $breadcrumb[] = l(t('Page 3'), 'Page 3');
        $breadcrumb[] = l(t('Page 3.1'), 'Page 3.1');
        break;
      default:
        $breadcrumb[] = l(t('Default page'), 'Default page');
    }

    $childs = taxonomy_get_children($term->tid);
    $html = theme('private_category_details', array('term' => $term, 'list' => $childs));

    drupal_set_title($term->name);
  }

  // Set Breadcrumbs
  drupal_set_breadcrumb($breadcrumb);

  return $html;
}


How to change Webform field value after a webform has been submitted

You should make a custom module, rather than using Rules.

Your module will implement the hook_webform_submission_presave, as shown also in webform.api.php inside webform directory.

Your function should look like this (well, this could be your entire .module file):

function mymodule_webform_submission_presave($node, &$submission) {
  $component_id = 3; //that's your hidden field
  $submission->data[$component_id]['value'][0] = 'Yes';
}

Making a custom module is very easy, take a look here.


Translated Taxonomy terms in node creation page?

I found the solution :

admin/config/regional/i18n/select

CONTENT TO FILTER BY LANGUAGE
 Select nodes by language
 Select taxonomy terms by language

unselect

  Select taxonomy terms by language


there are several ways to add js/css, one example:

Attaching custom javascript or css in your theme

Add a library to yourtheme.libraries.yml in your theme folder:

  yourlib:
  version: 2.6
  css:
    theme:
      css/your.css: {}
  js:
    js/your.js: {}
  dependencies:
    - core/jquery

The paths given are relative to your theme. Dependencies is optional, you can force loading of additional js like jquery.

Now to add this library to your theme go to yourtheme.info.yml and add it like this:

    libraries:
      - yourtheme/yourlib


How to send a notification to admin on profile picture change?

I suggest you try to use a combination of 2 approaches, as further detailed below.

Approach 1 - Prior approval required

If you'd use the the Profile 2 module, then the Profile 2 Moderation module, which depends on the Profile 2 module, enables moderation on user profiles. Here is a (self explaining?) screenprint from its project page.

Be aware however that, as mentioned on the project page, it requires a Profile revisions patch.

Approach 2 - After the facts

Use the Rules module to be informed about all sorts of updates that you're interested in, similar to what's detailed in my answer to "How to send an eMail notification when a specific field of a node or user has been changed?".

With this approach, and as per all the great things you can do with this module, your options are virtually unlimited. This approach also allows you to implement this type of moderation using a granular approach: start small, maybe only using a few custom rules, and keep refining them and continue adding new ones.

Not to forget all the available integrations with tons of other modules, of which the Flag module is probably your very first priority to also add that module for what you're trying to implement. Just a basic usecase about this:

Use Rules to flag any user for which some profile update happened.
Use Views to build a list of such flagged users.

If you'd only implement these 2 bullets of this approach (a matter of minutes, say an hour at max), you'd already have a Version 1.0 of your User Profile Moderation Dashboard (call it your MVP if you prefer ...).

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module.


After insert data to table, updating data in home page drupal7

Instead of implementing template_preprocess_panels_pane() and inserting your content there is something called ctools content types.

A ctools content type shows up in the panels interface as panes that can be added to a region.

In your case I would create a ctools content type in your module mysite.

Basically it's a block that contains rendered data that can be placed in a region of your choice.

It will be more easy to understand for other developers how the data is inserted on the front page also since it will be visible in the Panels interface.

/**
 * Implements of hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($module, $plugin){
  if ($module == 'ctools' || $module == 'panels'){
    return 'plugins/' . $plugin;
  }
}

Then create a folder in your module called plugins and in that folder create a folder called plugins. Place a file called MYPLUGIN.inc
The file should then be placed in mymodule/plugins/content_types/MYPLUGIN.inc

Place this content in your MYPLUGIN.inc

<?php

$plugin = array(
  'single' => TRUE,
  'title' => t('MYPLUGIN'),
  'render callback' => 'MYPLUGIN_content_type_render',
  'description' => t('Renders something.'),
  'category' => t('Custom'),
  'edit form' => 'MYPLUGIN_content_type_edit_form',
);

/**
 * Render the custom content type.
 */
function MYPLUGIN_content_type_render($subtype, $conf, $panel_args, $context) {
  $block = new stdClass();
  $block->content = 'MYDATA';
  return $block;
}

/**
 * Edit callback.
 */
function MYPLUGIN_content_type_edit_form($form, &$form_state) {
  $conf = $form_state['conf'];
  return $form;
}

/**
 * Implements hook_form_submit().
 */
function MYPLUGIN_content_type_edit_form_submit($form, &$form_state) {
  foreach (element_children($form) as $key) {
    if (!empty($form_state['values'][$key])) {
      $form_state['conf'][$key] = $form_state['values'][$key];
    }
  }
}

Now replace $block->content with the data you want to be rendered.


Drupal downloads the module update but need FTP

I sometimes have seen that message with Drupal 7, and I always got confused about why Drupal was asking for FTP access to save files in the same server it was running, and why I didn't get that message in some Drupal 7 installations.
Looking at the code used from Drupal to updates the modules, I then discovered Drupal first checks if local file transfers are allowed. If they aren't allowed, that message will be shown.
In particular, this is the code Drupal uses. (See update_manager_local_transfers_allowed().)
  // Compare the owner of a webserver-created temporary file to the owner of
  // the configuration directory to determine if local transfers will be
  // allowed.
  $temporary_file = drupal_tempnam('temporary://', 'update_');
  $local_transfers_allowed = fileowner($temporary_file) === fileowner(conf_path());

In other words, if the account owning a temporary file created in the temporary directory set up for the site isn't the account owning the directory containing the settings.php file used for the site, Drupal will show the message you saw.
Setting the temporary directory and the directory containing the settings.php file to be owned from the same account will make updates from the user interface possible via local file transfers. In this case, Drupal won't show any message about the FTP access being required.
update_manager_local_transfers_allowed() is called from _update_manager_check_backends(), which contains the following code. (The comments explain what is happening and why.)
  // If file transfers will be performed locally, we do not need to display any
  // warnings or notices to the user and should automatically continue the
  // workflow, since we won't be using a FileTransfer backend that requires
  // user input or a specific server configuration.
  if (update_manager_local_transfers_allowed()) {
    return TRUE;
  }

  // Otherwise, show the available backends.
  $form['available_backends'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $available_backends = drupal_get_filetransfer_info();
  if (empty($available_backends)) {
    if ($operation == 'update') {
      $form['available_backends']['#markup'] = t('Your server does not support updating modules and themes from this interface. Instead, update modules and themes by uploading the new versions directly to the server, as described in the handbook.', array(
        '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
      ));
    }
    else {
      $form['available_backends']['#markup'] = t('Your server does not support installing modules and themes from this interface. Instead, install modules and themes by uploading them directly to the server, as described in the handbook.', array(
        '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
      ));
    }
    return FALSE;
  }
  $backend_names = array();
  foreach ($available_backends as $backend) {
    $backend_names[] = $backend['title'];
  }
  if ($operation == 'update') {
    $form['available_backends']['#markup'] = format_plural(count($available_backends), 'Updating modules and themes requires @backends access to your server. See the handbook for other update methods.', 'Updating modules and themes requires access to your server via one of the following methods: @backends. See the handbook for other update methods.', array(
      '@backends' => implode(', ', $backend_names),
      '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
    ));
  }
  else {
    $form['available_backends']['#markup'] = format_plural(count($available_backends), 'Installing modules and themes requires @backends access to your server. See the handbook for other installation methods.', 'Installing modules and themes requires access to your server via one of the following methods: @backends. See the handbook for other installation methods.', array(
      '@backends' => implode(', ', $backend_names),
      '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
    ));
  }
  return TRUE;

As side note, the temporary directory is the one set on admin/config/media/file-system, which by default is set to /tmp.

Note also that, as 4k4 said in a comment, updating modules or themes from the user interface is a security risk. In fact, it requires the system account used to run PHP to be able to write files in the directory containing the modules. For example, with that permission, a malicious script could alter the submission callback used for the user login form, and add code that sends the login credentials to a remote server.
For a general discussion see Should PHP run as www-data or as the user who owns the website? where one of the comments says:

PHP should NEVER have write access to or ownership of the files it executes, or the directories they reside in. I cannot emphasize this strongly enough. It just takes one security vulnerability, and now you're phishing, hosting a reverse shell, spamming, participating in an outbound DoS, or otherwise compromised, because an attacker used PHP to write a malicious script into a place where it could be executed. #3 is the best solution, best implemented by changing the group of the upload directory to www-data and giving group write access. Also ensure that nginx will not ask PHP to execute scripts stored in that directory.


Views : List all user who didn't publish anything

Create a view showing Users
In Relationships add:

User: Content authored

In Filter criteria add:

User: The user ID:

operator: is not equal to value: 0 (it excludes the anonymous user)

Content: Nid:

operator: Is empty (NULL) [this gives you a list of users who have authored any content (excluding the anonymous user as mentioned above])

The exported view:

$view = new view();
$view->name = 'users_with_no_content';
$view->description = 'Displays a list of users who have added any content yet.';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Users with no content';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = TRUE; /* Edit this to false to make a default view enabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['style_options']['row_class'] = 'user';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['style_options']['type'] = 'ol';
$handler->display->display_options['style_options']['class'] = 'user-with-no-content';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: User: Content authored */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'users';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_type'] = '0';
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['name']['element_default_classes'] = FALSE;
/* Filter criterion: User: The user ID */
$handler->display->display_options['filters']['uid_raw']['id'] = 'uid_raw';
$handler->display->display_options['filters']['uid_raw']['table'] = 'users';
$handler->display->display_options['filters']['uid_raw']['field'] = 'uid_raw';
$handler->display->display_options['filters']['uid_raw']['operator'] = '!=';
$handler->display->display_options['filters']['uid_raw']['value']['value'] = '0';
$handler->display->display_options['filters']['uid_raw']['group'] = 1;
/* Filter criterion: Content: Nid */
$handler->display->display_options['filters']['nid']['id'] = 'nid';
$handler->display->display_options['filters']['nid']['table'] = 'node';
$handler->display->display_options['filters']['nid']['field'] = 'nid';
$handler->display->display_options['filters']['nid']['relationship'] = 'uid';
$handler->display->display_options['filters']['nid']['operator'] = 'empty';
$handler->display->display_options['filters']['nid']['group'] = 1;
$translatables['users_with_no_content'] = array(
  t('Master'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('nodes'),
);


how theme/template connected/related to each other

If your code is only in one module with the name module_id, then in
5. the file should be named module_id.module and the function module_id_theme()


If you mean the link in the right hand login block I'm pretty sure you've already got enough surrounding CSS to target it without adding any more classes, e.g:

.block-user #user-login-form a { color: blue; }


Install Drupal 8 on MAMP: can't detect version of Apache

Drupal uses Apache's ServerTokens in system_requirements() to determine the version number. You currently have that set to "Prod", which just reveals "Apache" as the token, without any version number.

For Drupal to detect the major and minor versions, plus revision, you need to update the config setting to one of:

Full - Server sends (e.g.): Server: Apache/2.4.2 (Unix) PHP/4.2.2 MyMod/1.2.
Min - Server sends (e.g.): Server: Apache/2.4.2.
OS - Server sends (e.g.): Server: Apache/2.4.2 (Unix).


Pass a multi value argument to a panel view

The entity context provided by CTools uses tokens to provide keywords for the given context.

So if you implement your own token which uses a node object as data source it will end up among your node context keywords, and you can pass it to the view as an argument.

Check out this answer to get an idea how to implement tokens.

Your token replacement method should extract the referenced node IDs from the loaded node, and concatenate '+' or ',' between them (it depends on how your argument is configured in the view).


Help me understand this Fatal error: Call to undefined function EntityDefaultMetadataController::bundleOptionsList()

The static method EntityDefaultMetadataController::bundleOptionsList() is a part of Entity API module that VBO is dependant upon. One of your modifiable entity properties needs this method to retrieve options for the modify operation.

You need to debug why this method isn't available. It's defined in entity.info.inc and should be included if the Entity API module is enabled.


Targeting nodes dynamically with breadcrumbs

I feel like what you are looking to implement would require you to use hook_menu_breadcrumb_alter and then using drupal_get_destination() to give you the necessary URL parameter. The results from drupal_get_destination() will be compatible with the l() function and can be handled from the hook_menu_breadcrumb_alter().


Filtering comment by date range in Views

Views uses in between operator i.e. BETWEEN min AND max expression.

This is equivalent to the expression (min <= expr AND expr <= max). Now the query that views create for date is:

(comment.created BETWEEN 1446336000 AND 1447545600)

Search for unix time value of 1447545600

The problem is with the date 2015-11-15, this is treated as 2015-11-15 00:00:00. So 2015-11-15 11:12:13 won't be included. Hope you get my point.


By default, no.  The relevant code is in \Drupal\datetime\Plugin\Field\FieldWidget\DateTimeDatelistWidget::formElement().

What you want is usually called a "partial date", which is a bit of an oxymoron.  In Drupal, datetime fields are stored as DrualDateTime objects, which derive from \DateTime so have both a full date and a proper time and timezone associated with them.

A partial date (year, year+month), has to make assumptions about the rest of the parts.  For example, the date-only field currently sets the time to noon UTC.  A year only field would have to do something similar.

You may be able to create your own widget for the datetime field to do this.  You could take DateTimeDatelistWidget as a starting point, and trim it down to be just the year.  Then, you would need a masssageFormValues() to set the rest of the parts and then call the parent method (because DateTimeWidgetBase::masssageFormValues() does stuff, too).  This may or may not work, it is just the idea that popped into my head.

There is an open issue about this, https://www.drupal.org/node/2703037, that may or may not be implemeneted.


After testing out for a day various combinations it was a problem with a view page that had path same as taxonomy/term/1.

So I renamed the view page path to car/bmw12, deleted taxonomy aliases and recreated them.

It was easy thing to do. I did not think of it earlier as i was lead by assumption that when you use pathauto to recreate paths it would do it for terms no matter if the path was taken in views already.


Moving the a view Contextual Filter default value("PHP Code") to a module code

This tutorial shows goes through exactly what you're wanting to do http://www.undpaul.de/en/blog/2013/04/04/contextual-content-flag-module-and-custom-views-default-argument-handler

You're definitely going to want to look at the module code in its entirety on his github linked in the article because in the blog post he left out some crucial code (like how to define the views_argument_default_flag handler as class that extends from views_plugin_argument_default.

In my own experience, I needed a custom argument validator instead of a default argument handler, so I followed this tutorial http://www.joetsuihk.com/en/en/custom_views_argument_validator_views_plugin_argument_validate and came up with the following working result.

The need for this custom argument validator arose from needing nested or hierarchical taxonomy term names in the URL instead of the taxonomy term IDs, like /parent-category/child-category/grandchild-category.  I tried to use the contextual filter validation method of converting the term name in the URL into its corresponding term id and replace spaces with dashes, but my category names have special characters like /, &, +, and -, which meant decoding the URL didn't always match the original term name.

So, the following custom views contextual filter (argument) validator correctly parses the term name out of the URL and figures out the corresponding term id by querying the url_alias table.  After querying a particular path once, the result is cached for better performance.  To get these hierarchical paths stored in the url_alias table, I set up a pathauto pattern for my taxonomy vocabulary, like store/[term:parents:join-path]/[term:name]

The info file:

name = Example Module
package = "Example"
description = Example Module custom views argument validator
core = 7.x

files[] = plugins/example_module_plugin_argument_validate_url.inc

The module:

/**
 * @file example_module/example_module.module
 * Implement hook_views_api - load up the custom views include files
 */
function example_module_views_api() {
  return array(
    'api' => 3.0,
    'path' => drupal_get_path('module', 'example_module'),
  );
}

The views include file:

/**
 * @file example_module/example_module.views.inc
 * Defines a custom contextual filter validator
 */
function example_module_views_plugins() {
  return array(
    'argument validator' => array(
      'taxonomy_url_alias' => array(
        'title' => t('Taxonomy URL Alias'),
        'handler' => 'example_module_plugin_argument_validate_url',
        'path' => drupal_get_path('module', 'example_module') . '/plugins',
      ),
    ),
  );
}

The contextual filter handler:

/**
 * @file example_module/plugins/example_module_plugin_argument_validate_url.inc
 * Contains the taxonomy url alias contextual filter validation plugin.
 */

/**
 * Validate whether an argument (contextual filter) is a valid
 * @ingroup views_argument_validate_plugins
 */
class example_module_plugin_argument_validate_url extends views_plugin_argument_validate {

  private $intAddUnixTime = 604800;
  private $error = FALSE;

  function validate_argument($argument) {
    $view = &$this->view;
    $handler = &$this->argument;

    if (!empty($view->args)) {
      //reconstruct the url from the views argument array
      $strPath = implode("/", $view->args);

      //get the taxonomy term id based on the url, not the term name
      $objAlias = $this->getTermId($strPath);

      //split the url_alias's source column up into an array.
      //the source column contains the term id at the end of a path like 'taxonomy/term/123'.
      $arrTermData = explode("/", $objAlias->source);
      $tid = end($arrTermData);
      $term = taxonomy_term_load($tid);

      //manually assign the term id to be the view's argument
      $handler->argument = $term->tid;
      return true;
    }
    else {
      return false;
    }
  }

  /**
   * Get the taxonomy term id from either the url_alias table or from persistent cache
   * @param string $strPath like 'parent-category/child-category/grandchild-category'
   * @return object containing the result of the url_alias table or persistent cache lookup
   */
  private function getTermId($strPath) {
    $objReturn = NULL;
    //attempt to get the taxonomy term id from cached url_alias table result object
    $objReturn = $this->getCache($strPath);

    //if cache is not set, do a select query
    if ($objReturn == NULL) {
      try {
        if(!$this->error) {
          $objReturn = $this->_dbSelect($strPath);
          //cache the response
          $this->setCache($strPath, $objReturn);
        }
        else {
          //log some error because $this->error was true
        }
      }
      catch (Exception $ex) {
        $this->error = TRUE;
        //log an exception
      }
    }

    return $objReturn;
  }

  /**
   * Run a query to look up the taxonomy term id based on the url alias path
   * @param string $strPath url alias like 'parent-category/child-category/grandchild-category'
   * @return object results of the query
   */
  private function _dbSelect($strPath) {
    $result = NULL;
    try {
      //The alias stored in the url_alias table is going to be prepended with 'store/' because of my pathauto taxonomy pattern
      $result = db_select("url_alias", "ua")
        ->fields('ua', array('pid','source','alias'))
        ->condition('alias', 'store/'.$strPath, '=')
        ->condition('source', 'taxonomy/term%', 'LIKE')
        ->range(0,1)
        ->execute()
        ->fetchObject();
    }
    catch(Exception $ex) {
      //log an exception
    }

    //$result is an object like:
    //$result->pid //'12345'
    //$result->source //'taxonomy/term/123'
    //$result->alias //'store/parent-category/child-category/grandchild-category'
    //$result->uid //1
    return $result;
  }

   /**
   * Get an object from cache
   * @param  string $strPath used as part of the cache id
   * 'cache_taxonomy_url_alias' is a custom cache bin
   * @return object data from the persistent cache
   */
  private function getCache($strPath) {
    $objCache = cache_get('example_module_plugin_argument_validate_url' . '::' . 'store/'.$strPath, 'cache_taxonomy_url_alias');
    if (isset($objCache->data)) {
      return $objCache->data;
    }
    else {
      return NULL;
    }
  }

  /**
   * Store an object in cache
   * @param  string $strPath used as part of the cache id
   * @param  object $objData contains the url alias table results
   * @return void
   */
  private function setCache($strPath, $objData) {
    cache_set('example_module_plugin_argument_validate_url' . '::' . 'store/'.$strPath, $objData, 'cache_taxonomy_url_alias', time() + $this->intAddUnixTime);
  }
}

After that I selected my custom contextual filter validator:


Dont bother, your basically going to have create module for something like that and someones already done it. This is probably the best mega menu for drupal, just install and away you go. You can add anything you want to the dropdowns, views, blocks, etc.

http://drupal.org/project/om_maximenu


How to properly add inline Javascript code to a webform with javascript injector module

You need to use proper Drupal jQuery Syntax.

Screw the js injector module, you can do the same like this:

Create a block, for Text format select Full HTML and put this code

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>

(function ($) {
$( document ).ready(function() {

$( "#edit-submitted-startdate,#edit-submitted-enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#edit-submitted-startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#edit-submitted-enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#edit-submitted-enddate').change(function() {
var start = $('#edit-submitted-startdate').datepicker('getDate');
var end   = $('#edit-submitted-enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#edit-submitted-days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#edit-submitted-startdate').val("");
$('#edit-submitted-enddate').val("");
$('#edit-submitted-days').val("");
}
});

});
})(jQuery);

</script>

Place the block in some region.

For Visibility Settings

Pages, select only listed pages and type the url for your webform.


Commerce - Require login only for specific products

You could use Rules to enforce login when the product is added to the cart.

e.g

Event: Before/After adding product to cart
Conditions: if user is not logged in (i.e. uid=0) and product match (e.g SKU matches)
Action: Redirect to user/login?destination=cart

Something like that could suffice.


The best way to do this is almost always by using the features module.

That being said if you do not want to use feature this is how you can do it.

In your module you're going to want to define a hook_image_default_styles().

If you already have a style on the database that you would like to define in this hook the best way to accomplish this is by doing something like

$style_name = "name_of_your_style";
$style = image_style_load($style_name);
//$style now has everything you need for your hook_image_default_styles definition.

It does has some extra stuff in there that can be removed such as the isid, ieid, and storage keys. You should remove those keys when using hook_image_default_styles.

If you want to find out how other items are exported out the best bet would be to look at the feature module. In there there's a directory call includes. There's going to be a file in there for everything that can be exported out in core. So you can use that for examples on how to export out styles, filters, field, etc.

Hope this answers your question.


Ubercart: PHP message if a Product is in cart

Create a block with input format as php code.  uc_cart_get_contents() function will help you to get current cart products. So use it to check for your products.

eg:

$items = uc_cart_get_contents();
// print_r($items); you can see all items in cart
foreach ($items as $item){
  //check your condition if condition true print your message,
}

Assign the block to a specific region and give display in cart page only


Rewriting a link field to link to 2 different places depending on what's given

The problem lies in trying to use the 'link to original content' in 'no results'.

Try putting the fields in this order with these formats:

Title - just plain text
Link to content - raw URL
Website field - raw URL

Then set Rewrite Results to [title]

And set No Results Behaviour to [title]

Note you'll have to find the right token for the links in the Replacement Patterns section that shows up when you tick 'Rewrite the output of this field'

Don't use 'Output this field as a link' or the link will apply to the No Results Behaviour as well, I think.


How to generate a downloadable CSV file from a View table?

You can create/export CSV files from Views in Drupal 7 with the Views Data Export module.  The module is currently in Beta.


Out of memory error in composer when requiring drupal/bootstrap

This is related to your php.ini file's memory_limit entry which defaults to 128M. You need access to your server's php configuration file. If you do here is the step by step for making that change on an Ubuntu server with PHP 7 and PHP CLI extension.

Open the PHP CLI configuration file located at /etc/php/7.0/cli; e.g. I use vim as follows sudo vim /etc/php/7.0/cli/php.ini
Search for the line containing memory_limit by pressing the / (forward slash) key, type the phrase memory_limit and press enter.
Once on that line go to vim's insert mode by pressing 'ESC' followed by 'i'.
Change the value for the memory_limit to something higher, e.g. memory_limit = 1024M since you already have 512M for the limit.
Save and exit the configuration file by pressing 'ESC' type in 'wq' and then press 'enter'.

If you don't see any changes it could be that you have an error in you php.ini configuration file. You are always welcome to comment on the answers to get more help.


You need to introduce the argument as a 'wildcard', and pass it through to your function in the page arguments like so:

$items['subscribe/verify/%'] = array(
  'title' => 'Verify Email',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('subscribe_terms_form_verify', 2),
  'access arguments' => array('access content'),
);

The hook_menu() docs are worth read, they explain wildcards in good detail.

Your form function will have this signature:

function subscribe_terms_form_verify($form, &$form_state, $unique_id) {

}

$form and $form_state are provided as parameters to your form through drupal_get_form(), so the 3rd argument will contain the information passed from the URL.


How can I have admin language English and frontend language another?

First go to Administration - Configuration - Regional and language - Languages - Detection and selection tab and make sure to have “Account administration pages“ enabled.

Then go to People and edit your user. Go down to the Language settings section. You should now see a Administration pages language dropdown. Select and save.


For each image uploaded in a node: get the url

Giving field_shooting_photos is a multi valued field of Files, this is how to generate your array of URI :

$photoUrls = [];
foreach($shooting->field_shooting_photos->referencedEntities() as $image) {
    $photoUrls[] = $image->getFileUri();
}

For media image :

$photoUrls = [];
foreach($shooting->field_shooting_photos->referencedEntities() as $media) {
    $photoUrls[] = $media->field_media_image->entity->getFileUri();
}

Note this will give you the File_id of the first image in the entite file reference list :

$shooting->field_shooting_photos->target_id;

NB : Best way is probably to generate render array or use built-in drupal themes, is none fit your needs, your may also generate a custom field formatter.


Access table form field's data from submitForm

Sorry, I must have overlooked the way you built the form. Unless you make your values in the table row part of the form, you cannot submit them. I changed the row '#type' to a text field and added a default value, in that way you can now pass that along with your form.
Try this:

public function buildForm(array $form, FormStateInterface $form_state)
{
    $form['name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Name'),
        '#required' => true,
    ];

    $form['template_components_list'] = [
        '#type' => 'table',
        '#caption' => $this
        ->t('My table.'),
        '#tree' => TRUE,
        '#header' => array(
            $this
            ->t('row_name'),
            $this
            ->t('description'),
            $this
            ->t('actions'),
        ),
    ];

    $form['template_components_list'][0]['row_name'] = array(
        '#type' => 'textfield',
         '#default_value' => 'Test1'

    );

    $form['template_components_list'][1]['row_name'] = array(
              '#type' => 'textfield',
         '#default_value' => 'Test2'

    );

    $form['actions'] = [
                '#type' => 'actions',
            ];
    // Add a submit button that handles the submission of the form.
    $form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => $this->t('Submit'),
            ];

    return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state)
{

   $SubmittedValues = $form_state->getValues();
   print_r($SubmittedValues);
   //Now you can access the form values as an associative array
    \Drupal::logger('some_channel_name')->warning('
' . print_r('START', TRUE) . '
');
    \Drupal::logger('some_channel_name')->warning('
' . print_r($SubmittedValues['row_name'], TRUE) . '
');

    \Drupal::logger('some_channel_name')->warning('
' . print_r($SubmittedValues['template_components_list'], TRUE) . '
');

    \Drupal::logger('some_channel_name')->warning('
' . print_r('END', TRUE) . '
');
}


get views customfield php value in another field

You should use the views_php module instead. It is the successor of Views Customfield PHP. The current module you are using does only render content, but has no value. views_php introduce the possibility to define both value and rendering settings. You should then be able to use the generated value in other fields.


Can't update hook_theme after clearing the cache

After doing a bit more reading I restarted my MAMP server and switched themes, then back again. I'm not sure which did it but it's working now...


Alter the results returned by "Display a summary" for the Addressfield module

Here is an alternative to @Kenny and @Bearden solution, using template preprocess instead of overriding the template. Not only it makes for a more readable solution, you can reuse it for other views. It should also work for list summaries, just remove _unformatted from the function name.

/**
 * Implements hook_preprocess_views_view_summary_unformatted().
 */
function MYTHEME_preprocess_views_view_summary_unformatted($variables) {
  if ($variables['view']->name == MYVIEW) {
    // Necessary for country_get_list().
    include_once DRUPAL_ROOT . '/includes/locale.inc';
    $countries = country_get_list();

    // Looping through the row keys for performance reasons.
    foreach (array_keys($variables['rows']) as $rowid) {
      $countryid = $variables['rows'][$rowid]->link;
      if (!empty($countries[$countryid])) {
        $variables['rows'][$rowid]->link = $countries[$countryid];
      }
    }
  }
}


Are you sure that your database server was offline when you tested ? The API description says

  "maintenance-page--offline.tpl.php" can be used when the database is offline to hide errors and completely replace the content.


You need to override theme_pager function in your template.php

You need to do couple of changes,

Use global $pager_limits variable, use in pager list rendering links to alter text data

Use below code which works

function YOURTHEMENAME_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];

  global $pager_page_array, $pager_total, $pager_limits;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('« first')), 'element' => $element, 'parameters' => $parameters));
  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ previous')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('next ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('last »')), 'element' => $element, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {
    if ($li_first) {
      $items[] = array(
          'class' => array('pager-first'),
          'data' => $li_first,
      );
    }
    if ($li_previous) {
      $items[] = array(
          'class' => array('pager-previous'),
          'data' => $li_previous,
      );
    }

    // When there is more than one page, create the pager list.
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
            'class' => array('pager-ellipsis'),
            'data' => '…',
        );
      }
      // Now generate the actual pager piece.
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
              'class' => array('pager-item'),
              'data' => theme('pager_previous', array('text' => ((($i - 1) * $pager_limits[0]) + 1) . "-" . $i * $pager_limits[0], 'element' => $element, 'interval' => ($pager_current - $i), 'parameters' => $parameters)),
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
              'class' => array('pager-current'),
              'data' => ((($i - 1) * $pager_limits[0]) + 1) . "-" . $i * $pager_limits[0],
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
              'class' => array('pager-item'),
              'data' => theme('pager_next', array('text' => ((($i - 1) * $pager_limits[0]) + 1) . "-" . $i * $pager_limits[0], 'element' => $element, 'interval' => ($i - $pager_current), 'parameters' => $parameters)),
          );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
            'class' => array('pager-ellipsis'),
            'data' => '…',
        );
      }
    }
    // End generation.
    if ($li_next) {
      $items[] = array(
          'class' => array('pager-next'),
          'data' => $li_next,
      );
    }
    if ($li_last) {
      $items[] = array(
          'class' => array('pager-last'),
          'data' => $li_last,
      );
    }
    return '
' . t('Pages') . '
' . theme('item_list', array(
        'items' => $items,
        'attributes' => array('class' => array('pager')),
    ));
  }
}

And the result you can see below.


How to check all checkboxes in a Views exposed filter by default?

If you click on the filter in the Views admin UI to get to the "Configure filter criterion" popup, and then select all of the options for the filter like so:

Then they appear ticked by default when you access the View page.


Try this for Drupal 7 documentation:

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      // code here
      // example function call
      Drupal.behaviors.myModule.exampleFunction();
    },
    exampleFunction: function () {
      // code
    }
   }
 })(jQuery);


Go to Admin -> People -> Permissions, and uncheck any permissions for anonymous users.

Go to Admin -> Configure -> People -> Account settings, and under 'Who can register accounts?', choose 'Administrators only'.


you could put those links in a menu and have that menu included to your xmlsitemap.


Is there a way to add infinite number of Add More on webforms in Drupal 6

I believe the answer is no. At least I've never found a way to do it. I've always had to add 10+ fields and use webform_conditional to hide them until they fill in one and then show the next, or provide a drop down so they can select how many fields to fill. Not ideal but I'm not sure any other way to do it.


How can I make a link to a node obtained from an SQL query?

foreach($result as $record)
{
  $list['#links'][] = array('title' => $record->title, 'href' => $account->name . '/' . $node->title);
}

You have $node->title in this code, but there is no $node object.  The href appears to be the user's name, and then the title of a node?  So the link would be http://example.com/johndoe/My Page Title, which doesn't seem right.

Is this what you're trying to do?  First, add node.nid to your list of SQL columns

foreach($result as $record)
{
  $list['#links'][] = array('title' => $record->title, 'href' => 'node/' . $record->nid);
}

You might also look into bypassing the $list array, and the drupal_render() function, and simply use:

$links = "
";

foreach($result as $record)
{
  $links .= "
" . l($record->title,'node/'.$record->nid) . "
";
}

$links .= "
";

return $links;


How to print barcode labels on standard printer drupal?

You have to set the permissions right. try 'chmod 755 -R /var/www/html/transgenic/sites/default/files/barcodes' Do this with the same account as the webserver uses.


Assuming the author of the blog is the same as the field and content type 'author' when a blog is created, I would suggest using core profile information for the author and use the Author Pane Module:

  Author Pane is a block of information about a given user, like those
  typically found on a forum post, but can be used in other places as
  well. From core, it collects the user picture, name, join date, online
  status, contact link, and profile information. In addition, any module
  or theme can feed it more information via the preprocess system. All
  of this information is then gathered and displayed using a template
  file.


How do I disable Commerce cart order refresh to preserve custom prices on line items?

You're approaching the problem incorrectly here. You shouldn't be trying to disable the cart order refresh. That includes things like discounts, taxes, etc. that may actually need to be applied to line items on the order in the future.

Instead, you should find a strategy to enrich the line item with the information it needs to reset the price to the proper custom price during the pricing process. This is the approach utilized in our old donation examples where customers can enter custom prices to donate:

https://drupalcommerce.org/videos/tutorials/donations-custom-line-item-types

I have no experience with the module you're using, so I can't say how to keep working within the framework it provides. Generally speaking, though, you could make this work by adding a price field to the line item called "Custom price" or something and then creating a pricing rule that sets the unit price of line items to the custom price at the appropriate point in time.

Alternately, you could store the necessary information in the data array of the line item, but then you'd still need a product pricing rule with a custom action that knows how to inspect the data array and reset the unit price to the appropriate amount.


The order of includes should be reversed (as you did). There is also accompanying css file and the following initialization js code (see examples src http://github.com/downloads/dimsemenov/PhotoSwipe/code-photoswipe.v1.0.11.zip).

<script type="text/javascript">

        // Set up PhotoSwipe with all anchor tags in the Gallery container
        document.addEventListener('DOMContentLoaded', function(){

            Code.photoSwipe('a', '#Gallery');

        }, false);
</script>


Instead of printing the form when you load it, create a new form item of type markup and add your subform there as markup.

$form['subform'] = array(
  '#type' => 'markup',
  '#markup' => $location,
);

This would fix the display order but your submit handler will need to handle the extra items.


Ubercart Coupon - only allow one coupon per order, but always apply the most recently entered one

The answer is very simple but will only work if you do not want to allow multiple coupons per order.

Visit /admin/store/settings/coupon and uncheck "Allow multiple coupons to apply to a single order"; Save the configuration.  Now the most recently applied coupon will be the only one added to the order.


How can I prevent or limit CRON during SimpleTest?

I didn't find a way to know directly whether SimpleTest is running. For now, I am checking a role that the module creates for users. If there are no users of that role, I assume its SimpleTest running and limit my CRON.


How to print add to cart form for drupal 8 commerce on my custom page programatically

I got solution to the above problem. I used a drupal commerce service to load the form. Below is the code which I used, please let me know if it is an acceptable solution.

$commerceProduct = \Drupal::service('commerce_product.lazy_builders');
$cart_array = $commerceProduct->addToCartForm($product_id, 'teaser', true, $language);

This gave me a renderable array which I rendered using render service. Add to cart form is working fine.


A better solution might be to add a link on the page that the user sees after the form, that takes them back to the form. You might need to put back in some session values. If the form was already submitted, you'll want to decide whether to load their submission or take them to a blank, new form.


The format shouldn't dependent on the Drupal version, most likely you're running Drupal 7 and 8 on different PHP version which may use different Xdebug.

Since XDebug 2.3, the format of cachegrind files changed and WinCacheGrind does not support this new Callgrind format yet.

So you should use XHProf, or different software which may support it, depending on your operating system.

See also: Missing function names when opening CacheGrind file in WinCacheGrind.


Is it true that CCK has no API to work with from other modules?

No, it's not true.

CCK does its field processing when node API hooks are invoked, so when you (or another system process) call node_save(), CCK will run through the node object and save any field values it needs to.

For example, this code would load a node, change the value of a field called field_my_field, and then save that to the database:

$node = node_load($nid);

$node->field_my_field[0] = array('value' => 'Some new value');

node_save($node);

There are also CRUD functions in includes/content.crud.inc which will come in handy to create fields and instances on the fly.


The above steps were correct. Additionally however, you need to add Author >> Name to the Fulltext search filter criteria in the view.


How can i add multiple instances of newsletter subscriptions?

Each block can be configured in different ways. You can by default give different paths to show or not show your block. Go to /admin/structure/blocks and click on "configure".

If you need more advanced settings, then have a look at the Context module. This allows you to define all kind of rules and conditions to show a block. Very powerfull.


It would appear that this is a very good candidate for your issue:

http://drupal.org/node/997444

Assuming you have altered your navigation menu, which many people will do when they are new, you may have inadvertently removed your access. Re-enable this access and you should be good to go. If this does not solve the problem I do not know what it would be.


How can I pass an array from a controller to a template?

You have to add the testmenu variable to the hook_theme implementation, like this:

function mdoner_custom_theme($existing, $type, $theme, $path) {
  return [
    'mdoner_custom_block' => [
      'variables' => [
        'title' => NULL,
        'testmenu' => [],
      ],
    ],
  ];
}

Then you have to pass it to the render array in your build() function like this:

return array(
  '#theme' => 'mdoner_custom_block',
  '#title' => 'MDoNER custom Block',
  '#testmenu' => $term_data, // #testmenu refers to the testmenu variable you set in hook_theme().
);

Now you should be able to iterate over the items in the testmenu variable like this:

{% for key, value in testmenu %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}


Permisssions based on file folders & content collection

The FileDepot module should do what you want.


How to remove the core stylesheets from a theme

Also, you can exclude a whole library at all by adding:

libraries-override:
  system/base: false


How to show snippet of an event when clicked in the calendar in Drupal 7 with the Calendar Module

There are probably many different ways of doing it.

One possibility is the Calendar Tooltips module.

Another is using Colorbox module to control the popup, you construct the Views output yourself so that the Colorbox library displays it as a popup: Does Calendar Popup Module exist in D7?, using-colorbox-display-event-details-popup


This is a known issue, whose fix didn't make it into the Drupal 7 core so far. The culprit can be found within the _drupal_exception_handler(). If another error occurs while handling an exception, it just returns the messages stated in your question without setting HTTP status codes (possibly to avoid further exceptions).

Compare https://www.drupal.org/project/drupal/issues/2666908

The above issue already has a small RTBC patch that solves the problem by adding a 500 status code to the handling of the second exception:

function _drupal_exception_handler($exception) {
  require_once DRUPAL_ROOT . '/includes/errors.inc';

  try {
    // Log the message to the watchdog and return an error page to the user.
    _drupal_log_error(_drupal_decode_exception($exception), TRUE);
  }
  catch (Exception $exception2) {
    // Add a 500 status code in case an exception was thrown before the 500
    // status could be set (e.g. while loading a maintenance theme from cache).
    drupal_add_http_header('Status', '500 Internal Server Error');

    // Another uncaught exception was thrown while handling the first one.
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
    if (error_displayable()) {
      print '
Additional uncaught exception thrown while handling exception.
';
      print '
Original

' . _drupal_render_exception_safe($exception) . '
';
      print '
Additional

' . _drupal_render_exception_safe($exception2) . '

';
    }
  }
}

Given the age of that patch, the line numbering differs a little from the current version of bootstrap.inc. But it still applies cleanly and works as expected.

After you patched your Drupal, you should be able to receive the 500 error code at your load balancer, if Redis is down or the error page can't be created for another reason.

Please note, if your Drupal already sent headers/output to the browser before the error handler kicks in, above patch may have unintended side-effects. You may have to test yourself, whether your webserver still generates 500 server errors for these edge cases.


Simple OAuth + JSONapi response when token is expired - Decoupled

Is there a reason why this is implemented like this?

200 ok is expected status code for collection resources, even if one, many, or all entities were excluded from the collection resource for access reasons.
From https://www.drupal.org/project/jsonapi/issues/2853066:

The status code for a "collection resource" should be entirely distinct from any or all of the entities represented at that resource.
Unless there is an access control mechanism that is explicitly a prerequisite for accessing any list of entities of a given type that we can leverage, then it must be assumed that any consumer must have access to any collection resource.
It is completely consistent with REST to return a 200 response to an empty collection, even when all those entities have been elided for access reasons.

Or is there a way to alter the response?

Of course, you can. Check the documentation about altering routes and providing custom access tagged service:

https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones
https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes

Finally, the link you provided in the question is to oauth specs, and is irrelevant to jsonapi. Oauth resource in Drupal (/oauth/token) will correctly give you 4xx in case of any errors when obtaining a new token.


Can't save custom field data: form submit function doesn't fire

If you add the custom field through hook_form_alter. You need to store the data manually in your custom table by using your custom submit handler..    Otherwise you could use the below code in your *.install file

function MYMODULE_enable() {
  // Check if our field is not already created.
  if (!field_info_field('field_myField')) {

    // Create the field base.
    $field = array(
      'field_name' => 'field_myField',
      'type' => 'text',
    );
    field_create_field($field);

    // Create the field instance on the bundle.
    $instance = array(
      'field_name' => 'field_myField',
      'entity_type' => 'user',
      'label' => 'My Field Name',
      'bundle' => 'user',
      // If you don't set the "required" property then the field wont be required by default.
      'required' => TRUE,
      'settings' => array(
        // Here you inform either or not you want this field showing up on the registration form.
        'user_register_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );
    field_create_instance($instance);
  }
}


How do you get the tid from a taxonomy term page?

You can use menu_get_object():

$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  $tid = $term->tid;
}


Interesting question. Since the $form_state variable is passed by reference to all form validation & submit handlers, you can modify it prior to it reaching the submit handler that saves it. What about adding a new validation handler that will empty the $form_state['values']['field_2'] value if the field is disabled in $form? That should ensure that the field is empty by the time anything tries to save it.


How do I detect if Twig is in debug mode?

I have found the solution to my question, by looking at the dump() function definition in the devel module.

Passing the Twig_Environment object into my function, I can use the isDebug() method:

public function myfunction(\Twig_Environment $env, $string) {
  if($env->isDebug()) {
    $string = 'foobar';
  }
  return $string;
}