How to use exchange rate from Currency Api in a field?

Here is a much leaner version of your setup:

In order to get your node to always display the current converted usd_value to EUROs, you will need only one computed field (no markup field required).
You just will need to place the following in the "Display Code (PHP)" textarea:

$conversion_factor = CurrencyYahooFinanceCurrencyExchanger::load('USD','EUR');
$node_usd_value = $entity->field_usd_value[LANGUAGE_NONE][0]['value'];
$euro_value_live = $conversion_factor * $node_usd_value;
$display_output = number_format($euro_value_live,2);

That should be all, just tried it and I am getting the following to display. My computed field is called "EUR Value (Live)":

Hope this does the trick for you!


You could export it with Node export module.

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

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


Do not show picture when video available

You can use conditional fields module for this.
https://www.drupal.org/project/conditional_fields
and set the  dependency for your field. See the screenshot it will help you.


Iterate through multiple value content field in Twig template

Agree with 4k4 the field template is the best place, if you really want it in the entity template (e.g. node) you can do something like this:

{% for key, item in content.field_tags if key|first != '#' %}

{{ item }}

{% endfor %}

But honestly I think it's a bit ugly, the field template is the right place.


Sometimes running cron does not entirely delete a field, especially if the field was ever used in a field collection. First, make sure the field isn't used anywhere else. Check all content types, field collections, custom user fields, etc. if the field is really not used but running cron does not delete the field table from the database, you may have to delete it manually. You can do this manually with a SQL query or via phpmyadmin.


How can I ask for a stable version of the module?

You can't install a stable version of Taxonomy Menu module for Drupal 9 at the moment because no such version exists.
If you look at the project page, you see the latest version is 3.4 which is marked Requires Drupal: 8.x.

So, if you want to use a stable version, you have to stay with Drupal 8 for now.
To use the dev version on Drupal 9, you can do this in composer.json:
    "drupal/taxonomy_menu": "3.x-dev",

Normally you should not need to authenticate to git.  It's probably a proxy issue; you might find some hints in this discussion.


Need example : D7 + XPath parser to import (mediawiki) XML - xpath parser settings?

Context should be : //Mediawiki/page,  Title field should be title and Text should be revision/text.


The aggregator is for importing feeds from other sites, but it sounds more like you're trying to create new feeds on your site from your content. For that use, you could use Views.


Re-enable forum commenting on a topic 24 hours after an admin has disabled them

Your friend here is hook_cron().

Furthermore, you would need to check how to find the nodes that have had comments switched off in the last 24 hours. There's something useful you can check (perhaps it is the node's change time), or you have to keep a record yourself by implementing hook_nodeapi().


How to create a multi step form that can be saved/edited by multiple users?

The Multistep module adds multiple-step functionality to CCK forms. It does so by assigning a step number to each fieldgroup within the content type and hiding all the groups that do not belong to the current step. The user can then use different submitting buttons that will redirect to the previous, next, or current step.

For further reference look into this link.


Products containing a hyphen or numbers not shown or wrong relevance

It is basically a feature of Word Delimiter Filter to allow matching of words on case-change, alphanumeric boundaries, and non-alphanumeric chars, so when typing "wifi", "wi fi" could match documents containing "Wi-Fi". That is why Product-123A is split to match more products. See: Intra-Word Delimiters.

So you can either disable WordDelimiterFilter, or customize it. For example:

<filter class="solr.WordDelimiterFilterFactory"
        protected="protwords.txt"
        generateWordParts="1"
        generateNumberParts="1"
        catenateWords="0"
        catenateNumbers="0"
        catenateAll="0"
        splitOnCaseChange="0"
        preserveOriginal="1"/>

Since the second part of your word consist number (e.g. 123W), you may try to enable catenateWords and catenateNumbers (set to 1) in your schema.xml file and apply the changes to your hosted Solr server.

You can also provide some customization usingwdftypes.txt file, see: SOLR-2059.

However, if you want to keep the feature as it is (without modifying any Solr config files), you can also consider increasing the score for certain fields, such as titles (e.g. a product name). So your Productx-123W phrase after a word split will match higher on documents with partial matches such as 123W in specific fields.

Related posts:

Search with various combinations of space, hyphen, casing and punctuations
Quering numbers containing hyphens with SOLR WordDelimiterFilterFactory isn't working?


Disabling Browse to Library in Media Upload Field

This can be accomplished with a module, and this hook:

/**
 * Implements hook_media_browser_plugins_alter().
 */
function my_module_media_browser_plugins_alter(&$plugins) {
  // Hide the "Library" tab on the WYSIWYG media upload widget.
  unset($plugins['library']);
}


Commerce / Rules: How to update node that references a given product when the product is updated

If you want to delete the product display node, you need to hook the entity update (e.g. on node update). If the product reference field is empty, you can delete the node. But the product reference field must be a required field.

When the Drupal commerce module deletes a product, it needs also to delete all the references from the product display.


When you add a new link, the link is validated from menu_edit_item_validate(), which calls drupal_valid_path() to check if the path is valid, or it can be accessed from the user.
drupal_valid_path() returns TRUE if

The path is <front> (<front>/directory, or similar paths are excluded)
The path is an external path (the function url_is_external() returns TRUE)
The path is associated with a menu callback

Apart from using absolute URLs, the only solution is to have a custom module that defines a menu callback associated with the path you want to use.
When you use the URL that points to a file, or a directory, the web server should show that file or directory, without invoking Drupal. That is what happens with Apache, as the .htaccess file that comes with Drupal contains the following directives:

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

In your case, the custom module should contain code similar to the following:

function mymodule_menu() {
  $items = array();

  $items['the_folder_for_the_other_content/%menu_tail'] = array(
    'title' => 'Folder content',
    'page callback' => 'mymodule_view',
    'access callback' => TRUE,
    'load arguments' => array('%map', '%index'),
  );

  return $items;
}

You can use any values for title and page callback, as that menu callback should never be called. The value of access callback says to Drupal that every user has access to that menu callback.

As an alternative you can define a menu callback associated to "alias_for_directory/%menu_tail" that redirects the user to the directory you want they see (using drupal_goto()). I would use this solution when the server does not use the content of .htaccess, and it would invoke Drupal even when the URL is pointing to an existing file or directory.


You should be able to use the getVocabularyId() function on the term object like:
$vocabulary_id = $term->getVocabularyId();

See https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/function/Term%3A%3AgetVocabularyId/8.2.x.


Enable Current Search submodule, you can also install Current Search Links

  Extension to the Facet API current search blocks module. Instead of just showing the current search it turns the current search keywords into links that you can drop from the search.


With JSON:API you can't filter by path because of technical limitations; JSON:API filters translate to entity queries on field values; because Drupal path aliases aren't fields you can't use the filter query param to look up articles by their alias.

A couple of different Drupal projects have cropped up around this limitation:

Decoupled Router: Provides a new endpoint where a client can query a path for any possible JSON:API resources.
Fieldable Path: Provides a new entity field (and thus queryable via the filter query param) that is designed to mimic the entity's path (with Pathauto support).

You can assess the tradeoffs from both modules and choose the one that makes the most sense for your use scenario.


Using Drupal 6's form ahah to have one dropdown field update the values of a second dropdown field

There's comprehensive example code in the Examples module that shows how to do this.

In the dependant_dropdown.inc file of the ahah_example module, you'll find an example form that does exactly what you're looking for. It's very well commented and should guide you through the process pretty well.

There's also a companion tutorial for the ahah_example module which would be worth looking it as it has more code examples.


I prefer Context module in most cases. I find it simpler and less heavy-handed than Panels, which takes over entire pages. A good use case for Panels is when site admins will be rearranging landing pages themselves or for sites with a lot of unique layouts.
I pick between Panels and Context for a given site when evaluating wireframes or designs. In some cases it makes sense to use both.

I can usually handle the Views arguments I need within Views itself (often by setting the default argument) and don't need the Panels side to do it.


It's true that policy file in drush prevents sql-sync from local to prod?

Yes this is still true you can find the relevant snippet in the drush source code:

/**
 * Implement of drush_hook_COMMAND_validate().
 *
 * Prevent catastrophic braino. Note that this file has to be local to the machine
 * that intitiates sql-sync command.
 */
function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
  if ($destination == '@prod') {
    return drush_set_error(dt('Per examples/policy.drush.inc, you may never overwrite the production database.'));
  }
}

You should include the policy.drush.inc in your .drush folder usually located in the users home folder.


Views - Contextual filter -  "page not found"

This is an unfortunate side effect of how the menu system works. When the paramter "%" isn't available, you match against a different path, and the View won't get called.

I suggest making /objects an alias to /objects/all, I believe this will then interact properly with the menu-system.
If that's not the case, you can force the issue with Path redirect which will redirect the user with an HTTP-response code, and thus land the user at /objects/all.

I minor drawback of using Path redirect is that the redirect logically belongs together with the View, but is now configured somewhere completely different. For that reason, I would prefer to accomplish the redirect and View rendering with Page manager, which will allow you to group the HTTP-response and a Panel together in a more logical manner.


Updating core with Composer doesn't work

Instead of trying to update Drupal directly with Composer, instead try starting with drupal-composer/drupal-project as a starting point. This project definitely works with Drupal 8.3.0.

Set up a new project with drupal-composer/drupal-project, and use composer require to add any modules you need. Once your code is the same in the new project as the old, you should be able to just copy the database over (or just point to your existing database with settings.php) and run updatedb.


how to redirect user login from other server?

On the Drupal side, create a custom module to implement hook_form_alter() and use it to attach a custom #submit handler to the user_login_form. In the custom submit handler, you can redirect the user to the headless DrupalGap web app:

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_form' && arg(0) == 'drupalgap') {
    $form['#submit'][] = 'example_user_login_form_submit';
  }
}

function example_user_login_form_submit($form, &$form_state) {
  $uid = 123; // This id will be somewhere in the $form or $form_state object.
  drupal_goto('https://example.com/#user_' . $uid);
}

Replace drupalgap with your service endpoint path, but by default it is drupalgap.


