What's the workflow behind [user:display-name] token?

As Clive said, the tokens are generated from hook_token_info() and hook_tokens(). For the User entity, those hooks are implemented from the User module. Token values aren't available just for email templates, but for every function/method that uses the token service. For example, in a controller, I could use code similar to the following one.

$bubbleable_metadata = new BubbleableMetadata();
$build['#markup'] = $this->tokenService->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata);
$bubbleable_metadata->applyTo($build);

As for getting the display name of a user account, that is easy: When user tokens are generated, user_tokens() gets a user object; calling User::getDisplayName() on that user object returns its display name.
See the code used from user_tokens(); in particular, see the following code. (Comments are mine.)

// Retrieves the user object passed to the hook.
$account = $data['user'];

// Generates the value for the display name token.
$replacements[$original] = $account
  ->getDisplayName();
if ($account->isAnonymous()) {
  $bubbleable_metadata->addCacheableDependency(\Drupal::config('user.settings'));
}

It is true there are user tokens available only for email templates, but that are generated from a callback used when replacing tokens in email templates. See user_mail() and user_mail_tokens().

  // user_mail()
  $token_service = \Drupal::token();
  $language_manager = \Drupal::languageManager();
  $langcode = $message['langcode'];
  $variables = ['user' => $params['account']];
  $language = $language_manager->getLanguage($params['account']
    ->getPreferredLangcode());
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);
  $mail_config = \Drupal::config('user.mail');
  $token_options = [
    'langcode' => $langcode,
    'callback' => 'user_mail_tokens',
    'clear' => TRUE,
  ];
  $message['subject'] .= PlainTextOutput::renderFromHtml($token_service
->replace($mail_config->get($key . '.subject'), $variables, $token_options));
  $message['body'][] = $token_service
    ->replace($mail_config->get($key . '.body'), $variables, $token_options);

function user_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
  }
}

user_mail() says to Token::replace() that user_mail_tokens() must be called after all the tokens are generated, and user_mail_tokens() replaces [user:one-time-login-url] and [user:one-time-cancel-url] (not replaced from Token::replace()) with the right values.

Similar code can be used from any module to generate tokens that must be  available only in specific context.


Which .tpl file should I use to theme the quiz module's detail page?

The answer surely will be here it describes how to create a .tpl files for ehat you want D7 theme suggestions


JSON:API error unprocessable entity status 422 entity_id this value should not be null

Check if you have the JSON:API Extras module enabled.
If you do, you or someone else may have disabled the field for the resource you are trying to POST to at /admin/config/services/jsonapi/resource_types.
In this case, I had disabled the entity_id field for my flag resource, causing the "null" error even when I posted a value with axios.


That was a hell of a problem to solve. I had to rebuild my code. Instead of hooks I took a bit different approach and I tried a solution proposed by @IvanJaros but I wasn't able to get lazy builders to work. I found that in drupal 7 there was a hook_init that was called everytime but it got deprecated in 8.

The answers are EventSubscribers, using them you can assign any function you want to specific event i.e. loading a page.
 Here's a great tutorial that intruduce you to that feature.

Here's my event code

    class MyEventSubscriber implements EventSubscriberInterface{

        public static function getSubscribedEvents(){
        // Its called when respond transfer ended
        $events[KernelEvents::TERMINATE][] = ['onRespond',28];
        return $events;
    }

  public function onRespond(FilterResponseEvent $event){
    $node = \Drupal::routeMatch()->getParameter('node');
    $user = \Drupal::currentUser();
    $name = $user->getUsername();

    $data = [];
    if(isset($node)&&isset($name)){
        $nodeType = $node->getType();
        switch($nodeType){
            case 'nodeType':
                $soap_response = new JSonGetter();
                $data = $soap_response -> getUserData($name);
                echo('<script>var JSONarray = ' . print_r($faktury,1) . ';</script>');
                break;
        }

    }
    }

}


Add 'Top product' field to products Ubercart

The default product and all product classes are a node content type that can have fields added to it. Go to Structure > Content types > Product > Manage fields to add your checkbox fields. The field will then be available in any node view for display or filtering.


How to import csv file for "field collection" using feed-importers

I recently had the same issue. Follow along with what I did:

Do NOT install the field collection feeds module.

Go here: https://drupal.org/node/1063434 and apply the patch in comment #16. (See https://drupal.org/patch/apply for details. Or you can just apply it manually, by copy & pasting the patch directly into /drupal/sites/all/modules/field_collection/field_collection.module).
EDIT: You may find more luck with one of the other listed patches on that page. #16 worked for me, so that is the one I suggested.

If the field collection fields have more than one instance, use the drupal module 'feeds tamper' to 'explode' the field collection mapping.

Clear your site's cache

Set new mappings to your field collection values (they should show up now as mapping targets).

Import your nodes, field collections and all!


Why on earth doesn't it return the newly created Entity/Term?!?

Why would it? You already have the term object, why do you need it to be chained in a return from a save method that can and does provide you with extra context??

Just use this:

$term = \Drupal\taxonomy\Entity\Term::create([
  'vid' => 'subject',
  'langcode' => 'en',
  'name' => 'Test af Tag',
  'description' => [
    'value' => '
My description.
',
    'format' => 'full_html',
  ],
  'weight' => -1,
  'parent' => array(0),
]);

$inserted_or_updated = $term->save();

$tid = $term->id();


How to create a user listing page with a tpl.php

Here I create similar page with views: http://cgart.ir/en/members

as you can see there is a list of users and 5 last uploaded image. the page created with views and latest artworks is another views.

to do that:

create first view for list users and in Format select Show:Rendered entity | Settings
create second view and configure CONTEXTUAL FILTERS and add Content: Author uid

edit user-profile.tpl.php and render second view there:

$account = $variables['elements']['#account'];
<?php print views_embed_view('second_view', 'page_1', $account->uid); ?>


Drupal 8: Class not found from module Controller, but works fine from module EventSubscriber

I never tried accessing theme classes from within any module classes. The reason is simple: The best practice you asked for is not doing so.

Whereas you can add classes to a theme for theming using object-oriented code, you should limit the operations performed by the theme to manipulating output generated by Drupal core and modules.

This should happen in a manner that allows for easily replacing your theme by another theme which is not featuring these classes.

Making a module dependent in a theme class will break this functionality.

Without having screened the core of Drupal, I could imagine that autoloading theme classes won't take place before theme negotiation happened.

Consider moving whatever your theme class does and is required by your module to a custom service provided by your module instead of the theme.

EDIT:

According to your comment, your original theme class had the use of creating a data table that should be themed for output.

The "Drupal way" then would be to moving your class to your custom module and making it a service by creating an according mymodule.services.yml (read more about creating a custom service here or here):

services:
  mymodule.myclass:
    class: Drupal\mymodule\MyClass

Then you can create an instance of your service by either using dependency injection (within the scope of other classes as your controller and/or event subscribers), or the static \Drupal::service('mymodule.myclass') getter within procedural *.module and *.theme files.

