I would use the organic groups module. The idea is to create a content type lets say "userprivatedir" make this a og group and a allow users to create one or more nodes of this type. By default the creator of a og group is the owner of this group. Then i would create another content type lets say "userfile" and make this a og content. Then you may configure og so only the members of the group (i.e. the user that created it has access into it). The "userfile" content type should have a file field that stores files in the drupal private filesystem (so files are not accessible just by hotlinking but only through their node page.

Also if you dont want user to be able to upload at his own  "userprivatedir" (i.e. og group node) then create the group node by another manager user and then add only this user (or maybe some more that should see this directory's files) to this node group so they have access.


How to print a raw field value containing special characters in a node template?

Something like $row->field_link['und'][0]['value'] should give you the field. For security you should use  $row->field_link['und'][0]['safe_value'] but I don't know how the link will be affected in this.
Drupal has a nice function called debug(), which can output arrays, objects etc. as drupal_message. It helps to see how the arrays are built up ;)


Found the solution here: can't edit panels page with highcharts chart in quicktab (w/ workaround)


Add a subquery to SELECT'd columns in a dynamic query

You can use db_query()

$result = db_query(
  'SELECT a, b, (
    SELECT x, y
    FROM {table}
    WHERE table.x = :value1) as c
  FROM {table_2} AS table_2
  WHERE table_2.a = :value2',
  array(
    ':value1' => 'value',
    ':value2' => 'value_2',
  )
);


You update another translation by getting an object for that language, and then you set the values of those fields.

$translation->set('field_my_field', 'my en value');
$translation = $term->getTranslation('ja');
$translation->set('field_my_field', 'my ja value');
$term->save();

Those translation objects are actually shallow clones that have a different internal active language code, so you can update multiple translations and then save, for example.


?format=json returns 'Not acceptable format: json'

\Drupal\rest\RestResourceConfigInterface is a namespace not a directory structure.

Configuration files need to be imported into the active configuration which is stored in the database.

In the case of a single config file:

Go to the
page /admin/config/development/configuration/single/import
Under "Configuration type" select "REST resource configuration" In the box
At "Paste your configuration here" paste your REST YAML configuration

Configuration can be exported and imported using the config directory, as specified in settings.php with the line $config_directories['sync'] = 'sites/default/config';.

To export the current active configuration to files in the sync directory use the drush command: drush config-export

To import configuration from files in the sync directory and overwrite your current active configuration, go to the page /admin/config/development/configuration.

Another option is to use the REST UI module to configure your REST services.


How can I programmatically copy all blocks of a given theme into the same regions of a new theme?

You can entity query your relevant block config then create a cloned entity object via Block::createDuplicateBlock() then modify the sub-theme clones before saving the new block config into sub-theme region.

For example:

$block_ids = \Drupal::entityQuery('block')->condition('theme', 'my_base_theme')->condition('region','my_region')->execute();
foreach ($block_ids as $block_id) {
  $parent_block = \Drupal\block\Entity\Block::load($block_id);

  $new_id = str_replace('my_base_theme', 'my_sub_theme', $parent_block->get('id'));
  $child_block = $parent_block->createDuplicateBlock($new_id, 'my_sub_theme');
  // @TODO: set other properties that might need to be unique to this new theme's block

  $child_block->save();
}


Can a Drupal Site Administrator view contents of settings.php or some other file in file system?

For brevity, it helps to think about this question in terms of roles/permissions (since "site admin" is an overloaded term):

Does the ____ role have an escalated permission to:

Write arbitrary files to the server?
Execute arbitrary code on the server?

If the first/second answer is "Yes," the answer would be:

____ role could probably come up with a clever way to read the entire contents of settings.php by injecting/running arbitrary code.

Generally, Drupal core tries to signal these potentially dangerous permissions with this warning:

  Warning: Give to trusted roles only; this permission has security implications.

However, there are many contrib modules out there that could have exploits (some known, some not) so you'll always have to take pro-active security steps like the principle of least privilege (if a role doesn't need a privilege to do the job, don't give it to them).

This also applies to your whole system (DB, web server, etc.), not just Drupal.


Programmatically disable content translation options in content edit form

You can not access to content_translation property in the hook_form_alter but you can do it in after_build callback.

  after_build: runs after the form or element is built for display.

Try with the following:

Add #after_build to the form:

/**
 *Implements hook_form_alter().
 */
function myModule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_YouContentType_edit_form') {
    $form['#after_build'][] = 'myModule_after_build';
  }
}

Implement your after_build function

    function myModule_after_build($form, &$form_state){
      $form['content_translation']['#access'] = FALSE;
      return $form;
    }


Why a module has a package for a 8.x-3.0-beta1+54-dev version?

The 8.x-3.0-beta1+54-dev version means the development snapshot is 54 commits ahead of the 8.x-3.0-beta1 version. Similarly, 8.x-1.1+1-dev means the development snapshot is one commit ahead of the 8.x-1.1 version.
Since development snapshots can change much during time, it is probably a way to make better understand how much the development snapshot changed.
Notice that 8.x-3.0-beta1+54-dev is the version reported from the page listing all the installed modules or in the .info file for the module (as you shown, between the lines added by the Drupal.org packaging script).

(The screenshot is for Drupal 7.)

It's not the title you see for a release node in the page showing all the releases (for the Field Group module, in this case), where the release is field_group 8.x-3.x-dev.
To answer your question, it's not a custom syntax. It's the version that the Drupal packaging script adds in the .info file for development snapshot releases, which could then be used in the user interface when showing the installed project version.
The Drupal.org packaging scripts alter the .info file when creating the archive for the project. If the project is copied using Git or Composer, for example, that information is not present, and the version wouldn't appear as 8.x-3.0-beta1+54-dev. (This is also the reason why I took the screenshot from a Drupal 7 instance created on simplytest.me.)


Determine Next Item in DrupalQueue for Drupal 7

SystemQueue::claimItem has the code you're looking for. https://api.drupal.org/api/drupal/modules%21system%21system.queue.inc/function/SystemQueue%3A%3AclaimItem/7.x

You can run the same query that will be used to get the next item in the queue. Just replace $this->name in the code below with the queue name.

    $item = db_query_range('SELECT data, item_id FROM {queue} q WHERE expire = 0 AND name = :name ORDER BY created, item_id ASC', 0, 1, array(
      ':name' => $this->name,
    ))
      ->fetchObject();

$item should have everything you're looking for.


The $directory variable doesn't contain the correct value

if you want to find the folder of your theme you have to use something like this:

<?php echo drupal_get_path('theme','your_theme').'/images/whateverfile.ext'; ?>


As pointed out in my comment above, most of the details are wrong in your implementation above. Fortunately in Drupal 7, there are six theming functions for the pager:

theme_pager()
theme_pager_first()
theme_pager_link()
theme_pager_last()
theme_pager_previous()
theme_pager_next()

These should allow you to make most of the customizations that you need. There's a good stackexchange answer about how to override Drupal theme functions() that you can refer to for the details.

Finally, you mentioned that you want to override the pager just for one page. I still think this might be worth doing with CSS alone, but in case it's not, you may be able to just override parts of the $variables array in whichever preprocess function contains the pager (I don't know off the top of my head if it's preprocess_page or preprocess_node or if it's accessible from any of the preprocess functions at all).


How to load the images in views using ajax?

Check out Image Lazy loader module

  This is a small helper module which will automatically lazyload all
  images for sites with multiple images, which will make the site load
  faster.

  All images will only load when it's visible to the browser window.


How to force account creation before commerce checkout is complete?

I suggest the following steps :

create a custom checkout pane (see  checkout_pane_example.module ) and embed the user register form in that pane:

/**
 * Implements hook_commerce_checkout_pane_info().
 */
function vts_register_commerce_checkout_pane_info() {
  $panes['register'] = array(
    'title' => t('Create an account'),
    'base' => 'vts_register_pane',
    'name' => t('NAME'),
    'page' => 'checkout',
    'weight' => -5,
  );
  return $panes;
}
/*
 * Add user_register_form to register pane
 */
function vts_register_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
  $pane_form = drupal_get_form('user_register_form');
  return $pane_form;
}
/*
 * Alter checkout form register pane
 */
function vts_register_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  unset($form['register']['actions']);
}
/**
 * checkout form submission callback.
 */
function vts_register_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
  $new_user = array(
    //dsm to find the correct $form_state['input'] for username here, because I have an altered user register form...
    'name' => $form_state['input']['field_name_first']['und'][0]['value'].'_'.$form_state['input']['field_name_last']['und'][0]['value'],
    'pass' => user_password(),
    'mail' => $form_state['input']['mail'],
    'init' => $form_state['values']['mail'],
    'status' => 1,
    'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),
  );
  if($GLOBALS['user']->uid == '0') {
    $user = user_save('', $new_user);
    //ASSIGN the current order to created user
    $order->uid = $user->uid;
    commerce_order_save($order);
    $GLOBALS['user'] = $user;
  }
  //check that you got a new user and the order was assigned to him
  dsm($user, 'user');
  dsm($order, 'order');
}
/**
 * Validation callback.
 */
function vts_register_pane_checkout_form_validate($form, &$form_state, $checkout_pane, $order) {
  //validation stuff
  return TRUE;
}
/**
 * Ouputs Review checkout pane.
 */
function vts_register_pane_review($form, $form_state, $checkout_pane, $order) {
  // add some info to review pane
  return;
}

Go to admin/commerce/config/checkout and set it as disabled
Install Commerce Rules Extra, it adds the features you need :

  Rules conditions : Total product of type quantity comparison

  Rules actions : Change pane properties : Change visibility, page, weight of a pane

Create a rule :

Event: Process checkout pane.
Conditions : user is anonymous ; subscription product quantity > 0.
Action : Change pane properties : enabled: true; move to checkout.


This isn't Views behaviour, it's standard for the Drupal menu system. Extra path components (separated by slashes) are ignored if they don't match a more specific menu entry. So if you have a menu entry for path xxx/yyy it'll also receive requests for xxx/yyy/zzz and xxx/yyy/zzz/aaa.