Filter taxonomy terms in autocomplete list by boolean field on vocabulary's terms?

Here is how I've added a new term custom widget:

/**
 * Implements hook_field_widget_info().
 */
function deepestlevel_taxonomy_widget_field_widget_info() {

  return array(
    'textfield' => array(
      'label' => t('deepestlevel_taxonomy_widget - Only deepest level'),
      'field types' => array('taxonomy_term_reference'),
      'settings' => array(
        'size' => 60,
        'autocomplete_path' => 'deepestlevel_taxonomy_widget/autocomplete',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function deepestlevel_taxonomy_widget_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $tags = array();
  foreach ($items as $item) {
    $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
  }

  $element += array(
    '#type' => 'textfield',
    '#default_value' => taxonomy_implode_tags($tags),
    '#autocomplete_path' => 'deepestlevel_taxonomy_widget/autocomplete'. '/' . $field['field_name'],
    // '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
    '#size' => $instance['widget']['settings']['size'],
    '#maxlength' => 1024,
    '#element_validate' => array('taxonomy_autocomplete_validate'),
  );

  return $element;
}

/**
 * Implements hook_menu().
 */
function deepestlevel_taxonomy_widget_menu() {
  $items['deepestlevel_taxonomy_widget/autocomplete'] = array(
    'title' => 'Autocomplete taxonomy deepest level',
    'page callback' => 'deepestlevel_taxonomy_widget',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

// THIS IS THE OVERRIDE CALLBACK copied from core taxonomy.pages.inc
// function taxonomy_autocomplete($field_name, $tags_typed = '') {
function deepestlevel_taxonomy_widget($field_name, $tags_typed = '') {

// NEW CODE HERE

}


Multilingual pages links showing node instead of URL alias

Add translation in Malay language for about-us node and add alias to it. When node hasn't translation to Malay language, it will be without alias when You change lng


Can I check a user is logged in using Services

Services module works with the entity system so you should be able to pull some user data out of the box like email, username etc. I'm not exactly sure if Services modules send you any clue about user data that you can use to determine if the user is online or not but you can add a small custom code that alter the read functionality of the Services for User entity to query and return the current session. See code sample below.

Couple of function you might need in the process is:

// you can alter the resources object and use your own
hook_services_resources_alter()

// implement it as below in your custom module
function YOURMODULE_services_resources_alter(){
  $resources['user']['retrieve']['callback'] = '_YOURMODULE_api_user_resource_retrieve';
}

// then implement the retrive
function _YOURMODULE_api_user_resource_retrieve($uid){
    $account = user_load($uid);
  if (empty($account)) {
    return services_error(t('There is no user with ID @uid.', array('@uid' => $uid)), 404);
  }

  services_remove_user_data($account);
  // DO YOUR SQL TO CHECK IF USER IS ONLINE
  // _check_this_user_online($uid);

  // Everything went right.

  return $account;
}


Why we need hook_cron if the cron job requires a path?

Using hook_cron() Drupal can run all the cron tasks using a single entry point (http://your.site/cron.php) and bootstrap code that is very specific for cron tasks, different from the normal bootstrap code used from Drupal.
This simplifies handling cron tasks since only a single URL is necessary to run them, and the code that runs them is faster compared to the normal code.

If I had the need to run groups of cron tasks at different times, then I could create different cron.php files to execute those specific groups. I would not implement different routes for executing cron tasks for the same reason Drupal 7 doesn't: The code that runs the routes is more complex than the code running the cron tasks and involves more hooks being invoked.
At least that was the reason for doing so when Drupal 7 was first released. With PHP 7, that is probably not a reason enough to prefer custom bootstrapping code to a route handler. As for Drupal 8, cron tasks are executed from a controller associated with a route.

In short, normally cron.php is enough, but it is also rare to even need a different route handler/controller for each cron task modules could.


Is there a way to tell if the current page is a node?

\Drupal::request()->attributes->get('node');

Taken from here: https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3Arequest/8

Now the docs say to never use this function, but I have used this to determine what kind of page I am on.

There is another function, but I am not sure it applies in your case:

https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/node_is_page/8

At the very least, if you do not have an entity, you could mimic that in your code:

  $route_match = \Drupal::routeMatch();

  if ($route_match->getRouteName() == 'entity.node.canonical') {
    return true;
  }


From my point of view, the better way is to use your own cache system, but don't worry is nothing very complicate.

Copy the includes/cache.inc and put it somewhere in sites/all/libraries or whatever you want. After in your settings.php you've to add $config['cache_inc'] = 'sites/all/...'; and Drupal will replace is own cache system by yours. This file contains three functions, clear_cache_all, cache_set and cache_get. Here the idea is to add the name of your theme before all $cid.

I never tried it, so I'm not sure if you can have access to this informations, but you can try .


How to dynamic change the size of the icon marker when using Leaflet maps and views

Maybe the Leaflet Extension module "Leaflet Label" helps to implement what you are trying to do? It provides a light-weight alternative to marker popups for Leaflet maps using labels, provided by the Leaflet Label javascript plugin.


How to hide My results tab for the User using Quiz module in Drupal 7

You can use Tab Tamer module.
Project page says:

Tab Tamer is an administration utility that provides easy re-ordering,
hiding, and deactivation of tabs and subtabs.

For more information go through the module documentation.


How to delete/block a list of users contained in a CSV file?

You really don't need a CSV; all you need is the identifying column (e.g. mail or uid). To that end, you have one option  with the Bulk User Delete module.

  This module allows you to bulk delete users through the admin
  interface. You provide a list of email addresses, one per line, and
  the users are deleted using the batch processing API.

With this module, you can grab your mail column to feed into the interface to bulk delete.


Easy way to do this in D7 is through the Display Format settings. Under the content type(s) of the nodes in your view, you want to add a custom display for RSS and then set the fields you want to alter to plain text.

Go to Structure -> Content Types, and select 'Manage Display' next to your content type.
On the bottom of the list of fields, expand 'Custom Display Settings' and check the box for RSS and save
Now, in the upper right-hand corner you should see that you have display format settings for Default, Teaser, and RSS - select RSS.
In the format settings for each of the fields, you want to select 'Plain Text' or whatever equivalent you like.


The following will do a svn export (unless you provide the --working-copy flag to drush) into DRUPAL_ROOT/profiles/contrib/myprofile

Drush make old-style syntax:

projects[myprofile][type] = profile
projects[myprofile][download][type] = svn
projects[myprofile][download][url] = svn+ssh://example.com/svn/path/to/subdirectory/of/myprofile
; This would place the checkout into /profiles/contrib/myprofile
projects[myprofile][subdir] = "contrib"

Drush make YAML syntax:

projects:
    myprofile:
        type: "profile"
        download:
            type: svn
            url: "svn+ssh://example.com/svn/path/to/subdirectory/of/myprofile"
        subdir: "contrib"

The drush make documentation is now located at http://www.drush.org/en/master/make.


You can call the macro by:

In the same twig Using _self:
From Documentation:

  It's possible to place the macro within the same twig from which you call it. The _self context is used in this case...

{{ _self.crop_text(text, len) }}

From External File using import :
Like the following:
Just move your croptext.twig into yourtheme/templates folder and then you can use the following call in any twig:

{% import '@yourtheme/croptext.twig' as cropText %}

For more information take a look at Macros in Twig Templates documentation.


Removing part of string retrieved from $_SERVER["REQUEST_URI"] in webform default value field

If you'r working with drupal you should use drupal_get_path_alias()

$path = drupal_get_path_alias();
$value = str_replace('content/', '', $path);


How to create content type programmatically with fields and vertical tabs

Wooho :) here is the answer
I was missing hook_ctools_plugin_api() in my module


How to list nodes that share only the first selected value in an entity reference field?

You should be able to set up something like what you are after with the following steps:

Create a view of content (nodes)
Add a contextual filter for NID with a that gets it's default value from "Content ID from url" (presuming the related products are to appear on the original products own page).
Add a relationship on field_category, call it something like "category", require this relationship
Add a filter of field_category:delta, value = 0
Add a relationship of "Content using field_category", require this relationship, use relationship: category, call this relationship something like "related"
Add another contextual filter that's also for NID with a that gets it's default value from "Content ID from url", use relationship: related, tick "Exclude" in the "More" fieldset at the bottom.
Now when you add your fields use relationship: related.


Drush alias - @alias status could not be found

The filename pattern mysite.net.alias.drushrc.php will only be parsed for aliases named @mysite.net.  Rename this file to mysite.net.aliases.drushrc.php, and you'll be fine.


Can we change the schema in services module?

If you need to expose the output that way, THeres 2 ways you can do it. You can alter the response before it gets sent as a payload, or you can write your own Response Format.

Both should do what you need, but its merely a preference.

/**
 * Triggered when the REST server request a list of supported response formats.
 *
 * @param array $formatters
 *  An associative array of formatter info arrays keyed by type extension. The
 *  formatter info specifies an array of 'mime types' that corresponds to the
 *  output format; a 'view' class that is a subclass of RESTServerView; and
 *  'view arguments' that should be passed to the view when it is created;
 *  a 'model' can also be specified which the controller then must declare
 *  support for to be able to serve data in that format.
 * @return void
 */
 function hook_rest_server_response_formatters_alter(&$formatters) {
   /*
    * Sample modifications of the formatters array. Both yaml and
    * rss are formats that already are supported, so the changes are
    * nonsensical but illustrates the proper use of this hook.
    */

    // Add a Yaml response format.
    $formatters['yaml'] = array(
      'mime types' => array('text/plain', 'application/x-yaml', 'text/yaml'),
      'view' => 'RESTServerViewBuiltIn',
      'view arguments' => array('format' => 'yaml'),
    );

    // Add a Rss response format.
    $formatters['rss'] = array(
     'model' => 'ResourceFeedModel',
     'mime types' => array('text/xml'),
     'view' => 'RssFormatView',
    );
 }

The altering of the response is, function HOOK_services_request_postprocess_alter


Well, just after posting here i went back to the problem. Turns out i only had to check off the "Display all values in the same row" in the "Multiple field settings" section of the field in the view. Pager showed up now.


No.

View modes are specified per entity type, not bundle, as hook_entity_info() shows.

It is also not possible to define extra fields which are only available for a specific bundle/view mode combination, only per bundle.


Unable to implement photo slider in theme template

What you did in your website is create a new content type that holds a static image for each entry. From what I see in the template link you posted, the theme you chose uses Nivo Slider as the default solution for a slider and even has an installation instructions link (which is not working).

My advice would be to follow the instruction on this link:
Nivo Slider Module, and install the module yourself. It will create a new content type for you to make the slider you need.


Change texts according to other language in template.php

Global $language variable returns current language object, you can get current language code by $language->language property. Example:

global $language;
$output = '

                   this is a lorem ipsum

';
if($language->language == 'en') {
    $output = '

                   this is a lorem ipsum in english

';
}

return $output;

But better way would be using Render Arrays

2-Solution: is to wrap the text with t() function. And translate the text by admin/config/regional/translate link.

function _site_footer(){
    $output = '

                   ' . t('this is a lorem ipsum') .
                '

'
    return $output;
}


How to add wysiwyg (like CKeditor) to Disqus module textarea?

Unfortunately, this is impossible. The Disqus comment form is in an iframe originating from disqus.com. It is basically a separate web page embedded within the content of your website.

If your page were to access the Disqus form, it would violate the Same-origin policy. This policy is to keep your information safe. Imagine if another page could read or modify data when you log in to your bank. Bad news.


Why is the rate widget (from the Rate module) not showing up?

From the screenprint about "edit widget" in your question it shows that you've created a "Yes / no" widget using the Rate module.

But nowhere in your question it shows for which "Node types" you've enabled your widget. Since you're using the "Yes / no" widget (located at admin/structure/rate/add?template=yesno when adding a new widget), you should indicate the desired "Node types" there for which the rating widget is to be enabled. If you didn't specify (select) any of node type, then that would explain why the rate widget is not showing up".


Automatically fill title attribute of image

If you use D6 try image_fupload module.

  Automatic node title creation and predefining of imagefield fields (customisable / themeable / editable by user / token support [imagefield])


How to get country list array with their corresponding country codes

You get the infinite loop, because the country name is a translatable markup and print_r() can't handle this object. If you cast the country name to a string, then it is printable in php:

 $countries = \Drupal\Core\Locale\CountryManager::getStandardList();
 foreach ($countries as $key => $value) {
   $country_name = (string) $value;
   print "$key - $country_name\n";
 }

This is not needed for rendering, because twig can handle this object. This is only for debugging.


It uses the default date format of the site, which is medium. You can configure that at admin/settings/date-time and choose a format which uses am/pm.

You can also implement hook_preprocess_node() in your theme or module and then override the 'submitted' variable set by template_preprocess_node(). That allows you to use a different date format just there.


warning: includes/database/database.inc has type 100755, expected 100644

You can trust that the file has been applied successfully, but not that the file was in the expected state to begin with.

755 and 644 refering to numeric notation of unix-system file permissions.

What the warning says is that the patch lists the file as being not executable, but it found the file to be executable.
This had no effect on applying the contents of the patch to the file though.


The Prepopulate module allows you to construct a special URL inside your table view that, when clicked, will prepopulate the correct taxonomy term on the "Create reservation page".

The special URL will looking something like this:

http://www.example.com/node/add/reservation?edit[field_equipment_term_reference]=123

You need to:

Download and install the Prepopulate Drupal module.
In your table view, add the Taxonomy Term ID field (if not already added).
In your table view, add a Global Text custom field.
In the Global Text field config screen, specify the text "create reservation page" and then expand the rewriting section, and turn the field into a link, with link destination of node/add/reservation?edit[field_equipment_term_reference]=[tid].

Please note:

the [tid] is the substitution token from the field added in step 2.
replace field_equipment_term_reference with the real machine name of the taxonomy term reference field you're using on the Reservation node.


Custom form with Date textfield with jQuery popup

You need to initialize the form with drupal_get_form():

$form = drupal_get_form('MYMODULE_birthdate_form');
$html = drupal_render($form);

function MYMODULE_birthdate_form($form, &$form_state) {
  $form['birthdate'] = array(
    '#type' => 'date_popup',
    // ...
  );
  return $form
}


How to receive JSON data in controller with Drupal 8?

In case you want to do it more the D8 way here is a rough outline what you could do, which allows you to be flexible without the requirement to do everything in your own. A proper rest integration requires you to work with all the different HTTP status codes, header fields etc. Rest takes partly care of that

The rest module provides a generic abstraction for REST, not tight to entities in the first place. Entities are just one example.

First you should register your rest plugin, like every other plugin:

namespace Drupal\pinguin\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;

/**
 * Provides a resource for database watchdog log entries.
 *
 * @RestResource(
 *   id = "pinguin",
 *   label = @Translation("Example rest plugin for pinguins"),
 *   uri_paths = {
 *     "canonical" = "/pinguin/{id}"
 *   },
 *   serialization_class = "Drupal\pinguin\PingInterface"
 * )
 */
class Pinguin extends ResourceBase {
}

If you do an updating request like PUSH or UPDATE, it uses the serializer component to convert your data into some php array/ object.
It uses two steps in order to do that. First the data incoming is decoded,
for example from JSON into a PHP array. The next step is the denormalization.
This step converts the denormalized data (PHP array) into a domain object,
for example the Ping (a single pinguin).

The first step is to specify the resulting class in the annotation (see above).
To register a new denormalization you add the following entry into your .services.yml:

services:
  pinguin.denormalizer.pinguin:
    class: Drupal\pinguin\normalizer\PinguinDenormalizer
    tags:
      - { name: normalizer }

This normalizer specifies which interface it can convert to:

<?php

namespace Drupal\pinguin\normalizer;

use \Drupal\serialization\Normalizer\NormalizerBase;

class PinguinDenormalizer extends NormalizerBase {

   // IMPORTANT
   /**
    * The interface or class that this Normalizer supports.
    *
    * @var array
    */
    protected $supportedInterfaceOrClass = array('Drupal\pinguin\PingInterface');

    /**
    * {@inheritdoc}
    */
    public function denormalize($data, $class, $format = NULL, array $context  = array()) {
      // Validate the data.
      if (empty($data['location']) || $data['location'] == 'northpole') {
        throw new \UnexpectedValueException("this can't be real pinguins");
      }

      // create the domain object.
      return new Ping($data['name'], $data['location'], $data['family']);
    }
 }

Once this serialization is done, it calls a method named after the HTTP method
on the plugin class, so for example "post". There you can do whatever you want.

<?php
class Pinguin extends ResourceBase {
  public function post(PingInterface $ping) {
    // deal with the data, save it for example.
    $ping_storage->save($ping):
  }
}

The advantages of these abstractions are that you don't have to deal with the incoming format but on the other hand it needs a bunch of code to get started.


It appears to me that you are directly editing the sources of the linkedin module. This is considered bad practise, as any module update will remove your changes and subsequently lead to unexpected errors in your Drupal.

The reason why the queries do not work is that the corresponding database fields are missing.

You have to do several steps:

Create your own custom module. (I use MYMODULE as name in the following examples; alter that to your module's name.)

Add the linkedin module as dependency to your custom module's .info file, to make sure your changes will be removed before the linkedin module will be uninstalled:

dependencies[] = linkedin

Implement hook_install() within your module's .install file to add the field to the database:

/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Add additional field to table 'linkedin_token'.
  if (db_table_exists('linkedin_token') && !db_field_exists('linkedin_token', 'token_expires')) {
    db_add_field(
      'linkedin_token',
      'token_expires',
      array(
        'type' => 'int', // I suppose, you will save a unix timestamp.
        'description' => 'Token expiry date/time',
      )
    );
  }
}

Implement hook_uninstall() within your module's .install file to remove the field from the database when your module will be uninstalled:

/**
 * Implements hook_uninstall().
 */
function MYMODULE_uninstall() {
  // Remove additional field from table 'linkedin_token'.
  if (db_table_exists('linkedin_token') && db_field_exists('linkedin_token', 'token_expires')) {
    db_drop_field(
      'linkedin_token',
      'token_expires'
    );
  }
}

Implement hook_schema_alter() within your .module file to publish your changes to Drupals database schema information:

/**
 * Implements hook_schema_alter().
 */
function MYMODULE_schema_alter(&$schema) {
  $schema['linkedin_token']['fields']['token_expires'] = array(
    'type' => 'int',
    'description' => 'Token expiry date/time',
  );
}

Copy over the altered functions / code snippets from the linkedin module to your module, and rename the functions to MYMODULE_your_function_name. Afterwards restore the original module's source code.

Implement hook_menu_alter() to alter the menu callbacks of the linkedin module to point to your customized functions. (Refer to function linkedin_menu() to identify the items of question.)

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['the path of the menu callback to alter'])) {
    $items['the path of the menu callback to alter']['page callback'] => 'MYMODULE_your_function_name';
  }
  // Repeat the above step for every menu callback you like to change.
}

An additional note: Try rewriting as less as possible code from the original module's functions and check whether you can utilize hooks or do a call to the original function as well to make sure the application won't break once the original module is updated.


What is the right place for Product Image

It is related to want you want, if you want have a product display with some variation that each variation  different with each other ( different image) it is better put product image field in product , but if all product variation has equal image (or you have not product display  with multi variation product ) it is better put image field in product display content type .

I hope this can helped you.


Is there a way show user that the content has been automatically translated?

Instead of setting an integer field, create a text field called original language or source language. Use Rules to store the language code of the source language when the node is created. That way the value of the field is correct regardless of which language the user is viewing the node.

You can then compare the source language of the node with the user's current language and display a message if they do not match.


Group Audience field in Group Content does not show any values other than None

Making sure the Group is published solved the issue for me.


Example of writing Latitude Longitude to a Geofield?

And the answer:

    $entity_metadata_wrapper = entity_metadata_wrapper('node', $node_object);

    $data = array(
       'lat' => 44,
       'lon' => -93
    );

    $entity_metadata_wrapper->field_position->set($data);


Detecting a form change. Is jQuery the way to go?

Will using jQuery to attach a change event on each checkbox take a major performance-hit?

Probably, but it depends on the client's configuration. I have a form with around 3 hundred of controls, half of them hidden, some of them auto-copying content using jQuery, and sometimes FireFox has it's problems with it.

  Is there a faster Drupal way to do it?

Nope, Drupal way is to use Behaviors, or states, and Behaviors & states thou shalt use... but they are merely Drupal's way to initiate jQuery-based code.

  Will using the Drupal way, make performance faster?

Nope, as Drupal way is basically jQuery way too. But it will merely allow you to be reasonably sure that other modules will not interfere with your code (without any significant slowdown).


Are edited files in core modules overwritten on updating Drupal?

YES, for sure. Clear enough ....?

PS: that's also why one should never hack core ...


Show file field as thumbnail if file is an image?

I could also create a template for the comment, or the field and then insert an "if".


For drupal 7 the best way will be write hook_enable function in *.install file of your custom module:

<?php

function YOUR_MODULE_NAME_enable() {
          $blocks = array(
            array(
              'status' => 1,
              'weight' => 20,
              'region' => 'sidebar_second',
              'visibility' => 1,
              'pages' => "instruments/*",
              'module' => 'instruments',
              'delta' => 'instruments_sidebar',
              'theme' => 'markets',
            ),
            array(
              'status' => 1,
              'weight' => 19,
              'region' => 'sidebar_second',
              'visibility' => 1,
              'pages' => "instruments/*\n<front>",
              'module' => 'instruments',
              'delta' => 'instruments_search',
              'theme' => 'markets',
            )
          );

          foreach($blocks as $block){
            db_merge('block')
              ->key(array(
                'module'=>$block['module'],
                'delta'=> $block['delta'],
                'theme'=> $block['theme']
              ))
              ->fields(array(
                'status' => $block['status'],
                'weight' => $block['weight'],
                'region' => $block['region'],
                'visibility' => $block['visibility'],
                'pages' => $block['pages'],
              ))
              ->execute();
          }
    }

This is code from my custom module, and it works :)
Here I enable my custom blocks, so I modify 'block' table. For custom blocks you should update 'block_custom' table too.

If you don't know how drupal store settings, just make changes manually and then check DB.

NOTE: db_merge function is very useful - it inserts data if they absent (if you just installed your module) or updates it (if you disabled and then enabled module)


Show pages with a specific template when user is logged-in

The most basic way of providing a custom template for a node that meets certain criteria, is using theme hook suggestions.

You can for example add a custom theme suggestion by implementing hook_theme_suggestions_HOOK_alter() in a custom module. There you can check whether your criteria are met and add a custom theme suggestion, if they are:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_node_alter(array &$suggestions, array $variables) {

  if (
    // Do your checks here, e.g authenticated user?
    \Drupal::currentUser()->isAuthenticated()
  ) {
    // Add your custom template here. The following
    // example would apply to 'my-node.html.twig'.
    $suggestions[] = 'my_node';
  }

}


How can I loop through all article content types and get the content of each

you can use

function YOURTHEME_preprocess_node_article(&$variables){
  $node = $variables['node'];
   $nid = $node->id();
   // similarly you can fetch other fields
}

then override article content type as node--article.html.twig
and pass data to twig file


standalone rsync and ssh work, but drush gets me a "Permission denied (publickey)"

You are not specifying a remote-user on @bak so who are you performing operations as on the server at @bak? You are also not specifying any ssh config options. In this case, you are asking @bak to authenticate with @prod via ssh/rsync but you are not using agent forwarding so @prod can't see your private key. Try specifying something like

'remote-user' => 'user_on_bak',
'ssh-options' => '-T',

So that drush will execute as 'user_on_bak' and ssh will pass along your local key to @bak so when it opens a session with @prod it will have a key to pass along.


Hosting Multiple Domains seamlessly with same site code, theme, modules, data etc. not a multisites situation!

This has worked for me in the past. Given the following assumptions:

I assume the server is already configured to direct requests for the domain oxustech.com to the correct site (meaning that this is already working for you)
I assume Drupal is finding for your site's settings.php file in the directory /sites/oxustech.com/settings.php
I assume you want to make requests for the domain oxustechnologies.com to show the SAME site (same database) as oxustech.com, but displaying the domain oxustechnologies.com as the base URL for all pages accessed through this requests.

IF this is the case, this has worked for me. Try this:

In the /sites directory, rename the file example.sites.php to sites.php
Add the following line at the end: $sites['oxustechnologies.com'] = 'oxustech.com';

This will effectively tell Drupal that oxustechnologies.com is an "alias" of oxustech.com, will use all settings (including the database) for oxustech.com. It will also always display oxsutechnologies.com as the base URL when you navigate inside the site. But people who access the site through the name oxustech.com will continue to see that as the base URL.


How can I set a variable based on the render element $vars[‘body’][‘#object’][‘vid’]?

The #object in the $build array is an object, therefor it's properties have to be referenced with an arrow, ->

$orig_vid = $build['body']['#object']->vid;
$build['body']['#object']->orig_val = $orig_vid;
$build['body']['#object']->vid = 100;

thanks Gulok for answering this


Programmatically logout user without redirect

You need to change your hook code.

function MODULENAME_init() {
  if (!user_is_logged_in() && request_uri() != '/user') {
    // Log in the user as user #31.
  }
  elseif (user_is_logged_in() && request_uri() == '/user') {
    module_load_include('pages.inc', 'user');
    user_logout();
  }
}

Since user_logout() is defined in modules/user/user.pages.inc, you need to first load that file, and then call that function, or you will get an error about a not defined function. You don't need to first check the file has been already included, since it will not be included twice.

Keep in mind that http://ggames.kz/user could be directly accessed from users to see their user page, and that Drupal redirect logged-in users who try to access http://ggames.kz/user/login to http://ggames.kz/user.


If the user is not logged into your app and if you don't let anonymous users to access the API, how can you let them to log in without accessing API?

What you can do is you can maintain a API key for your application. You should call the API using the key all the time. That should be your first check point. Then you should add that API key validation for accessing the API. Then you can give access to your login API function using that key.

Once user is successfully login to the system you can return a dynamically genarated(random) session key to your APP so that the user login to the app and he/she has a session key. From that point call the API using the session key and add validation method to validate both session key and API key.

So all API functions are accessed by logged in users only. When the user logs out from the app call a session key function to remove your key.

I think you are looking for this kind of a solution.


How can I hide the title in a custom page made with hook_menu?

Not sure if processed on time but I would try using drupal_set_title. And making sure you have an if statement around the h1 or h2. So use drupal_set_title to create empty title and use:

if(!empty($title)){
echo '<h1>' . $title . '</h1>';
}


JavaScript supposed to always be called on front page, but doesn't always run

I think perhaps the issue stems from the browser's "BFCache" which is a browser feature that caches a page for quicker loading when a user presses the Back/Forward button. See below to understand more about this feature.

Try adding the following code inside of your attach function.

// Prevent the bfcache.
$(window).bind("unload", function() {});

The "BFCache" as taken from page:
https://stackoverflow.com/a/2218733/955858

To quote that post:

  The modern browsers (Firefox, Safari/Chrome, and Opera) all support the special "back/forward" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). This allows it to re-load the page very quickly and exactly as the user left it, which is what the user wants.

  The load event is not supposed to fire when the page is loaded from this bfcache. For example, if you created your UI in the "load" handler, and the "load" event was fired once on the initial load, and the second time when the page was re-loaded from the bfcache, the page would end up with duplicate UI elements.

  This is also why adding the "unload" handler stops the page from being stored in the bfcache (thus making it slower to navigate back to) -- the unload handler could perform clean-up tasks, which could leave the page in unworkable state.

  For pages that need to know when they're being navigated away/back to, Firefox 1.5+ and some next version of Safari (which contains the fix for bug 28758) supports special events called "pageshow" and "pagehide".

  References: http://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ and https://developer.mozilla.org/En/Using_Firefox_1.5_caching.


Error trying to submit webform programatically multiple times: Duplicate entry for key 'PRIMARY'

Not entirely sure why, but moving the line that sets $submission_out inside the loop fixes this problem.


Feeds : creating a node dependencies at importation

I have done something similar with importing images. If the image exists in the files table I just add the fid, and if it does not yet exist I create it.

I created a custom module and implemented hook_feeds_processor_targets_alter, and hook_feeds_dimension_set_target

Aside from that I don't know of an answer that does not require a bit of coding.


Adding Data to a Variable in a Contributed Module

You will not need to 'hack' this module, you can use a legitimate hook to modify the $nvp array, hook_commerce_paypal_api_request_alter

At line 382 of the commerce_paypal_wpp.module, right after the part you mention, the whole array is passed to the commerce_paypal_api_request where the mentioned hook is called early on, to allow modifications from other modules.

Following your example code, your hook implementation would look like this:

function yourmodule_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method) {
  ...
  $fname = 'examplename';
  $lname = 'examplelastname';
  $arr = array($fname, $lname);
  $allthedata = implode('+', $arr);
  $nvp['CUSTOM'] = $allthedata;
  ...
}

