Explanation of pear's include path, and why Drush cr clears it?

Pear has no connection to this. The error message displays the include path value in brackets for debugging purpose. You can check the value as follows:

drush ev 'print get_include_path();'

In your case the PHP is trying to include the file from this location and emits the error as it fails.
/var/www/d8site/modules/custom/somemodule/somemodule.module

My guess the file still presents in Drupal registry because the module wasn't uninstalled properly. Check out this guide to fix it. https://www.drupal.org/node/2487215


Disabling the site cache brakes the page output

It seems that I've found a temporary solution to this problem.

Edit core/includes/entity.inc

Comment reset check lines.

function entity_view(EntityInterface $entity, $view_mode, $langcode = NULL, $reset = FALSE) {
  $render_controller = \Drupal::entityManager()->getViewBuilder($entity->getEntityTypeId());
  //if ($reset) {
    $render_controller->resetCache([$entity]);
  //}
  return $render_controller->view($entity, $view_mode, $langcode);
}

If someone has the same problem, please let me know whether the solution works.


multi price in drupal commerce in drupal 7

Commerce Multicurrency module enhances some of the multi-currency capabilities of Drupal Commerce. You can show two or more currency for a product and check this video tutorial and this one

  Current features:

  UI for fine granular definition of exchange rates.
  (Every currency combination can be defined separately if needed)
  Synchronization of currency exchange rates directly from the European Central Bank (ECB).
  UI to specify which rates shall be synchronized and which are handled manually.
  Generation of currency specific price fields inclusive generation of rule-set to handle them.
  hooks for easy integration of custom currency exchange rate sources.

this tutorial will help you without sync http://mcaleaa.wordpress.com/2012/04/08/drupal-commerce-multicurrency-recipe/


It says "No Solr instance available when trying to clear the cache", should I reinstall that module?

First check whether your solr instance working properly or not. Goto http://localhost:8080(your port)/solr/admin/.
And in your site goto admin/config/search/apachesolr/settings/solr/edit page and enter SOLR SERVER URL and click on test connection whether your solr instance working or not. If not try to re-install solr if there is not indexing.


Where and why are style tags removed in the render process?

To complete Clive answer, you could directly use your $fieldRenderable variable into a new renderable array that you will return from your build() function.

Example (not tested) :

$build = [];
foreach ($fieldsToRender as $field_name) {
  // Do your stuff
  $build[] = $fieldRenderable; // you can put whatever you want for the key
}
return $build;

The render process is done when you return the $build variable.


Typically you would use a check on $form_id to make sure your hook_form_alter would only apply the specific form. A node editing form is normally only present on edit pages, so it would only apply to edit pages as the form is not displayed anywhere else.

Don't forget that hook_form_alter is called on all forms, so you need to check for the some values to not apply it to all forms. Usually this is the form_id.

To check for a specific form you would use:

/**
* Implementation of HOOK_form_alter()
*/
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // 1.UNIT CONTENT TYPE FORM
  if ($form_id == 'unit_node_form') {

  }

}

This can be helpful if you modify multiple forms in one module.
If you prefer not to do that you should maybe use hook_form_FORM_ID_alter() to modify only a specific form.

Checking the form api $form_id is defined as:

  String representing the name of the form itself. Typically this is the name of the function that generated the form.

The question this throws up now is:

Is $form_id defined from

$form['form_id']['#value']

or from

$form['#form_id']

Both of which give the same results.
So unfortunately I can not directly give you an answer, other than that the form will only display on edit pages, so using $form_id seems to be standard proceedure.


I didn't fully understand your question. But what is get is you have multiple fields that each one is specific product say, tablet,cellphone,food and every product field has its own specific sets of options.

I recommend you to use field collection module and set the number of values to unlimited. By this module, define the filed collections and specify what sets every product field is free to choose.


I'm assuming you're using Drupal 7.x and the latest alpha version of the Meta Tags module, correct? They are still working out the views integration functionality for this module but there is a sandbox project for this issue called 'meta tag views'. In Drupal 6.x nodewords, this was easier to do based upon path by just adding a custom entry at: /admin/content/nodewords/meta-tags/custom/add.

In the meantime, you can try the metatags_quick module which lets you assign meta tags to specific paths. You would need to add the 'canonical url' as a possible field but the interface is simple to use.


How to set custom markers with Openlayers?

To "set custom markers" (as in your question title), you may also want to look at the IP Geolocation Views & Maps module. Partial quote from its project page (especially note the last paragraph of it):

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

Get Locations,
Geofield,
Geolocation Field
Location.

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

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.


Removed default login by mistake and logged out. Can't login

Jimajamma's answer is correct, but the real question here is: How do I hack a new password for user 1, given that I lost/corrupted/forgot my old one?

If you haven't turned off user registrations, create a new user. Now you have a password hash in your database for a known password. You could come up with some SQL to move this hash to user 1's password column, couldn't you? :-)

Then log in, change the password if you need to, delete the user you created, etc. And write it all down. :-)


This is all subjective to your situation, but...

If you're the sole developer on the site then you just need to make sure that your Apache user's group has write access to your files directories (or any other directories where files are uploaded or generated.  That way both you and apache can access those files using 775 mode.

If you uploaded all of the directories as a user with a primary group that apache is not in, you are better off changing the group to one that apache is in and keeping 775 rather than granting 777 permission.-

If you're on a shared hosting, in some cases group write permission on files is dangerous, so don't do the above in that situation.


Accuracy of numbers provided by the "Statistics Advanced" module?

As it relates to Statistics Advanced, you may want to take into account some of the options mentioned on its project page. Such as:

  Only track 'unique' views of content: If you keep viewing a node over and over again, the "x reads" counter won't increase each time. This is applied on a per-user basis as well as a per session id for anonymous users.

Refer to the project page for other options mentioned there.

Disclosure: I'm the (new) maintainer of Statistics Advanced.


How To Create Combined Search Filters In Views?

The newest version of Views integrates this feature without the need for Views filter populate.  It's a filter called Combine fields filter.

To make use of it you first need to add all of the fields you want to filter on.  You may check Exclude from display if you want to search for it, but don't want to display it.

Once all of the fields are there, add a Combine fields filter, and choose to Expose it.  Choose Single field for the Filter type to Expose

This is a different approach than Views populate filter, but as this is integrated into Views I find it much more intuitive.


How to display image height and width in pixels?

Have you created an image style for the image (what used to be ImageCache in Drupal 6 now in Core)?  Configuration -> Media -> Image Styles

If not perhaps you should because this will give you much more control over the size of an image without having to worry about theming the size directly.  Set up a preset for the image display in question and you can choose the size it should be generated at for a particular use.


Views switches to another view on apply or any change

I finally tracked it down to a setting in Views (where it shows all of the views) and the Settings tab. Under the Advanced Option here, I was able to turn off a "Disable Javascript on Views" setting that had somehow gotten turned on. The Ajax function was not firing and the main URL was resetting for every update of any kind. This meant jumping between views for every change of any field whatsoever.

That setting fixed everything though, so I'm posting in case anyone else has the issue and can't find a reason.


Update a user field after commerce checkout

I did figure this out and its working.  I had to use some extra code to expose the custom field but it does work.

The component is as follows, this extracts the coaching hours and sends it out to the main loop via a provider variable:

{ "rules_get_coaching_hours" : {
"LABEL" : "Get Coaching Hours",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : {
  "current_line_item" : { "label" : "Commerce Line Item", "type" : "commerce_line_item" },
  "included_coaching_hours" : {
    "label" : "Item Coaching Hours Included",
    "type" : "decimal",
    "parameter" : false
  }
},
"IF" : [
  { "data_is" : { "data" : [ "current-line-item:type" ], "value" : "product" } },
  { "data_is" : {
      "data" : [ "current-line-item:commerce-product:type" ],
      "op" : "IN",
      "value" : { "value" : {
          "coaching" : "coaching",
          "consulting" : "consulting",
          "product" : "product"
        }
      }
    }
  },
  { "entity_has_field" : {
      "entity" : [ "current-line-item:commerce-product" ],
      "field" : "field_coaching_hours"
    }
  },
  { "data_is" : {
      "data" : [ "current-line-item:commerce-product:field-coaching-hours" ],
      "op" : "\u003E",
      "value" : "0"
    }
  }
],
"DO" : [
  { "data_set" : {
      "data" : [ "included-coaching-hours" ],
      "value" : [ "current-line-item:commerce-product:field-coaching-hours" ]
    }
  }
],
"PROVIDES VARIABLES" : [ "included_coaching_hours" ]
}
}

The the main rule is as follows.  It loops through the line items and sums up total number of hours.  The last line then updates the custom field in the user record.

{ "rules_update_coaching_hours" : {
"LABEL" : "Update Coaching Hours",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_payment" ],
"ON" : { "commerce_payment_order_paid_in_full" : [] },
"IF" : [
  { "commerce_order_contains_product_type" : {
      "commerce_order" : [ "commerce_order" ],
      "product_type" : { "value" : {
          "coaching" : "coaching",
          "consulting" : "consulting",
          "product" : "product"
        }
      },
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "decimal", "value" : "0" },
      "PROVIDE" : { "variable_added" : { "total_coaching_hours" : "Total Coaching Hours" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "current_line_item" : "Current line item" },
      "DO" : [
        { "component_rules_get_coaching_hours" : {
            "USING" : { "current_line_item" : [ "current_line_item" ] },
            "PROVIDE" : { "included_coaching_hours" : { "included_coaching_hours" : "Item Coaching Hours Included" } }
          }
        },
        { "data_calc" : {
            "USING" : {
              "input_1" : [ "total-coaching-hours" ],
              "op" : "+",
              "input_2" : [ "included-coaching-hours" ]
            },
            "PROVIDE" : { "result" : { "coaching_result" : "Coaching Summation result" } }
          }
        },
        { "data_set" : { "data" : [ "total-coaching-hours" ], "value" : [ "coaching-result" ] } }
      ]
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "commerce-order:owner:field-coaching-hours" ],
        "op" : "+",
        "input_2" : [ "total-coaching-hours" ]
      },
      "PROVIDE" : { "result" : { "updated_hours" : "updated coaching hours" } }
    }
  },
  { "data_set" : {
      "data" : [ "commerce-order:owner:field-coaching-hours" ],
      "value" : [ "updated-hours" ]
    }
  }
]
}
}