Rather than a 404, why not serve a 301 redirect? That's better for SEO. If you can't do that at the server level (always preferable for performance) then a module such as https://www.drupal.org/project/match_redirect might help.

See: https://api.drupal.org/api/drupal/includes%21menu.inc/group/menu/7

  When responding to a page request, the menu system looks to see if the path requested by the browser is registered as a menu item with a callback. If not, the system searches up the menu tree for the most complete match with a callback it can find. If the path a/b/i is requested in the tree above, the callback for a/b would be used.


PaymentMethodManager() get plugin on NULL ubercart error

You can fix this error by applying the patch here: https://www.drupal.org/project/ubercart/issues/2826324


What Hook to Use to Execute a PHP on Header and Footer in Every Page?

hook_init() is run at the beginning of the page request. So this is where you should start your timer.

hook_exit() is run at the end of most regular page requests. And it's here you should stop your timer.

I did a search on similar modules and found Arooga, maybe you can find some ideas there. Also Devel has functionality to log page execution time, slow queries etc.


You may need to rename the CSS file.

  The word "style" can not be used in the name, like "myown_style.css".
  It will conflict with the default style.css. Anyhow, myownstyle.css
  will work.

See Adding style sheets from .info files for more details.


How do I change the Date module to get 'days back and forward'?

You need to implement hook_form_alter() to add a new form validation handler. To avoid any conflict with the existing validation handler, you should probably remove the existing one added from the Date module, if there is one.


How do I theme a block created with the Views module?

I'm not perfectly sure what you are asking...

If you want to theme a view then you can add a css class name under the advanced drop-down, or add a  css class to any field.

Or are you looking to adjust how a block appears using views?


Custom Views Sort Order Using Filter Value

In the end, my client agreed this feature was overkill and it was ommitted but I thought of a way it could be achieved.

Potential Solution

The following is only feasible if you have a finite and relatively low number of filter values because you need to create a field for every filter value.

Create a field of type boolean for every filter value.  In our case we had 10, 11, 12, 1, 2, 3 as potential values for hour and 00, 15, 30, 45 for minute.  24 possible combinations, so 24 fields need added to the event type.
The field should be named according to the filter combination, e.g. Sort: 10:00, Sort: 10:15 etc.
The field value should be set as either 1 or 0.  If the event start time matches the time in the name of sort field then this should be set to 1 otherwise it should be set to 0.  hook_node_insert and hook_node_update could be used to set the values.

E.g on each event you would have:

Start Time - 11:00

Sort 10:00 - 0
Sort 10:15 - 0
Sort 10:30 - 0
Sort 10:45 - 0
Sort 11:00 - 1
etc (the rest would be set to 0).

When the filter is applied, use hook_views_query_alter to grab the filter value.  Then set the sort based on that field.

E.g if the user entered 11:00 as the filter value, we could force the sort to use the Sort: 11:00 field.  The following is written off the top of my head, so would need some tweaks:

function my_module_views_query_alter(&$view, &$query) {
  if($view->exposed_input['field_start_time'][0]['value'] == "11:00am") {
    $view->query->orderby[0]['field'] = "field_data_field_sort_11_00_value";
    $view->query->orderby[0]['direction'] = "DESC";
    // Add any secondary sorts.
  }
  else if($view->exposed_input['field_start_time'][0]['value'] == "11:15am") {
    $view->query->orderby[0]['field'] = "field_data_field_sort_11_15_value";
    $view->query->orderby[0]['direction'] = "DESC";
    // Add any secondary sorts.
  }
}


Creat a test user with no access permisions

I would say to create a role that has access to content, grant that to the existing users, then uncheck "access content" from the 'Authenticated' role. This will also allow the system to know that even if a user is logged in, this does not grant them special privilege until they have an elevated role assigned to them.

The authenticated role should be just a starting point for a user that logs in. I never leverage it for granting permissions in a way that would make it a 'unique' role - just make that role. Otherwise you are going to have to jump through hoops with code which can be easily avoided by creating a few roles.

You can assign a user multiple roles. During authentication, I take it you can figure out how or what role to assign to them. Every authenticated user will get the 'authenticated' role by default.


Sending email only to active (unblocked) users of the site

Add a category in Mass Contact

http://localhost/sitename/admin/config/system/mass_contact/add

and "Roles to receive e-mail" , just check "authenticated user" and save configuration.

And "authenticated user" are active user not the blocked user.


Undefined index: und in mytheme_preprocess_page()

For a field, $entity->$field_name['und'] is not always defined. Instead of the code you are using, you should use the following code.

if (isset($node->field_banner)) {
  // Render the image as a variable in the page template.
  $field = field_get_items('node', $node, 'field_banner');
  $vars['banner'] = theme_image_style(array('path' => $field[0]['uri'], 'style_name' => 'mybannerstyle', 'height' => '200', 'width' => '700'));
}

I would also consider using field_view_value(), instead of fields_get_items(), but the first function doesn't allow to customize the output, if not through the $display parameter. (See field_view_field() for a description of that parameter.)

field_get_items() and field_view_value() get the language ID from field_get_name(), which returns the correct value for the language to use for the field.


How to generate my own patches to update core for security when fuerstnet.de's "Drupal upgrade the easy way" page is out of date?

Per https://www.computerminds.co.uk/articles/quickly-update-drupal-core, Github itself can create patch-files for you. You can use commandline curl or wget to download the appropriate patch easily:

curl 'https://github.com/drupal/drupal/compare/7.66..7.67.patch' > "drupal-7.66-to-7.67.patch"

Alternatively, you can download the tar'd (or zipped) packages for both your current version of Drupal and the target and recursively diff them as described here, resulting in a functionally-identical patch-file.

This can then be tested out in the normal way:

patch -p1 --dry-run < "drupal-7.66-to-7.67.patch"

And then applied if no hunks failed:

patch -p1 < "drupal-7.66-to-7.67.patch"

Note of course that just because patching succeeded, it doesn't mean the successfully-applied patch hasn't broken your site in some way, so be sure to  back up everything (files and Drupal database) before patching, trying this first on your dev site, running tests, etc. before repeating the process for real in production.

Gotcha!

If you've upgraded using fuerstnet.de before, Drupal may falsely continue showing security-update warnings, because at least one package with $file->info['project']=='drupal' and $project['project_type']=='core' will still be considered out of date. That's because some of your .info files may contain extra lines which override standard version-numbers:

; Information added by Drupal.org packaging script on 2019-04-17
version = "7.66"
project = "drupal"
datestamp = "1555533576"