Hope this helps!


Use the module Jquery Update:

  Upgrades the version of jQuery in Drupal core to a newer version of
  jQuery.

For 1.11, I believe you will need to use the DEV version, and take a look at this item in the Issue Queue for updating to that version.


How to modify the language switcher block to only use the language code instead of its full name?

One possible solution would be to insert this snippet in your .theme file

In this example I am using bartik as a theme.

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function bartik_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'language_block:language_interface') {
    foreach ($variables['content']['#links'] as $key => $value) {
      $variables['content']['#links'][$key]['title'] = strtoupper($key);
    }
  }
}

Please, let me know if this solution works for you.

Best regards,

Oleg


Views - group/aggregate by field with multiple content types

I would suggest using the default Views attachment display so you can have different queries and/or fields next to each other.


Rewrite rules for Development & Production Environments

Try changing (or assigning) the base url in sites/default/settings.php


Personally, I would create a custom module with a custom form and block. You're gonna want to study up on the form api. You can pass variables to your form, which for you would be your node object.

The block is really easy, just use hook_block_info() to define your block, hook_block_view to define a subject and callback function, and then just define a callback.

Something like this:

function mymodule_block_info (){
   $blocks[0] = array(
      'info' => t('radio thing'),
      'cache' => do_stuff
    );
   return $blocks;
}