Why I don't get the encryption methods? Encrypt module

The Encrypt module provides an API, but no encryption methods. You'll need to install a module that provides one. I recommend the Real AES module


How can I inject a different service in an existing one, i.e. exchange one already injected service by an own one?

Create a ServiceProvider in your module. And then replace the argument using Definition::replaceArguments like so:

<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

// @note: You only need Reference, if you want to change service arguments.
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the language manager service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('basic_auth.authentication.basic_auth');
    $definition->replaceArgument(1, 'NEW_SERVICE');
  }
}

Please note:

  Note that if you want this service alteration to be recognized
  automatically, the name of this class is required to be a CamelCase
  version of your module's machine name followed by ServiceProvider, it
  is required to be in your module's top-level namespace
  Drupal\your_module_name, and it must implement
  \Drupal\Core\DependencyInjection\ServiceModifierInterface (which
  ServiceProviderBase does).

Relevant article: https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services


You can use Panels to display a node create form anywhere you like. With a bit of extra config, you could probably make it disappear when a node exists. Panels allows you to set visibility rules to determine whether to show content.


Getting user photo url and profile url using views_json

To get the user pic url, you can do it using Image URL Formatter. Once enabled, when you click on the user picture field, you will now see a formatter option, select image url.

For the user, assuming this is a user view, in FIELDS add the User: Uid as a field and checkmark ☑ exclude from display.

Now, add Global: Custom text as a field. In the text box, put http://ultrabob.com/user/[uid]

I got [uid] from replacement patterns. Side note, in order for fields to appear as a replacement pattern, they must be above the current field.

Else, if you're using pathauto so the user pages are /user/[username] then add the User: Name field instead and use the [name] token.

Now, if your view is a content view, ex: shows articles, then you will need to add a relationship of node author first, once you do that, the user fields will become available to be added as a field.

  OK, that issue got me sorted with the pictures, I'm now working on the
  solution for profile page link. Can you think of a good way to get the
  domain part of the url (http://ultrabob.com/) in your example
  dynamically in views from the site configuration. I would like this to
  continue to work without modification as it is deployed across test
  servers and onto production

You can using php. Ex: <?php echo $_SERVER['HTTP_HOST']; ?>

Either you could enable the Views PHP module, but remember to turn it off on production, or use a template file.

views-view-field--[view-name]--views-data-export--[field-name].tpl.php

<?php

$fields["field_name"]->content = 'http://' . $_SERVER['HTTP_HOST'] . '/user/' . $fields["field_name"]->content;

echo $fields["field_name"]->content;


Is there any way to find broken images across an entire site?

You can try the linkchecker module.   It does check the source of <img> tags in the body, however it doesn't do it perfectly like it does for <a> tags.

If <img> have alt text, it thinks it is fine, even though the link is broken
<img> with links like "sites/testing/file/image.jpg" are returned not broken, links like "/sites/testing/file/image.jpg" are returned broken
External links work pretty well.

Your best bet is to use Xenu’s Link Sleuth project  (windows freeware)

Additional resources:
Here is a comparison of the link page modules.  Maybe you can find something else.
Broken Link Checker thread on drupal.org


Make support ticket subscriptions visible by default

It proved far easier to just add a line of JQuery to the page. jQuery('#edit-subscribed').removeClass('collapsed'); added to the footer took care of it.


Group entity reference field by a field on those entities

Use the module Entityreference View Widget and set up a view with grouping based on location type.

Alternatively, using custom code:

// Grab our list of all possible location types.
$location_types = list_allowed_values(field_info_field("field_location_type"));
$options = array();

// Cycle through each location type.
foreach ($location_types as $location_type_key => $location_type) {
  // Find all the nodes that are set to use this location type.
  // You may need to adjust this query if you need to limit it to only nodes of a specific type in the event you use field_location_type on other content types that you don't want showing up in this list.
  $efq = new EntityFieldQuery();
  $locations = $efq->entityCondition('entity_type', 'node')
    ->fieldCondition('field_location_type', 'value', $location_type_key)
    ->propertyOrderBy('title', 'DESC')
    ->execute();

  // If any nodes are found with this location type, add them to the options array under the appropriate location type
  if (!empty($locations['node'])) {
    foreach($locations['node'] as $location) {
      $options[$location_type][$location->nid] = entity_label('node', node_load($location->nid));
    }
  }
}

$form['field_location']['und']['#options'] = $options;


I want to add more fields to be indexed by solr. How can I do that

Go to admin/config/search/search_api and click "Edit" next to your Index and select "Fields".

Check the checkbox next to the fields you want indexed under the column "Indexed" and click "Save Changes" when you're done.


How to let users choose one role from 2 offered on their account page?

Using Rules, I would do it this way (untested):

Create a user field, select list (or radio button, whichever you prefer) - we will call this field_user_role_choice with the options (Role1Name, Role2Name)

First Rule:

Create a new Rule, React on Event: After updating an existing user account

If you don't assign a default value,

Condition: Data value is empty - selector: account:field_user_role_choice, Negate (this is to ensure it doesn't trigger on a registration or if the user doesn't select a role)
Condition: Data comparison - selector: account:field_user_role_choice, value: Role1Name key
Actions: Add User Role - whichever role is associated with Role1Name
Actions: Remove a User Role - whichever role is associated with Role2Name (this is to prevent both roles being assigned to one person)

Second Rule:

Create a new Rule, React on Event: After updating an existing user account

If you don't assign a default value,

Condition: Data value is empty - selector: account:field_user_role_choice, Negate (this is to ensure it doesn't trigger on a registration or if the user doesn't select a role)
Condition: Data comparison - selector: account:field_user_role_choice, value: Role2Name key
Actions: Add User Role - whichever role is associated with Role2Name
Actions: Remove a User Role - whichever role is associated with Role1Name (this is to prevent both roles being assigned to one person)


DIsplay Block content after certain time delay

Create a block and set it to the region and page you'd like it to appear at
Use CSS to hide the contents of the block
Use JavaScript to override the hiding and display at a specific interval

The CSS would look something like this:

.block-DELTA {
  display: hidden;
}

And then just use JavaScript to display the block after a specified interval.  You could also add some animation to your CSS property to make it fade in.  (That's just one example tutorial on animating, google and you'll find hundreds more)

You can add the CSS and JavaScript to the block in a number of ways.  The quickest and dirtiest is in the block content itself.  I'd strongly recommend storing any code in either a module or theme.  See drupal_add_css() and drupal_add_js() for more information on implementing.


Why isn't my sub-theme using its CSS file?

In Drupal 8 you setup your subtheme libraries in subtheme.libraries.yml. These libraries are then loaded from subtheme.info.yml.

You should check the paths in those files if they are correct.

It's good practice to search for all occurrences of the base_theme's machine_name inside your subtheme folder and replace those with the machine_name of your subtheme.


How to reference existing entity using Inline Entity Form?

To add more clarity to the answer:

In Edit tab, check "allow users to select existing nodes"
as shown below

In your content creation form, you could find two buttons: Add New Node and Add Existing Node  as shown below


CKEditor custom configuration (implemented using WYSIWYG module)

Look at hook_wysiwyg_settings_alter

  Act on editor profile settings.

  This hook is invoked from wysiwyg_get_editor_config() after the
  JavaScript settings have been generated for an editor profile and
  before the settings are added to the page. The settings may be
  customized or enhanced; typically with options that cannot be
  controlled through Wysiwyg module's administrative UI currently.

  Modules implementing this hook to enforce settings that can also be
  controlled through the UI should also implement
  hook_form_wysiwyg_profile_form_alter() to adjust or at least indicate
  on the editor profile configuration form that certain/affected
  settings cannot be changed.

Additionally this blog post by Fuse Interactive: WYSIWYG MODULE + CKEDITOR: TAMING THE BEAST goes into great depths on how to make use of this hook. From the blog post ...

/**
 * Implements hook_wysiwyg_editor_settings_alter()
 */
function ckeditor_custom_wysiwyg_editor_settings_alter(&$settings, $context) {

  // The $context variable contains information about the wysiwyg profile we're using
  // In this case we just need to check that the editor being used is ckeditor

  if ($context['profile']->editor == 'ckeditor') {

    // The $settings variable contains all the config options ckeditor uses.
    // The array keys correspond directly with any setting that can be applied
    // to CKEditor - as outlined in the CKEditor docs:
    // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
    // Another way to override configuration is to use your own configuration javascript
    // file. In this case, we're going to add our own configuration file that will
    // Hold our stylesSet customizations...
    $settings['customConfig'] = base_path() . drupal_get_path('module', 'ckeditor_custom') .
                                '/ckeditor_custom_config.js';

    // We are also going to specify a custom body id and class
    $settings['bodyId'] = 'ckeditor_custom_id';
    $settings['bodyClass'] = 'ckeditor_custom_class';

    // To see what's in $settings and $context, install the devel module
    // And run the variables through the dpm() function.
  }
}


How to create a Privatemsg thread with multiple recipients in a Rules component?

I found a solution using a rule component with custom php code. It needs some changes in privatmsg module, see in this discussion: https://www.drupal.org/node/2725325


Wanted to post my solution(i encounter it too) if anyone stumble upon.

You don't have to uninstall and reinstall fieldgroup if you know which content type is causing this issue.

Go to Configuration Export ( [your URL]/admin/config/development/configuration/single/export)
Choose Entity View Display in  Configuration type
Look for your content type in Configuration Name
Copy the configuration that appeared in Here is your configuration:
Open a text file and paste your config.
Look for field_group: , delete it together with it's child or until id
Then re-import your config.

That works for me without resetting other content type field groups.


Multiple axis voting system (star rating)

The idea behind this technique, is to have a node that can be reviewed, and then create review nodes that contain the votes.

The first step you list, requires you to add a node reference field on the review node, where you can select nodes of the type that can be reviewed. That will enable uses to select what they are reviewing.

The second step is to setup fivestar for the review node. You need to add the axis that should be voted on, and which users will be able to set when creating the node.


Entityreference not saved correctly inside ContentEntityForm

Found the cause!

Someone had added the line

$this->getReferencedEntity();

to the MainEntity::__construct()-method.

getReferencedEntity()-method uses some database-magic to find the reference and then set it to the MainEntity.

This worked fine before Drupal 8.5 but it seems that after that the system thought it already had the reference and didn't bother to insert it to the database.


You need to set up relationships between the three content types in your View. Essentially, you have to set up relationship user->category, then relationship category->manufacturer, at which point the manufacturer fields will become available in the exposed filters section. There is a great tutorial here how to do this.


adding a field to the form during form_validate

In form_validate(), make sure your arguments are being passed by reference:

myform_validate(&$form, &$form_state)

Then the last thing you should have in _validate() is:

$form_state['rebuild'] = TRUE;

Edit: You will want to handle the actual adding of the element in the form builder. This is tested and working:

function customform_custom_form($form, $form_state) {
  $form['field_a'] = array(
    '#type' => 'textfield',
    '#title' => 'Field A',
    '#required' => TRUE,
    '#weight' => 1,
  );

  // Add field b depending on the value of field a.
  if (isset($form_state['input']) && !empty($form_state['input']['field_a'])) {
    $form['field_b'] = array(
      '#type' => 'textfield',
      '#title' => 'Field B',
      '#weight' => 2,
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#weight' => 99,
  );

  return $form;
}

function customform_custom_form_validate(&$form, &$form_state) {
  if (empty($form_state['values']['field_b'])) {
    form_set_error('field_b', 'Please enter something in Field B.');
    $form_state['rebuild'] = TRUE;
  }
}

function customform_custom_form_submit(&$form, &$form_state) {
  drupal_set_message('You entered ' . $form_state['values']['field_b'] . ' for Field B.');
}


How to make user profiles of specific role as public in drupal 7?

You are looking for Profile2 module.

  With profile2 user account settings and user profiles are conceptually
  different things, e.g. with the "Profile pages" module enabled users
  get two separate menu links "My account" and "My profile".
  Profile2 allows for creating multiple profile types, which may be
  assigned to roles via permissions (e.g. a general profile + a customer
  profile)
  Profile2 supports private profile fields, which are only shown to the
  user owning the profile and to administrators

Check out this Demo video.


Drush make and SVN: Leaving behind the .svn folders

Use the --working-copy option.

Help tekst: Preserves VCS directories, like .git, for projects downloaded using such methods.


Webform, creating customized directories for uploaded files

Greetings welcome to the land of Drupal stuff :)

In general here are some tips:

creating a folder off of a textfield ID is going to be cumbersome. How will you know subsequent users aren't putting in the same ID and or overwriting eachothers files?
Webform has an API of available hooks. For instance look at webform_submission_presave() which allows you to change/capture a users submitted answer and alter it; you could likely alter the destination of the file to be saved, and assure the destination directory exists with a Drupal API function file_prepare_directory.

If you're looking for an all-in-one no code solution. Look at this issue queue PATCH for webform that looks like it supports custom tokens for upload files.


To be honest I would forget about using that module and simply have a field that contains the desired image, and change your node template file to display that image in place of the title.

It is important to have a text title (even if it is not displayed) because it is used in search engine listings.


You can programmatically change the filter configuration before executing the view:

$view_name    = 'my_view_name';
$display_name = 'my_display_name';
$handler_name = 'title';
$terms        = array('foo', 'bar');

$view = views_get_view($view_name);
$view->set_display($display_name);

$handler = $view->display_handler->get_handler('filter', $handler_name);
$handler->value = implode(' ', $terms);

$output = $view->preview();

This will work even without exposing the filter.


Drupal 6 custom theme development using Zen starter kit

For setting up a Zen sub-theme check here. And there is a good podcast there ;-)