Based off of experience, generating your own patch as described above will not remove this information, since it is not present in the vanilla packages, and the files containing these extra lines won't necessarily fail to patch either, if no changes to the vanilla editions' code occurred in the last update. (Common because .info files don't change very often.)

These extra lines need to be removed (or adjusted, if you prefer) before Drupal will stop complaining that you're behind on core updates, even though you're actually up-to-date.


Set All Day checkbox on date field programmatically

I found a "hacky" way of doing this. A couple things I noticed after investigating further is that the All Day single day events in Drupal are set to the same time on both the start and end dates. So first I changed the time of each date format to 05:00:00, just a random time but the same time for both.

This seemed to trigger the All Day checkbox which is great. But single day events were still showing as if they spanned over 2 days, not 1.

Upon further review of how iCal specifies formatting an all day single event, it wants the DTEND to actually be offset by 1 day, so I it comes in like this for a single all day event:

DTSTART 01/01/2018
DTEND 01/02/2018

So I added this to my DTEND handling:

if(isset($icsEvent['DTEND;VALUE=DATE'])){
    $end = $icsEvent['DTEND;VALUE=DATE'];
    $endDt = new DateTime ( $end );
    $difference = $startDt->diff($endDt);
    if($difference->days == 1){
        $endDt->modify('-1 day');
    }
    $endCom = $endDt->format ( 'Y-m-d 05:00:00');
}

This modifies the end date to offset -1 day, so it ends up being the same day as the start. This is seems work great now for single all day events.

It appears though that I need to also apply this to spans of all day events, like a winter recess break that last all week. Even though it's supposed to be Monday - Friday, because of the offset in iCal, it's stretches to Saturday.

So probably instead of the difference check, I should just offset the endDt all the time by -1 day.

---- Update to Answer ---

The above worked great but I was finding some events that were supposed to be all day, showing as starting at 1am. Not sure why, the timezone looked right but some events started showing as this.

But if I set the date field to "no timezone conversion" first, then do the following with my start and end dates.

// Start Date
if(isset($icsEvent['DTSTART;VALUE=DATE'])){
    $start = $icsEvent['DTSTART;VALUE=DATE'];
    $startDt = new DateTime ($start);
    $startCom = $startDt->format ( 'Y-m-d 00:00:00' );
} else {
    $start = $icsEvent['DTSTART'];
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone("America/New_York");
    $startDt = new DateTime ($start, $UTC );
    $startDt->setTimezone( $newTZ );
    $startCom = $startDt->format ( 'Y-m-d H:i:s' );
}

// End Date
if(isset($icsEvent['DTEND;VALUE=DATE'])){
    $end = $icsEvent['DTEND;VALUE=DATE'];
    $endDt = new DateTime ($end);
    $endDt->modify('-1 day');
    $endCom = $endDt->format ( 'Y-m-d 00:00:00');
} elseif(isset($icsEvent['DTEND'])) {
    $end = $icsEvent ['DTEND'];
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone("America/New_York");
    $endDt = new DateTime ( $end, $UTC );
    $endDt->setTimezone( $newTZ );
    $endCom = $endDt->format ( 'Y-m-d H:i:s' );
}

Basically if there is no time set, and it's just an event that spans as All Day, set no timezone and default to midnight. If it has a time, set the new york time zone.


Can I only traverse a DatabaseConnection object once?

This is expected behaviour; Drupal wraps around PDO and this is how PDO query functions behave also. Have a look at Is it possible to rewind a PDO result for a more in-depth discussion.

The standard way to get around this would be to use either fetchAllKeyed() as you've mentioned, or fetchAll() instead. The latter will produce an array of object results that can be iterated over as many times as you want.

$query = db_select( ... );
$result = $query->execute();
if ( $result->rowCount() > 0 ) {
  $data = $result->fetchAll();

  foreach ($data as $item) {
    // do something with data
  }

  foreach ($data as $item) {
    // do something with data again
  }
}


Bottom line: it's your database, you can add as many fields to whatever tables you like.

Drupal won't know anything about them, obviously, and it may cause unforeseen issues further down the line, as you're potentially changing the way the core system works. It's not possible to be any more specific than that without knowing pretty much everything about your application, so you'd need to test until you're happy you haven't broken anything.

The correct way to extend core entities is through the use of fields, I'd strongly recommend using those rather than hacking at database tables.


How can access the Question from its Course when using the E-learning module?

This module creates an hierarchical structure COURSE > UNIT > EXERCISE > QUESTION.

These are entity types connected with each other using an Entity Reference field. You can attach and reuse different units to each course, different exercises to each unit, etc.

So to access the Question from the Course, you follow the "links" that are created via the Entity Reference field. Obviously, for that you must first have entered the data (entity references) for each Question (and its related Exercise), and for each Exercise (and its related Unit), etc.


Is this acceptable for passing data from a module to a template?

If you pass the variables like the following:

class MyBlock extends BlockBase {
  public function build() {
    return [
      '#firstname' => 'John',
      '#lastname' => 'Doe',
    ];
  }
}

You can access to your variables #firstname and #lastname like:

{{ content['#firstname'] }}
{{ content['#lastname'] }}


How do I save a managed_file to a user profile in a hook_submit

I'm not sure how your collecting this CV (apart of registration process, on your own custom page, apart of the user profile page... whatever).

I would add a field to User Accounts at /admin/config/people/accounts/fields, or maybe install the Profile2 module for D7 if you have alot of types of Users.

After you call file_save($file) if you use the Devel module you'll see that $file should have a new value fid so you can then load a user account (or Profile2 profile) and give the CV $file->fid as the File field value.


When creating/editing a field, scroll down to ELEMENT ACCESS. There you can set all the limitations based on roles.

If you use YML you can use something like:

'#access_create_roles':
    - administrator
'#access_update_roles':
    - authenticated
'#access_view_roles':
    - authenticated

Finally, if you want to change the accessibility of the webform, check the Access tab (admin/structure/webform/manage/FORM_NAME/access).


Menu Block won't display when a page has a View Block on it

Well, it's an old question but I'll post what worked for me in D7 (since my views were already 'fields' as the OPs, but that didn't solve my problem).

I used the menu position module, and set rules for the content types that were being displayed via Views, I set their parent menu item and that's it. This makes the menu block treat any page with views as a normal page, and the menu block finally appeared correctly configured.


Commerce - adding a product to a cart programmatically with custom price

This is covered at length in a variety of other places. Your price is being lost due to the shopping cart refresh system and your avoidance of the core product pricing API.

You need a custom price field or something to store the price on the line item and then a pricing rule that swaps that custom price in for the unit price during the price calculation process.


This is a shot in the dark, but I would do the following.  This assumes you are on Drupal 7.

On, admin/structure/types/manage/page/display, open Custom Settings and select Search Index.  Save.  Then click on the Search Index tab and configure the view mode for all of the fields that you want to search in.

On admin/config/search/settings, make sure that you have Node selected.

On admin/config/search/custom_search/content, double check that you have selected the content types that you want to search (or leave that fieldset empty).  Also check that you aren't excluding any types that you actually want to search.

If your site isn't that big, I would dump the search index and rebuild id.  I normally do this from drush:

drush search-reindex
drush search-index

Then, open your MySQL tool of choice, and look for a few keywords that you know you should have hits on:

SELECT
    *
FROM
    search_index
WHERE
    word = 'foo'

If all of that works, then you shouldbe getting search results.  If not, you need to find what is interfering with the indexing, which could be specific to your system.


There is a tab titled "Analysis" for this. Alternatively you can use the "Download" option. See the example in the screenshot below.


hook_form_alter building dynamic textfields

You should use following code in the form. It will display the array structure in $form_state['values'] in form_submit.

$form['#tree] = TRUE;


You can set redirect state for your node form. For example

function my_module_form_alter( &$form, &$form_state, $form_id ){
  if($form_id == 'your_node_form_id') {
    $form['actions']['submit']['#submit'][] = '_mymodule_node_redirect';
  }
}

/**
 * Custom Submit Handler to set conditional redirection rule.
 */
function _mymodule_node_redirect($form, &$form_state) {
  // If terms are already in the system.
  if($form_state['values]['your_taxonomy_field']['und'][0]['tid'] ==  'tid_to_compare_with') {
    $form_state['redirect'] = 'whereever you want';
 }
}


How to translate the language switcher links

I'm still looking for this same answer, but there is a way to translate them, so you can have them as English | Deutsch | Français in the language switcher for all languages: just translate the language name on /admin/config/regional/language


complete installation proess for drupal 7.15 and ubercart-7.x-3.0

Note: This is an alternative way by using Drupal commerce module and not the Ubercart module.

As a beginner I'd suggest you should try the Commerce Kickstart distribution first. It includes the latest versions of Drupal core, Drupal Commerce, and the other modules it depends on.  You can explore Drupal after that ;)

Just make sure you select the Commerce profile while installing (see screenshot)

And also create the example content after configuring the site


Views date range filter adds weird condition

After some test I have found that a module was changing filter form states, and then the filter fields were wrong when the query were constructed. I fix that and now it works good.


How to make translated taxonomy terms correctly be shown in a view?

Make use of i18nviews Modules

  Translate views using Internationalization. This is a work in progress
  and not all Views properties can be translated yet.


Send email to specific user by using webform

Finally i found the solution by myself

1) Create a hidden field in webform say username field.

2)then go to /webform/emails .select the component value that is equal to username hidden field you previously created.then edit added component value in E-mail from address section select the component radio button instead of Default: abc@yahoo.com radio button.

3)then create a custom module add this code

 function your_module_form_alter(&$form, &$form_state, $form_id){

 if ($form_id == 'your_webform_id') {
    $uid = arg(1);
   if ( arg(0) == 'user' && is_numeric($uid) ) {
       $account = user_load($uid);
        $form['submitted']['Your-hidden-field-machine-name']['#value']   = $account->mail;
     }
   }

   }


Any way to stop Drupal css from dynamically resizing pages?

You need to add some css to various places in your theme, then. Give a 'width' attribute to the divs that contain the pieces of your page.

You may also be interested in 'min-width' and 'max-width' attributes.

Check out the drupal theming guide, or better yet, the README in your active theme's folder, to learn where and how to add the css. You don't have to be an expert- with just a little bit of time, this should be pretty easy.


Removing the comma between Attribute Option and Attribute Price in Ubercart for Drupal 7

theme_uc_attribute_option($option, $price) is what you're looking for. Override that theme function in your theme and you can eliminate the "," & the price adjustment amount.


How to get granted and expires fields of commerce license updated?

After monitoring how database tables change with recurring products, I've noticed that saving license with the new data was not sufficient and that the cl_billing_cycle should also be updated with the new granted and expire dates.

I am doing that with a direct database query for now. Let me know if there is a better way to update the cl_billing_cycle.


Adding a delete button for webform attachment fields

There is an example in the examples module.

There is a module with in that called form_example. If you check the 9th example you would get what you are looking. It has an example of adding and removing fields dynamically and the code is well documented.

change value '#value' => t('Remove'), to '#value' => t('Remove' . $i),

and in function you could get that as given below

function form_remove_attachment($i) {
    $clicked = explode(' ', $form_state['clicked_button']['#value']);
   //$clicked[1] would have the value of $i

    $form_state['rebuild'] = TRUE;
}


How can I design the standard user login form with twig?

I found the solution how to add user and password placeholders an modify user and password labels:

function THEMENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_login_form' ) {
    // Add placeholders.
    $form['name']['#attributes']['placeholder'] = t('User Placeholder Text Here');
    $form['pass']['#attributes']['placeholder'] = t('Password Placeholder Text Here');

    // Labels
    $form['name']['#title'] = t('User Label Here');
    $form['pass']['#title'] = t('Password Label Here');

    //Submit Value
    $form['actions']['submit']['#value'] = t('Submit Button Text Here');
  }
}

To remove "Create new account" and "Reset your password" links, just override block--user-login-block.html.twig file. Change

{{ content }}

to

{{ content|without('user_links') }}


Why do I get "Command 'drupal-update' is not defined" when I run "composer drupal-update"?

Neither Drupal core nor Composer define that command. It's the Composer Manager module that defines it.

Be sure to read carefully the instructions to properly install the module, and the following note the project page gives.

  Drupal 8

  The Drupal 8 version of this module is deprecated and no longer needed, due to improvements in Drupal 8.1. Use Composer directly to get the needed modules, which will also download their required libraries.

The installation instructions are the following.

  Installation

  Install the Composer Manager module.
  Run the module's init.php script on the command line
  (php scripts/init.php from inside the composer_manager module directory).
  This registers the module's Composer command for Drupal core.
  Run composer drupal-update from the root of your Drupal directory.

If you are wondering why you don't see the Drupal 8 version in the project page, that is because, as the project page says, the Drupal 8 version is deprecated. The last Drupal 8 version is 8.x-1.0-rc2, visible in the releases page.


Limit the results returned by 'published'

The node table has a field called status - 1 is published, 0 is unpublished.

Are field_test_2004 and field_test_2005 Drupal generated tables?

Normally table names take the form of field_data_field_test_2004...

Anyway, assuming they are Drupal generated tables they will have a field called entity_id which you can join to the node table with.

If you are building queries like this I would suggest you look into using Drupal Dynamic Queries as opposed to string concatenation - it is much easier to add bits to and manipulate the query.