function do_stuff(){
    //where radio_form is the implementation of your form (make sure it has a param for the node
    drupal_get_form ('radio_form', $node)
    return $stuff
}


Best practice approach for environment specific keys

So, I reached out to one of the authors of key and the lockr service to get some help.
What I learned is, if using the key module without lockr, you can change the value of the key while keeping its machine name the same.
But, if using lockr (and you should be using lockr) it will create and swap keys for you based on your environment automatically. So, your encryption profile will automatically be kept up to date. Awesome stuff.
Hope this is helpful to others, the docs are here; https://docs.lockr.io/#separate-environments


Drupal 6

Option 1:

Enable the 6.x-2.x XML sitemap custom sub-module.
Manually add the links to your views at admin/settings/xmlsitemap/custom

Option 2:

Enable the 6.x-2.x XML sitemap menu sub-module.
Create a new menu at admin/build/menu/add with the menu name xmlsitemap and title XML sitemap. Make sure that the 'Include this menu in the sitemap.' checkbox is selected.
Edit your view's page view, and add the view to the 'XML sitemap' menu under the 'Page settings'.

Drupal 7

Modules/XML Sitemap: Check "XML sitemap node" (Adds content links to the sitemap.)
Configuration/Search and Metadata/XML sitemap/Settings: Click on the "Content" tab. Go to your View created content, click on it.
In the XML sitemap tab, set Inclusion to Included. Save.
Back to Configuration/Search and Metadata/XML sitemap/ - click on Rebuild Links. You'll now have all of the Views created pages listed in sitemap.xml