Drupal 7: can't get ckEditor module configured for inline editing

I believe you need Quick Edit, which is the Drupal 7 backport of the Spark core initiative for Drupal 8.


Creating a field that has node values using FAPI

If it is for a custom module, Drupal makes it quite easy to do an autocomplete field.

See a tutorial here... http://timonweb.com/posts/how-to-create-an-ajax-autocomplete-textfield-in-drupal-7/

You would then do a validation function to determine whether the entity exists, or you would only provide a list of existing entities in the first place.

If you are using the core fields, then try the entity reference module.


You can try to insert the JS files by the preprocess function in your theme's template.php file:

Here goes an example:

function MYTHEME_preprocess_page(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');
}

You can use an if() to validate the current path in the $variables in order to prevent the script to be loaded on every page.

To debug the $variables values you can install the devel module an use the dpm() function.

For example:

function MYTHEME_preprocess_page(&$variables) {
  dpm($variables);
}


You should be able to go to the manage fields area for that field - something like admin/structure/types/manage/article/fields/field_field_path

and for the "file path" setting, enter [current-date:custom:Y].

This is untested, but should work. Get back to me if it doesn't.


View data not showing after moving website

You can export the whole view from local server to production server, if it works it means that there must be a problem in db, so try exporting the database again. And one suggestion you can use features module for deployment process.


The Nivo Slider library could not be found

Nivo Slider Requirements

Libraries API
jQuery Update

You need to download the Nivo Slider Plugin and extract it to sites/all/libraries. The extracted folder must be named nivo-slider.


Trying to give a reply to the question title:

you use views_get_view_result() when you need the result of a view inside your custom code. It works fine inside module or theme files.

For instance: you need  to get a list of users inside your custom module. Instead of querying the database with db_query, yuo can build a
Users View named a_list_of_users and get results with

    $res = views_get_view_result($name = "a_list_of_users", $display_id = "default");

Any additional parameters will be passed as arguments.

I love this function!


How to preserve Drupal file permissions after compressing and moving as tarball?

I move sites as tarballs between servers fairly often when I can't deploy with rsync or git.

According to the man page:

  -p, --preserve-permissions extract information about file permissions (default for superuser)

is the proper option to use.  However, this never works well for me.

Typically, I will just use normal tar options, and then run a script after the fact to fix things up.

The Securing file permissions and ownership article has a very good script.  As that gets adjusted from time to time, I am not going to reproduce it here.  It essentially does some find/chown/chmods on the tree to fix things up.

I would use this script as a starting point for your needs.  One thing that it doesn't address is having the private:// filesystem outside of docroot, which I always use.  I will also use 2775 as the permission for the public:// path, as well as a separate use for core/contrib and the site specific code.


How do I identify what type of data or object I have? It's a referenced entity

Do I have a renderable block in $campaignFundraisingBlock, or a type? How can I tell? How do I find out what type of data I have?

I will try to address the question how to determine the type of data in this scenario with entity references and the following block of code, which uses Entity and Typed Data APIs.

tl;dr $campaignFundraisingBlock should be an entity of whatever entity type(s) is referenced by the Entity Reference field "field_compaign_fundraising_block", and this entity can be passed to its View Builder dynamically to create the appropriate render array.

$campaignFundraisingBlock = $campaign
  ->get('field_campaign_fundraising_block')
  ->first()
  ->get('entity')
  ->getTarget()
  ->getValue();

I would break down the method calls to understand this.

$campaign seems to be the entity that is injected into the Display Suite Field Plugin. I don't know much about Display Suite, but it's an entity, so some of the basic entity methods are available to determine what it is:

EntityInterface::getEntityType can get an object described by its corresponding @EntityType (or @ConfigEntityType or @ContentEntitType) plugin. This can be useful to determine the property/field definitions the entity is capable of.

$typedData = $campaign
   ->get('field_campaign_fundraising_block')
   ->first()
   ->get('entity')

The get method here returns FieldItemListInterface, and the subsequent methods are really a part of the lower-level Typed Data API (See Entity API "implements" Typed Data API quotation mine). When we get an object that is an instance of TypedDataInterface, then we have some different methods for getting definitions.

The basic interface here is very limited, and, depending on what Typed Data Data Type is being represented, then it might implement additional interfaces.

TypedDataInterface::getDataDefinition provides Typed Data Definition class that describes this Typed Data Data Type. The DataDefinitionInterface::propertyDefinitions returns an associative array DataDefinitionInterface keyed by the property name, and the getDataType method returns the plugin ID/string of the data type its representing. In this case, for Typed Data Data Type representing an entity, it's EntityDataDefinition, which calls up to the Entity Type (back in the higher-level Entity API) to get its base and bundle field definitions.