Also feilds is spelt fields (sorry, couldn't help myself)


FontAwesome character added via CSS only appears when logged in

Is it possible that your CSS rule is in the CSS for your administrative theme (by default "Seven"), but not in the theme for your public (non-logged-in) users (by default "Bartik")?

If so, you need to copy this CSS fragment into the public theme too.


After creating a view, you can follow these steps to accomplish what you need:

Add a contextual filter, Search for nid - So you will have Content: Nid.

In When the filter value is NOT available:

Select Provide default value -> Type -> Content ID from URL.
Apply

Add a relationship in your view:

Search for field_associated_resident (your machine name), if there are two things come up. choose the one which says something like this: A bridge to the Content entity that is referencing Content via field_associated_resident (Language can differ).
Check Require this relationship.
Apply

Now go to your field selection, for example, you may want to display title. Add a field title and choose the relation you just created and Save.

To test this, you can use the nid of the Resident profile where you want to display it in the view itself. You should get your expected results there itself.


How to download file upon submitting a form?

You need to set the filename with setContentDisposition, as the constructor only takes the file, but doesn't set the name itself:

$response->setContentDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    'my_doc.docx'
);

Don't forget to add use Symfony\Component\HttpFoundation\ResponseHeaderBag; at the top of your file.

There is quite a bit more you can do with BinaryFileResponse as well, so check out some of the methods.


How to retrieve a select box option and set the field's value to it?

This question looks a little old, but here is an answer for you.  Reading your comments you have

//Declare the callback for after_build for page node form
function set_keywords_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'part_node_form') {
        $form['#after_build'][] = 'set_keywords_after_build';
    }
}

function set_keywords_after_build($form, &$form_state) {
    $keyword = $form['field_product_keyword']['und']['#options'];
    $form['field_product_keyword']['und']['#value'] = $keyword;
    $form['field_product_keyword']['und']['#default_value'] = $keyword;
    return $form;
}

I applaud your efforts, especially that you are attempting to do this clean and proper with a hook_after_build.  The hook_after_build allows your value setting code to run after the Reference Field Option Limit has done its adjustments, so you are certain to be getting the value you want.
I see one mistake in your code, and that is that #options is an array of Label => Value so that the form can display language in the select field instead of raw values.  I think all you need is this one adjustment:

// remove the -None- option from the start, then set the next option
array_shift($form['field_product_keyword']['und']['#options']);
$keyword = array_shift(array_keys($form['field_product_keyword']['und']['#options']));
// this is safe because $form is not passed by reference,
// do not do this on $form_state

When trying to do things like this, I find it helpful to look inside what it is I am manipulating.  If you know the string of references that you need to access some data, you can print it on the form like this:

//Declare the callback for after_build for page node form
function set_keywords_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'part_node_form') {
        $form['#after_build'][] = 'set_keywords_after_build';

        // see what our options are, print them as text on the form:
        $form['some_text'] = array(
            '#markup' => '<p>'. $form['field_product_keyword']['und']['#options'][0] .'</p>',
            '#weight' => '-80'
        );
    }
}

As you have mentioned you are using the devel module, you could easily throw the #options array into a dpm() or krumo() inside the form alter and get it printed to your form page also.


How can I display comments/comment form with a custom module?

Solution

To append the comments form, add this to your render array:

$foo = array(
    'comments' => drupal_get_form('comment_form', $comment),
),

Add this, just above your render array:

$comment = new stdClass;
$comment -> nid = $nid;


Adding an input filter to automatically replace text with HTML via a script

I would rewrite the relatively short script. This shouldn't be a problem because you can re-use the Perl Regex in PHP, see http://php.net/manual/en/book.pcre.php

More Drupal specific would be caching. Add a cache tag to the filter result

  public function process($text, $langcode) {
    ...
    $result = new FilterProcessResult($text);
    $result->addCacheTags(['mymodule:filter']);
    return $result;
  }

so that you can invalidate the cached entities when the replacement text file gets updated:

\Drupal::service('cache_tags.invalidator')->invalidateTags(['mymodule:filter']);


Block is displayed on page even though no region is selected, how is this possible?

This happened to me once, turns out it was added through the context module. So check if your site has it.

Else, could have been added through the Panels module or the Display Suite module. So check if you have any of these modules also.

If you have non of the above modules are installed then maybe it was added via a template file. So check your template files in your theme's template folder.

Last but not least, perhaps through a preprocess function? check your template.php file if on D7 or themename.theme file if you're on D8.

Good luck detective.


Add images from external URL in WYSIWYG Editor

This question was answer in the Drupal issue queue - https://www.drupal.org/node/2119379

  Reusing existing images will be possible in Drupal 8 contrib by
  overriding the managed_file element, which is the element that renders
  the image upload button. E.g.
  https://drupal.org/project/filefield_sources does that: it provides a
  "Reference existing" option.

  When you disable image uploads, you can insert image URLs. It's either
  of the two, not both. If you want both, then again something like
  https://drupal.org/project/filefield_sources provides the solution.


Custom error messages on search result page

please check this, their is a procedure for translating words using Locale module


I've never used it myself -- but see Inline Entity Form which should allow you to reference an existing author, or implement that modules form controller class to show an author and email field to create the new author as needed.

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.

From the README

Integrating with Inline Entity Form
-----------------------------------
An entity type can add support for this module by declaring the
inline entity form controller class in its entity info:

$entity_info['commerce_line_item']['inline entity form'] = array(
  'controller' => 'CommerceLineItemInlineEntityFormController',
);

The controller needs to extend EntityInlineEntityFormController and at least
override entityForm() to provide a function entity form.


Alert after form radio has been selected

'wrapper' is a required key for #ajax on form elements, you're probably just missing that. From the docs

  This property is required for using AJAX requests in on a form element

If you add the wrapper it should work:

$form['field_radio']['#ajax'] = array (
   'callback' => '_get_member',
   'progress' => array('type' => 'throbber', 'message' => ''),
   'wrapper' => 'some-element-id'
);


How to add a local image file to an image field programatically

public:// is the Public file system path that you can set in /admin/config/media/file-system.

In your case it would probably be sites/subsite.example.com/files.

To get the image you must then use, public://blog.dir/1/gallery1/image.jpg, where public:// is the same as sites/subsite.example.com/files.


To add an image field to a webform:

To go the webform tab where you manage the fields.
Add a new field of type file:
On the new field configuration page it's a good idea to set an Upload directory for your images. This means all the images upload from this field will sit in a particular folder in your files directly and help prevent too many files from sitting in one folder. You can also choose what types of files you want to allow users to upload. For an image field I would suggest only gif, jpg, and png.
Set any other settings such a label or display settings as required.
Finally save the component.
Now when you visit the frontend of your webform you should see your new field:


You can do this in the views ui.

Create a custom field
Hide the display of the image field
Use tokens provided to add image field output to your custom field

Example:

[image_field]

UPDATE

Also ensure the style options are set to none on the image field so you don't get any div wrappers.


Storing variables in a theme outside preprocessing

I'm not sure if that's exactly what you're looking for, but Drupal has the concept of theme settings, which allow to configure a given theme with variables.

See http://www.metaltoad.com/blog/how-add-theme-settings-drupal-7 for a great introduction to them.

And according to theme_get_setting(), you can for example store defaults in your theme's .info file, something like

settings[your_setting] = the_value

Should work.


How to exclude items from search api solr by negative keywords field

You don't need to do this in solr, you can do it in the query or with views filters.

Something like this:

$solrIndex = \Drupal::entityTypeManager()->getStorage('search_api_index')->load('global');
$query = $solrIndex->query();
$query->addCondition('title', $search_string);

$search_terms = explode(' ', $search_string);

// Don't match items where elements in the title match the stop words
// for an entity.
foreach ($search_terms as $term) {
  $query->addCondition('field_stop_words', $term, '<>');
}


Capturing Data on Multistep form to send to an API

You should write a custom WebformHandler that adds the return API data to $form_state and then alters the form elements as needed. There are some blog post available about writing webform handlers.

Here is how to get the current page from the $form_state.

/** @var \Drupal\webform\WebformSubmissionForm $form_object */
$form_object = $form_state->getFormObject();
$current_page = $form_state->get('current_page');


Where do I set which template file to use for a block?

Most of the times I just do

$block['subject'] = t('My block title');
$block['content'] = theme('my_custom_theme', $block_content);

return $block;

from hook_block_view() function if you're making a module that creates a block. The theme function my_custom_theme can use a template file such as my-custom-theme-block.tpl.php. Also you can suggest theme hooks through hook_preprocess_block. Just check for the delta of your own block and set a theme hook there.

function HOOK_preprocess_block(&$vars) {
  if ($vars['block']->delta == 'my-block-delta') {
    $vars['template_suggestions'][] = 'my-custom-theme-block';
  }
}


How do I create a taxonomy tag from node title

I wouldn't recommend you doing that, you might get crazy node title names like "hello world I love peaches" and you dont want that tag.

anyway you can do a Hook_node_insert in your custom module to add your code after creating a node, then you should use taxanomy_term_save to insert your new term.

let me know if you need more on this.


How duplicate order automatically with commerce 2

Here is the code for duplicate order with a cron job:

function commande_et_paiement_cron() {
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'abonnement');
$query->condition('field_livraison', 3);//livraison le vendredi
$entity_ids = $query->execute();

foreach ($entity_ids as $entity_id) {
$abo = Node::load($entity_id);

//utilisateur
$user = $abo->get('field_utilisateur')->getValue()[0]['target_id'];
$utilisateur = \Drupal\user\Entity\User::load($user);

//profile
$entity_manager = \Drupal::entityTypeManager();
$profile = $entity_manager->getStorage('profile')->load($user);

//abonnement
$nid= $abo->id();

//livraison
$date_livraison = new DateTime();
$date_livraison->modify('next friday');

//ligne de commande
$line_items = array();
$abo_array= $abo->get('field_abo_produits')->getValue();

foreach ($abo_array as $abo_item) {
    $ligne = $abo_item['target_id'];
    //load produit abonnement
    $item = \Drupal\commerce_order\Entity\OrderItem::load($ligne);
    $quantite = $item->getQuantity();
    $produit = $item->getPurchasedEntity();

    $order_item = \Drupal\commerce_order\Entity\OrderItem::create([
    'type' => 'default',
    'purchased_entity' => $produit,
    'quantity' => $quantite,
    //'unit_price' => $role_price,
    ]);

    $order_item->save();
    array_push($line_items,$order_item);
    }

//creation de la commande
$order = \Drupal\commerce_order\Entity\Order::create([
      'type' => 'default',
      'store_id' => 1,
      'checkout_flow' => 'boulangerie',
      'uid' => $user,
      'billing_profile' =>$profile,
      'field_abonnement' => $nid,
      'placed' => time(),
      'field_date_livraison' =>$date_livraison->format('Y-m-d'),
      'order_items' =>$line_items,
      'state' => 'draft'
    //'completed' => time(),

    ]);
    $order->save();
    $order->set('order_number', $order->id());
    $order->save();
    $order->set('state', 'complete');
    /*$comment = 'blabla';
     $logStorage = \Drupal::entityTypeManager()->getStorage('commerce_log');
    $logStorage->generate($order, 'order_comment', ['comment' => $comment])->save();      */
    $order->save();
   }
}