Temporarily disable all modules for troubleshooting

You can collect the machine names of all the enabled modules with the drush pm-list --type=Module --status=enabled --pipe > enabled.txt command.

And then iterate through the list do disable:

drush -y dis $(<enabled.txt)

or enable

drush -y en $(<enabled.txt)

them.


use menu item title instead of page title in breadcrumbs

Perhaps you could look at this module: http://drupal.org/project/menu_breadcrumb
It sounds perfect for your needs.

Some details from the module's project page:

  By default, Drupal 6+ use the Navigation menu for the breadcrumb. This module allows you to use the menu the current page belongs to for the breadcrumb.


views exposed filters - return user selection or another value

Easy to do but hard to find the answer.

In the views's FILTER CRITERIA click the down pointing arrow and select the second option (and/or, rearrange). Then create a new filter group and play around with the options there :)


How to obtain the average of the number of a field according to the term of taxonomy?

I'm not aware of a configuration that can do that out of the box on the Content type Views. But if it must be that exact Taxonomy Terms Views you can do it with the help of an additional module (check out Views Calc and Views Aggregator Plus).

But if you only want the result, to show the Average number on Term pages, then you can create a different View, of type Taxonomy term and display it as a Block on term pages. This type will work without additional modules.

Create Term Views type
Filter to your Vocabulary, filter Note field to be Not empty
Add the Taxonomy Name field, just to test, you'll see terms listed in separate Views rows
Add the Relationship to all content using the field Content using Note, (Relate each Content with a Note set to the term.) You can require this Relationship
DO NOT add any Sort criteria, sorting often messes up Aggregation
Add the Note Field, it will show separate Nodes' Note numbers in separate Views rows
Turn ON Aggregation
Edit the Note Field Aggregation and set it to Average, Group column Value

You should now again only see individual terms in rows, and the Note will show the average number calculated
Check the Note field Formatter, the Default might round the numbers not to show decimal places, Unformatted might show more
If this is all working the last thing to do is to add a Contextual filter to filter according to the term page you're viewing: Add the Contextual for the field relating to your relevant Taxonomy terms and configure it:
 When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from term page
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID

Now you can enter a term ID into Preview field and you'll see what the block will display on that term's taxonomy page.

Place the block in a region, configure the block, limit the Visibility to term pages etc.


Unless you want or can modify $qt_project and add in the rel to the attributes array of the links, the only way I see is to add in a custom renderer in your module.

This would entail some ctools integration implementing hook_ctools_plugin_type(), some quicktabs integration implementing hook_quicktabs_renderers() and then basically copying QuickQuicktabs.inc from the quicktabs module to your module's directory structure, changing the name to something appropriate, and then inside, also changing the name of the QuickQuicktabs class to something similar, and then in the guts of that, changing

/**
 * Helper function to construct link options for tab links.
 */
protected function construct_link_options($tabkey) {
  $qt_name = $this->quickset->getName();
  $id = 'quicktabs-tab-' . implode('-', array($qt_name, $tabkey));

  // Need to construct the correct querystring for the tab links.
  $query = drupal_get_query_parameters(NULL, array("qt-$qt_name", 'q', 'page'));
  $query["qt-{$qt_name}"] = $tabkey;

  $link_options = array(
    'attributes' => array(
      'id' => $id,
    ),
    'query' => $query,
    'fragment' => 'qt-' . $qt_name,
  );
  return $link_options;
}

to most probably just

/**
 * Helper function to construct link options for tab links.
 */
protected function construct_link_options($tabkey) {
  $qt_name = $this->quickset->getName();
  $id = 'quicktabs-tab-' . implode('-', array($qt_name, $tabkey));

  // Need to construct the correct querystring for the tab links.
  $query = drupal_get_query_parameters(NULL, array("qt-$qt_name", 'q', 'page'));
  $query["qt-{$qt_name}"] = $tabkey;

  $link_options = array(
    'attributes' => array(
      'id' => $id,
      'rel' => 'nofollow',  // just this one little addition :)
    ),
    'query' => $query,
    'fragment' => 'qt-' . $qt_name,
  );
  return $link_options;
}

and then calling quicktabs_build_quicktabs() with 'render' pointing to your custom renderer in the $qt_options array.


Error when adding BCC to email handler with webforms and smtp

It looks like the issue lies with the SMTP module. The release notes for 8.x-1.0-beta6 include a bug fix for:

#2993124 by jmuzz, qichanghai, Chris Matthews: Call to Undefined Method error _get_components when there is a BCC


Passing PHP objects and methods as strings to FormAPI

I think your best bet is to call a function that will call

$myObject->_my_after_build_function();

One way that won't work most likely.

$method_name = _my_after_build_function;
"$myObject->{$method_name}"

Another shot in the dark that might work if using PHP 5.2.3+ http://php.net/manual/en/function.call-user-func.php.

"myObjectClassName::_my_after_build_function"

You can try the above 2 methods but with a & in front of it. http://www.php.net/manual/en/language.references.pass.php


What would be a comprehensive but safe set of html tags to use with the HTML Filter but compatible Markdown?

But you don't need enable all of it, just simple reorder the filters, and put the markdown filter under the html filter. So the html filter will drop the unavailable tags, before the markdown process the text, and build own html.

Edit:
Checked the OpenAtrium's dedicated Markdown filter, it has the following in HTML

Markdown PHP Version: 1.0.1n
Markdown Extra Version: 1.2.4

And own filter weights:


how to use Profile information for payments

It sounds like you're using a custom module with instructions that run counter to the Authorize.Net instructions. Is that what you mean by customer_profile_type_ui? I assume that isn't part of the core Commerce Customer module, so a link would be helpful, but honestly it looks like you've already answered your own question.

I don't really get why you'd disable the core Billing information checkout pane for having insufficient fields. If you add a field to your billing customer profile type, it will show up in the checkout form. What else would you need to do besides that?


How to pull pictures and summary information from external web pages when posting links?

AFAIK there is no module available for this specific use case. However FBSMP module has its own implementation of crawling links/image/video and other media types from the given URL.

You may need to take that as a base and develop your own version.

Below is the sample code on how its crwaling the links

$result = drupal_http_request($url, array('timeout' => $options['timeout']));

  if ($result->code != 200) {
    fbsmp_log_error(t("Could not connect to @url, HTTP error @error", array('@error' => $result->code, '@url' => $url)));
    return $data;
  }

  $page_url = $url;
  if (in_array($result->redirect_code, array(301, 302, 307))) {
    $page_url = $result->redirect_url;
    $data['title'] = $page_url;
  }

  if (stripos($result->headers['Content-Type'], 'image') !== FALSE) {
    $images = array();
    if (($imagesize = _fbsmp_link_validate_filesize($page_url, $options['max_imagesize'], $options['min_imagesize'], ($options['timeout'] - timer_read(__FUNCTION__) / 1000))) != -1) {
      $images[$page_url] = $imagesize;
    }

    $data['images'] = $images;
  }
  else {
    _fbsmp_link_detect_charset($result->data);

    $document = new DOMDocument();
    if (@$document->loadHTML($result->data) === FALSE) {
      fbsmp_log_error(t("Could not parse the content on @url", array('@url' => $url)));
      return $data;
    }

    $xpath         = new DOMXPath($document);

    //Get title of the page.
    $titles        = @$xpath->evaluate("//title");
    $data['title'] = trim($titles->length > 0 ? $titles->item(0)->nodeValue : $data['title']);
    //Get description of the page.
    $descriptions  = @$xpath->evaluate("//meta[@name='description']");
    $data['description'] = trim($descriptions->length > 0 ? $descriptions->item(0)->getAttribute('content') : $data['description']);

    if (!$emfield['emvideo_valid'] && !$emfield['emaudio_valid']) {
      $hrefs         = @$xpath->evaluate("/html/body//img");
      $images = array();

      if (!fbsmp_include_library('url_to_absolute.inc', 'url_to_absolute')) {
        fbsmp_log_error(t("Could not find url_to_absolute.inc file in the libraries folder"));
        return $data;
      }

      for ($i = 0; $i < $hrefs->length; $i++) {
        $image_url = $hrefs->item($i)->getAttribute('src');
        if (!isset($image_url) || empty($image_url)) {
          continue;
        }
        $abs_url = url_to_absolute($page_url, $image_url);
        if ($abs_url && ($imagesize = _fbsmp_link_validate_filesize($abs_url, $options['max_imagesize'], $options['min_imagesize'], ($options['timeout'] - timer_read(__FUNCTION__) / 1000))) != -1) {
          $images[$abs_url] = $imagesize;
        }
        if (($options['timeout'] - timer_read(__FUNCTION__) / 1000) <= 0) {
          fbsmp_log_error(t("Request timed out for @url", array('@url' => $url)));
          break;
        }
      }
      asort($images);
      $images = array_reverse($images, TRUE);
      $data['images'] = $images;
    }
  }

  //Cache the results.
  if ($options['cached']) {
    cache_set($arghash, $data, 'cache', REQUEST_TIME + $options['cache_duration']);
  }