Your service could either have a method that returns the data table only, or even have a method for returning a themed version of the data table (render array with a #theme wrapper), whereas you implement a custom hook_theme() with a template and/or pre-processing from within your module.


hook_user_presave is an event listener that's called when a user account is saved.

It's invoked from user_save and shouldn't normally be called manually.

// Invoke hook_user_presave() for all modules.
user_module_invoke('presave', $edit, $account, $category);

If you want to save data on the user account, just use user_save


How to find which templates are affecting a display?

First, you can easily debug everything with Devel module. Another trick that I use to inspect what tpl is generating a particular element is by adding $conf['theme_debug'] = TRUE; in settings.php. After adding that refresh your page (or clear your cache first) then use inspect element. The tpl should be visible now in the HTML source. See the screenshot below.

Here is a blog that describe on how to theme a field.

Hoe that helps.


The entity_export function comes with the following caveat:

  Note: Currently, this only works for entity types provided with the entity CRUD API.

This means that if your entity type does not come with this, a call to entity_export() will return NULL.

This seems to be the case with node.

I am not sure, but I think the core team never got around to adding CRUD API to core entities.

If you inspect a node entity with dpm(), there is nothing. If you do:

 debug($node->delete, 'node->delete');

it prints NULL.


Load external php library in custom module

You cannot require classes with require or library hooks. Nor should you be editing external packages.

You are supposed to require external php packages with Composer. Composer will update the autoloader. Then in your class, you can say:

use ExternalPackage\namespace\Foo;

In the header and Foo class is then usable. Furthermore, you can inject it to the constructor with a little more work.

I would advise using SoapClient instead of nusoap as that is very old.

Regarding SoapClient, here is something I solved recently injecting it proper to my class, because that's the same road you're heading down.

Dependency inject a class with values from a config object?


Alter views with hook_views_query_alter()

I found a slightly different solution that works.

Instead of adding programatically the relation, I instead added a clause in $query->where

function taxonomy_location_views_query_alter(&$view, &$query) {
  $tid = subdomain_get_sid(subdomain_get_current_subdomain());
  if($tid) {
    $query->where[0]['clauses'][] = "(node.vid IN (SELECT tn.vid FROM term_node tn WHERE tn.tid = %d))";
    $query->where[0]['args'][] = $tid;
  }
}


There might be TinyMCE version issue with 4.7.x. Once I have facing the same problem. Then I uses the version 3.5.x of TinyMCE and its worked fine for me.

I hope it will work.


logging of access to images in image field

Take a look at the Mail Tracking module.

Drupal can only register requests for public files that aren't present yet (e.g. image derivatives that have not yet been created). Otherwise the file will be served directly by the web server.


You can't as such but you can store the values in the form somewhere and pick them up in your submit handler:

function mymodule_my_form($form, &$form_state) {
  $form['saved_value_1'] = array(
    '#type' => 'value',
    '#value' => 'The Value'
  );

  $form['#submit'][] = 'mymodule_my_form_submit';

  return $form;
}

function mymodule_my_form_submit(&$form, &$form_state) {
  $saved_value_1 = $form_state['values']['saved_value_1'];
}

Exactly the same principle applies if you're doing this in a form alter hook.


How to show contact profile and membership details in one Civicrm report?

Since you are using Drupal it can often be easier in my non-coding experience, to build a View to provide you with these kind of Reports - happy to provide more pointers if that is the direction you end up going


This is the Main Menu section as I see.

You need to made changes "settings.js" file present inside mobile-application\app folder.

Example:

// Main Menu
drupalgap.settings.menus['main_menu'] = {
  options: menu_popup_get_default_options(),
  links: [
    /*
    {
      title:'Content',
      path:'node',
      options:{
        attributes: {
          'data-icon': 'star',
          'class': 'ui-btn ui-btn-icon-right'
        }
      }
    },
    {
      title:'Taxonomy',
      path:'taxonomy/vocabularies',
      options:{
        attributes:{
          'data-icon':'grid'
        }
      }
    },
    {
      title:'Users',
      path:'user-listing',
      options:{
        attributes:{
          'data-icon':'info'
        }
      }
    }
    */
    {
      title:'Home',
      path:'home',
      options:{
        attributes: {
          'data-icon': 'home',
          'class': 'ui-btn ui-btn-icon-right'
        }
      }
    },
    {
      title:'Services',
      path:'websolution',
      options:{
        attributes:{
          'data-icon':'star'
        }
      }
    },
    {
      title:'Our Work',
      path:'ourwork',
      options:{
        attributes:{
          'data-icon':'star'
        }
      }
    },
    {
      title:'About Us',
      path:'articles',
      options:{
        attributes:{
          'data-icon':'star'
        }
      }
    },
    {
      title:'Testimonials',
      path:'testimonial',
      options:{
        attributes:{
          'data-icon':'star'
        }
      }
    },
    {
      title:'Contact',
      path:'node/58',
      options:{
        attributes:{
          'data-icon':'action'
        }
      }
    }

  ]
};

You will get details http://docs.drupalgap.org/7/Menus


Views: displaying related (referenced) content in a block

You would need to add a relationship from the reference field in views (under advanced > relationships). This will extend the scope of fields available to the view include those of the referenced node (Cook).

However this will as you state show all cooks as it will come from all recipes. In order for the block to know how to filter out all irrelevant cooks (ones not referenced) you will need a contextual filter which knows what recipe you are currently on.

On this contextual filter you can specify the relationship to the one you have already created, then you will need to let the block view know which recipe you are on. You do this with the setting "provide default value" and "Content ID from URL". This will tell the view which content you are on and hopefully apply the filter. Sorry I do not have access to D7 right now for a better explanation


I haven't done a D7 to D8 migration, but for a migration to D8 from an sql source, I find it's best to do a "child" migration before its "parent. So do the users, terms, and files before migrating the articles. And then if you roll back, do that in the reverse order: parents before children.

This blog post was helpful to me: http://www.mediacurrent.com/blog/migrating-content-references-drupal-8

This is the way I organize things in my migrations...

In the child migration:

process:
  parent_id:
    plugin: migration_lookup
    migration: parent_migration
    source: my_parent_id

In the parent migration:

process:
# for the label field and any other non-reference fields, create 'stub' values in this manner:
  label_field:
  -
    plugin: get
    source: my_label_field
  -
    plugin: default_value
    default_value: 'Stub Label'
child_items:
  plugin: migration_lookup
  migration: child_migration
  source: my_child_items

Note: if some of your parent entities don't have any child items, you can use the skip_on_empty process plugin as follows to make sure those parent entities are still migrated properly. (If child items are required for all parent entities, you can omit from the migration any parent entities with missing children by changing the 'method' from 'process' to 'row'.)

  child_items:
  -
    plugin: skip_on_empty
    method: process
    source: my_child_items
  -
    plugin: migration_lookup
    migration: child_migration


Email notification or several reminders at different time points

You need to use rules and scheduler module which is work with rule to send mail at period of time.


Commerce- How to add a product image on a product display to the shopping cart summary view

You should be able to do it by adding two relationships. First add Commerce Line item: Referenced products

and then that allows you to add Commerce Product: Referencing Node.

From there you should be able to add and reference fields from your display node.


Create a new region within an existing one

You can use the region.tpl.php

And add a template_preprocess_region to add the new region variable with in this region.

You can use the following code to add the region variable to the region.tpl.php

$variables['custom'] = block_get_blocks_by_region('custom');

So the over all process would be as follows.

first you would create a preprocess_region function as given below

function theme_name_preprocess_region(&$variables) {
  $variables['region_name'] = block_get_blocks_by_region('region_name');
}

next you would create a region template file called region--region_name.tpl.php

and print the variable $variables['region_name'];


Have user register or login on cart instead of checkout in drupal commerce

Is it possible: Yes.
Should you do it: No.

Why?

Having the user account pane at the the cart is a bad idea, since it probably would be very complex to do, and that there isn't really anything that hinders the user to start the checkout flow. You are also forgetting a very important thing.

The Commerce checkout flow is very customizable. This means that you can define extra pages in the checkout flow, and via the interface customize what should be displayed in each page. A much better solution would be to create an initial checkout page with account info only, an extra page that displays info about the order being validated and not allowing to process the order until it is approved. Once approved, the link could simply be that checkout page which with the updated order status can be skipped.

This will keep the customer in the checkout process and leverage the Commerce flexibility.


with limit(20) it runs only the first 20 values of DB

The common pattern is to store the last ID processed in a variable, using variable_set(). Then you can retrieve it using variable_get() with a default of 0 before running your query, and add a condition to the query for wid being greater:

$last_id = variable_get('mymodule_last_id', 0);
...
->condition('wid', $last_id, '>')

...
$last_id = value from row
variable_set('mymodule_last_id', $last_id);


Calculated field returns undefined index

$entity->language is the same as und so try using:

$entity_field[0]['value'] = $entity->field_ae_stimclasswrk[$entity->language][0]['average'];


Rule works but produced "err_empty_response" error when I want to edit it

Have you tried this on multiple servers as well? It is likely something on the server, so other browsers and computer won't make the difference. You did not specify the Drupal version but I ran into a similar situation with Drupal 8 while editing Views.

For me the solution was to increase the PHP memory limit. The linked page shows several ways to do this, but I chose to do it in the php.ini file. I believe it is 256M now.


Contextual filter with multiple entity reference fields

I think it's because you did not select a Relationship in your field.

Example: Title field (By the way, field_test is my entity ref field name)

Also make sure your contextual filter does not have a relationship


how to submit a text field input from a user in a views filter form to a javascript ?

got it I never used Jquery before and jquery is magic it when used with drupal behaviours as magic just listens to click or any event you want it to listen to and passes the value and you can retrieve it using $(# id of the field).val()[.val() is a function to retrieve the value].


Drush Bootstrap Error on Multi-Site Install

There are several ways to specify which Drupal site Drush will target.  The most basic option is fairly verbose; run:

$ drush --root=/path/to/drupal --uri=http://mysite.com status

You can do the same thing with a slightly different syntax:

$ drush /path/to/drupal#mysite.com status

You can also specify the Drupal site implicitly, by setting the cwd to the folder that contains the settings.php file for your site:

cd /path/to/drupal/sites/default # or /path/to/drupal/sites/mysite.com, as appropriate

$ drush status

In all of the cases above, if settings.php is in a folder called "default", then you do not need to specify the --uri component; you may, for example, cd /path/to/drupal followed by drush status, and the correct Drupal site will be found.  If settings.php is not in a folder named 'default', then you will need to either specify --uri, or cd to the folder that contains the settings.php file.

You might also want to investigate Drush site aliases, which are another way to conveniently specify which site you'd like Drush to target.


With the help of hook_theme_registry_alter you can override(actually by passing) any theme function.

Usually module's will define their theme functions in hook_theme(), however using hook_theme_registry_alter you can alter those information.

For your case below code will achieve the desired functionality,

/**
 * Implements hook_theme_registry_alter().
 */
function <my_module>_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['date_display_range'])) {
    $theme_registry['date_display_range']['function'] = 'theme_custom_date_display_range';
  }
}

/**
 * Returns HTML for a date element formatted as a range.
 */
function theme_custom_date_display_range($variables) {
  $date1 = $variables['date1'];
  $date2 = $variables['date2'];
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];

  // Wrap the result with the attributes.
  return t('!start-date - !end-date', array(
    '!start-date' => '' . $date1 . '',
    '!end-date' => '' . $date2 . $timezone . '',
  ));
}

So whenever you call theme('date_display_range', $variables), theme_custom_date_display_range() function will be invoked instead of theme_date_display_range().

Don't forget to clear the caches after adding hook_theme_registry_alter


BOA Aegir Octopus, APC disabled: Module's php files seem to be cached, changes are not reflected. Why?

Clearing Drupal cache may be not enough in this case.

Since Redis is active by default, it may still cache some include paths, or there can be old paths still present in your system table, so you need to run the "Rebuild registry" task followed by "Flush all caches" task (the second is the same as running drush cc all on command line).

If this still doesn't help, upgrade to latest BOA-2.0.6-dev (head), which includes recent APC 3.1.14 version to avoid this known APC bug.


How to fix the fatal error due to cached data while migrating?

Drupal uses code registry to load the files containing a class or an interface. While the code registry is cached in cache_bootstrap, it is contained in the registry and registry_file database tables.

To rebuild it, I would edit those database tables to change the path shown in the filename row to match the new site's path. Other methods that require bootstrapping Drupal would probably not work, since any class Drupal would use would not be found, causing a PHP exception, and stopping the bootstrap, with the effect that Drupal would not run the necessary code.


How to fix my problem when trying to create a Drupal sub-theme with Drush?

The issue mostly will be with environment/php and this is issue with MAMP (mismatch of path your MAMP-php and Server-php). Follow this link from that article.

  The Solution: A Symlink

  For the sake of ease, let’s just make your terminal sessions use the
  same PHP executable as MAMP. So run this:

$ mv /usr/bin/php /usr/bin/php.bak
$ ln -s /Applications/MAMP/bin/php/php5.5.3/bin/php /usr/bin/php

But you need to check path as per your folders.


How to let flexslider's picture point to its own node uri?

you can set the configuration in the view configuratin page, just see my screen shot.


Drush set block setting only working for one value

Ended up having to use:

drush config-set block.block.bootstrap_powered status --value=''


That's not correct, the default is AND. To use or, you need to use:

$or = db_or();
$or->condition();
$or->condition();
$query->condition($or);

But the main conditions on the query are definitely joined with AND.


Is there module that will add a drop down widget that auto-populates with a list of the site users?

You're looking for the References  module

  This project provides D7 versions of the 'node_reference' and 'user_reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts. See http://drupal.org/node/533222 for details.

Similar module is Entity Reference

  Provides a field type that can reference arbitrary entities:

You can add a new field for user list by selecting User Reference as a field type and select list as Widget Type in your content type.

Here is the screenshot for that


What is the difference between getValue() and referencedEntities() to fetch paragraphs?

Performance

EntityReferenceFieldItemList::referencedEntities performs better because it uses loadMultiple() instead of loading the entities separately.

Best practice

You use static code to load the entity which should be avoided when possible. You could make proper OOP code out of it, but it is also best practice to not reinvent the wheel.

Edit:
You've added the info this is in node preprocess. Then best practice would be to render the paragraph field in the node template {{ content.field_paragraph }}. Configure the field in UI, for example add a custom view mode. Theme the output in field and paragraph templates for this specific field or view mode.

Magic method

No, this doesn't involve a magic method,  the method is called directly. A magic method is involved in getting entity fields as if they were object properties, like the example you've mentioned $node->field_paragraph.

Translation

You need to translate the entities for both methods before you can output translated field values directly:

$paragraph = \Drupal::service('entity.repository')
  ->getTranslationFromContext($paragraph, $langcode);

By the way core translates the entities later when building the rendered output using the entity reference field formatter. This works for core because it usually doesn't output field values directly, so this could be considered as bad practice as well, see for example this question from today How to display Paragraph bundles fields links inside a page.html.twig file that are within a paragraph bundle in Twig?.

Revisions

Paragraphs are stored in an EntityReferenceRevisions field. Your example code ignores the revision data and so you might load the wrong version. One more reason to use the methods provided by the field, referencedEntities() or $item->entity in case you need to load a single entity.


location

gmap

views

With these three drupal modules you can easily create a map which will display all nodes with location details.


Changing image styles in a node view (Drupal 7)

You can manage image-styles under

  admin/config/media/image-styles

and then use these styles to show up in your node view. Settings can be found on the "Manage Display" tab of your content-type. There's a little gear on the right side of the field row...


There seems to be no method to update a complete node.

But you can do this on a field basis:

foreach ($field_array as $field => $values) {
  $node->set($field, $values);
}


How to define a menu with and without url arguments in hook_menu?

You have two options:

1) Define both paths, jobs and jobs/%.

2) Define only the first path

$menu['jobs'] = array(
  'page callback' => 'my_page_callback',
  ...

Then make the argument optional:

function my_page_callback($job_id = FALSE) {
  ...

This callback will be called for both paths.


How to create a main menu with dropdown?

You need to use any of this module

Nice Menus

  Nice Menus enables drop-down/right/left expandable menus. It uses only
  CSS for most browsers, with minimal Javascript for IE6.

Superfish Menu

  You will see several blocks called Superfish", move any of them to a
  region, use the "Configure" link of the block to configure it
  accordingly to your needs, and save.

Responsive Dropdown Menus

    Responsive Dropdown Menus provides a new menu tree rendering to make
    responsive, drop-down enabled main menu possible on any theme.

Provides new menu blocks for each menu.
All module blocks add dropdown menu support and responsive menu toggles.

Megamenu

  Mega menus are a type of drop-down, which seeks to overcome some of
  the usability drawbacks of traditional drop-downs. Hierarchy of your
  navigation is made visible all at once and the amount of clicking,
  searching, and navigating is reduced.


How do I get the current year in the footer?

That happens because you are creating a custom block, but you didn't select PHP code as input format.

In Drupal 7, you need to first enable the PHP module (php.module); in Drupal 6, you need to first enable the input format on admin/settings/filters. Once you have done that, you will be able to choose PHP code as input format, and write PHP code between <?php ?> tags; the code will be executed, and the output will be the content of the block.


We had a similar issue and traced it to the nginx fastcgi_read_timeout option. Because the code to clear the cache doesn't send any output to the browser until it finishes, nginx doesn't receive anything from PHP for 60 seconds. At this point, the default fastcgi_read_timeout is reached, so nginx aborts the request.

When you added the echo $path, you forced PHP to output something, which meant that nginx had something to read, so it didn't reach the timeout.

You should try increasing the fastcgi_read_timeout to, say, 120s and see if that helps.


My PECL uploadprogress bar appears, but why doesn't it show any progress?

Have a look at the (very old) issue # 633862. Even though it's an old issue, it includes quite a few comments that may help you to find "the clue". E.g. that it it doesn't seem to work for the more "exotic" server configurations.

Comment # 41 states this:

  Apparently secure servers also have an issue with it https:// won't work with this.

Comment # 43 in that issue also suggest the (sandbox for now)  upload_progress module, here is what that comment includes:

  I have created a little module that uses client-side JavaScript instead of server-side code to display the progress. This will finally bring upload progress to more "exotic" server configurations.


Show Targeted Content Based on Content Field and User Roles

You can make your content field a taxonomy term and you can accomplish this with a simple view without any custom coding.

If we assume

vocabulary Departments
user has field Departments
some users with department selected
token and views_argument_token installed

Add a content view

Add any relevant filters (content types, etc)
Add user relationship
Add contextual filter Has taxonomy term id

Provide default value > token and fill in the current user's selected term id which in this case is [current-user:field_department:target_id]
use Browse available tokens to find the relevant token

Here is a screenshot of a working view


Are you clicking Save at the bottom of the edit page after uploading the new PDF?

You need to do this to save the file reference in the node field.


Can't find location of files after running drush make

Look for errors and warnings in the output of the make command. An empty directory is often the result of an error. This leaves your install directory in the drush temp location (usually /tmp/drush-xxxx).

You can add the --force-complete argument ignore errors and to copy the directory in to place anyway. But it's probably worth figuring out what the errors are.

drush make --force-complete qmlc.make

https://github.com/drush-ops/drush/blob/master/commands/make/make.drush.inc#L58


Processing the content generated by a node?

In Drupal 8, you can use hook_ENTITY_TYPE_view_alter() (which in this case would be hook_node_view_alter()) to alter the render array for the entity; otherwise, as the documentation for that hook suggests, you can use hook_preprocess_HOOK() (which in this case would be hook_preprocess_node()).

  If a module wishes to act on the rendered HTML of the entity rather than the structured content array, it may use this hook to add a #post_render callback. Alternatively, it could also implement hook_preprocess_HOOK() for the particular entity type template, if there is one (e.g., node.html.twig).

As for template_preprocess_node() implemented by a theme, that is not different from hook_preprocess_node(): It can either add new variables, or change the content of existing variables. In both the cases, the $variables parameter is passed by reference, so any change to the array is passed back to the function/method invoking those hooks.

The other alternative would be implementing an input filter in a module, and add the input filter to the input format used from the content type. This would have the pro of stopping the replacements simply by removing the input filter from the input format, and it would also have the pro of changing in the site configuration which content types would have the text replaced, and document to users the changes done to nodes.
The con is that it cannot be used in fields that don't use input formats, but it works for the body field of nodes. If you need to alter the text that appears in a link field, for example, an input filter would not help (since the link field would ask for a URL and the text to show as link title).


For install content, you can use Default Content for D8 (also on GitHub). For ongoing content syncing Entity Pilot is expected to enter public beta this week and there is an active initiative around Deploy module.

Disclaimer: Entity Pilot is my project.


Change page title on user-profile using a field value from Profile2

If you actually seek to always use the full name for the user's Profile2 when his/her username is displayed, then you should implements hook_username_alter(). Any well behaving module (contrib and core) should use it.

function MODULE_username_alter(&$name, $account) {
  // Get the user profile
  $profile = profile2_load_by_user($account, 'profile_type');
  if ($profile) {
    $fullnames = field_get_items('profile2', $profile, 'field_fullname');
    if ($fullnames) {
      $name = $fullnames[0]['value'];
    }
  }
}

If you only want to override the username when used as title of the user page, you can alter the menu entries for user and user/%user to change their title callback to a custom one.

function MODULE_menu_alter(&$items) {
  $items['user']['title callback'] = $items['user/%user']['title callback'] = 'MODULE_user_menu_title';
}

function MODULE_user_menu_title($account) {
  if (is_object($account)) { // Updated here
    $profile = profile2_load_by_user($account, 'profile_type');
    if ($profile) {
      $fullnames = field_get_items('profile2', $profile, 'field_fullname');
      if ($fullnames) {
        return $fullnames[0]['value'];
      }
    }
    return user_menu_title($account);
  }
  return '';
}


To clear drupal caches using drush 9x use the following command:

drush cache:clear

Command aliases:

drush cc
drush cache-clear

To clear all caches you can use:

drush cache:rebuild

Command aliases:

drush cr
drush rebuild
drush cache-rebuild


Print field from reference of reference (node)

There is always more than one way to solve a problem in drupal.  How easy those ways are is up for debate, but they exist.

You could:

Make a view with those reference fields as relationships and a nid context filter that would recognize the Node.1 end of the relationships.  Set this view to have a block display, and A) put the block on the page with a context or B) summon the view to be rendered by name in your tpl. Or with the function views_embed_view
Make database fetches or entity field queries directly in your node.tpl.php.  This is uncouth, as such logic should not be put in the theme layer, but functional.
Forget about node.tpl.php entirely and do this in panels.  I'm pretty sure it supports using referenced fields.