How to collect and publish input from user, using webform and views?

For web-form refer to the link http://www.cmsquickstart.com/blog/build-styled-user-feedback-form-webform-drupal-7

And for view you can create node pages and give the permissions to the user to be able to create the node page....


How do I show a basic search block on the front page that integrates with search api?

Search API module has the ability to integrate with views module. All you need to do is to install views module and then create Search view,expose search filter and in your views configuration choose Exposed form in block option to yes, now you will the see the search block from your search api and place it on front page, the block will take you automatically to the search page to show the search items.


Multiple nodes in one slide using views slideshow or another module

The only thing I can think of is to use like Relation to tie these things together using a relation as Slideshow Content and then a field tacked onto the relation as slide number.

You should be able to then have any number of content types -- relate them to your slideshow and define the ordering as needed that content.

To ease the generation of relating (linking) things these additional relation modules may help:

Relation Add

  Small block that allows the user to add an appropriate relation from
  an entity page to any other appropriate entities, with a generic
  autocomplete for each endpoint, and relation fields.

Relation Autoconnect

  Module allows to setup invisible widget to Relation Dummy Field. This
  widget loads information (entity type and ID) about another entity
  from arguments in the path and create relation between determined and
  newly created entity.

  For example, you can use path "node/add/story/node/22" to connect new
  story content with node number 22.

Relation Select

  This module provides a field widget for creating & editing relations.

  The selection interface is based on views. Use exposed filters to
  search for entities, & select items from the view output displayed as
  a clickable drop down list.

So the idea is you have all your content on the backend -- related via a Relation and its field to grab it for a Views Slideshow later. Some of these modules attempt to make creating that (meta-)relation with your slideshow content easier.

You might be able to use like Arrange Fields or FieldGroup to make a tab for "slideshow properies" for each of your content types that shows the Relation info in the node edit form.


Is there a way to ask migrated users to complete their profile?

You can take help of Mass Password Reset module.

I had same kind of situation when I made a existing website of D6 into D7 & migrated users from there.


Don't repeat yourself: Natural place for clculations on the FieldItemList of a custom FieldType wanted

The natural place would be a method in a custom field item list:

class MyFieldItemList extends FieldItemList {

  public function addAllNumbers() {
    $sum = 0;
    foreach ($this->list as $item) {
      $sum += $item->some_number;
    }
    return $sum;
  }

}

Set the list class in the field type:

 * @FieldType(
 *   ...
 *   list_class = "\Drupal\mymodule\MyFieldItemList",


Feeds creates duplicate content each time cron runs

In order to update existing nodes, Feeds needs a unique ID to match the source item with the target node. Otherwise, Feeds cannot know which node to update, so it just creates a new one.

When configuring the mapping for your feed importer, choose a unique field in the source, map it to the 'GUID' target and check the 'unique target' checkbox.


Stop Varnish from caching 302 redirect from POST responses

Disable caching in fetch if response status is 302

sub vcl_fetch {
set beresp.grace = 24h;

if (beresp.status >= 400) {
     return (hit_for_pass);
}

// New Set Longer Cache
if (req.http.user-agent ~ "(Googlebot|msnbot|Yandex|Slurp|Bot|Crawl|bot|Baid|Mediapartners-Google)") {
    unset beresp.http.set-cookie;
    set beresp.ttl = 5d;
    return (deliver);
}
if (req.request == "GET" && req.url ~ "\.(css|xml|txt)$") {
    set beresp.ttl = 5d;
    unset beresp.http.set-cookie;
    return (deliver);
}
// multimedia
if (req.request == "GET" && req.url ~ "\.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|img|tga|woff|eot|ttf|svg|wmf|js|swf|ico)$") {
    unset beresp.http.set-cookie;
    set beresp.ttl = 5d;
    return (deliver);
}
//Fix to stop caching 302 responses
if (beresp.status == 302) {
  remove beresp.http.Cache-Control;
  set beresp.http.Cache-Control = "private, no-cache";
  set beresp.ttl = 0s;
}
set beresp.ttl = 5d;
return (deliver);

}

Setting cache control for 302 redirect:

sub vcl_deliver {
// Remove Varnish identifying information from headers
// Note: Both cache hits and cache misses will use this subroutine.

set resp.http.Access-Control-Allow-Origin = req.http.X-Saved-Origin;

remove resp.http.Via;
unset resp.http.Server;
remove resp.http.Age;
remove resp.http.X-Powered-By;
remove resp.http.X-Varnish;
remove resp.http.X-Generator;
remove resp.http.X-Mod-Pagespeed;
remove resp.http.X-Drupal-Cache;
remove resp.http.Link;
set resp.http.Server = "Prism";
// Stop Caching 302 redirects
if (resp.status == 302) {
  remove resp.http.Cache-Control;
  set resp.http.Cache-Control = "private, no-cache";
}

if(req.http.host ~ "printsites.net"){
     set resp.http.X-Robots-Tag = "noindex, nofollow";
}

return(deliver);

}


Each time Display Suite is used in content output, it's wrapped in an <article> element with the content type as a class. You can see below that the content type can be found as node-enterprise-blog class.

I'm not sure what your end purpose for this is, but this way you can select the element using .node-enterprise-blog .field-field-name. If you need to add a class to the field, consider using the Field Template option under DS Extras. It allows you to change the markup of each field in a view mode.


get timestamp of most recent comment of an article

As @IvanJaros pointed out the comments statistics are stored in a database table. You don't need an API function to get them. The comment module does this for you and places them in the field while loading the node from storage:

function comment_entity_storage_load($entities, $entity_type) {
  ...
  // Load comment information from the database and update the entity's
  // comment statistics properties, which are defined on each CommentItem field.
  $result = \Drupal::service('comment.statistics')->read($entities, $entity_type);
  foreach ($result as $record) {
    // Skip fields that entity does not have.
    if (!$entities[$record->entity_id]->hasField($record->field_name)) {
      continue;
    }
    $comment_statistics = $entities[$record->entity_id]->get($record->field_name);
    $comment_statistics->cid = $record->cid;
    $comment_statistics->last_comment_timestamp = $record->last_comment_timestamp;
    $comment_statistics->last_comment_name = $record->last_comment_name;
    $comment_statistics->last_comment_uid = $record->last_comment_uid;
    $comment_statistics->comment_count = $record->comment_count;
  }
}

So you can access the statistics directly from the node field:

$node->comment->last_comment_timestamp;
$node->comment->last_comment_name;
$node->comment->last_comment_uid;
$node->comment->comment_count;


If you list complete node teasers, it means, the nodes are rendered by node.tpl.php. So just add a class to the node template in _preprocess_node something like this:

$node = $vars['node'];
$menu_object = menu_get_object();

if ($menu_object && $menu_object->nid == $node->nid) {
  $your_custom_class = 'this-is-the-actual-node';
}


Maybe in your formats, there is no <a> allowed? You can find it under /admin/config/content/formats
Or you checked that HTML will be rendered as text.


You can use this line instead:

$node->content['myfield'][0]['#markup'] = '55';


You should look into Relationships for this.


Get the return value of a hook defined in a module?

module_invoke() is a very simple function:

function module_invoke($module, $hook) {
  $args = func_get_args();
  // Remove $module and $hook from the arguments.
  unset($args[0], $args[1]);
  if (module_hook($module, $hook)) {
    return call_user_func_array($module . '_' . $hook, $args);
  }
}

As you can see, it passes the arguments straight through to the hook function by way of call_user_func_array().

So, you just need to pass the extra arguments with the call to module_invoke(). For example, to invoke views_block_view() with a specific block delta, you would use:

$block = module_invoke('views', 'block_view', 'some_block_delta');


custom js in bootstrap sub-theme is loaded, works in console, but doesn't actually work in browser

what am I missing that it's not working in the Drupal theme

You're not using proper jQuery Drupal syntax

(function ($) {

     //code starts
     $('p').click(function(){
        alert("hello");
     });
    //code ends

}(jQuery));

See Working with JavaScript and jQuery for an in-depth explanation.


Redirecting and removing user role after user account submit

I would try implementing hook_user_presave().

function custom_module_user_presave($edit, $account, $category) {
  $role_position = array_search('undesired_role', $account->roles);
  // Use !== or === here since $role_position may be zero or FALSE
  if ($role_position !== FALSE) {
    unset($account->roles[$role_position]);
  }
}


Asking for confirmartion on node creation

@AgA: "I want ask for confirmation if a duplicate node is getting created. But how do I do it?"

The way you do it is to validate any new node added by a user against existing nodes.

Towards this end, hook_node_validate() is your friend. :-) You'd make a module that implements hook_node_validate(), and within that function do a query using the data the user input. If you find similar nodes that already exist, you can form_set_error() an error message. Click through to the API site and there's even some sample code.


I figured out the answer to this problem

I went to admin/structure/types/manage/faq/display/teaser and noticed that the format said 'Trimmed'. I changed that to 'default' and the answer is no longer cut off.


Drupal 7: How can I display nodes of specific author in a taxonomy term?

I probably wouldn't have used a taxonomy term to store that info, but that's not a big deal.

It sounds like you want a block containing the information in the taxonomy term to appear on a user's post.

You need an entity reference connecting a user/author with the appropriate taxonomy term.

Create View that is based on the taxonomy vocabulary. Use a "contextual reference" starting with the post's node id in the URL to a relationship to the author of the post to another relationship to the taxonomy term using the entity reference.