You may also check following references,

embed.ly
Using Yahoo API to crawl the link


Highlight searched keyword using exposed filter views?

Using search_excerpt function you can highlight the searched keyword. It show the keyword in bold.

  Returns snippets from a piece of text, with certain keywords
  highlighted. Used for formatting search results.

An example is shown below,

for eg:
 //a body field is exposed here

in your views tpl file add the following code

 <?php foreach ($rows as $id => $row):

      $keys = $_GET['body_value'];
      $row = search_excerpt($keys, $row);
 ?>

it will highlight the searched word, see the screenshot below


Image cache present in which config file

Image cache is core in Drupal 7 IIRC. So you can access its config and settings via /admin/config/media/image-styles. The cached images themselves are saved in your theme/files dir as defined in /admin/config/media/file-system.


Does Multiupload Filefield Widget for Drupal provides a Form API element?

Yes it does, as defined in multiupload_filefield_widget_element_info(). The element type is mfw_managed_file, so you can use something like:

$form['multi_upload_element'] = array(
  '#type' => 'mfw_managed_file',
  '#title' => t('Some file'),
  '#upload_location' => 'public://',
);


Get translated taxonomy terms with Entity Translation

You are using Entity Translation, so keep in mind there can't be any translated term load because you're translating fields not whole term. Term will load by

$term = taxonomy_term_load($tid);

use in devel mode or by dpm see the $term object. There you'll see structure

$term->name_field['en'][0]['value']

You can fetch it this way or by field_get_items() for en language.

$name = field_get_items('taxonomy_term', $term, 'name_field', 'en');

AND

$term->name_field['fr'][0]['value']

You can fetch it this way or by field_get_items() for fr language.

$name = field_get_items('taxonomy_term', $term, 'name_field', 'fr');

This is how you can get the data per language


How to implement 'Starts With' for exposed filter of User ID

If you use the "User: Name" filter it will give you an autocomplete text field where you can start typing and it will show you a list of patching users as you type.

That field will not let you enter partial user names though, you must select a user from the autocomplete (you can have multiple comma delimited values if you like).

To match partial user names, use the "User: Name (raw)" filter.

This one allows you to have a text field that doesn't have any validation.
This field can have the operator set to "Starts with".


How to remove the name of the language? Menu Language Icons

On the configuration page of the Language Icons module, admin/config/regional/language/icons, you should set the option 'Icon placement' to 'Replace link'. If I'm not mistaken, choosing this option ensures only the flags are shown.


How do I create a nested tree with terms & nodes with Views 3?

Thanks to refino, I found a nice solution using the following modules: Views Tree
Views Field View

Below you find the explanation:

First create a new Taxonomy (let's call it "Folder")
Then, create a new content type (let's call it "Element") with a term reference field to the "Folder" taxonomy
Create a new "Content" View (let's call it "Element View")
Choose Field Display
Add a Contextual Filter to your term reference field
Create a new "Taxonomy" View (let's call it "Folder Tree")
Add 2 fields (term name and term id). The second field can be excluded from display
In Relation: add a "parent term"
Add a third field (term id) and assign it to your parent relation. This field can be excluded from display
Choose Format "Tree (Adjacency model)" and select in the parameters : Ordered list + Main field (your first tid), Parent field (your tid assigned to the parent relation). You now should have a nice tree with all your terms nested
Add a 4th field "Global:View" (this comes with Views Field View) and choose your "Element view", display Master add [tid] in the Arguments textfield

Hope this help

Cheers

Edit by iStryker:   This is what I got.  The only thing I changed was make Element View a table view, and removed the default (row & strip) classes.


Commerce Add to Cart Extras

  This module provides alternative ways of adding products to cart.

  The initial version provides a views field handler ("Commerce Product:
  Quantity input field") that relies on the Views Form API (a part of
  Views 3 since RC1) to output a quantity textfield that turns the view
  into an add to cart form. The default quantity can be configured, and
  only products with a quantity larger than 0 are added to the cart.


Message (from message stack) not translated into the preferred language of the recipient

I have made a path here: https://www.drupal.org/project/message_notify/issues/2965975#comment-13559090

Feel free to test it and report any problem


Modules that will allow search for external data using either Apache Solr or Elastic Search

You need Search API with either of the plugin modules. Search API is a fantastic way to abstract out the engine from the logic. Although I've only use the Solr implementation I've spoken with several developers who have switched to Elastic.

https://www.drupal.org/project/search_api
https://www.drupal.org/project/search_api_solr
https://www.drupal.org/project/search_api_elasticsearch

Search API also works with Facet API (which supports the ApacheSolr module too -- the 'competitor' to Search API).
https://www.drupal.org/project/facetapi

In Drupal 8 those two modules (Search API and ApacheSolr) have become one.


Your woes are most likely coming from apache (or whichever web server you are using) unless you are using the domain module. Either your .htacces file or virtual host (depending on whether you have "AllowOverride" on in apache) should be setup to route requests through 'example.com' and not 'server.example.com'.

Are you on a VPS or shared host? What flavor of Linux are you using?


Getting a custom field to appear correctly in Rules using entity form module

I have managed to find a work around using hook_tokens(). Through viewing the $data array, I was able to find the field and write some code which manipulated the incorrect field and created the token correctly for Rules by walking through the field array.

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
 $replacements = array();
 $sanitize = !empty($options['sanitize']);
  if ($type == 'entityform' && !empty($data['entityform'])) {
    $elementform = $data['entityform'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
       case 'field-foo':
         $name = str_replace('-', '_', $name);
         $field = $elementform->name
         $replacements[$original] = $field[und][0]['value'];
         break;
      }
    }
  }
  return $replacements;
}

I would be happy to learn if there is a better way of achieving this goal in Drupal.


How to Create and Retrive a product programmatically in Drupal commerce 2.x

To create a product is similar to how you'd create a node:

use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;

$variation1 = ProductVariation::create([
  'type' => 'default',
   'sku' => '123',
   'price' => new Price('14.50', 'USD'),
]);
$variation1->save();

$variation2 = ProductVariation::create([
  'type' => 'default',
   'sku' => '1234',
   'price' => new Price('10.00', 'USD'),
]);
$variation2->save();

$product = Product::create([
   'type' => 'default',
   'title' => t('Product Title'),
    'variations' => [$variation1, $variation2],
]);
$product->save();


How to call hook_theme_suggestions_HOOK_alter twice, if node is shown twice?

Nodes are rendered only once per view mode and then are cached. So the easiest solution would be to configure different view modes. Which makes sense in this case, these are in fact two different displays of the same node. Another benefit, you don't need this hook, because view modes have theme suggestions out-of-the-box.


Create a sample HTML select of taxonomy terms

You will need to get your terms (with a query or load the vocab), loop over them and create an array of term tid and term label. Set that array as the #options property on the select field in your form code.


How to use Oracle as a remote/local database for Drupal 7?

There is a stable Oracle database driver in Contrib: http://drupal.org/project/oracle

However, if you want to use Oracle for your main Drupal database, you will need to test each contrib module that you are planning to use for Oracle compatibility. Many still have MySQL specific SQL, even though the situation has improved a lot thanks to the new database abstraction layer.

Using the Oracle driver to access data from a secondary database for imports and so on should work fine, though.


How can I hide empty Quick Tab item when there is no content in it?

I already checked it. But still the 'View' I assigned to that quicktab renders some div's which I posted in my question. By the way, I found the solution, you just need to add the filter in that particular view. Suppose view of content type 'movies' then add a filter "content:movies => not empty (IS NOT NULL)". That's it.  Hope this help others too.


Anonymous page cache does not respect cache contexts, I'm guessing that is your problem.

To get that working, you need to switch out the PageCache service in a custom module with a ServiceProvider and override the getCacheId() method.


Unsupported Operand Types theme_image_style

According to theme_image_style page you tried wrong parameters,

as an example, your code should be something like the following snippet

$variables = array(
        'style_name' => 'thumbnail',
        'path' => $image_fields[LANGUAGE_NONE][0]['uri'],
        'width' => $image_fields[LANGUAGE_NONE][0]['width'],
        'height' => $image_fields[LANGUAGE_NONE][0]['height']
);
$thumbnail_image = theme_image_style($variables);

and in short

$thumbnail_image = theme('image_style', array(
        'style_name' => 'thumbnail',
        'path' => $image_fields[LANGUAGE_NONE][0]['uri'],
));


Solution 1 - Using module Charts (with Views)
There is no out-of-the-box answer to your question to make this work with the Charts module, at least not as of today (yet). That's because "Radar chart" is not one of the currently supported chart types (those that are supported are: Pie, Bar, column, Line, Area and Scatter).
But if you're willing (and able) to complete a few extra steps, you should get it to work. Use the details below as a guide, but know also that there are so many options / features in either of the supported charting engines (libraries), i.e. Google Charts and Highcharts. Which is also why it's virtually impossible to support all those options out-of-the-box.
Option 1
Refer to the issue about Stacking column/bar charts for an example of how you can do this with a custom module. Comment #3 in it contains a sample like so:
<?php
function MYMODULE_chart_alter(&$chart, $chart_id) {
  dsm($chart_id); // Need Developer module enabled for dsm to work
  if ($chart_id == 'MYCHARTVIEW__DISPLAY') { // Watch out for those double underscores
    $chart['#stacking'] = TRUE;
  }
}
?>

This should work for both Google Charts and Highcharts as the charting library (engine).
The remaining challenge for you is what exactly you should specify as chart_id, and which specific charting option is needed for such "radar chart". My best bet, for Highcharts, is that it is what that library calls a "Polar Chart" (would be too easy for all those charting libraries to use at least the same terminology ...).
Option 2
A possible alternative (or maybe refinement, depends on your needs) that you may want to look at is using the approach as described in the issue about Pass library-specific options via existing #raw_options, AFTER you apply the patch in comment nr 4 of this issue. If you're using the most recent dev version of the Charts module (which is stable and includes various patches on top of the rc1 release), then this patch is already available (no more need to apply it). Be aware that this only works for Highcharts as of right now (waiting for a similar patch to become available for Google charts also).
Refer to the question about "https://drupal.stackexchange.com/questions/183018" (and its answers) for an interesting use-case of these "raw options".
Solution 2 - Using module Forena (without Views)
The sample radar chart in your question is actually from the Supported chart types, one of the Community documentation pages from the Forena module.
The very same sample is also included in SVG Graph Demo, one of the samples that gets installed by the Forena module, such as in this demo site.
So such chart can ALSO be created with the Forena module, which uses the (free and open source) PHP SVG Graph library, without using Views. And by using the integration of Forena with the BEAN module (as explained in its documentation about Bean Integration, you can put such chart in a block that you'd put on your page where it fits your needs.
For (way) more details, head over to the Forena Documentation included with the module (or its equivalent in the demo site). Or have a look at various questions around here tagged with forena ... and add your own questions if needed (using this tag).
Disclosure: I'm a (co-)maintainer of Charts and Forena.


How to add a checkbox for contact page in drupal?

You can do this with Drupal core Contact module and with small custom code. As Drupal 7 contact module provide personal contact form and site wide contact form. See here Working with the Contact Form. You can enable Personal contact form by default for each user and hide the Contact Settings under /user/[uid]/edit which will be enabled for all users. Then with custom code you can show and hide Contact form Based on the Checkbox you added.

The setting shown in below screenshot will be enabled for all users by default then you will hide this setting with custom code. Because there is no configuration to show this setting on user registration form.

Steps:

Enable Drupal core Contact module.
Then Goto admin/config/people/accounts and enable Enable the personal contact form by default for new users. setting.

Give the following permission to Authenticated Users

View user profiles
Use users' personal contact forms

Add the checkbox field in User profile and enable that on registration form. Assuming the field name is field_do_you_want_contact_form.
Then in custom module with hook_form_alter hide the personal contact form setting and show/hide the contact form based on the value of checkbox.

//custom.module
function custom_form_alter(&$form, &$form_state, $form_id){

  // Hide the personal contact form setting under /user/[uid]/edit

  if ($form_id == 'user_profile_form') {
   $form['contact']['#access'] = FALSE;
  }

 // Show the Contact form Or custom message under contact tab based on checkbox value.
  if ($form_id == 'contact_personal_form') {
    $user = $form['recipient']['#value'];
    $wrapper = entity_metadata_wrapper('user', $user);
    $do_you_want_contact_form = $wrapper->field_do_you_want_contact_form->value();

    if (!$do_you_want_contact_form) {
    // hide all the contact form element.
        $form['name']['#access'] = FALSE;
        $form['mail']['#access'] = FALSE;
        $form['to']['#access'] = FALSE;
        $form['subject']['#access'] = FALSE;
        $form['message']['#access'] = FALSE;
        $form['copy']['#access'] = FALSE;
        $form['actions']['#access'] = FALSE;

    // Add custom message
        $form['not_rechable']['#markup'] = t('Contact: not rechable');
    }
  }
}


Cannot get just the text of an option from submitted data

I scanned Webform's code base for [webform_submission:values: and eventually found the webform.token.inc file to list a number of Webform tokens from submission values. One of them being entity:*. And another being delta.
'
element_key:entity:*
' .
'
element_key:delta:entity:*
'

The 'entity:*' applies to the referenced entity
The 'delta' is the numeric index for specific value

And when I scan Drupal core's code base for :entity:title] there's [comment:entity:title]. When I scan for just :title] there's [node:title] among the first hits. Okay, with all that I'd assume it must work with either:
[webform_submission:values:ELEMENT_KEY:entity:title]

Or if it's a multi-value field try it with a :delta of 0 to ensure you only get the first referenced node's title.
[webform_submission:values:ELEMENT_KEY:0:entity:title]

Just found out for taxonomy terms it's :name at the end:
[webform_submission:values:ELEMENT_KEY:entity:name]


What is the recommendation for mapping state?

There is no mapping/schema for state nor for the underlying key value system.

This question can't be "answered" other than saying "None". Anything else would need to be in the form of a feature request and I'm not convinced this makes sense.


Facet API, exclude option, and a field with multiple values

I did ask the same question in search_api issue queue and this problem needed 2 patchs to be commited.

One for Search_api_database_search : https://www.drupal.org/node/2361329

Another for Search_api : https://www.drupal.org/node/2371099

Hope it can help !


Is it possible to install Drush 9 without using Composer?

No.
As it says in the docs:

Drush 9 only supports one install method. It requires that your Drupal 8 site be built with Composer and Drush be listed as a dependency.

If you don't know how to use composer, you need to learn now, because you'll have serious problems using Drupal without it.


Change Quantity of multiple products and add it to cart

This should be possible. What I would do (from the bottom of my head, other alternatives can be easily implemented) is described below.

Assumptions:

There is an entity reference field to indicate relevant products.
There is no relation of 'additional' products back to 'main' or other products (the additional products are refered to by main products and they have no other reference to any other).
You have basic Views knowledge
You have basic Rules knowledge
You have basic Views Rules knowledge

Method:

Create a rule on event 'add an item to the cart'
Condition: the added item has reference to 'additional' products (so this is not an additional product).
Redirect to a view page which presents all products that are relevant to the current user's cart items (a view on order items entities).
The view should have an add to cart button without quantity
Create a rule on the same event 'add to cart'
Condition: the added item has no reference.
Loop through all cart items and call a rules component.
Create a rules component with 2 arguments (item added, item from loop) and 1 condition: if item from loop has reference to the item added), return the quantity.
Set the item quantity to the one returned by the component.
Optionally redirect to somewhere else.

Mind that the condition needs a bit of care. Alternatively, you can avoid Rules altogether and create a custom module which will use the Drupal Commerce API.


One view to do everything or a different view per page?

Personally, I create a view per content type and set up decent defaults and then have displays to handle the different uses.  Special pages and other one offs (like the home page in your case) have specific views.

I find this approach better handles changes that may come down the line.


How to display 'new' by unread forum posts (like drupal.org)?

You can do this by a custom module.

Create a new table in database with 3 column [ nid | uid | viewed_time ] representing node view history.

And override hook_node_view(). The logic could be something like:

if (user is authenticated) {

  if (the node type is forum && nid with current uid is not in a row of view history table) {

    append 'new!' to node title

  } else {

    write [nid , uid, current time] to the view history table

  }

}


SQLSTATE[23000]: Integrity constraint violation

When setting up this product variation, I selected for the SKU to be automatically generated. In doing so, it was tripping up the feeds importer. Not sure if this was a timing issue, but I reviewed the importer set up and product variation fields for the importers that were working vs. not.

This SKU setting was the only difference. Since this field is unique ID, this seemed like the most likely culprit.

I would appreciate an explanation of why this was triggering an issue, but am happy to be able to move on.


Custom Entity Not Showing in View Creation UI

You need to add a views_data handler, like this:

"views_data" = "Drupal\views\EntityViewsData"

That exposes your entity as views data.

That is the default implementation, which does a lot, but you might need to subclass that and extend the definitions if you need additional filters/fields/...


Please check answer. I think this may help you toy solve your problem.

ANSWER LINK


How to create RSS feed for particular content type in drupal 8?

Can create the views as well for generate the rss feed with following steps:

Enable Serializer and RESTful Web Services module, available in Drupal 8 core.
Create views for retrieving the contents of required content type.
Select the option Provide a REST export, present in the REST export settings (present at the bottom of views).
Configure the views as per the requirement.

Example:


Batch API times out when running a single operation

In BulkPrintForm::submitForm() you invoke batchFunction method by calling it directly via $this->batchFunction($nid) line. This will effectively skip the batch API and run it for all nodes. You should pass the callback instead, check http://cgit.drupalcode.org/examples/tree/batch_example/src/Form/BatchExampleForm.php#n93


Is it necessary to use cache in hook_init?

Sure, why not. All three options should work fine. But using Drupal's cache mechanism will work the best. The page cache is not the same as other caches which can still be used for whichever purpose you require, in this case, to store the results of a DB call. There are a number of core caches each with their own purpose besides the generic one (simply named cache), and you can also roll your own cache table if you like.

Here's an example on using cache_set and cache_get which should be similar to what you are attempting to do (albeit not in hook_init).


Outputting the sum of multiple fields into a new view that then gives a grand total

Probably the simplest way to do this via Views is to add the Computed Field module to your site, and build a new content type (maybe "summary"), and add a summary for each kind of property you'd want to add in the view, and then use the computed fields to calculate all the grand totals. Display the computed fields in a new view, and it should work fairly well.

However, that wouldn't be all that dynamic. There are probably ways to do this in views itself by adding groupings, relationships, and calculated fields, but you'll end up with a view that's fragile and a real pain to maintain via the UI. You might want to approach adding a views attachment, or a display after the view, or just use some plain old custom code to generate a block (or within a block if you use the PHP filter, but I would not recommend this approach).

Another possible solution (if it's simple feature set gives you what you'd need) is the Views Summarize module.


Sure. Drupal 8 still allows #attached, the difference is just that you specify a library instead of a specific javascript file, but that is irrelevant for your question.

You can implement hook_page_attachments() and ask the route context if this is an admin route.

/**
 * Implements hook_page_attachments().
 */
function yourmodule_page_attachments(&$page) {
  // This returns TRUE for admin paths.
  if (!\Drupal::service('router.admin_context')->isAdminRoute()) {
    $page['#attached']['library'][] = 'yourmodule/yourlibrary';
  }
}


The tricky part of what you're trying to do, seems to be related to correctly specifying the filename of the attached file (= the value to be stored in your field-image field). For this, have a look at what is suggested in Comment # 25 of the support issue (not bug ...) #1431572 and which states that the correct way to do so is something like so:

[node:field-file-attachments:file:path]

Use Rules debugging

This question is pretty tough to answer with the limited info you provided (and without access to "your" site). Therefor, if needed, you might also consider some Rules debugging, by (temporary) enabling the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of the entire node/webform that's used to submit that attached file). For way more details about such debugging, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


how add js files to create a responsive theme?

Copy the plugin on your subtheme's folder like "plugins/fullpage/".

Edit subtheme.info file adding:

stylesheets[all][] = plugins/fullpage/jquery.fullPage.css
scripts[] = plugins/fullpage/jquery.fullPage.min.js

Check if you need to add the other js files like vendor/jquery.easings.min.js, jquery.slimscroll.min.js...

It seems that the plugin needs jQuery 1.9.1 so https://drupal.org/project/jquery_update may be helpful

More info about the plugin: https://github.com/alvarotrigo/fullPage.js


Views: Aggregations Do Not Group by a Date Field

To group on a date field just copy the contextual filter from the default archive view. No need for aggregation to be turned on.  Settings shown in pic:


The simplest way would be to go to /admin/config/development/configuration/single/import, select Webform and paste the YAML.

More information: Configuration Managment.


Comments form action points to different node

I think I've patched the problem clearing the cache just before the comment form render:

    <?php print render($page['content']); ?>
    <?php cache_clear_all('*', 'cache', TRUE); ?>
    <?php print render($content['comments']); ?>

As I said, seems there is a variable cache problem, and it seems to be on the Ctools module. This is only a patch until the fix comes.

Hope it will be useful.


How to display the alt below images in Panels?

If you add your images by using content and content type, this might help.

Content type -> one of the list -> manage field

click on image hyperlink follow by edit tab

Check Enable Alt field and it wil appear in edit content.

Hope this help.


Try taking off the "8". "3.0-beta1" works for me.

They have started changing the format of the versions by removing the "8" for some reason.  Not all the projects have changed yet.


Compress images before generating PDF file

The "standard" way to go would probably be to create a "reduced" image style (in admin/config/media/image-styles) and use it for the image field in your "Appointment" content type. Like that, you would let Drupal itself do the compressing of the images.


Add markup inside a link (in the renderable array) in preprocess field

Use the FormattableMarkup class for this:

$markup = new FormattableMarkup('', [
          '@url' => $url->toString(), // If $url is an Drupal\Core\Url object.
        ]);

$renderArray['your_element'] = $markup;

After edit:

Use the Markup class for this since your seem to be in control over your markup. If not use FormattableMarkup with placeholders for safety:

  function mymodule_preprocess_field(&$vars) {
    $fn = $vars['element']['#field_name'];
    switch ($fn) {
      case 'my_field':
        foreach ($vars['items'] as $key => $item) {
          $icon = '';
          $uri = $item['content']['#title'];

          $formattedIcon = \Drupal\Core\Render\Markup::create($icon . $uri);

          $vars['items'][0]['content']['#title'] = $formattedIcon;
        }
        break;
    }
  }

From the FormattableMarkup docs:

  When cast to a string, this object replaces variable placeholders in
  the string with the arguments passed in during construction and
  escapes the values so they can be safely displayed as HTML. See the
  documentation of
  \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for
  details on the supported placeholders and how to use them securely.
  Incorrect use of this class can result in security vulnerabilities.


I can't get hook_form_alter or hook_form_FORM_ID_alter to add placeholder text to the search input

This is what eventually worked for me. Posting because other people seem to be having the same issue.

I placed this at the very end of the MyTheme.theme file.

/**
 * Add placeholder text to the search forms.
 */
function MyTheme_form_search_block_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Search this site...');
}