The echo $view->render('block_view'); method would be my suggestion to you.  Views is a very powerful module, has built in theming overrides (and more if you want more tpls) and can do all sorts of rewrites and manipluations while laying things out for you.  Add the ability to conjure it's database bending powers from your tpl with just 6 lines of code, and it is stupendous.


I've never done this before so I'm not sure if this will work but I assume you can manually update the schema_version column in the {system} table to the highest hook_update_N number. For example if there's mymodule_update_7101 in the .install file of mymodule then update the schema_version column of the system table for mymodule to 7101.

I don't get it though, how come if you have updated fields in the module table of same database, how is it that the system table is older?


You can add custom parameters through hook_apachesolr_query_alter, eg

function MYMODULE_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  $query->addParam('group', 'true');
  // etc
}


Toggle Modules on or off at a certain time with Rules

Since you run cron in every 15 minutes, you can use module_disable or module_enable in hook_cron of your module. Using

format_date(time(), 'custom', 'l j F Y');

you can get the current date and time. What is difficult for you to build such module?


Changing form field title within hook_preprocess_form() does not work

Use hook_form_alter() to change the form before it gets rendered.


In the "Rewrite results" section, when you checked check-box "Trim this field to a maximum length", there is check-box "Field can contain HTML" in this section. If you check check-box ""Field can contain HTML", then Drupal will maintain your HTML with content.


The user register form is located in Drupal\user\RegisterForm. Check the annotation on the User class.

/**
 * Defines the user entity class.
 *
 * The base table name here is plural, despite Drupal table naming standards,
 * because "user" is a reserved word in many databases.
 *
 * @ContentEntityType(
 *   id = "user",
 *   label = @Translation("User"),
 *   handlers = {
 *     "storage" = "Drupal\user\UserStorage",
 *     "storage_schema" = "Drupal\user\UserStorageSchema",
 *     "access" = "Drupal\user\UserAccessControlHandler",
 *     "list_builder" = "Drupal\user\UserListBuilder",
 *     "views_data" = "Drupal\user\UserViewsData",
 *     "route_provider" = {
 *       "html" = "Drupal\user\Entity\UserRouteProvider",
 *     },
 *     "form" = {
 *       "default" = "Drupal\user\ProfileForm",
 *       "cancel" = "Drupal\user\Form\UserCancelForm",
 *       "register" = "Drupal\user\RegisterForm"
 *     },
 *     "translation" = "Drupal\user\ProfileTranslationHandler"
 *   },
 *   admin_permission = "administer users",
 *   base_table = "users",
 *   data_table = "users_field_data",
 *   label_callback = "user_format_name",
 *   translatable = TRUE,
 *   entity_keys = {
 *     "id" = "uid",
 *     "langcode" = "langcode",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "canonical" = "/user/{user}",
 *     "edit-form" = "/user/{user}/edit",
 *     "cancel-form" = "/user/{user}/cancel",
 *     "collection" = "/admin/people",
 *   },
 *   field_ui_base_route = "entity.user.admin_form",
 *   common_reference_target = TRUE
 * )
 */

_entity_form: user.register pulls from here.


Override Field.tpl.php for a specific node/add form

Implement hook_form_alter() or one of its relatives by setting the #theme key of the form elements.


Field groups not showing when nested using field type HTML

the solution and patch can be found here:
https://www.drupal.org/node/1503094#comment-11981615


Why my hook_filter not work in Drupal 6?

Given that you are only seeing 'list', I would make sure that your filter is added to an existing Input Format (check at admin/settings/filters and click on configure next to the appropriate input format) and also that all caches are cleared.  Sometimes if you start entering/coding a filter and it runs before you've got all the kinks worked out, the case 'no cache' gets in the way and stores the initial/wrong result.  Until you are sure of everything, you may want to change that to return TRUE; as well.


How do I prevent a module from being loaded?

See module_disable and the comments therein for how to place it within a profile.install or module.install file.


Drush: Listing all modules installed on multiple servers

You can add Drush Aliases for each site, and then add an alias containing all your sites.

Then:

$ drush @allsites up


How do I override a function in a module

It sounds more like you want to use hook_menu_alter to override what the Taxonomy Menu module's hook_menu function does.


Please try Entity reference autofill with Entityreference prepopulate Module.

Add an entity reference field in your entityform.
The entity reference autofill will automatically fill reference value into field. We can load default value from URL. (?field_name = value)
Entityreference prepopulate will prepopulate the values. (you have to add existing fields for that.)

Hope this will help you.


How do I migrate only the items that previously failed?

Another possibility is to use the "--needs-update" option as "migrate-import Article --needs-update" .

You might need to status of needs-update field for these 40 records as needs_update=1.

This option is only needed when your Drupal DB is on a different DB server from your source data. Otherwise, these records get migrated with just migrate-import.


Plain Unstrucutred HTML Content Types, How to Pull image from them in Views

you will need to only create one view theme. That will be a theme for the BODY field of your node. It's actually super simple.

create a PHP file in your theme folder called views-view-field--YOURVIEWNAME--body.tpl.php
your file has one variable you need to worry about, $output and that's the HTML. Write your PHP code to isolate the very first image tag and then this site has a nice example of how to do that

I think the code in this file would end up looking like this

  $first_img = '';
  $numMatches = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $output, $matches);
  if($numMatches){
    $first_img = $matches [1] [0];
  }else{ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  echo '<img src="' . $first_img . '" alt="thumbnail" class="thumb"/>';

add some CSS to make the thumbnail, or alternatively you can use theme with imagecache I think.
refresh your template cache

You're done!


In the views under fields add "Custom Text" field. Wherein text field you can Replacement patterns from exisiting fields. There you can give link

{{field_name}}.

After that edit email field and check "Exclude from display".


Is there a way to make a unique view template for a specific type of view?

Yes it is. Open the Views Admin UI and in Theme Information there is a list of available template files

For example in my website it is:

You can use any of them.


It sounds like you're looking for the PDF Reader module.

  PDF Reader will render your entity file fields with the selected PDF
  renderer.

  The implemented PDF renderers are:

  Google Docs Viewer
  pdf.js - PDF Reader in JavaScript
  Direct PDF embed
  Microsoft Office Web Viewer(7.x-2.x-dev)

This module lets you specify any file field to render as a PDF embedded in a node. It also has an option to display download link for the embedded PDF.


https://stackoverflow.com/users/763010/tyler-frankenstein created a grate article that can be found here

you might also find https://stackoverflow.com/questions/10428014/steps-to-make-a-mobile-application-using-drupal-as-a-back-end-or-service/13662041#13662041 useful it has links to articles that describe services in full.

I'd also advise a couple plugins
Firefox: poster
Chrome: postman

http://drupal.org/node/1795770 might be more applicable it's how to login, post a comment, and loggout from curl hope it helps.


How to add custom fields in Apache Solr's search result?

If you have D7 and latest Solr search integration module then you can follow these steps:

Create a custom module with the following code (If your field is single value text then you should add "ts_" prefix to its name.)

function mymodule_apachesolr_query_alter($query) {
  $query->addParam('fl', 'ts_field_name');
}

Add the following function in the template.php file

function YOUR_THEME_preprocess_search_result(&$variables) {
  $variables['ts_field_name'] = $variables['result']['fields']['ts_field_name'];
}

Display the field in search-result.tpl.php

<?php if ($ts_field_name): ?>
  <?php print $ts_field_name; ?>
<?php endif; ?>

This is a quick way that doesn't use any  theme function like theme_apachesolr_search_snippets() for search results snippets.

You can find more information here:

http://archive.org/details/ApacheSolrSearchMastery_250
http://www.slideshare.net/AcquiaInc/apache-solr-search-mastery


Math Field doesnt recalculate when fields are populated

The (fairly new) Math Field module for D7 is a not commonly known/used alternative to Computed Field).

However, there are still a few other (known) issues with it, as mentioned also on its project page:

The cTools math expression library causes an error when using function that take more than one parameter. This effects pow(), min(), max() (#1958538: Improve math expression engine).
Math Field does not yet support multivalue options fields (checkboxes, or multiselect) (#2483453: Add aggregate functions for multivalue fields).

However, if you're trying to use this module to handle multivalue fields, then that would explain why you can't get that to work (as per the issue mentioned before: multi value fields are not yet supported).


My module adds a CCK field to an existing content type. How do I then modify an existing view to sort using the new field?

You should override the view and change the sort. I have never seen a module that attempted to alter a view defined by another module.


You may have to review your code, your sliding effects javascript file is missing from your other pages except for the front page.

<script type="text/javascript" src="http://karelmaes.stijnaerts.be/sites/all/themes/business/js/sliding_effect.js?n8jrx6"></script>

Above missing.

You can check this out for more information Adding Javascript to themes


You can do this in Panels.

First, remove the print title statement from page.tpl.php in your theme.

Usually it looks something like this:

      <?php if ($title): ?>

<?php print $title; ?>

          <?php endif; ?>

This will prevent Drupal from printing the title automatically.

Then open up Panels and activate (if you haven't already) the node override template and the user override template as well as any other places where you need to display the title.

Then add the title where you want it to appear from within the Panels interface (Add content -> Page elements -> Page title).


How to display another message instead of 403 when trying to open a display of an unpublished product?

You could add a view as the error page.

Add the view with page (with appropriate path) and attachment as your error page. Filter it on your Product display, pass in the nid as contextual filter and be as creative as you want. The attachment can show the details for the Product that is no longer available, the actual page view can show similar products as alternatives etc. The not found for the contextual filter can be the generic 403 for anything other than products.

Then add the path of the view to the 403 error page setting at admin/config/system/site-information


How can I import the contents of an uploaded csv file into a drupal managed table using rules custom php?

So conceptual steps:

Extract CSV file path from the node.
Open CSV file, read fields from header.
Read each row, convert the keys, save row using drupal_write_record().
Close the CSV.

I'm not sure how the rules integration will work I'm assuming you can pass the node into it some how.

So for step one assuming it's stored into $node and your field is named field_csv_file we can hand the URL to fopen():

$csv_uri = $node->field_csv_file['und'][0]['uri'];

So now we can open fopen() to get a file handle:

$handle = fopen($csv_uri, 'r');

If there's no value we don't want to procede.

Read the header row:

$row = fgetcsv($handle);
$columns = array();
foreach ($row as $i => $header) {
  $columns[$i] = trim($header);
}

Then load each row and convert the format:

while ($row = fgetcsv($handle)) {
  $record = array();
  foreach ($row as $i => $field) {
    // This is pretty brittle... if someone screws up the field
    // names the data won't be written.
    $record[$columns[$i]] = $field;
  }
  drupal_write_record('your_table', $record);
}

Close the file:

fclose($handle);

So issues with this:

All this code it totally un-test.
What happens if someone re-uploads the file? You'll probably get duplicates.
What happens if someone messes with the headers?


Workflow assign user to handle node in given state

I am developing a module that address that very issue and some other things. Besides it is on sandbox yet, it is fully usable (I am using it on production).

  Workflow Hide Fields is an addon to the Workflow module.

You can clone it:

git clone --branch 7.x-1.x git://git.drupal.org/sandbox/fpap/2575131.git

And can visit the module page.


Creating a rule to display Terms Of Service upon Ubercart checkout

So after a lot of failed methods and frustration I found a solution.

You will need the following modules:

Ubercart Terms of Service (https://drupal.org/project/uc_termsofservice)
Ubercart Product Checkout Pane (https://drupal.org/project/uc_product_panes)

First install the Terms of Service module and set up your terms accordingly. Then install the Ubercart Product Checkout Pane and set the TOS to appear at checkout with the specified product(s).

This allows you to display the terms for each product that requires them.


This is off the top of my head with some parts but I think this is the way you would do it.

print theme('image_style', array('path' => $message->author->picture->uri, 'style_name' => '{image-style}'));

With {image-style} replaced with image style that you want like thumbnail.

If this doesn't work I will take a second look.


How do I use a "contains" operation as restful contextual filter for text fields

When you expose a filter, you can set a filter identifier.  This can be used to set the filter value via the URL, E.g.:  /search?keywords=foo or  /search?keyworks=foo+bar.

Note that if you need to hide this filter in a user view, you can do that with CSS or the Views Block View Filter module which allows you to move exposed filters to separate blocks that don't need to be placed on a user page.  Not part of your specs.. but nice to know if you need REST and user pages.

Also, given your requirements, you might want to consider either using the Search API module with it's views structure or code your own rest handler.

The Search API module will lets you easily set up full text searches and manage results order based on boosts, e.g. words found in titles are more important. The DB backend works well in D8, so you don't need Solr server for this.  (Though Solr has a lot of neat features).

Coding your own shouldn't be too hard with the D8 rest implementation.  You can then do any query variations you need.


Add a filter to the View, and filter out all events where date is NULL.


How to render $site_name without html tag?

In a preprocess function you can get the title like this:

variable_get("site_name");


Drupal Commerce: Get selected payment method programmatically

I don't think there's anything built in, but you can use an EntityFieldQuery to grab the transaction(s) related to the order, and from there the payment type(s) used:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_payment_transaction')
  ->propertyCondition('order_id', $order->order_id);

$results = $query->execute();
if (!empty($results['commerce_payment_transaction'])) {
  $transactions = entity_load('commerce_payment_transaction', array_keys($results['commerce_payment_transaction']));
  foreach ($transactions as $transaction) {
    $payment_method = $transaction->payment_method;
  }
}


If yo don't want to modify the template file you may implement it using js, some thing like this,

$('.title-class').parent().parent().click(function(){
      var url = $(this).find(".title-class").attr('href');
      windows.location = url;
});

BUT YOU MUST BE SURE THAT THE DIV DISPLAY MUST BE SET TO INLINE-BLOCK IN ORDER TO BE AS LARGE AS ITS CONTENT


I thought of another way to do it.

Start with code that just adds the product to the cart without modifying.

function addToCart($product_id, $quantite) {
    commerce_cart_product_add_by_id($product_id, $quantite);
}

Then you can use a hook to modify the line item amount

//alter the price in cart & order
function my_module_commerce_cart_line_item_refresh($line_item, $order_wrapper) {

    $price = 100; //1 dollar
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['amount']=$price;
    //alter the base_price component
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['data']['components']['0']['price']['amount']=$price;

}

If this doesn't work try forcing the cart refresh
e.g.

function addToCart($product_id, $quantite) {
    global $user;
    commerce_cart_product_add_by_id($product_id, $quantite);
    $order = commerce_cart_order_load($user->uid);
    commerce_cart_order_refresh($order);
}


Whether to keep redirects is an SEO question. Do you have good search results on Google which you don't want to loose. Or you have external sites or even print stuff that point to your old URLs. Then you have to keep them.

If all this is not true, you can safely delete you old redirects.

About the DB:

The redirects are stored in the url_alias table. It has two indexes for the mapping from nid to redirect url and from redirect url to nid. This means that reading is fast even if you have thousands of redirects.

If you are creating a lot of redirects this can get slow. But this will not hit you for a few thousand redirects. If you have millions you have to dive into MySql details (or whatever DB system you are using) and find what you can do about it. Since you are only adding records to the DB table, there's a lot of DB tuning stuff that can help you.


Taxonomy term reference field from custom database table

The easiest solution would be to use some sort of system to synchronize those terms from whatever data set you have to real taxonomy terms.

It would probably function similarly to Node Auto Term.


Grouping multiple columns in a view result for a report

To group the quantity, Batch no and expiry date fields in another column, use the views secondary row module

  Provides a way to split a views table row into two. In the table style
  settings, select a "Secondary row" option.

  So if a table looks like this: Name | Description | Edit link | Delete
  link selecting "Name" as the secondary row option for "Edit link" and
  "Description" as the secondary row option for the "Delete link" will
  render two rows:

For summary of the quantity in the footer, use Views summarize

  Enables an extra display style which displays summaries of a column on
  the last row.


Do I have to use Views to use all the behaviors of OpenLayers maps module?

The learning curve is a little steep when first working with openlayers if you really want to use it you can create your map and add a geoJSON layer to it and just write the geoJSON code in the textarea provided to create the point and popup info. Checkout openlayers plus module for more behavior options.


Content Template no longer displaying new nodes. Works fine for older nodes

The module's page explicitly states:

  NOTE: This module may be deprecated in Drupal 7! Here's your reason,
  basically the theming changes in D7 mean the field theming gets bound
  a lot lot later in the process, so it's not possible to generate the
  output into a Textarea for you to edit

In fact the module has been marked as deprecated and not updated since 20 September 2011.

Also there is a long discussion on https://www.drupal.org/node/1285558 about better ways of doing things without Contemplate module.

So it's just time for you to give up the deprecated module and re-code your template files as it simply won't work with later versions of Drupal 7.


Sensible way to rewrite a field for all views in Drupal 8?

You can use hooks the same way as in Drupal 7, if you want to change the content of the node before rendering, you can put a hook in your module or theme:

module/theme_preprocess(&$variables, $hook) {
   if ($hook == 'node') {
      ...

check if you are in the right node and change it.

The simplest solution for your problem would be to put all children images in the node display and then hide the images you don't want:

hide($variables['content']['field_image_?']);

So you don't need to lookup the children image yourself.


Create dynamic text fields on form based on other entities

Paragraphs is what you want. What you are describing is Paragraphs' exact use case. We use Paragraphs as a staple of our platform because of its re-usability.
Assigning an existing Paragraph to an Entity Reference Revisions field on a node is as simple as:
// Note that the value will be a nested array, even if cardinality is 1.
$node->get('field_food')>setValue([
  [
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ],
]);
$node->save();

// Another example: assigning multiple references to a single field.
$node->get('field_myfield')>setValue([
  [
    'target_id' => $paragraph1->id(),
    'target_revision_id' => $paragraph1->getRevisionId(),
  ],
  [
    'target_id' => $paragraph2->id(),
    'target_revision_id' => $paragraph2->getRevisionId(),
  ],
  [
    'target_id' => $paragraph3->id(),
    'target_revision_id' => $paragraph3->getRevisionId(),
  ],
]);
$node->save();

If you need to generate a paragraph programmatically, that is also easy:
// Note that I'm using the DIC for demonstration's sake.
// Be sure to use dependency injection and other best practices in your project.
$storage = \Drupal::entityTypeManager()->getStorage('paragraph');
$paragraph = $storage->create([
  'type' => 'food',
  'title' => 'A title',
  'field_a' => 'a value',
]);
$paragraph->save();

You can then assign this newly created paragraph to an Entity Reference Revisions field using the method I mentioned above.


If you are using a distribution, etc., it may be the case that there are content types that are provided by another feature or custom module.  These will not appear in the Features UI by default in order to prevent conflicts.


How to hook into fivestar_ajax_submit function?

My friend helped me with this solution:

function MYMODULE_element_info_alter(&$info) {
    $info['fivestar']['#process'][] = 'MYMODULE_fivestar_process';
}

function MYMODULE_fivestar_process($element) {
    $element['vote']['#ajax']['callback'] = 'MYMODULE_fivestar_ajax_submit';
    return $element;
}

function MYMODULE_fivestar_ajax_submit($form, $form_state) {
    $result = fivestar_ajax_submit($form, $form_state);

    $type = $form_state['build_info']['args'][1]['content_type'];
    $id = $form_state['build_info']['args'][1]['content_id'];
    $votes = fivestar_get_votes($type, $id, 'vote', $GLOBALS['user']->uid);

    $result['#commands'][] = array(
        'command' => 'insert',
        'method' => 'replaceWith',
        'selector' => 'span.vote-count',
        'data' => '' . format_plural($votes['count']['value'], '1 vote', '@count votes') . '',
        'effect' => 'fade'
    );
    return $result;
}

This code adds and change votes counter displayed after fivestar voting widget.


Getting the role ID from the global $user

You can use array_key_exists() to do this:

$rid = 42;

if (array_key_exists($rid, $user->roles)) {
  // Do stuff
}

If you just want an array of RIDs, you can use array_keys():

$rids = array_keys($user->roles);


With a custom form, how to sanitize user input before query gets to URL?

Drupal's mantra is to sanitise upon output, not input. See Writing secure code for Drupal 8 for more information.

So there's no need to sanitise upon submission, just make sure that if you're rendering that value anywhere, it's done in a secure manner (as explained in the docs above).

If you decide that you still need the solution you've outlined, it's going to have to be implemented in JavaScript. Your form method is GET so the browser handles the input -> URL conversion, not Drupal.


Folder permission errors on public:// after upgrade to 8.8.5

Update:

Find current mode of SELinux and temporarily shut it down. "#" is for comment and can be removed.

Getenforce # see current mode.

getsebool -a # find al boolean values

Sudo setenforce 0 # shut it down, but will be back at reboot.

Try your thing.
If that’s cause, just add rule to allow locations like /var/www/your Docroot.

SElinux will come back with reboot so to add a permanent rules for /var/www/drupal-document-root.

I do the following.
Line 2 will work but won't survive rename & restorecon
(line 3 will survive such things).

 ls -dZ /var/www/html  # See SELinux context of
 sudo chcon -R -t httpd_sys_content_t /var/www/html/drupal-document-root
 sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"

I have also done the following in the past to give apache write permission.

# Selinux allow httpd read & write to /var/www/html/my-project
sudo chcon -R -t httpd_sys_script_rw_t /var/www/html/my-project/
sudo chcon -R -t httpd_sys_script_rw_t /var/www/my-Symfony-project/var/log/

SELinux references:
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/selinux_users_and_administrators_guide/sect-managing_confined_services-the_apache_http_server-types

Beside that, the following is what I do when I setup new site and run into this kind of thing.

1) cat /etc/http/http.conf | grep user , to see user Apache is running as
2) from the vhost file, check the document root
Then follow it and make sure Apache can write to it
3) Check your docroot or Symlinks
Post and show the following
1&2& then l would love to see
Ls -al /document root that Apache is pointing to
And output showing Apache user is in right group

Don't forget to reset your drupal permissions to the best practices after resolving the issue. look at 2nd answer of the following.

What are the recommended directory permissions?

Ps: assuming your not setting up multisite as few more things will be needed.


How to record how much time user has spent on my node?

Without using any custom modules

Drupal core doesn't have any such feature. So if you don't want to consider using a contributed module, the only options you have is to:

Write a custom module (or further enhance the custom module you already have for it).
Add something like a javascript to the theme(s) you're using.
Wait for a future release of Drupal (core) that may include such feature.
Consider using a contributed module (e.g. as further explained below).

Using the Javascript Timer module

The Javascript Timer module (available for D6 and D7) seems to be a possible answer to your question. Here is a quote from its project page:

  ... provides a timer API that can hook HTML elements to javascript widget objects. This is useful if you want a moving timer/clock or a widget that updates every second. It comes with widgets for a count-down timer, a count-up timer, and a clock. It uses jQuery and a single event loop to handle as many timers as you need on a single page.

Its Readme.txt file contains various examples, both Inline HTML Examples and PHP Input Format Examples.

Comment #4 in issue #1195560 contains an interesting comment that may help to get you going:

  It allows for redirecting to a new URL or refreshing the existing page.
  On the setting page it is called "Timer complete redirect". If you use a "redirect path" of <reload> it will just reload the current page.


EntityFieldQuery does not support 'OR' operators. There is a workaround presented here 'OR' Queries with EntityFieldQuery  where an 'OR' operator is added.


You can do this by creating two different display of same view. If your current view display is page at path like /view/list-view then create another page display of same view with path like /view/grid-view. Then Configure that display as Grid view under views Format settings. You can use that path to create link to that view later anywhere you want.


access denied when viewing profiles of other users

Impossible to say exactly without having access to your site, but something ON the profile page is causing this.

Do this (assuming you're on Drupal 7):

Open /modules/user/user.module
Scroll down to line 820 (which should be: return isset($perm[$account->uid][$string]);)
Immediately above that line, add this code:

.

if (!isset($perm[$account->uid][$string])) {
  echo 'denied permission: ' . $string . '<br/>';
}

Reload the page as a user that's getting Access Denied, and you'll get a printout of all permissions the current user got denied - one (or more) of them will be the culprit.

Don't forget to remove the code changes once you've found the issue.


How to limit/throttle speed of Views feed?

This is possible, but not with just feeds.

You'll have to implement some sort of queuing, that looks at previously published nodes to determine if the new group of nodes can be added to the feed yet, or if they need to wait.

You should be able to get this working with some clever rules and a few VBO views.


I am using a Menu Block module and Context to achieve a similar thing.

For conditions, I have this fire on a Content Type of Instructor Profile. I add Menu Block's blocks to region's One and Two accordingly.

And I use Context to automatically select the menu level for me


How to modify the layout or look-and-feel of a specific node?

One of the things you can do to help with this is to enable Theme Debug mode, see here:

https://www.drupal.org/node/223440#theme-debug

This will tell you what templates are currently being used, and will provide suggestions for what templates to use, when you inspect the source of your node page (the suggestions are in HTML comments, so make sure they're enabled in your inspector).

It also details how to create your own custom template suggestions, the patterns of which is detailed here:

https://www.drupal.org/node/1089656

Make sure you place the templates inside your theme directory in order for the theme to pick them up.


RSS Feed does not validate using Views RSS module

In some cases this error will be caused by space in one of your modules. Best way to find the issue is to edit module.inc file in includes folder and add this after the drupal_load function in the module_load_all function:

print $module.'|';

you will probably get a huge list but one that starts on line 3 will be the issue.


Drupal 8 custom block with html and javascript

You need to use hook_theme() in your module, and declare a new Twig template that you want to use for your block.

Here's an example that needs to go to YOUR_MODULE.module file:

function YOUR_MODULE_theme() {
  return [
    'YOUR_TEMPLATE_KEY' => [
      // Here you can pass any variables you want, if necessary.
      'variables' => ['var1' => NULL],
    ],
  ];
}

Then create a folder called /templates in your custom module, and YOUR_TEMPLATE_KEY.html.twig file where you can have any markup you want. See below how to use the variables you pass to the template:

<div id="your-block">
  {{ var1 }}
</div>

Finally, to use it:

public function build() {
  return [
    '#theme' => 'YOUR_TEMPLATE_KEY',
    '#var1' => 'Variable one passed here',
  ];
}

Hope this helps.


Please open a feature request in the core queue for 'no ui' blocks. This currently does not exist but it's an interesting (and probably necessary one).


How to embed Responsive Youtube video in Drupal Bootstrap subtheme?

This might help:

responsive-youtube-embed

The essential bit:

  You will need to wrap the responsive youtube embed code with a  and specify a 50% to 60% padding bottom. Then specify the child elements (iframe, object embed) 100% width, 100% height, with absolute position. This will force the embed elements to expand fullwidth automatically.


Header and many components missing in Open Social

Generating demo content is optional but recommended.
Follow these instructions on generating demo content (Drush support only for now).
Still stuck? Explore the thorough guide to installing and updating which includes help for working with Docker.

OR

drush command to add demo content

drush demo-content-add file user group topic event event_enrollment comment post like


The Answers module should do the trick:

  Answers provides a question & answer service. Users can post questions and other users can answer them.

  ...

  The displays are based on standard CCK node displays and Views, so can be themed in the typical ways.


How to get user data/authenticate with bearer token - Simple OAuth - Decoupled

I'm not familiar with the Nuxtjs framework discussed in the tutorial you linked to, but basically once you have the access_token the user should be authenticated in Drupal. It should be enough that you on each request set an Authorization header that contains that access token, as described in the tutorial:

this.$axios.setHeader('Authorization', 'Bearer ' + resp.data.access_token)

Drupal will then read the Authorization header value and authenticate/authorize the user based on the Drupal role that the user has assigned to itself. So provided you have the REST endpoints for user information active you should be able to make a GET request to /user/{user} and get the logged in user information.

You can try this out using curl or Postman by manually adding the header to the request:

Authorization: Bearer HereGoesTheValueOfTheAccessToken

A curl example:

curl --request GET \
  --url https://mydrupaldomain.com/user/123 \
  --header 'authorization: Bearer HereGoesTheValueOfTheAccessToken'


Create chart for user count of user role using chart module(c3 lib) in Drupal 8?

This is an issue of needing to be sure that you first set the format of the attachment display to "This chart attachment (override)", and then adjusting the format settings. Don't forget to attach your "Chart attachment" display to the appropriate display.

I wanted to set the style plugin to do this by default (see this issue: https://www.drupal.org/project/charts/issues/2899035), but I am unable to find any documentation on how to do this programmatically.


You can use this not so well maintained module Statistics Granularity or learn how to do it yourself with this blog post: Advanced statistics for Drupal: most viewed nodes in a week, month, ...


How do I override the content region for a specific page?

For this you have to override preprocess region

function MYTHEME_preprocess_region(&$variables) {
    if(CONDITION){
        $variables['theme_hook_suggestions'][] = 'regionspecial__' . $variables['region'];
    }
    print_r($variables['theme_hook_suggestions']); // comment this statement
}

After that your template suggestion name will be 'regionspecial--content.tpl.php' For certain desired condition.  Once you clear Drupal's caches your new template file should start being used for that region. It might be worth noting that you'll probably need a copy of the core region.tpl.php file somewhere in your theme folder as well, or the theme registry might not pick up your custom file.


Making track of who has seen which content

The solution is Seen module! Just read and use it


View that uses both taxonomy terms and title(or nid) in contextual filters

I wasn't able to find a neat solution to this problem.

What I ended up doing was manually creating a page view from each taxonomy e.g. metals/gold/% and passed it the node title through contextual filters. This meant I was able to create a view of the correct product and the Easy Breadcrumb trail still looked good and a single product may exist in multiple breadcrumb trails. This works but isn't an elegant solution.

It would be great to find a solution to this that didn't need manual creation of page views. So any further thoughts on this are appreciated.


Drush command to run cron won't work in Crontab

I ran into a similar issue multiple times. I think in all cases cron was running a different version of php.  To fix I ended up having to define my php path in my drush call:

*/5 * * * * /usr/local/bin/php /home/myuser/bin/drush elysia-cron run --root=/home/mysite/public_html --uri=www.mysite.com

Also, another thing that helped me debug the issue is by adding a log path > path/to/file.log like this and then looking at the exact error:

*/5 * * * * /usr/local/bin/php /home/myuser/bin/drush elysia-cron run --root=/home/mysite/public_html --uri=www.mysite.com > /home/mysite/cron.log 2>&1


The link given is a nice one to deal with the default search result number count. In Apache Solr you can use the following code to get the total number of documents returned in the search result.

if (apachesolr_has_searched() && ($response = apachesolr_static_response_cache())) {
  $returned_doc_num = $response->response->numFound;
}


How to set a multi line value from drush vset

Well, I just put my drush code in a text editor like this:

drush vset antibot_form_ids "webform_*
user_login
any_other_form
even_more_values" -y

Then copy & paste the whole statement to your command line and voila the values are set correctly.


How to define template suggestions for node add and edit form by content type?

I usually use something like this for template form suggestions : (works for all forms, not only entity forms)

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function <HOOK>_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if (isset($variables['element']['#theme']) && is_array($variables['element']['#theme'])) {
    foreach ($variables['element']['#theme'] as $theme) {
      if (strpos($theme, '_edit_') !== FALSE) {
        $suggestions[] = 'form__' . str_replace('_edit_', '_', $theme);
      }
      $suggestions[] = 'form__' . $theme;
    }
  }
}


When I POST an image file via rest, response is 201: Object Moved, status is temporary

Suggestions

I think filemime is autogenerated depending on the file you're uploading.
To make the file permanent, have you tried sending the property status: [value: 1]?

A status of 1 indicates that the file is permanent.


I ended up (as suggested) adding a token to all unsecured forms with hook_form_alter.

Seemed efficient to use drupal_get_token() for this, but that did not work because the session ID (used by drupal_get_token() to generate a token) alters when an (anonymous) user logs in.

I therefore stored the first session id (when displaying the login page) in $_SESSION so I could retrieve it when validating. But putting something in $_SESSION apparently prevents Drupal from regenerating the session_id. And now that the session id is preserved during login, drupal_valid_token() also works as expected so I did not have to write a special token validation function.

This is the code I ended up with:

function MY_MODULE_form_alter(&$form, $form_state, $form_id) {
    // add a custom csrf token for forms that do not have one
    if ($!isset($form['#token'])) {
        $form['anon_token'] = array(
            '#type' => 'token',
            '#default_value' => drupal_get_token()
        );

        $form['#validate'][] = 'MY_MODULE_validate_anon_token';

        // store current session id
        // touching $_SESSION alone seems to preserve the session id after login
        $sess_id = session_id();
        if (isset($_SESSION))
            $_SESSION['anon_session_id'] = $sess_id;
        else
            $_SESSION = array('anon_session_id' => $sess_id);
    }
}

function MY_MODULE_validate_anon_token($form, &$form_state) {
    $token = '';
    if (isset($form_state['values']['anon_token']))
        $token = $form_state['values']['anon_token'];

    if (!drupal_valid_token($token)) {
        // not a valid token!
        $path = current_path();
        $query = drupal_get_query_parameters();
        $url = url($path, array('query' => $query));

        // Setting this error will cause the form to fail validation.
        form_set_error('form_token', t('The form has become outdated. Copy any unsaved work in the form below and then reload this page.', array('@link' => $url)));
    }
}


You could use the hook_comment_links_alter()

use Drupal\comment\CommentInterface;

/**
 * Implements hook_comment_links_alter().
 *
 * Unsets the "Reply" link of a comment.
 *
 * @param array &$links
 *   A renderable array representing the comment links.
 * @param \Drupal\comment\CommentInterface $entity
 *   The comment being rendered.
 * @param array &$context
 *   Various aspects of the context in which the comment links are going to be
 *   displayed, with the following keys:
 *   - 'view_mode': the view mode in which the comment is being viewed
 *   - 'langcode': the language in which the comment is being viewed
 *   - 'commented_entity': the entity to which the comment is attached
 */
function mymodule_comment_links_alter(array &$links, CommentInterface $entity, array &$context) {
  // Unset the "Reply" link
  if(isset($links['comment']['#links']['comment-reply'])) {
    unset($links['comment']['#links']['comment-reply']);
  }
}


Update all update available modules other than locked modules.

drush pm-update

or

Update specified module only.

drush up 'module-name'


How do I get rules to select a random node?

See How to Use EntityFieldQuery, particularly the section "Random ordering".


How can I set a webform's field value by query parameter?

This can be done in the webform backend settings: Edit your webform and go to Settings >> Form; then go down to Form Behaviours and select Allow all elements to be populated using query string parameters.

If you go back to the webform element, select the particular field, and enter [current-page:query:full_name] as default value (where full_name is the field name), if the query string contains full_name=John+Smith, the full_name field will be populated with Josh Smith.


Use Apache Solr Multisite search https://www.drupal.org/project/apachesolr_multisitesearch This is the proper way to have multiple sites sharing one index. You can search all sites or single sites.


How to pass variable from WidgetBase to .module

Just incase someone stumbles upon this and struggles to follow the thread above this is how to pass the variable.

$element['#attached']['drupalSettings']['signature_field']['sign']['id'] = $text_area_id;

Here is the full widget code.

<?php

namespace Drupal\signature_field\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\ElementInfoManagerInterface;

/**
 * Plugin implementation of the 'field_signature_field_widget' widget.
 *
 * @FieldWidget(
 *   id = "field_signature_field_widget",
 *   module = "signature_field",
 *   label = @Translation("Signature Data"),
 *   field_types = {
 *     "field_signature"
 *   }
 * )
 */
class SignatureWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

     //
     //$sign_thumb = array( '#type'   => 'html_tag',
     //                     '#tag' => 'img',
     //                     '#attributes' => array('src' => '', 'id' => 'signature_thumb_test', 'class'=>array('align-right'), 'width' =>'120px', 'height' => '60px' ));

    $field_name = $items->getName();

    /*function getFieldName() {
      return $field_name;
    }*/

    $text_area_id = 'signature_field_' . $field_name;

    $file_upload_help = array(
      '#theme' => 'signature',
      '#sign_src' => $value,
      '#text_area_id' => $text_area_id,
    );

    $element += array(
      '#type' => 'textarea',
      '#default_value' => $value,
      '#attributes' => array(
        'id' => array($text_area_id),
                        ),
      '#attached' => array(
        'library' => array('signature_field/signature_pad'),
                        ),
    );
    $element['#attached']['library'][] = 'signature_field/signature_pad';
    $element['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help);
    $element['#attached']['drupalSettings']['signature_field']['sign']['id'] = $text_area_id;

    return array('value' => $element);
  }

}

It is then available in your JS as follows.

var canvasId = drupalSettings.signature_field.sign.id;
            console.log(canvasId);


After giving you this context, my actual question is, if I will only
ever need 1 type of every entity bundle, do I really need entity
bundles? What would entity bundles do for me?

No, you don't need bundles. Configurable fields are stored in bundles. Since you don't want to configure fields you don't need bundles.

I still wonder, if I will have only one bundle per entity type, do I
need to set up a configuration entity for the the bundle?

The core user entity is an example for a bundleless entity type for which you can configure bundle fields. It looks like having one bundle but there is no bundle config entity. The bundle fields use the entity type id as placeholder.
So even if you later need to add configurable fields, through UI or YAML, you don't need to set up a configuration entity for the bundle. See Adding Field To Bundle-less Entity On Installation Not Working


Do I need to give a complete copy of my site's source code to a themer?

The minimum they need depends on what you are having them theme.

Basically they have to have everything they need to do their job.

If you exclude something that affects any visual part of the site it could impact their ability to do their job.

If they are making the whole theme for your site I feel you really should give them everything, because if you don't it is possible that some things will not get themed.

If I was the one implementing the theme and I was not given the whole code I would definitely specify that any problems with the theme that relate to not having all the parts are not covered by warranty.

In the end though it depends on your specific site and what you are having themed.
Maybe on your site there are pieces of functionality/code that could be excluded without impacting the parts of the site being themed.

If your worry is them seeing your code, because there are specific things regarding your code that are very sensitive then you either need to find a themer you can trust, and have them sign legal NDA agreements or whatever else is required.

If you are worried about them doing bad things to your code, use version control.
Have everything in version control before you give it to them so that when you get their work back, you can see exactly what has been changed, so if they are changing things they shouldn't be you can more easily know about it.

You could also try to get someone to review their work (or you review it yourself if you have the knowledge).

Another thing you could do is host the site somewhere on the internet where the themer can work on it, but only give them access to the theme directory. So they are allowed to FTP to the theme directory only, and not have access to the rest of the site, but they still get to use the fully functioning site.

The harder you make things for them though, the more chance you have of getting an inferior result or having the work take longer than expected.


How to automatically change a Content type field value based on Date field?

I think you have to do this with some custom JS code.

You can do something like this:

$('.end-date-field').on('change', function () {
  var endDate = new Date($(this).val());
  if (endDate < Date.now()) {
    $('.status-field').val('inactive');
  }
});

This code is not 100% correct, but it can help you to get an idea of what you have to do.


lets say your url is : example.com/services , and services is 1 content type of drupal , and if you want to replace whole page with static html them create services.html page on root folder of your drupal and add whole html inside it and then run url it will display only html added in that html file.

Note : this html file name must be same as url , if url is example.com/abc then file name should be abc.html

Hope this helps you.


You could try creating a session variable. Taken from this question

You can try this.

function lists_session($key, $value = NULL) {
static $storage;
if ($value) {
$storage[$key] = $value ;
$_SESSION['lists'][$key] = $value ;   // I use 'lists' in case some other module uses 'type' in $_SESSION
}
else if (empty($storage[$key]) && isset($_SESSION['lists'][$key])) {
$storage[$key] = $_SESSION['lists'][$key];
}
return $storage[$key];
}

So, to save a variable in Session:

lists_session("s_key", "value");

And to retrieve the value, just use:

$myVar = lists_session("s_key");

EDIT

To attach the above to the form submit (Add), try the following, taken from this question. You can do this in template.php with THEMENAME_form_alter if you prefer not to create a new module, but it would be theme specific if you do that.

You will need to create a custom module with hook_form_alter() implementation.

function [YOUR_MODULE]_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == "YOUR_FORM_ID")
  {
    // target the submit button and add a new submission callback routine to the form
    $form['#submit'][] = 'YOUR_SUBMISSION_CALLBACK_FUNCTION';
  }
}

The code above will execute your new callback function YOUR_SUBMISSION_CALLBACK_FUNCTION AFTER the form's default callback function.

To make your new callback function called BEFORE the form's default callback function, use the following code instead of the giving above:

array_unshift($form['#submit'], 'YOUR_SUBMISSION_CALLBACK_FUNCTION');

To cancel the form's default callback function and force it to use your function ONLY, use the code below

$form['#submit'] = array('YOUR_SUBMISSION_CALLBACK_FUNCTION');


Automatically filling field in related content type

So if I undersand you don't have any relation Groups -> Projects? You just have a relation Projects -> Groups (that you also call parents)? .
And you want to show by views, Groups and their children (projects)?

If this is what you want you have several choices.

Add many relationships in the view advanced filters in order to reach groups projects, (could be tricky).
Add a field entity relationship Groups -> project that you programmatically set on every projects insert/update/delete. Thanks to this it would be much more easier to build a view.
create your own custom block, with your dedicated SQL query. listing all children of a group and attaching this block to all "groups" content type pages.


How to correctly access entity elements in a twig template

As the exception explains, you tried to print an object that is not renderable and cannot be converted to a string. In this case it was Drupal\Core\Field\FieldItemList which is the object returned by drupal entities when you ask for a field ({{ entity.id }} / {{ entity.label }}).

To get the actual value you need to call to methods of your entity (the actual value of the fields is protected from outside access).

The long way:

{{ entity.get('id').get(0).get('value').getValue() }}

The above is the actual path you need to take to get from the entity object to the value of the id field.

However drupal supplies shortcuts through what is known as magic properties.
The short way

{{ entity.id.value }}


Hook update performs an update on a node, it wont be too useful in your case. When you create a field it creates a table in the DB with appropriate datatypes. You cannot just change the datatype of a field without going down the line and changing all the details, including the data in most cases. which trust me is a huge pain in the ass.

I've had to do this before but what i ended up doing was creating new field with the datatype I wanted, then used View Bulk operations Execute arbitrary PHP script and ran custom php to get the FID from all the File and then add it to the new field. I think there was a user reference for each file as well, so the fidelity is there to transfer your data between fields. Then delete the old field

Worst case scenario, find ways of limiting what types of files(image only) your file upload field can upload.


Javascript not working in body field. Using Full HTML

Most likely , your FULL HTML content authoring text format settings are limiting the markup you can use, stripping out the script (that's default behavior).

You can either:
1. Modify the settings for the text format to not restrict markup
2. Create a new text format, without any of the filter options enabled; then switch the format on the body field in which you want to insert the script.

If these options still fail, you may have a theme where a preprocess hook or twig filter is stripping out the script.


How to make Drupal 6 search result URL use "-" instead of space?

You could add the functions custom_url_rewrite_inbound() and custom_url_rewrite_outbound() in the settings.php.

custom_url_rewrite_outbound() would rewrite the URLs which are output from any module, and custom_url_rewrite_inbound() would rewrite the URL being requested to Drupal.

This is the example code used in the documentation of custom_url_rewrite_outbound().

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  global $user;

  // Change all 'node' to 'article'.
  if (preg_match('|^node(/.*)|', $path, $matches)) {
    $path = 'article' . $matches[1];
  }
  // Create a path called 'e' which lands the user on her profile edit page.
  if ($path == 'user/' . $user->uid . '/edit') {
    $path = 'e';
  }
}

In your case, the code could be something similar to the following one.

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  if (preg_match('|^search(/[^/]+/(.+))|', $path, $matches)) {
    $path = 'search/' . $matches[1] . str_replace(' ', '-', $matches[2]);
  }
}

custom_url_rewrite_inbound() should do the exact opposite.
The code I wrote does not consider the case the - is included in the search string. The code should consider that case, for example adding another - where there is already one; when it does the opposite operation, the code should first replace a single - with a space, and then remove a - where there are more of those characters in row.


Views: Sort items using contextual filter arguments

Yes. I would first get my contextual filters working so that my view was returning results for matching color, texture and size. Then I would use my Sort Criteria to add sorting filters to sort first by Color, then by texture, then by size. Order is important in the Sort Criteria.


Which table are field instance widget settings stored? Is it ok to update these everytime a node is saved?

You can use field_info_instance() to get the details, and field_update_instance() to save them:

$entity_type = 'node';
$field_name = 'field_name';
$bundle = 'content_type';

// Load
$info = field_info_instance($entity_type, $field_name, $bundle);

// Get
$min = $info['settings']['min'];
$max = $info['settings']['max'];

// Set
$info['settings']['min'] = 1;
$info['settings']['max'] = 10;

// Save
field_update_instance($info);

I can't see any problem with updating those values during a mass import, but I can't see the benefit of doing it for every single node save. It would probably be better to run it once at the beginning/end of the import process.

You can use the same code in hook_node_view() to retrieve the values for display on the node page if you need them.


It sounds like you're wanting the use case covered by the Profile2 Registration Path module:

  By default, the Profile 2 module permits you to add fields from chosen
  profile types to the default user registration form. Unfortunately,
  there is only one user registration form. Thus, every user will be
  presented with these fields during registration. If you have two
  profile types targeted at two different audiences, you cannot have two
  separate registration forms.

Anything else, might need to be covered by a form/menu altering custom module or Tab Tamer.


Making entities under another entitytype

I'm not sure if your case is closer to the typical bundle/config entity > content entity use case (because you mention machine name, so that sounds like a config entity to me) or content entity > content entity but the way this works is pretty much the same.

You need to define a route that contains the parent entity ID, then create your entity with the reference to that and then display the add form for it.

Examples for the first use case are for example node type/node or vocabulary/term, the second are comments. While the first is usually not seen as a hierarchy/grouping, it's essentially that.

Route from node.routing.yml:

node.add:
  path: '/node/add/{node_type}'
  defaults:
    _content: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE

NodeController::add

public function add(NodeTypeInterface $node_type) {
  $account = $this->currentUser();
  $langcode = $this->moduleHandler()->invoke('language', 'get_default_langcode', array('node', $node_type->type));

  $node = $this->entityManager()->getStorage('node')->create(array(
    'uid' => $account->id(),
    'name' => $account->getUsername() ? : '',
    'type' => $node_type->type,
    'langcode' => $langcode ? $langcode : $this->languageManager()->getCurrentLanguage()->id,
  ));

  $form = $this->entityFormBuilder()->getForm($node);

  return $form;
}

The only relevant part is passing through the entity reference value ($node_type) to the new sub-entity. There are issues to make the uid/name and the langcode default value handling work by default.


How do I translate view's page path alias that has a dynamic path?

Views pages generate routes including route parameters for contextual filters. So you could add for each language a duplicate page, set a language specific path and inherit all other properties from the master display.

But as the routing system is not language specific this has some shortcomings. You get multiple language prefix/route path combination, which is not good for SEO and makes it difficult to build outgoing links.

Language specific path handling is outside of the routing system. The standard tool for this is path aliasing, so you would need to set for each dynamic value and language combination an alias in the lookup table. Don't know if you can generate them with Pathauto, but I wouldn't recommend it anyway in this case, because the path has a clear pattern you can easily transform in a custom path processor to match the internal view's page display route.


The module Cache actions provide very fine grained control over your cache clearing.

Unfortunately, whether it will solve your exact problem depends on how this particular url is built up. In case it doesn't do exactly what you want, it's codebase would still be an excellent start for building more exactly what you need.


Most user friendly way to organise this content?

I'd recommend using the Bootstrap 3 theme/module it is very easy to install and use, and has built-in responsiveness to mobile vs laptop screens, which automatically moves your images below text, changes your menu to the mobile menu button, and other nifty features. You can copy its subtheme and make it into your own custom theme and there change many of the vanilla styles as well, so its very customizable.


Form api: Combine two text fields into a div?

<?php
function foo_form($form, $form_state) {
  $form = array();

  $form['range'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
 );

  $form['range']['min'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  ),
  $form['range']['address2'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
     '#suffix' => '
',
  )
  // Remaining code
  return $form;
}


Display User Author Details in Block UserProfile

The alias doesn't matter, you get the argument for a contextual filter from the internal path, no matter if the URL in the browser was aliased (unless you enable the option "Use path alias"). For a user profile the internal path is /user/[uid].

For the user ID there is also a contextual filter "User ID from route context", this filter is able to get the user without specifying in which path position it is.