Commerce programatically Create Order with Customer Profile

After running a debug on the $order object in the commerce_order.controller.inc save method it was simple to work out the right format for the data. But this is probably not best practice but is useful for generating a bunch of orders.

function create_order_with_products ( $product_ids , $uid, $profile_id ) {
    $order = commerce_order_new ( $uid , 'pending' );

    // Save the order so its ID is assigned.
    commerce_order_save ( $order );

    $order_wrapper = entity_metadata_wrapper ( 'commerce_order' , $order );

    //add products to order by ids array
    foreach ( $product_ids as $product_id ) {
        $product = commerce_product_load ( $product_id );

        // Create a line item with quantity 1 and this product.
        $line_item = commerce_product_line_item_new ( $product , 1 , $order->order_id );

        // Save the line item to get its ID.
        commerce_line_item_save ( $line_item );

        // Add the line item to the order using the wrapper.
        $order_wrapper->commerce_line_items[ ] = $line_item;
    }

    //create the right array for the save controller
    $profile_object = array (
        'und' => array ( array ( 'profile_id' => $profile_id , ) , ) , );

    $order->commerce_customer_billing = $profile_object;

    // Save the order.
    commerce_order_save ( $order );

    return $order;
}


How do I redirect back to the source page after the user submits a comment?

To redirect a form after submission you would do this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_comment_form_alter(&$form, &$form_state) {
  // Add a custom submit handler to act when the form submits.
  $form['#submit'][] = 'MYMODULE_custom_comment_submit_handler';
}

/**
 * Custom submit handler for the comment form.
 */
function MYMODULE_custom_comment_submit_handler($form, &$form_state) {
  // Redirect the user after submission
  $nid = arg(2);
  $form_state['redirect'] = 'mymodule/' . $nid;
}


How to trim view field to height or number of lines?

There is no way to handle this with Drupal modules, I suggest you use  Ellipsis in your Style( style the result rows items with Ellipsis .

You can read below help content :

link1

link2


How to restrict block for particular subpath, yet allow for all other subpath of a specific parent path?

Assuming all of your underwriting/* nodes are of a certain content type and this content type does not have anything else than underwriting/* as path

Go to /admin/structure/block and find your block and click on Configure link.

Then under Visibility settings, Pages tab, select all pages except for underwriting/example

and then


How to show form elements within PDF by print module?

Not sure if this is exactly what you mean but you can show / hide elements via the ui.

go to admin/structure/types/manage/your-content-type/display
Under Custom Display Settings enable Print
admin/structure/types/manage/page/your-content-type/print

This will show or hide form elements for the pdf version as well as the print version.


How to output the label of a field in a template?

This code will print all labels .

     $entity_type = 'node';
     $bundle_name = 'CUSTOM'; //machine name of your content type

  foreach ($node as $key => $value) {

        $field_name = $key;

        $info = field_info_instance($entity_type, $field_name, $bundle_name);

        $label = $info['label'];

        print $label;
        print "<br>";
   }

You can modify it according to your need.


Turns out that tickets posted by deleted users do not show up in the management interface, but did show up in our view.

Problem was resolved by changing the owner of the tickets to a dummy user, then deleting them through the management interface.


I want to define a hover color in the style sheet

Just put this in the css of your subtheme ("styles.css" i think):

a:hover, li:hover {color:#E3007B !important;}


Rename/hide "Save" and "Save as draft" buttons for non-admin roles

Focusing just on the save draft module (whatever rules you are using are unrelated).

You can implement a custom module will the following form alteration:

/**
 * Implements hook_form_BASE_FORM_alter().
 */
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Get the current user object.
  global $user;
  // Role ids of the current user.
  $user_roles = array_keys($user->roles);
  // Role ids of your admin roles.
  // Change these to suite your role ids.
  $admin_roles = array(8, 9);

  // For users that don't have the appropriate roles.
  if (!array_intersect_key($user_roles, $admin_roles)) {
    // Restrict access to the save button.
    $form['actions']['submit']['#access'] = FALSE;
    // Change label of save draft button if it is present on this
    // content type.
    if (isset($form['actions']['draft'])) {
      $form['actions']['draft']['#value'] = t('Save as draft button label');
    }
  }
}

For this to work your module's form alter function needs to run after the save draft module.
To achieve this you need to either add an install function that changes the
weight of your module in the system database table so that it is 1 (save draft is 0 so you need a higher number), or you can implement hook_module_implements_alter() to make your form alter hook run after.

For more information on making your form alter run after the save draft form alter see the two answers at How can I modify the advanced search form when my hook runs too early? - these explain how to do both the solutions I mentioned above.


drush features-list-packages in drupal 8 doesn't include prefix

For configuration management in Drupal 8, you don't need to use features, you can use the configuration management module, which outputs .yml files.

The files are saved at sites/default/sync

to export them, use

drush cex

(drush configuration export)

and to import them use

drush cim

You can also manually do this from /admin/config/development/configuration

See https://www.drupal.org/documentation/administer/config


How do I add repeating dates programmatically?

Add [] to the end of the data field.

eg.

    foreach($vals->field_event_date as $fed){
        //notice the []!
        $node->field_date_of_event['und'][]= array(
            'data1' => $fed->data1,
            'data2' => $fed->data2
        )
    }


Delete option 'None' of the select list of a cck field

Make the field required in Global Settings.


How to get the user ID from the last profile page?

The easiest way would be to add the user id as a ref argument to the form url in your message button, on the user profile page:

<a href="/path/to/custom/form?userid=<?php print arg(1); ?>">go to custom form

Then, on your custom form:

$args = drupal_get_query_parameters();
$userid = (isset($args['userid']) ? $args['userid'] : false);


Migration tries to create existing entity

It's rather premature to create an entity at the source plugin, when the destination plugin will create the entity for you... It's much simpler for the iterator to simply produce an array of fields representing the raw data, have the process pipeline map those source fields to the Drupal destination entity's field names, and have the destination plugin 'entity:my_entity' create and save the entity to Drupal.


Is it possible to resize image before saving it with media module?

First off, image dimensions are not the same as image sizes. Images could have the dimensions of 800x600 but still exceed 10 MB in size.

One possible solution is to create new image styles under /admin/config/media/image-styles/ providing your desired dimensions (e.g. 800x600). See attached image:

Then under the Manager Displays section of the Content Type containing the image field, choose the Image style you just created. See attached image:

Then set the Maximum upload size for your field in the Manage Fields section of the Content Type containing the image field. See attached image:


I'm pretty sure this can't be done in the standard Views UI.

A bad solution would be to use the Views PHP module to programmatically alter the order of the view results, or perhaps the Views Raw SQL module to insert some sorting statements into the SQL, although I haven't ever tried that.

A good solution would be to implement hook_views_query_alter() in your own custom module and add your custom sorting order to the SQL query.

Going by this answer I think something like this might work, although I haven't tested it:

function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view') {
    $query->orderby = array(
      0 => array(
        'field' => 'my_date_field < CURDATE()',
        'direction' => 'ASC',
      ),
      1 => array(
        'field' => 'greatest(my_date_field, CURDATE())',
        'direction' => 'ASC',
      ),
      2 => array(
        'field' => 'least(my_date_field, CURDATE())',
        'direction' => 'DESC',
      ),
    );
  }
}

You would obviously have to substitute in the names of your view and your date field.

Note that this code overwrites any sorting already defined by the view. You could of course add to the $query->orderby array rather than replacing it.


Suppose u have a content type called as Article. So simply add the fields in the view that you wish to show.

After adding the required fields add a contextual filter for the taxonomy term (Content: Has taxonomy term ID). In the contextual filter, select provide default values "Taxonomy term id from the url".

Save the view and it would serve your purpose.


Dynamic profile2 fields - User can add more fields while registration

I think you can use the Field Collection module.


To register content type grammatically you can by code and by the module - features. But I do not see a reason why you need to create it problematically.


Programmatically add a file upload field to all webforms (+more file extensions)

In this way (hook_form_alter) you will have this field in existing and next created webforms, and you must have own additional _validate and _submit function to process the $form['file'] field.
Other way, the question is how to add programmatically file upload component to existing webform?
To see structure of webform file component, add manually field file to one existing webform and make your setting from the picture, and see devel output tab (enable devel module). Also you may be interested to see http://api.drupalize.me/api/drupal/function/webform_component_insert/7. Then create update script to loop webforms.


How to translate "Sort by" region of the KickStart commerce into Russian?

To translate "Sort by" region:

Go to the "Display products" view edit at path admin/structure/views/view/display_products/edit
In edit view page of the view you will find "Edit View Name/Description" dropdown menu on the right, from dropdown select "Translate View".

On the translate page, you will get fields to translate view stings.


Field collection item not visible to anonymous user

The permissions for the individual groups also have to be set for each added field...it was kind of buried and hard to find.  The path would be like /group/node/13/admin/permissions


Using panels everywhere... without Panels Everywhere

I believe the answer to your question is "Use Panels everywhere". :)

As one of the maintainer of Panels Everywhere, I wonder what you mean with "completely dead"? Yes, I'm a bit slow in the issue queue, but that's because 1. Both me and merlin are crazy busy with the Panels queue (318 issues vs 15), and 2. I'm also not aware of any serious issues. Any help from the community in the Panels queue will greatly help with any PE issues as well.

You should use Panels Everywhere because:

There only thing that's preventing a stable release is a bug on d.o. (I just now updated the module page to say so.)
Merlin is also planning to redo the UI to be much more user friendly.
I build websites with Panels everywhere every single day at work. It works great. If any serious issues were to come up, they will most definitely be fixed. At NodeOne, we build nearly every single site with PE. We need it to work well. :)

I will take the opportunity to shamelessly suggest that anyone interested in Panels and/or Panels everywhere could contribute a bit of time to the issue queue. The current number of contributors, 2, is vastly outnumbered by the number of questions being asked. This slows down development considerably. My d.o profile has the necessary info for contacting me about this. :)