Hopefully this will be helpful for some.


How do I a custom entity operation with a webform submission?

It seems the answer came from spending a day (and a bit) just studying the inner workings of D8 and realizing just how much is done for you that wasn't the case in D7.

Ultimately I want to send the action to a Controller, not a plugin and the primary source for getting enough grounding to figure it out came from the following:

https://www.drupal.org/docs/8/api/routing-system/structure-of-routes
https://www.drupal.org/docs/8/api/configuration-api/creating-a-configuration-entity-type-in-drupal-8
https://www.drupal.org/docs/8/api/entity-api/creating-a-content-entity-type-in-drupal-8


How can i get the value from the Dynamic query

The problem is that the following line is wrong:

$query->fields('n',array('title','nid'),'d',array('field_cmp_userscore_value'),'e',array('field_cmp_usersupport_value'),'f',array('feld_cmp_status_tid'),'g',array('.field_cmp_attend_time_value'),'h',array('field_cmp_end_date_value'));

You need to call fields() separately for each table. Right now, the additional arguments are ignored.

Also note that it is strongly recommended to use EntityFieldQuery to query field tables, that however has the limitation that you need to load the node object to get the field values.


How do i increase length of existed link title field in Drupal 8?

What you can do is this:

Create new link field
Update configs, like form display, views etc to use new field.
Migrate all the data to the new field, in an update hook. Example code could look like this (Assuming link field is on a node)

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'node_type');
foreach ($nodes as $node) {
  $node->new_field = $node->old_field;
  $node->save();
}

Delete old field.
Done

Alternately you can update field field, manually update the SQL tables etc, but this is quite tricky to do properly. If you want to go down this road you should take a look at the entityDefinitionUpdateManager.


At first you need to implement hook_node_presave($node)

  Act on a node being inserted or updated.

  This hook is invoked from node_save() before the node is saved to the
  database. Parameters

  $node: The node that is being inserted or updated.

So it reacts when a node is going to be saved , then you have to check if the node type is the proper node type . then setting field value , so this is some code snippet :

function mymodule_node_presave($node) {
  if($node->type == "Your Node Type") {
      //dsm($node);//it will show the structure of node
      // as example
      $data = $node->title.'-'.drupal_get_path_alias('node/'$node->nid);
      $node->field_alternative_titles_title[$node->language][0]['value'] = "data";//check the node structure,this code wont work for sure
  }
}

of-course this is just an snippet , to make it work you have to know the structure of your content type , Devel module will help you , install and enable it so dsm function will work.


This is what will work

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

   $form['name']['#title'] = Null; // Change text on form
    $form['name']['#attributes'] = array('placeholder' => t('username'));
    $form['pass']['#title'] = Null;
    $form['pass']['#attributes'] = array('placeholder' => t('password'));

    $form['name']['#attributes']['class'][] = 'nui-input';

Here is the reference : How do I use hook_form_alter() to add CSS classes to a custom input field in user_register_form?


I know there are some parent and tree properties in the form API, but to be honest I have never use it. In a case like your I will create 3 text fields with a limit number of characters depending on the part of the phone number I am collecting ( 3 (for area code) - 3 (for the exchange) - 4 (for the number) ) and then on the submit function of the form I will concatenated them together.

function my_module_example_form($form, &$form_state) {

// If you edit the data using the same form then
// get the previously store phone number
$phone = $phone_from_db;

$form['area-code'] = array(
  '#type' => 'textfield',
  '#title' => t('Area Code'),
  '#default_value' => substr($phone, 0, 3),
  '#size' => 3,
  '#maxlength' => 3,
  '#required' => TRUE,
);

$form['exchange'] = array(
  '#type' => 'textfield',
  '#title' => t('Exchange'),
  '#default_value' => substr($phone, 3, 3),
  '#size' => 3,
  '#maxlength' => 3,
  '#required' => TRUE,
);

$form['number'] = array(
  '#type' => 'textfield',
  '#title' => t('Number'),
  '#default_value' => substr($phone, 6, 4),
  '#size' => 4,
  '#maxlength' => 4,
  '#required' => TRUE,
);

  return $form;
}

function my_module_example_form_submit($form, &$form_state) {
  // Submission logic.
  $phone = $form_state['values']['area-code']+$form_state['values']['exchange']+$form_state['values']['number'];
  // Save the $phone variable
}

There are also a couple of modules with the ability to add phone fields and they even offer validation of the phone number depending on the country.

http://drupal.org/project/phone
http://drupal.org/project/cck_phone
http://drupal.org/project/location


http://drupal.org/project/simpletest - it provides essentially the same testing API as the core D7 module and you still have to write the tests yourself. There is also http://drupal.org/project/simpletest_automator that apparently will help you 'record' your actions on a site into a SimpleTest for you.

Additional helpful links:

http://drupal.org/project/selenium
http://drupal.org/simpletest


How to hide an image field from teaser view if video field has data?

function mymodule_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\
  EntityInterface $entity, $context) {
  // For nodes, change the view mode when it is teaser.
  $current_path = \Drupal::service('path.current')->getPath();
  if($current_path=='/dblog'){
    if ($entity->getEntityTypeId() == 'node') {
        // kint($entity->getFields()['field_videos']
        //  ->getValue()[0]['target_id']);
        if(!(empty($entity->getFields()['field_videos']
        ->getValue()[0]['target_id']))){
        $view_mode='single';
        }
    }

  }

}

well in my case, i solved my problem like this, i created new view mode with needed fields and switched view modes using above hooks.I think this one is a good alternative.Thanks Guys
@OPTASY Canada
@Chriss Happy