$referencedEntity = $typedData
  ->getTarget()
  ->getValue();

The EntityReference::getTarget method (really weird in my opinion) gets either a cached version of the Typed Data representation of the entity or loads the entity and returns the Typed Data representation of it.

Calling getValue on a Typed Data Data Type will return the underlying data. So in the case of primitive data types, a string scalar might be returned, or in the case of complex data types, an entity or an associative array.

Typed Data Data Types do not necessarily return render arrays or have methods that return render arrays. The Entity API has that concept for entities. This is why the entity object returned from getValue can be passed to its view builder.

Unfortunately we can't instantiate a View Builder from the Entity object or EntityType object of an entity because of dependency injection, which is why we need the EntityTypeManager to do so. However I do know the entity type dynamically because getEntityTypeId method so I can dynamically return a render array for the correct entity:

$render = \Drupal::entityTypeManager()
  ->getViewBuilder($referencedEntity->getEntityTypeId())
  ->view($referencedEntity);

So in short, again, if you don't necessarily know what entity type you're dealing with, then you can use EntityInterface::getEntityTypeId from an entity object and pass that into getViewBuilder. And hopefully the explanation about Entity and Typed Data will help to realize why that huge method chain is necessary to return the entity object.


print drupal_render($form['actions']);

that should output the save button


How can I remove self-closing source tags when rendering HTML markup?

I use this code for replace < /source> in theme
  $content_this =  render($content['body']);
  print str_replace("</source>","",$content_this);

in node.tpl.php


Filtering a views result two month ago from now

enable the Date Views sub module in the DATE module. Then goto views and expose the date field . There you can set the operetor between and the 2 dates there


How do I remove the classes from the pager item-list in Drupal 7?

To override the markup of the pager, override the theme_pager() theme function.

However in your case you want to override the class in the item list so for that you need to also override theme_item_list().

For information on overriding theme functions see the beginners guide to overriding themeable output, and for more thorough drupal themeing information see themeing drupal 6 and 7


Running PHPUnit test from CLI and debug in PhpStorm: Remote file path '/directory/path/-' is not mapped to any file in project

You can disable "Force break at first line when no path mapping specified" in "Debug" settings and this error goes away. While execution is paused, you can see that the break is happening in a secondary callback that is called with - as an argument (See $_SERVER['argv'][0]).

This doesn't happen with purely unit tests because there isn't a secondary callback but BrowserTestBase. KernelTestBase must be working simillarly to BrowserTestBase.


How to configure breakpoints and picture to use span data-picture

The demo page you've linked says it was Submitted by admin on Thu, 04/25/2013 - 13:31. That's over 1 year ago.

What makes you think the output you're seeing isn't correct for your current installed version of Picture? If your breakpoints are installed and configured correctly as in the documentation you have linked, then the images should be responsive.


Display one image of commerce product in product display view

I used the Image Delta Formatter module : https://www.drupal.org/project/image_delta_formatter and set the delta to 0 in the product commerce display teaser


Rating for all images in a singular node?

You can take a look on FiveStar module : https://www.drupal.org/project/fivestar


You actually don't need a module to do this

The previous/next links can be directly modified by 'just' overriding the file modules/books/book-navigation.tpl

<?php if ($has_links): ?>

      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('‹ ') . $prev_title; ?>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print $next_title . t(' ›'); ?>
      <?php endif; ?>

<?php endif; ?>

this is also described a bit more detailled in this answer to a very similar question:

Next/Previous button for nodes within a book

The book tree is quite a bit more complex.
A good start would probably be to look at the functions template_preprocess_book_navigation and book_children and menu_tree_output and then override the parts you want to 'style' (theme) in your template.php – but that can be tough.

I ran into a similar problem a while ago – and not using the book module was the solution for me. Instead I dived into Entity reference and found it a way more flexible approach than using and theming the book module.


How to tell if content has been migrated

You could alter the incoming data and attach a taxonomy tag, like 'migrated', to indicate this.

You could also add (migrated) in the title, but you would have to ensure this does not affect users, terms, URL aliases, etc. Hence why I suggest a taxonomy term. I am not that familiar with D2D API but I know this is very easy to do with Migrate Framework.


How to print an image in a paragraph that references a node with an image field

I went in circles for hours before I found the solution. There are many posts with partial or theoretical solutions, but none of them worked for me.

My solution consists of a twig file, paragraph--timeslot.html.twig, which prints all of the fields from the Timeslot paragraph. The line which prints the Class Badge image looks like this:

Working from right to left:

entity.uri.value is the uri value for the image field in the referenced node, which is the url prefaced by public:// or private://

entity.field_class_badge is the field in the referenced node that contains the image.

paragraph.field_class is the field in the paragraph that references the node.

file_url strips public:// or private:// from the uri that is retrieved so it can be used as the src in the image tag.

It is worth noting that uri is one of the database fields in the file_managed table. An alternative approach above could have been to use the filename field instead, and construct the URL manually within my code. Other fields that may prove useful would be filesize, created, and status.

Hopefully this helps someone. I doubt it's the definitive solution, but it worked for me.

UPDATE: I have since extended the solution above to display a specific image style, rather than the original image. Simply change the  tag in the code to look like this, where class_badge is the machine name of the image style.

Essential - you'll need to install the Twig Tweaks module to get this version of the solution to work.


What are the best e-commerce modules/setups?

I have not yet built an e-commerce site on D7, so I cannot get really specific.

That said, the obvious starting point for e-commerce on Drupal 7 is the Drupal Commerce package. Just start with the basic package, see if it fits your needs, and install add-ons if you need them. There even is a dedicated Drupal Commerce website with documentation, a forum and more.

There are a couple of themes that are specifically geared towards e-commerce, for instance Acquia Prosper and AT Commerce.


How to turn fieldset to normal field for date field

Drupal 8 core date field looks like this ....

perhaps your theme is overriding this field type like boostrap or some thing if that is the case find the template file move to your sub theme and change it back to normal.

UPDATE:

But If you are using the Select Widget You have some options:

1) Make css to fix the look of it, a good fast option all you need to do is find the field ID then change the rules for that id only. if not using a custom theme you will need a form alter and attach a custom css library.

2) Override the Field set template if you turn on theme debugging (https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates)
and inspect the element will see the templates that the field uses, you can copy them in to your theme and override them, or create your own theme hooks see my example of hook_theme_suggestions_HOOK_alter on https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_theme_suggestions_HOOK_alter/8.2.x


When editing a node, some markup disappears

I have the same issue, and this is caused by the WYSIWYG editor: When you try to edit a node created with a input format with WYSIWYG enabled, the HTML markup will be changed by the editor.
To solve it, you have two options.

Disable the WYSIWYG editor by default, unselecting the checkbox as shown in the screenshot.

Create a node using an input format that doesn't use the WYSIWYG editor (for example Full HTML, or Filtered HTML). If the Full HTML format is already associated with a WYSIWYG profile, try to create a custom format from /admin/config/content/formats, and use it to create new nodes. Remember to not associate a WYSIWYG profile.


How can I collapsible the facet search block with checkbox

I did work on similar functionality, where the client wanted a set of check boxes inside the collapsible Facet Block.
I found a module Collapsiblock which allows us to have check boxes inside the Facet Block.
This module will most probably help you.


Duplicate value fields when creating relationships field collection of views

on right hand others >> query settings of you view there is one distinct checkbox enable it. Which will distinct your result


How to effectively remove module created fields?

This is the code snippet I usually use to remove fields created by a custom module:

if (field_info_field('my_field_name')) {
    field_delete_field('my_field_name');
    field_purge_batch(100);
}

Hope this helps


bookmark organize for anonymous user permission

To my knowledge, the features of the flag module are designed to be used by authenticated user only, so not by anonymous users.

The closest you can come to address your question, is as is described in How to display a flag to anonymous users?, i.e.:

  When an anonymous user clicks on flag, then such user should be redirected to the login page. After login the user should be able to set flag.

And then do as described in the answer to that same question, i.e.:

  You can do this in your 'node.tpl.php' ...: if user is logged in then display flag as normal; if not logged in then redirect user to logging page with destination parameter.


does indexing tables have a bad effect on drupal?

The gains far outweigh any drawbacks; I'd add the index.


Node form validates fields with #access = FALSE after ajax image upload

You can use hook_form_alter() to hide the fields so that when the form is rebuilt (with AJAX or normal page load) the fields will still be hidden.

Also if you wanna make a field not validate then use the code below in your hook_form_alter() hook.

function mymodule_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'your_form_id'){
    // To hide the field
    $form['your_field']['#access'] = false;
    // To remove validation
    $form['your_field']['#required'] = false;
  }
}


hook_install() doesn't seem to work, even though I have disabled and uninstalled module

The code in your git repo is not the same as the code posted here.  Both has syntax errors.  See @ARUN's answer for the bug in the code posted here.

As for the code in the git repo, there are two lines of random junk in it (indicated with red striketroughs below), causing Drupal to crash before the table is created in the database.

Remove those two lines and try again.


How can I create a field to hold data on users' countries and states?

In Drupal 7 you should use the dedicated addressfield module for that purpose.
The composite address field provides a country drop down box with other address fields such as state loaded via ajax depending on the selected country.
USA

Canada

It's a requirement of the Commerce module for address selection.
You can hide some of the address sub-fields if needed.


What does "Use aggregation" option under Other in the Views UI do?

Technical what it does it allows you to add "GROUP BY field" and "count(field)" to the sql query. This might be able to reduce duplicates but in general if you have duplicates it's most often a problem by design/your choosen view type(node, user, terms etc.)


This is the PageSpeed section from my .htaccess:

<IfModule pagespeed_module>
    ModPagespeed on
    ModPagespeedEnableFilters extend_cache
    ModPagespeedEnableFilters collapse_whitespace
    ModPagespeedEnableFilters combine_css
    ModPagespeedEnableFilters move_css_to_head
    ModPagespeedEnableFilters remove_comments
    ModPagespeedEnableFilters inline_css
    ModPagespeedEnableFilters rewrite_javascript
    ModPagespeedEnableFilters insert_img_dimensions
    ModPagespeedEnableFilters rewrite_images
    ModPagespeedEnableFilters rewrite_css
</IfModule>

Whilst there is a little overlap with the js and css compression, I'm not seeing any negative results. I've set Drupal 7 to aggregate and compress CSS and JS.

The site isn't particularly high traffic though.


Just in case other might encounter it and bump in this page. To recap on how we fixed this error. In @MG1 case, restore the database from live site and downgrading the php version on her local machine from 7.0.8 to 5.4.42 and upgrading the Drupal core module in latest version did fixed the problem all errors are gone.

We also encounter this one just in case other's encountered it.

  Fatal error: Call to undefined function
  form_process_autocomplete() in
  /Users/***/Documents/Sites/Link-New/includes/form.inc on line
  1850

this one help us out in trouble https://www.drupal.org/node/2610498

Note:
This might be fix in other way but in MG1 case this solved the problem.


This can be a bit tricky, there are a few steps to get right. First create and save the node, then add the file to the node as a second pass. Here's an example implementation.

/**
 * Add a file to a field on a node
 * @param int $nid  node ID to add the content to
 * @param string $field_name the machine name of the field to add to
 * @param string $filedata the raw binary data as a string
 * @param optional boolean is the attachment an image (should image validation
 *        be performed)
 */
function mymodule_addfile($nid, $field_name, $filedata, $is_image = FALSE) {
  $node = node_load($nid);

  $field = content_fields($field_name, $node->type);

  // Load up the appropriate validators
  $validators =
  filefield_widget_upload_validators($field),
  if ($is_image) {
    $validators = array_merge(
      $validators,
      imagefield_widget_upload_validators($field)
    );
  }

  // Where do we store the files?
  $tmp_files_path = file_directory_temp()."/$file_name";
  $files_path     = filefield_widget_file_path($field);

  // Put the file in the temp folder
  $ret = file_put_contents($tmp_files_path,$filedata);
  unset($filedata);
  if ($ret === FALSE) {
    watchdog('mymod_error',"Could not write $nid ($file_name) to temp: $tmp_files_path");
    drupal_set_message("Could not write $nid ($file_name) to temp: $tmp_files_path", 'error');
    return FALSE;
  }

  $path = $files_path.'/'.$file_name;

  // Create the file object
  $file = field_file_save_file($tmp_files_path, $validators, $path);

  if ($file == 0) {
    watchdog('mymod_error',"Failed to save file $file_name");
    drupal_set_message("Failed to save file $file_name",'error');
    return FALSE;
  }

  // Apply the file to the field
  $node->{$field_name}[0] = $file;

  node_save($node);
  return TRUE;
}

A variation on the bottom works too, just assign the result to the file field.

function _fhi_add_existing_file($file_drupal_path, $uid=1, $status=FILE_STATUS_PERMANENT) {
  $fs       = filesize($file_drupal_path);

  $res = db_query("SELECT fid FROM files WHERE filepath = '%s' AND filesize = '%s'", $filepath, $fs);

  $fid = db_fetch_array($res);

  if ($fid) {
    //drupal_set_message("$filepath already found. fid: $fid");
    $fid = $fid['fid'];
    return field_file_load($fid);
  } else {
    $file=(object)array(
      'filename'  => basename($file_drupal_path),
      'filepath'  => $filepath,
      'filemime'  => file_get_mimetype($file_drupal_path),
      'filesize'  => $fs,
      'uid'       => $uid,
      'status'    => $status,
      'timestamp' => time()
    );

    drupal_write_record('files',$file);
    return field_file_load($file_drupal_path);
  }

}

This code drawn from memory and without interpreter (I've got too much time on my hands this morning) so be wary of typos I may have introduced. As with anything, not responsible for death of poodles as a result of the use of this code.


Should I manually upload these large files?

Manually uploading the files and hardcoding the links into a block, Shouldnt be a problem.

You Could also check this module out :) Download File Module


How do you clear a field value with entity_metadata_wrapper()?

The problem is that you must set an empty value that is compatible with the data type of your field. If you do not, you will get an exception raised. Passing NULL or array() when a string is expected will therefore raise an error.

Another thing to keep in mind is that the data you pass will also depend on whether your field is a single value, a multi-value field, or a field with multiple properties.

If your field is a single value (and thus the wrapper for the field is an instance of EntityValueWrapper) then you should assign it an empty value compatible with the data type in question. For instance the two following methods are equivalent:

$wrapper->title = '';
$wrapper->title->set('');

However the following three examples will raise an exception, because the data types are not compatible with the title field:

$wrapper->title->set();
$wrapper->title->set(NULL);
$wrapper->title->set(array());

If your field is a field with multiple properties (for instance a formatted text field, which defined both a value and format property) and thus an instance of EntityStructureWrapper, then array() or NULL will be the correct empty value. So you can do the following:

$wrapper->field_formatted_text = array();
$wrapper->field_formatted_text = NULL;

But in that case, passing an empty string would have raised an error. Note that you could have chosen to make the value property empty instead, in which case a string is the correct data type:

$wrapper->field_formatted_text->value = '';

Finally, if your field is a multi-value field (and thus your wrapper is an instance of EntityListWrapper) then array or NULL are the correct empty values, and the following three lines are equivalent:

$wrapper->field_example_multiple->set();
$wrapper->field_example_multiple = array();
$wrapper->field_example_multiple = NULL;

Note:
Calling the clear method on the wrappers is not equivalent to setting the field to an empty value. When the field is set to an empty value, it then calls EntityMetadataWrapper::updateParent on the field's parent wrapper. This ensures amongst other things that the setter callback defined by hook_entity_property_info is called. Calling clear does not do that.


Render a view exposed filter in a region without exposing it as a block

That's interesting, there may be a possibility...

This would work if you 1) have the View object, or 2) if you can figure out which view to load via the url path or something...

You would put this code in a preprocess function for your region, or perhaps a template although that wouldn't be recommended.  However you insert it into your region, the following code will generate the exposed filter form markup:

$view = views_get_view('view_name');
$form_state = array(
            'view' => $view,
            'display' => $view->display_handler->display,
            'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
            'method' => 'get',
            'rerender' => TRUE,
            'no_redirect' => TRUE,
            'always_process' => TRUE, // This is important for handle the form status.
          );
          $form = drupal_build_form('views_exposed_form', $form_state);

          $exposed_filter_markup = drupal_render($form);


Drupal's built-in xss filters vs. HTML purifier module

I trust the filter_xss function a bit more than htmlpurifier simply due to the complexity of the htmlpurifier code. Neither function is easy to understand, but at least filter_xss is shorter and more stable.

It is true that htmlpurifier is a general library used by other systems and therefore it could have "more eyes" on it. If you look at the HTMLPurifier Summary they claim that kses (which is what filter_xss was originally based on) is "Probably" XSS safe but misses out on other features of HTMLPurifier. The Drupal input format system handles many of the other features that HTMLPurifier mentions in that table so it's not an apples-to-apples comparison.

By the way, you may want to post questions like this to https://drupal.stackexchange.com/ in the future.


You would need to not close the form but use hook_webform_submission_form_alter() to change all elemnts to be readonly and hide the submit buttons.


How do I get Context to cache blocks?

Anyway a lot of block don't use cache by default. You need to use http://drupal.org/project/blockcache_alter to improve the control of what you want to cache. Sadly block cache alter is not compatible with context but a small glue module make it works :) http://drupal.org/project/context_blockcache_alter . But need a port on D7.

So using block cache alter going to do a real performance boost.

To not use block module the answer from Adam S is correct.


When do hook_views_data() and hook_views_data_alter() get called?

In case anyone else is making the same mistake I was, here's the answer.

First of all, hook_views_data() will not ever, ever be called if you put it in yourmodule.module. It has to be in yourmodule.views.inc.
You should probably implement hook_views_api() to tell Drupal where your yourmodule.views.inc file resides. Do so like this:

function yourmodule_views_api($module = NULL, $api = NULL) {
  return array(
    'api' => '3.0',
    'path' => drupal_get_path('module', 'yourmodule') . '/includes/views',
  );
}

This tells Drupal that yourmodule.views.inc can be found at /yourmodule/includes/views/yourmodule.views.inc. If you don't use hook_views_api(), put the .inc file in the same folder as your .module file.

Once you have this set up, yourmodule_views_data() will be called when you clear the caches.


Unable to override ctools selection plugin class from my module

same problem, two days wasted according to http://lookalive.co.uk/blog/drupal-entity-reference-how-make-custom-entity-reference-selection-handler and all it's copies.

entityreference_get_selection_handler() code dpm() showed that "*.inc" should be named 'base.inc' as in your case.

After renaming in my case *class.php started to execute.

So all i can advice to you - check if module has higher weight than 'entityreference' module, see here https://www.drupal.org/node/110238

And add the first line to '*class.php' (for inheritance)

require_once drupal_get_path('module', 'entityreference') . '/plugins/selection/EntityReference_SelectionHandler_Generic.class.php';

If this helped to you - pleace vote [+] this answer (i need more scores, tks)


User-Profile-Form.tpl.php not working. Help!

I'm struggling with what you're asking in the first portion of your question, but looking into the previous Stack Exchange page you referenced you can use the Panels module to quickly accomplish two column layouts for these forms.  You can also use template overrides to change the layout of the registration pages.

If you're specifically looking to quickly implement a tabbed UI for the user profile, I believe the Profile2 module may offer a built-in solution.

  "Also what would the variable look like for calling the custom field
  added to a user?"

You may need to use load_user() first to get a complete user object to access custom profile fields.

$account = user_load(<USER-ID>); //$node->uid or $user->uid


Trigger whenever a user uploads an image

If you're using a field field in Drupal 7, you could accomplish this with the use of stream wrappers, core-supplied file API hooks, and a file field.

See the file examples in the Examples for Developers module. Also read through the 'Stream Wrappers and You' post from Advomatic for some background.

For more advanced triggered actions, you could also consider using the Rules module to react to a file being uploaded to the site via a new node or other entity type.


Entity Reference - Auto complete field in content type

You can do this in various ways.

An easy option would be to display a view as the field. There are quite a few solutions that enable you to do so, such as:

Viewfield,

  Viewfield provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.

Field Embed Views,

  The module provides a field type to attach any Views View display
  with, configurable on per-entity level, default values for exposed
  filters and sorting.

EVA,

  "Eva" is short for "Entity Views Attachment;" it provides a Views
  display plugin that allows the output of a View to be attached to the
  content of any Drupal entity.

Panels, Display Suite,  etc.

The view will list partners and the contextual filter will be the current project you are looking at.

If your field is also an entity reference field, then you should probably look at Corresponding Entity References.

Think about your solution where you will be duplicating database storage (both ends of a relationship) when one end can easily be computed (via an sql query for instance). Maintaining the data on both ends means more work as you have to synchronize it constantly, as well as more storage. Maintaining the data on one end only and making the other end purely a display issue is more maintainable.


The symptoms you describe is usually due to some caching happening. Make sure you've turned off all caching in Drupal (sometimes, just clearing the cache isn't enough). Also, make sure that you clear your browser's cache (SHIFT+reload).


Have a look at the domain access module.

I think it is what you're looking for.


"Filename cannot be empty in file_unmanaged_save_data()"

Oy! My temp folder had bad permissions.

Of course I only thought of this after I restored a back up from last Friday -- thus, overwriting all the work from this morning and Friday evening. Arg. Okay, Thanks for letting me vent here.


How to make JS Async and eliminate unnecessary JS?

you can use async_js for loading asynchronly.

and in hook_js_alter you can remove js files you don't want to have on the page.

you can also place the JS at the bottom of the page in your theme's html.tpl.php, by printing

<?php print $scripts; ?>

just before the </body> tag.


Fusion Accelerator Skins windows are blank after core upgrade to Drupal 7.1.9

It was a cache issue. I cleared my cache and that fixed the issue.


How to change my homepage based on the time of day?

Consider using the Rules module to set the appropriate node as your frontpage.

Based on the sample in the question, I'm assuming that node/4 is what the value is of site_frontpage. Here is the actual rule to be created that could work in your case:

Create a new rule
Event = Content is viewed
Condition: data comparison -> node:nid equals 4
Add an extra condition to check if current time is between 7pm and 8am.
Action: page redirect to node/5

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great (+ free) video tutorials Learn the Rules framework. Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module. Maybe also review the set of 30 video tutorials about the Views module ... Familiarity with only those 3 modules (Views, Rules and Flag) can get you pretty far in mostly any Drupal site (as a site builder).


How to implement invitations limits per user when using the Invite Module?

Invitation expiration

Quote from the Community documentation about the Invite module (from its installation instructions):

  Invitation expiry: Set the expiry period for user invitations, in days (default select up to 365 days).

So the answer to your 2nd question do unclaimed sent invites expire? is YES. That's what's stated also in comment #3 of the issue about Set expiry date to never.

Setting invitation restrictions

Looks like this feature "used to be available in a prior version of the module". And according to comment #3 of the issue about Limit invitation per user/role, it should be back some day.

While waiting for that to happen, you may want to use some type of Rules integration. Such as the solution as included in the issue about Rules integration for D7. It includes a patch for the 7.x-2.x version (status "RTBC"). If you're using 7.x-4.x however, then note the issue status "Needs work" ...


Getting image SRC with xpath - Simpletest (WebTestBase)

Perhaps you could try the following XPath: //span[@class="cke_button_icon"]/img/@src.


While doing the research to add the additional information, I discovered the uid for the node was set to 0. Updated that to 1 and the webform now appears.


Overriding a specific view mode html.tpl.php template

As I am sure you know, the teaser view is only/mostly used when a list of nodes are put together, eg, the promoted to front page listing, a View listing, etc.

So, let's say you have a View page listing the most recent Articles, and it's sitting at www.yourhost.com/recent/articles, you could override the html.tpl.php there by creating a html--recent-articles.tpl.php file in your theme and modifying it accordingly.

Views itself also allows the use of node templates when a node is presented in a listing; if that is what you are needing or requiring, the template files there are along the lines of node-view-VIEWNAME.tpl.php.


AFAIK Drupal's t() function does not provide any hooks for neither altering its input values nor its results.

However, if your intention is to override specific translations of the locale module, you can alter them within the translation interface of Drupal at '/admin/config/regional/translate/translate'.

If you don't want to alter the database stored locale translations, or don't have the locale module enabled, you can also provide according overrides within your settings.php by defining $conf['locale_custom_strings_' . TARGET_LANGUAGE][CONTEXT]. Replace TARGET_LANGUAGE with the target language shortcut, and CONTEXT with the context of the translation (usually an empty string):

$conf['locale_custom_strings_en'][''] = array(
  'some string' => 'some stringBOOM',
);


Form - Show partial form in block then populate full form with partial data

As contrib is an extension of core there are always ways to do stuff in core that you can do with contrib, it's just often contrib makes it easier, quicker, and more easily maintainable at the sacrifice of more code.

For this I would look at the prepopulate module which allows fields in most forms to be pre-populated from the $_REQUEST variable:

https://drupal.org/project/prepopulate

If you want to use just core then you know what you're outputting in the block, at a guess you could form_alter the form linked to prepopulate.


After 3 days, I haven't found the solution, even by programmatically.

Then what I had the last option(in my mind, huh) is,

I get all the fields in one block only, not creating the different blocks for different tab or buttons.
Used the description of Better Exposed Filters, in which I pasted my buttons/tab UI HTML as its.
Now on changing the language all the fields are fetched according to the selected language. But in this case my active tab/button get lost its activeness.
Now, I need to get the last active tab/buuton, so that I can click it again to get the active tab after filtering my languages.

Below is the piece of code which is need to my js file.

// Active target element to make the tab/button active after
// ajax responds in filter
var activeTargetElement;
Drupal.behaviors.events = {
    attach: function (context, settings) {
        $('#views-exposed-form-MY_VIEW_MACHINE_NAME-BLOCK_NAME', context).ajaxStart(function () {
            // my tabs/button are active on the basis of data-target attribute,
            // so need to memorise which tab/button is active before fitering any language
            activeTargetElement = $('#MY_TABS li.active a').data('target');
        }).ajaxSuccess(function () {
            // if any target is memorised, then simply click it or trigger a click event for it
            if($('[data-target="'+activeTargetElement+'"]').length){
                $('[data-target="'+activeTargetElement+'"]').click();
            }
        });
    }
};


Issues migrating site back to local server

As the OP noted in a comment, there is documentation available from Aquia that explains how to do this. For a better formatted answer please follow the above link.

  IMPORTING AN EXISTING SITE OR CODEBASE INTO ACQUIA DEV DESKTOP

  To run an existing site or new Drupal distribution on your local
  computer, complete the following steps:

  Ensure that your local computer contains a copy of your site's Drupal
  files and directories (codebase).

  Save your site's codebase in a place where you can find it and where
  you won't delete or move it unintentionally. This protects your site
  from accidental removal, and helps when you need to modify site
  content or change the installed modules.
  You cannot import zipped or compressed codebases into Dev Desktop.
  Ensure that your site's code is uncompressed.
  For more information about backing up the Drupal file system, see
  Drupal file system backup.

  Note: Dev Desktop does not move or copy your site's code into the Dev
  Desktop installation directory. Instead, Dev Desktop records where the
  Drupal directories are stored on your local computer.
  Open the Acquia Dev Desktop Control Panel, click Settings, and then
  select the Sites tab.
  Click Import. The Import site window opens.
  In the Codebase section, click Browse to select the source code
  directory (also known as [docroot]) of your Drupal installation. This
  directory contains Drupal's files and directories, including
  index.php, the /includes directory, and the /modules directory.
  After you select the your codebase, in the Subsite drop-down menu,
  select the site to import from the source code directory. For
  single-site codebases or Drupal distributions, select default. If
  you're importing a codebase that contains multiple subsites, select
  the subsite you want to import from the Subsites drop-down menu.

  Note: Dev Desktop can only import one site at a time.
  Configure the database settings for the site import process. The
  settings are based on the type of site or codebase you're importing
  into Dev Desktop.
  In the Database name field, enter a name for
  the database. If you're restoring a backed up database, the name does
  not have to match the backed up database's previous name.
  Under Domain, enter the elements (server, subdomain, and URL path) of
  the local URL you want to use for your site. For example, if you want
  to reach your site locally at http://my.example:8082/mysite, enter my
  for the Subdomain, example for the Server, and mysite for the URL
  path. The subdomain and URL path are optional.
  Click Import.

  Acquia Dev Desktop records the location of your site's Drupal
  codebase, creates its new database (if selected), and adds the site to
  the list of sites in the Sites tab.


D2D file migration cannot processes a number of rows?

I just faced the same issue, and have a suspicion what the cause may be, though have not tested it.

I ran a migration of files in manual batches, e.g.

drush migrate-import MyMigration --limit="100 items"

several times. After the last batch (for which I did not specify an item limit, i.e. it should have imported all remaining unprocessed items), migrate-status still showed almost 900 unprocessed items. All calls thereafter to migrate-import would process 0 items, even with the --update flag -- which I thought should have either imported or updated (accordingly) ALL items...

Just as you did, I then queried for the source IDs it would not process. Upon inspection I noticed that large sets of them had the same exact timestamp (specifically, file_managed.timestamp column in the database). I recalled that Migrate can use a specified field to store a highwater mark for each migration, such that future import runs will only process items whose value of that field is greater than the stored highwater mark from previous runs. So for files, the timestamp value is used by default (per Migrate D2D implementation -- see DrupalFile7Migration::__construct()), and the query is ordered by timestamp ASC to cooperate with this.

I realized that the items it would not process were definitely older than the stored highwater timestamp (which is that of the newest item imported). Why then did Migrate not process those in an earlier batch, based on the query's order-by? Well... if many of my files had the same exact timestamp, the results of the query were not guaranteed to be in the same order across different runs. So if I was working with a limit of 100 items per run, but the results were not consistently ordered, it's possible some items never ended up falling within the batch (range of results) that was actually being imported at the time.

I'm not entirely sure if this could account for nearly 900 unprocessed images, but it's a thought.

Workaround

You can import items regardless of their status vs. the highwater mark by using the --idlist argument. So since you've queried to find the source IDs that won't process, just pass them as a comma-delimited string and I think it should work no matter what. Example:

drush migrate-import MyMigration --idlist="538,2891,485"

Actual fix? (untested)

If my suspicion is correct, then probably the solution is to order by not only timestamp, but additionally by fid, which is guaranteed unique, and thus the results order will be exactly the same every time. In your migration subclass, override query() and after calling the parent implementation, add $query->orderBy('fid', 'ASC'). This sets secondary ordering.


How to make content of a (cck) field visible when pressing a button?

The best way to do this is in the theme. Simply add the CSS and JS needed for this effect. Should be pretty simple as all fields has unique ids.


How can I protect development sites with Basic Auth module enabled?

The steps are as follows:

Modify .htaccess to read DirectoryIndex index.html index.php
Construct your index.html file to show whatever you need.
Modify your robots.txt to disallow any search engine robots to index your site.

Clients can check http://www.example.com/index.php whenever they like, and you can revert your .htaccess and robots.txt when you are done.


Regarding content slider on mobile screen

Option 1:

Flex Slider allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

  Touch enabled navigation
  Keyboard navigation
  Configurable slide animations
  Multiple sliders per page

Option 2:

Views Responsive Grid provides a views plugin for displaying content in a responsive(mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality


How do I programatically submit a webform via drupal_form_submit?

I used PhpStorm and xdebug to step through the form.inc code and finally found the correct structure for my $form_state.  The structure I posted was close, just needed to add the 'op' => t('Submit').  See my final working code below.

To answer my questions:

Yes, drupal_form_submit is what I should be using.
See code below for the magical $form_state structure.

<?php
$form_id = 'webform_client_form_55805';
$form_state = array(
  'values' => array(
    'submitted' => array(
      'first_name' => 'David',
    ),
    'op' => t('Submit'),
  ),
);
$node = node_load(55805);
$submission = (object) array();

drupal_form_submit($form_id, $form_state, $node, $submission);
$form_errors = form_get_errors();
?>


When should I not use Views for listing content?

That's quite a subjective question, but generally speaking, use Views if

You need it done quickly
You need to allow flexible UI edit access
You don't mind a slight performance hit
You need Views for some other module integration ( VBO, views_data_export etc.. )

Otherwise, you can use custom page callbacks

If you don't mind taking a bit longer to build
You don't need UI edit access
You want the fastest performance.
You want to do something Views can't do, or that is much easier to do custom.
You are a capable developer.


How can I arbitrarily execute a rule from the UI to test a login togobban workflow using selenium?

I ended up solving this with rules by making a new rule.

Event- "User has logged in"

Conditions- "User has roles" -> The role of the "unverified user" (set on the
logintoboggan configuration screen)

Actions- "Show a message on the site"

Message text:

validate your account

This will present a message to unverified users when they log in allowing them to verify their accounts.  Of course this has to be disabled for production, but it allows one to test validation workflows in Selenium.


Custom region in theme not on front page?

You can create a page--front.tpl.php file in your theme. This file is the same as page.tpl.php but only for the front.

Remember clear cache after the creation of the file.


How to render a page with arrays and text

You can do

$page['text'] = array('#markup' => 'hello');

Or

$page = render($page) . 'hello';


View to filter a list of nodes which has TWO taxonomy terms

Download the Views PHP module:

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

In Views:

create a new View of 'video post' content type, as a block and set it up to show all entries for now, in the format and layout you desire
add a contextual filter for the star rating field (you will need to adjust the field names appropriately):

Provide a default value, PHP code:

$node = menu_get_object();
return $node->field_star_rating['und'][0]['tid'];

add another contextual filter for the warm up field:

Provide a default value, PHP code:

$node = menu_get_object();
return $node->field_warm_up['und'][0]['tid'];

The first line retrieves the page object (which should only ever be a video post node if the block is set up properly), then returns the term ID associated to the current node as a contextual filter to the view. This assumes a single language site.

add a regular filter, Global PHP code:

$node = menu_get_object();
if($data->nid == $node->nid) return true;
else return false;

The first line again retrieves the page object, and compares its node ID with the node ID of the current entry, filtering it if they match. It may appear backwards, but that's how the Global PHP works for some reason. Returning true excludes the row.

under admin/structure/block, set the view-block to show where you want on the page, restrict it to show only on the content type video post.


Node's cache isn't automatically cleared on update (intermittent problem)

I updated the APC module to 7.X-1.0-beta4 from beta3 and it seems to have fixed the problem. At least the client has not reported any further issues for several days now and we have not been able to reproduce the issue in our somewhat limited testing.

I noticed nothing in the change lot between beta3 and beta4 that would suggest a fix to this issue. I'm not convinced that this is what fixed it, but I have no other clues.


Drupal caches the already rendered block and doesn't check for changes in code, so after changing #cache in the block's render array as shown, you'd still need to use drush or the UI option to force-clear the render cache after changing this.

As an alternative, try deleting the block instance and placing it again.

Since you don't indicate that the form is making changes to the database, it's not clear if there is any cache tag to associate - is it data input or something more like a search form?


Allowing a user to choose which image style they want for a single uploaded image

You can add an additional field to your content type that stores the values of the image style presets on your site. This will allow them to select which image style they want once they've uploaded an image.

You'll need to write a small custom module to pull the existing image style presets from the database and programatically populate the allowed values of the in your new select field.

You can create a custom node or views template and use the value of the image style field to display the uploaded image with the selected image style.


Drupal 7 list all the nodes that match a specific tag

Tags are terms of a taxonomy vocabulary. Each term has its own page listing all the nodes for the term at taxonomy/term/<tid> where <tid> is the numaric term identifier. The Pathauto module allow automatic creations of cleaner aliases for these pages using patterns like <vocabulary-name>/<term-name>. So instead of being at taxonomy/term/42 the page for the "Foo Bar" tag will be at tags/foo-bar.


You want to use the "Scale" option, and only set 1 of the variables. Either width OR height. You can leave 1 of them blank. This way the image styles will respect the aspect ratio of your images. I usually only set width, and leave height blank.

Don't use "Scale and crop" as crop will cut parts off your image to make it fit the size you specified.


I figured out the answer to my question.  In the filter option, if you filter the relative time format "first day of this month," and assign the operator "is equal to or greater than," the output will be the first day of the month to the current day.
Hope this helps anyone that reads my post.


How to use User Points for storing Quiz scores?

Userpoints has an API.

See especially userpoints_userpointsapi() Something like this: userpoints_userpointsapi(array('uid'=>$some_user, 'points'=>9000));

You might also be interested in the Quiz module which supports Userpoints.


Customising the print stylesheet for the print module

Though I haven't worked with print module but as per Drupal structure, if you have to override any CSS file(in your case print.css) of some module, you can simply write your style in your own CSS file which stay in your theme directory. But if you want to use the same file & keep your styling separate then simply cut that from the module directory & paste in your theme directory...mention the CSS file in your INFO of theme...and extend it as much as you want...

Don't forget to clear your cache after you do cut/paste & done with INFO file edit..

In same way...you can copy your print.tpl.php file from the module folder & paste in your theme directory(no need to mention tpl in INFO file)...& then you can do as much editing as you want to have custom look...clear your cache in this case too..

I hope this will solve your worry about maintenance as you will get this file in your theme folder itself...


How to show a block between the body and a paragraphs field?

Enable "Layout builder" module first. On "Manage display" in entity config Default "Custom display" enable "Full content", then go there and enable "Use Layout builder" and "Allow each content item to have its layout customized."

This will give you "Layout" tab in each node (of this type where you enable this in config) for ex. - how to arrange each field of this entity, also ability to add custom block, user fields, etc. If you want Contact form there you should probably have to write custom block in custom module and put the form inside - just to have it for placement from the Layout builder.


You're already passing $name as a parameter, but you're not actually inserting it into the body so it won't show up in the email.

It's best to use a keyed array so you can easily refer to parameters by name, something like this:

$params = array('name' => $name);
drupal_mail('mymodule', 'mymodule_mail', 'myemail', language_default(), $params);

...

$message['body'][] = t('This is a body text');
$message['body'][] = t('Name: @name', array('@name' => $params['name']));


The best way I have found to do this was to use Paragraphs. You can create an Accordion paragraph type, and an Accordion Item paragraph type. The Accordion holds Accordion Items. The Accordion Item has 2 fields, Title, and Body.

This allows a user to add an Accordion paragraph to a node, then add as many Accordion Items as they want (and be able to sort them in the form). From there, the theming/js is up to you via templates and js, but that part is fairly easy.

Since Paragraphs are based on fields, it's intuitive for the editor who use used to the node edit interface.


How can I load a custom twig template depending on a view mode?

Now the new theme hook is the same as the base hook. You need to declare the more specific theme suggestion as hook:
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'pdf_report__new_style' => [
      'base hook' => 'pdf_report',
    ],
  ];
}


How to create revision for a node programmatically

// Make this change a new revision
  $node->setNewRevision(TRUE);
  $node->revision_log = 'Created revision for node' . $nid;
  $node->setRevisionCreationTime(REQUEST_TIME);
  $node->setRevisionUserId($user_id);
  $node->save();

Use Above Code to create a revision. :)


Create custom display of element using field values

I assume you have an entity reference field "Company" in the content type "Article". You could implement hook_node_view() to achieve this on the individual article node page. Check the following example code:

function mymodule_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        if( $node->type == 'article' ){
            // load the entity reference 'company' in full
            $company = node_load($node->field_company[LANGUAGE_NONE][0]['target_id']);

            $logo        = $company->field_logo[LANGUAGE_NONE][0]['uri'];
            $logo        = '';
            $website     = $company->field_website[LANGUAGE_NONE][0]['safe_value'];
            $description = $company->body[LANGUAGE_NONE][0]['safe_value'];
            // delete the default entity reference display
            unset($node->content['field_company']);
            // add the company logo to the node view
            $node->content['logo'] = array(
                '#markup' => l($logo, $website, array('html'=>TRUE))
            );
            // add the company description to the node view
            $node->content['tooltip'] = array(
                '#markup' => '
'.$description.'
'
            );

        }
    }
}

API reference for functions used in the hook.

node_load
file_create_url
l


I finally managed to work it, the issue was ralated to Memcache Storage module somehow, as it's lock_inc config is not compatable with pecl memcache extension, so the solution was a removing pecl memcache and install php's memcache module.

I think I need to post this to Memcache Storage Module's bug report..


How to check if an edited form is editing a translated node

I could answer myself for the first question. The following line will give me the edited language.

$form_state->getFormObject()->getEntity()->get('langcode')->value;

But, maybe, the following is better:

$is_original_language = $form_state->getFormObject()->getEntity()->get('default_langcode')->value;

It is better, because original language could vary. In this case on the Add/Edit Node, Add new translation and Edit translations the return value can be parsed directly. Add Node or add new translation returns a Boolean while the edit forms return an int (1/0).


User authentication handled by a web service

Remote authentication can range from moderately complex to major complex.

In general, you will need Drupal users that match your external DB users.  Drupal security and coding is tied to this.  The easiest way is to create users that match your remote DB and then only do authentication.

How you syncing the remote to the local can quickly add complexity.

Other things you will need to deal with are overriding the password reset functionality.  Changing it in Drupal will not change it in your remote DB.

Some reference material / modules to look at:

Authentication API (incomplete)

The LDAP Project - A full featured implementation with dynamic provisioning (creates local Drupal id's if user authenticated) and other stuff.

The External Auth Module - Just ran across this.  May or may not be applicable.


How can I set site.com/node/1 into site.com (clean)?

I think @JimmyKo and @Gulok, misunderstood the question OR I myself misunderstood the question(If so comment me I will delete the answer).

As stated in the question,

  I am trying to get my site as site.com and when I type the URL, I get
  site.com/node/1.

The issue is user want site.com as his Front-Page but when he types site.com he is redirected to site.com/node/1.

If this is the case. You need to set your home page. Now to set the home page, you need to go Configuration/Site information for D7 and Configuration/Basic site setting for D8, there you set the front page path as shown in following images.

For D7 case,

For D8 case,

Now Reverse Case, In case I misunderstood the question

If you want to make your front page to some node like node/1, Go the same path as mentioned above and put your path there as shown in follwoign image. NOTE: There is a difference between D7 and D8 path which is '/', you can see in following images.

For D7 case,

For D8 case,

Other case(Less likely): Have downloaded other Font-page creating module or are you using panel which provides the option of making any panel a front-page. If that is the case, those modules are overriding this default setting, Hence you have to modify accordingly.


How do I alter image field code without hacking core?

You won't (easily) be able to use a preprocess function to do this as the element is generated by a form.

You could use a non-generic hook_form_alter() implementation to do this on a single form, but the best way would be to write a small custom module and implementhook_field_widget_form_alter() to override the element.

The alt and title fields (along with some others) are only added in a #process function of each image element (image_field_widget_process()), so you'll need to add your own #process function to run after that one, and alter the field type in there.

The following code is tested and seems to work well (including playing nicely with the AJAX functionality on the image field):

function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // If this is an image field type
  if ($context['field']['type'] == 'image') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element
      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
  // Change the title field to a textarea
  $element['title']['#type'] = 'textarea';

  // Return the altered element
  return $element;
}

It produces results like this:

It might be worth bearing in mind that the maximum size of the title column is set in the database, so you won't be able to go any higher than 1024 characters.


Alter and set a id attribute for a field in drupal 7

You will want to implement template_preprocess_field() in your theme's template.php

Also helpful to you will be the drupal.org documentation on Overriding Themable Output.


Is it possible to dynamically select between two different template files for the same content type?

Yes. You can implement hook_theme_suggestions_HOOK_alter() to set up different templates based on the field.
In your case, you want to add templates for nodes, so the theme hook is node. As such, you would implement the following:
function hook_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $node = $variables['node'];
  if ($node->hasField('some_field') && $node->some_field->value == 1) {
    $suggestions[] = 'node__product';
  }
}

With this code, when some_field does not exist, or does not have a value of 1, the default node.html.twig template will be used, and when some_field has a value of 1, the template node--product.html.twig will be used. Adjust accordingly.


Javascript does not work when signed in or when comments are open

To get the jquery alias $ working in drupal, you have map it like this:

(function ($) {
  $(document).ready(function() {
    alert("Here I am");
  });
})(jQuery);

The document ready function is not the best option, better use Drupal.behaviors and once():

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


How to format user profile content to be printed on a printer?

One of the easiest is to create your separate CSS for print. If you have a custom theme you can add the css file in the theme's info file. This way you can hide regions you don't need on paper to be printed.


Send email with profile2 fields with account email token in rules

Your token will be - [profile2:user:mail]. It is available in your rule with the setup that you described. You might not see it in replacement patterns for the "to" field when you are using "direct input" mode, but if you switch to "data selection" mode - you'll be able to find that token much easier.


Having trouble getting mega menu to work responsively

No, that module doesn’t claim to provide responsive menus.
Quite the opposite, in fact; its mission is to provide you with the tools you need to build your own styles, which can of course be responsive if you desire:

The module provides classes and ID's that allow for a full-range of styling customization, from more traditional (but multi-level) drop-downs to full width slide out menus.
A couple demo skins are supplied, but these are purely for instructional purpose to help get you started with theming your mega menu. Currently, you should have an understanding of how Drupal overrides module CSS files and how to add CSS to themes, in order to provide your own styles in your particular theme.

So the module just gives you a framework to start from, you need to provide your own CSS.


How do I get name and label of fields in user profiles?

You can use the field_info_instances() function to get that data:

$fields = field_info_instances('user', 'user');

foreach ($fields as $field) {
  $machine_name = $field['field_name'];
  $label = $field['label'];
}


Fivestar rating for anonymous user should redirect to login or register

You can use the Rules module to achieve this.

Check out this Great tutorial.


When building a SelectQuery, why can't I use the alias from addExpression() in a condition()?

The MySQL you're trying to build is invalid - you can't refer to an expression field in a WHERE clause.

You need a HAVING clause for that, which in Drupal-ese is:

$myquery->havingCondition('sumcalc', 5, '<');


How to get a "node" value from URL using arg(0)?

You can get aliased path using drupal_get_path_alias API Function..

$alias_path = drupal_get_path_alias();
$alias_arguments =  explode('/', $alias_path);
print $alias_arguments[0];


Variable containing HTML is not rendering when sent by message notify

Try using the HTML Mail module, Which will help you to render HTML in your email notification

Lets you theme your messages the same way you theme the rest of your website.


Required taxonomy term fields for node publishing?

This is a workflow requirement that can be handled by Rules.

Set your user car type set to unpublished by default.
Create a rule for the event Before saving content of type User Car (or whatever your node type is called)
Add a Data value is empty condition. On the Data selector you'll want something like node:field-MYTERM_FIELD:0:field-MYREQUIRED_FIELD (it depends on your field names). Make sure to check the Negate checkbox so that the rule is triggered when the taxonomy field IS NOT empty.
Add a Publish Content action.


How to update a computed field in a rule's "set data a value" action

I cannot answer your question directly, so I will propose a solution without computed fields for your specific situation. Since your computed field is just a sum of two other fields, it is perhaps easier to replace it with an ordinary integer field Balance and update its value with a simple Rule every time the entity in question changes. In order to allow users to see the field Balance, but deny them access to edit it, you can use the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.