For this you should have to implement hook_node_grants and hook_node_access_records. It look something like that -

 /**
  * Implement @hook_node_grants
  */
 function MODULENAME_node_grants($account, $op) {

  $grants =array();
  $grants['Node_Edit_Permission'][]=array($account->uid);
 return $grants;
}

/**
 * Implement @hook_node_access_records
 */
function MODULENAME_node_access_records($node) {

  $grants = array();

  if ($node->type == 'node_type') {
    $user_id = /* list of user id which you want to block */;

     // Revoke Permissions from these Users
    if (!empty($user_id) {
      foreach ($user_id as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }
  }

  return $grants;
}


Since this was a bit of pain to work through I thought I'd post a solution for everyone.

The base of the solution comes from this post:

http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/

There are is another solution to CSS only styling for upload buttons, but it involves wrapping the input element in a label, which is difficult
with how Drupal handles the markup.

1. Add CSS

First we add the following two chunks to our CSS file, you can read through the explanation at the post above basically we're making the file input button transparent and styling the area behind it.

Then when you try to click on the area behind it, you actually click on the invisible input button.

.form-type-managed-file {
  position: relative;
  overflow: hidden;
}

input.form-file {
  position: absolute;
    top: 25px;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}

Now you may have noticed that we want to style the area behind it. To that we're going to need to add an HTML element to the managed file output which we can then style:

2. Change HTML output

Copy the image file function into our template file (for this example we'll be changing the image upload style) and then add two divs after

function MY_THEME_image_widget($variables) {
  $element = $variables['element'];
  $output = '';
  $output .= '
';

  if (isset($element['preview'])) {
    $output .= '
';
    $output .= drupal_render($element['preview']);
    $output .= '
';
  }

  $output .= '

Choose File

No File Selected
';
  if ($element['fid']['#value'] != 0) {
    $element['filename']['#markup'] .= ' (' . format_size($element['#file']->filesize) . ') ';
  }
  $output .= drupal_render_children($element);
  $output .= '
';
  $output .= '
';

  return $output;
}

If you don't care about the filename of the uploaded file remove the second div and you're done. (You'll need to alter the CSS to make the invisible button sit above your added upload div.)

However if you want the name of the file then leave it in and we move onto a little JS.

3. Add JS

It's impossible the get the name of the file without JS so we add a quick JS script to get it to run, first we call it in the template file:

function MY_THEME_preprocess_page (&$vars) {
    drupal_add_js('sites/all/themes/MY_THEME/js/file_upload.js', 'file');
}

Then we add the following script:

(function ($) {
  Drupal.behaviors.uploadfunctionAddClass = {
    attach: function (context, settings) {
      $(":file").change(function(){
        $(this).prev().text($(this).val().replace(/C:\\fakepath\\/i, ''));
      });
    }
  };
})(jQuery);

It looks for any changes to elements of type file, which in the output for a drupal managed file field is one.

Grabs the element directly before it (the second div we added in step 2) and changes the text in it to it's new value. The path will have C:\fakepath\ added to it, so we remove that as well.

The reason we use Drupal Behaviors rather than document ready, is because we need the script to apply after an AJAX call. If someone uploads a picture, removes it and adds a different one then the script won't have applied to the new elements because they've been added with AJAX. The Drupal Behaviors wrapper causes them to be called every time.

Congrats we're all done.


Should we document AJAX-callback parameters?

Is there any way to tell PHPCS that the function is an AJAX-callback (so that such warnings are generated)?

Yes, it's as simple as implementing hooks except that instead of "Implements hook_", it starts with "Implements callback_".

The only problem is that currently (August 2019) it is not supported by Drupal's PHPCS standard and you don't get any warnings yet.

  Or, Should we document all AJAX-callback parameters, with @param PHPDoc?

That too is an option, for your newly hired dev interns, but especially when there was no official definition in any existing *.api.php file and when you do not want to write your own *.api.php file.

Source:

In Drupal's Official-documentation of August 2019, we can find below Callback implementation:

/**
 * Implements callback_batch_finished().
 */
function _node_mass_update_batch_finished($success, $results, $operations) {
  // …
}

  Note: Unlike hooks any callback starts with an underscore (i.e. it is "_MYMODULE_descreptive_name").

Callback definition example:

In our case, because Drupal's own *.api.php files did not cover AJAX-callbacks, we added our own *.api.php file to prevent copy/paste until Drupal's own *.api.php files cover that section as well, something like below:

<?php

/**
 * @file
 * Callbacks and hooks related to MYPROJECT system.
 */

/**
 * @addtogroup callbacks
 * @{
 */

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Form\FormStateInterface;

/**
 * Callback for AJAX events.
 *
 * AJAX callback functions can be used to update existing or
 * add new form fields, update values in form fields and more,
 * while users can still interact with the form.
 *
 * @param array &$form
 *   All data of the form.
 * @param \Drupal\Core\Form\FormStateInterface $formState
 *   State of the form.
 *
 * @return \Drupal\Core\Ajax\AjaxResponse
 *   Returns the data back as AjaxResponse object.
 */
function callback_form_ajax(array &$form, FormStateInterface $formState) {
  // Here we do something meaningful with the results.
  $response = new AjaxResponse();
  $response->addCommand(new HtmlCommand('#message-box', 'my message.'));
  return $response;
}

/**
 * @} End of "addtogroup callbacks".
 */

/**
 * @addtogroup hooks
 * @{
 */

/* Place any hook definitions here. */

/**
 * @} End of "addtogroup hooks"
 */

Callback implementation example:

/**
 * Implements callback_form_ajax().
 *
 * Prevents popup's redirection from dashboard to another link.
 *
 * Users were redirected to another page as soon as the Event-creation
 * popup form was submitted, just added an AJAX handler to submit button.
 * which prevents the redirect using ajax,
 * and when there is any error on the form, the message is sent to the popup.
 */
function _amt_dayview_popup_submit(array &$form, FormStateInterface $formState) {
  // ...
}


LogicException: The database connection is not serializable - when I try to open any "gear" on checkout flow page?

I experienced the same problem. It's not a commerce issue, and there is no general rule which module causes the problem.
The problem probably occurs, because one of your checkout panes depend on a service, which has an indirect dependency to Drupals database connection -- Drupals database connection is not serializable and this causes the error.
It's not that easy to debug, because the form is soooo big, and loads all the CheckoutPane Plugin Forms. The good news: I figured out a way to debug the issue:
First of all, we need to determine the problematic checkout pane. To do that, we loop over all panes and try to serialize them independently.
Temporary add the following snippet to the Drupal\Core\Form\FormState::getCacheableArray()
if(!empty($this->getStorage()['panes'])) {
  // loop over all panes and try to serialize each independently,
  // catch possible serialization errors and dump the problematic pane.
  foreach($this->getStorage()['panes'] as $key => $pane) {
    try {
      serialize($pane);
    } catch(\Throwable $throwable) {
      // dump pane, which causes the error and die
      dd($pane);
    }
  }
}

FYI: The dd() output does not look very pretty in chrome's network tab (all the properties are expanded). I copied the request as CURL Request (in chrome: right click on the XHR Request --> copy as CURL) and pasted it into Insomnia (my Rest Client).  When executing the Request there, the dd() is displayed as usual with the possibility to expand and collapse the properties. That makes it much easier to find the problematic service..
There should be a dumped object, which is the non-serializable checkout pane. If thats not the case, you have a completely different problem than me and you can skip this answer.
But if there is a dump of the pane, you can now have a detailed look at the properties of the pane. It is necessary, that the properties which are services have a _serviceId property; if this property is missing, the Pane's DependencySerializationTrait isn't recognizing the Service as a Service.
Unfortunately, there can be Services, which haven't the _serviceId property. In my case, a contrib module (mail_login) provided a decoration service, which decorated the service user.auth. The service user.auth is injected as dependency to the Login-pane (and I think another one too).
This decorated service, had no _serviceId property, so Drupal tried to serialize the the user.auth Service.
The problem is now, that the user.auth service has a dependency to Drupals database connection, but no DependencySerializationTrait
--> Drupal tries to serialize the Database connection and throws the error.
To solve the issue, I created my own decorator service class within a custom module, which extends the original decorator class from mail_login (because i need the logic from the mail_login decorator). I just added the DepenencySerializationTrait to my own decorator and replaced the service class for the decorator service in my modules service provider (in my case, the decorator service is called "mail_login.auth").
I'll share my code too.. (I modified it for the post, so there may be errors. But you can use the snippets for better understanding)
My decorator only uses DependencySerializationTrait:
<?php

namespace Drupal\my_module;

use use Drupal\mail_login\AuthDecorator as MailLoginAuthDecorator;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;

class AuthDecoratorDependencyFix extends MailLoginAuthDecorator
{
  use DependencySerializationTrait;
}

My Serviceprovider just replaces the original service class:
<?php

namespace Drupal\my_module

use Drupal\Core\DependencyInjection\ContainerBuilder\ContainerBuilder;
use Drupal\my_module\AuthDecoratorDependencyFix;

class MyModuleServiceProvider
{

  public function alter(ContainerBuilder $container) {
    if($container->hasDefinition('mail_login.auth')) {
      $mailLoginAuth = $container->getDefinition('mail_login.auth');
      $mailLoginAuth->setClass(AuthDecoratorDependencyFix::class);
    }
  }
}

I'll create an issue for the mail_login module (maybe on Monday ;)).
Please let us know, if it's another service, or a completely different error on your side.


You are talking about two different concepts here. The first question is related to whenever one wants to organize content into different categories or if one wants to build a relationship between existing content types. The other question is, if, when using a taxonomy, will it be better to use a taxonomy reference field or an entity reference field.

Regarding the first concept

It depends on your use case. Taxonomies are great for building hierarchies, as you mentioned, but ideally, you shouldn’t use taxonomies to contain actual content. The reason for that is easy — while you can add fields to taxonomy terms, all hierarchical levels in a taxonomy use the same fields. Taking your example with members belonging to different teams, this might lead to problems. If you want to store more information about a team or member than just the name, If, for example, you want to store information about a member’s first name, last name, and biography, and add this fields to the taxonomy, they would be available on team terms as well. And if you add a team description field for the teams, those will show up for team members.

Taxonomies are best used when organizing similar items hierarchically. Like tags, for example:

vegetable

carrot
potato

fruit

apple
banana

Entity references are excellent for establishing relationships between content types. Examples include when you have a node type ‘team’ and a node type’ team member,’ each with their own fields. Or a node type ‘song’ which is referencing an ‘album’ which itself references a ‘musician.’ In this regard, entity references are more flexible than taxonomies, as it allows for more complex relationships. When you use views, you can also utilize these relationships. Taking your example, you could create a view of all team members, and using the entity reference for a relationship, and one could display any field on the team content type along with fields from the member node.

Mixing node referenced and taxonomy fields are legit too. In your example with the teams, both team and member could be a node, referencing each other with an entity reference. At the same time, the department could be a taxonomy with all available departments.

Regarding the second concept

When D.O. released D7, it shipped with a taxonomy reference field to use when referencing taxonomies. Since then, we’ve seen the release of the Entity API module and, consequently, the entity reference module, and since terms and taxonomies are entities, one can reference them like any other entity. At this point, the two are working very similarly, and in many cases, it doesn’t matter which one you use. However, there are still some contributed modules providing field formatters and widgets, which only work for one or the other. So, it mostly depends if you need such a formatter if you should use taxonomy reference or entity reference.

As D.O is replacing the taxonomy reference field with the entity reference field in D8, I prefer to go with the entity reference field to link to taxonomies rather than the field supplied by the taxonomy module.


Let "Availability Calendars" start on monday

As a best practice whenever an issue like this arises - disable the module, uninstall, flush all cache, verify settings for regional locale is set to start on Monday.

Now re-enable the module. Flush all cache. Re-configure. And see if things are working as expected.

As an added additional option if you care to contribute to the community, on a fresh install of Drupal, attempt to recreate the issue that "potentially" caused this issue to arise by re-tracing any steps you may have taken (other contributed modules, other seemingly unrelated changes, etc.). If you're able to trace what caused the issue, then perhaps the potential bug can be fixed.

Of course, regardless if the uninstall, reinstall works and functionality doesn't again fail after a few days then you have solved your issue! This should be a fairly typical go-to strategy of troubleshooting for any module issue.


Can node reference be altered to include views pages?

You could use a separate viewfield for the related views, and theme it so that the nodereferences and viewfields appear in the same list.

You could also use a link and use a custom widget if you don't wanna type the full path every time.

On a couple of sites I ended up never (or very rarely) using a view's page display. Instead I attached the view to a node, and always referred to the view via its node. This was because my advert banner system was based on nodereferences. It's not the most extensible approach, but it worked for those sites.


Cannot fetch form_state['values'] of text field from dynamically created Ajax fields

You have used $form_state['num_names'] instead of $form_state['values']['num_names'].

Please try to update and see.


How do you force Drupal to re-render images?

You can try to flush your image style cache, eg. with this module: https://www.drupal.org/project/imagestyleflush

See also this answer: Rebuild images from image style


Correct - the way the attributes system works, it requires you to define a SKU for every possible combination - depending on how many measurements options you have, it could be infinite. Instead you should look into line item fields that allow a customer to associate unstructured data with a product when it is added to the cart. This could accommodate both your fixed and variable sizes.


Send order notifications when user is anonymous

Since the user account for anonymous orders is created upon checkout completion, it may be that you just need to assign your custom rule a higher weight. It would need to execute after the other rule that creates and assigns the order owner user account to the newly completed order.


The field Content: Link allows you to enter Text to display.

Add a new Field Content: Link
Under Text to display enter Bestel nu

Easy :)

For more complex changes you can use the "Rewrite the output of this field" option on the "Content: Link" field. It's more reliable to use this field than Path.

You can use "Global: Custom text" field to construct some output (also "Rewrite the output of this field") using the tokens for the fields listed above it, but it isn't necessary in this case.


Is there a way to use a generic 'Site is Down' page?

Yes, it is quite simple. Just go to "admin/config/development/logging" and set "Error messages to display" to "none". You will then have only the error page with message "The website encountered an unexpected error. Please try again later.". The PDO exception will not be displayed.


You should look into drush, drush deploy and especially features.  Not all Drupal configuration options are supported by features, and you will need to do some work to create a deployment process that works for you.  There is no single script that will do everything correctly for you.


How do I use inline CSS in "Global: Custom text"?

I've solved overriding view-view-field--field-myfield.tpl.php and in template file I've used color from $row variable.

<?php
$title = $row->field_field_myfield[0]['rendered']['#markup'];
$color = $row->field_field_myfield_color[0]['rendered']['#markup'];
?>
<h3 style="border-color: <?php print $color ?>"><?php print $title ?>


Manage content type's different status for different users

Based on chat with @parth I realised the status field belongs more to relation of book and user rather than book. Here is my recommendation in that case.
Way 1:
The easiest way I could think of is

have a custom table as book_inventory with columns as book_entity_id, user_id,status,record_id

In order to allow admin to a UI in place to udpate status with fields as

autocomplete field for book
autocomplete field for user
status could be dropdown field

this UI will let admin to set status for any book against any user
down to your form UI, you can list what books are assigned to what users from your custom table with an edit link
when the admin clicks the edit button the same form UI will open but prepopulated with all the fields
now with help of this table
you always have information user and book status with you, you can query your database and get the status runtime
and in case you do not have a record agaisnt requested user and book, in that case you can have a default status, I believe 'not purchased' in your case
Way 2:
Other approach would be to try Relation module instead of entityReference, as relation module will allow fieldable relation between book and user.


What is the replacement of drupal_match_path()?

New PathMatcher service reports that the path.matcher service was introduced to deprecate most procedural functions in the path.inc file with its methods.
In particular, the equivalent of $path_matches = drupal_match_path($path, $patterns); is the following code.

$path_matches = \Drupal::service('path.matcher')->matchPath($path, $patterns);

The same service is used to check if the currently viewed page is the front page.

$is_front = \Drupal::service('path.matcher')->isFrontPage();

As usual, injecting the dependency is preferred over calling \Drupal::service().


How do I remove a validation handler from a form?

Use hook_form_alter() to change the $form['#validate'] to be your custom validate handler.

function custom_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
   $form['#validate'] = array();
   $form['#validate'][] = 'my_custom_validation';
  }
}


Go to admin/store/settings/checkout and disable checkout.


Saving multiple field values in a users entity

The way you're setting the values may be failing to work if you've got the wrong keys in your array - setting any field from code requires you to know how that specific field type stores its data in the entity.

If you're not sure about that key, using the devel module you can simply save one of those users filling the field_clinic field with appropriate values then switch to the devel tab for that user and inspect what keys are actually being used to store the values in that field (probably one named target_id).

According to what you find there, fixing your code may be just matter of changing this:

$clinics = [
    array('value' => 132),
    array('value' => 133),
    array('value' => 134),
];

to this:

$clinics = [
    ['target_id' => 132],
    ['target_id' => 133],
    ['target_id' => 134],
];

(disregard the difference between declaring an array using the [] or the array(), I used the former in my edited code just for coherency)


I have found Webform Alternate UI to be quite buggy as well and have opted to use just the Form Builder module by itself, which gives a good UI for users to build forms (and is not buggy).


Content editor cannot view unpublished taxonomy terms when editing a node

You don't need to use permissions, just adjust the field's reference method.
Add a new entity reference display view that returns all taxonomy of the given type with the published = 1 filter removed (so it display all terms regardless of publish status).
Edit your entity reference taxonomy field for the relevant node type. Under the Reference Type, adjust Reference method to Views: Filter by an entity reference view, then select your newly created view.
After saving the field settings, the node form should display all taxonomy regardless of user permissions on viewing unpublished content.


I could find three possible ways. Supposing your module name is example and content type to check is article.
1. Validating the argument in the form builder
It is the simplest way.
First define your route as usual:
example.routing.yml
 example.node.edit_form:
  path: /example/{node}/edit
  defaults:
    _form: 'Drupal\example\Form\ExampleNodeForm'
  options:
    _node_operation_route: TRUE
    parameters:
      node:
        type: entity:node
  requirements:
    _permission: 'edit any article content'

Then simply put these lines to Drupal\example\Form\ExampleNodeForm::buildForm before the other code.
if ($node->getType() != 'article') {
  throw new AccessDeniedHttpException();
}

2. Validate the argument using custom access callback
The route definition is the same as above except custom_access option under the requirements section.
example.routing.yml
 example.node.edit_form:
  path: /example/{node}/edit
  defaults:
    _form: 'Drupal\example\Form\ExampleNodeForm'
  options:
    _node_operation_route: TRUE
    parameters:
      node:
        type: entity:node
  requirements:
    _permission: 'edit any article content'
    _custom_access:  'Drupal\example\Form\ExampleNodeForm::access'

Drupal\example\Form\ExampleNodeForm::access() should return instance of Drupal\Core\Access\AccessResult. This can be done as follows.
return AccessResult::allowedIf($node->getType() == 'article');

3. Validation the argument with access checker
example.routing.yml
 example.node.edit_form:
  path: /example/{node}/edit
  defaults:
    _form: 'Drupal\example\Form\ExampleNodeForm'
  options:
    _node_operation_route: TRUE
    parameters:
      node:
        type: entity:node
  requirements:
    _permission: 'edit any article content'
    _content_type:  'article'

As you can see this includes _content_type requirement. To make it work you need to implement custom access check service.
example.services.yml
services:
  example.content_type_access_checker:
    class: Drupal\example\Access\ContentTypeAccessCheck
    tags:
      - { name: access_check, applies_to: _content_type }

Drupal\example\src\Access\ContentTypeAccessCheck.php
namespace Drupal\example\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\Routing\Route;

/**
 * Checks if node type matches the one provided in the route configuration.
 */
class ContentTypeAccessCheck implements AccessInterface {

  /**
   * Access callback.
   */
  public function access(Route $route, NodeInterface $node) {
    return AccessResult::allowedIf($node->getType() == $route->getRequirement('_content_type'));
  }
}

The last approach can be helpful if you want to reuse access control code accross multiple routes.
Documentation: https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes.