In Views the pattern for the path cannot have a contextual filter as the first part of the path.

Contextual filters and paths

  The normal way a view gets values for contextual filters is by the
  view path. The easiest way of doing this is to append filter values to
  the path, separated by slashes. It is also possible to have contextual
  filter values within a path. This is done by using a percent sign
  where the view expects a contextual filter value in the path of the
  view (for example user/%/comments).

So your pattern needs to change to something like this:

resorts/%/restaurant-guide/%

as in resorts/[resort]/restaurant-guide/[restaurant-category]

Then two contextual filters:

**content resort (field resort)**
Taxonomy term ID from URL
Validator: Taxonomy Term
Vocabulary: resort
Filter value type: Term name converted to Term ID

**content restaurant category (field restaurant category)**
Same as above but with Vocabulary: restaurant category

Then keep in mind that you might need to deal with spaces in your taxonomy terms


You have join the distinct table with watchdog. So the all result of watchdog will be displayed and the matching record of distinct table. So try changing query like :

$query = db_select('distinct', 'di');
$query->join('watchdog', 'wa', 'di.wid == wa.wid')
  ->orderBy('wid')
  ->fields('wa', array('variables', 'type', 'severity', 'message', 'wid',
    'timestamp'))
  ->range(0, 20);
$result = $query->execute();


Sounds like an issue with the ordering of the javascript files. Drupal is defined in

/misc/Drupal.js

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} };

Check Drupal.js is added to your HTML source, prior to when that variable is requested.


How to assign role(s) for a new user based on node_field?

Yes this should be possible using the Rules module.

When trying to do so, make sure to add a Rules condition Entity has field (related to your my_field field). That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


The Batch API won't continue running if the browser is closed correct? Can a batch be run with Drush?

It seems possible, have you tried: Processing batch jobs with drush.


Published checkbox only available for administrator

You can use the following module.

Override Node Options

The Override Node Options module allows permissions to be set to each field within the Authoring information and Publishing options field sets on the node form. It also allows selected field sets to be set as collapsed and / or collapsible.


If you are using default (Unformatted list) formatter override double-field-item.html.twig template with the following markup:

{{ item.first }}

{{ item.second }}

Note that Double field ships with HTML list formatter which may render definition list so you might not need to override anything.


local copy of my drupal site doesn't seem to link

Make sure apache has mod_rewrite enabled, and that the drupal .htaccess file is there in your drupal root. If you're on debian/ubuntu, you should be able to do:

sudo a2enmod rewrite
sudo /etc/init.d/apache2 restart


You can change the label using the template_preprocess_field hook.

For instance, if your field was named "phone" and the content type was "business", you could add this to your template.php:

template_preprocess_field (&$variables) {
  $content_type = $variables['element']['#bundle'];
  $field_name = $variables['element']['#field_name'];

  if ($content_type == 'business' && $field_name == 'phone') {
    $variables['label'] = '<img src="http://www.carloancentre.ca/wp-content/uploads/2014/03/Contact-Methods-Phone-icon.png" height="16" width="16"/>' . $variables['label'];
  }
}


As of 2016/03/04, these are open issues in Drupal 8.  See Support for end date and D8: Date repeat feature requests.  The decision was made to move these from contrib into core, but they are complicated issues, and unfortunately touch the exact same portions of code, so working on them simultaneously is difficult.

As of 2016/12/07, support for end date is officially part of core, starting with 8.2.0.  It is looking like the date repeat feature is going to end up in the datetime extras module as part of contrib, and not core.  However, work on this is still preliminary.


What module should I use to save a module settings in a feature?

Many modules store their settings in variables, that's what Strongarm is good for : it can help you export those variables with features.

My usual way of finding out which variable to export (and exporting it) :

see the source HTML of the form where you set the values
in the "name" attribute you will most often find the name of the variable
use drush vget *that_variable* to check if it exists

drush vget is useful because it searches all variables that have a name similar to the string you provide, so sometimes you can do some testing to see other variables that could be useful

if you confirm the name of the variable, put it into the feature's info file

features[variable][] = that_variable

run drush fu your_feature

this will export the variable's value

The other module you heard off might have been Features Extra. Me personally i don't find it that useful anymore.

There is a free video on drupalize.me about features. And an article on d.o.


Filter for landscape format images in views

One simple solution
in given content type, add a CCK (select list) field having  option "width > height". select this field when the image is landscape. then in views add this filter too.  by doing this, only images that are "width > height" will be shown


How to move files already uploaded to a new subfolder?

It sounds like you're looking for File Maintenance.

  Ever wanted to move files from your sites/default/files directory (or
  whatever you have configured) to a (new) subdirectory? Never did it
  because you knew it's a damn mess since you need do move the physical
  file, adjust the database files table and look through all the
  node_revisions table and other content to adjust the link to the file
  so as not to break your site?

That should cover any files that are managed under the files table (pretty much any field you should have). If you have any other files under sites/default/files that aren't managed by Drupal, then custom redirect htaccess rules should cover those files.


How to create a dynamic menu block system with 3-tier system?

Part 1 - Rules is definitely your friend!

It seems that you should definitely have a look at how the
the Rules Block visibility module can help you in "reducing" the challenge contained in your question here.

Admitted, you'll probably need MORE then just that module (and appropriate custom rules) to make it work, but I would definitely recommend this module as part of the solution you're looking for.

Even though your question does say so (yet), I imagine the various scenarios / menu items each also correspond to some combination of paths (URLs). With that, and by using the Rules event "Drupal is initializing", you should even get closer to what you're looking for.

And to avoid you'd get too many (separated) custom rules to make it all work, I'd also try to keep your number of custom rules to a minimum, by also adding the Conditional Rules module to this mix.

Part 2 - BEAN might help too!

Because you have quite some blocks-related requirements, I'd definitely also have a look at the Bean module, to check if it can help also to answer this question. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

So by adding appropriate fields to your blocks, you may be able to reduce the number of blocks you'd actually need. E.g: maybe your Scenario 1 could be implemented with just a single block.


Cloning the Base theme bartik, seven, and stark in Drupal 8

A few things that could have been missed -

Cache clear,
Changing the name of the theme in .info.yml of the new theme,
Not putting the base theme in the .info.yml.

If none of those work, this is a pretty good guide. https://www.drupal.org/theme-guide/8/creating-a-sub-theme


twig debug what does % mean - name of page.twig

page--node--%.html.twig

This would be a universal template for page level views of any content type.  So if you wanted to have the same template for different content types you could use this convention.  If you need different templates for each content type you could apply:

page--node--[content type machine name].html.twig


Filter nodes by paragraph user reference

According to this issue, Unable to filter on columns of entity reference fields. It seems like you need to add .entity after the field name to the entity reference fields.

Try to use this URL instead:

/api/node/exercise?filter[field_related_users.entity.field_user.entity.name]=some_user

Or if field_related_users can contain multiple values, you might want to do like this instead:

/api/node/exercise?filter[field_related_users.0.entity.field_user.entity.name]=some_user


How to create a view showing content linked with an entity reference field?

OK, finally worked out how to do it. Thanks to this video which explains it all: https://www.youtube.com/watch?v=4Pdii7aFIvc&t=392s
However, in case anyone else is stuck you need to first create a relationship based on your entity reference field, sthen create a contextual filter using node:id based on url. This is all you need to do.


Load AJAX form on every page via drupal_get_form

I solved this issue, problem was in 'wrapper' so this is how it works

<?php  print '
'.drupal_render(drupal_get_form('ajax_contact_form')).'
';  ?>


How to access replacement tokens present in views field rewrite output in its .tpl file of that field

Under the Field settings, you can add a class to the field:

this can accept replacement tokens, so for example you could:

create 5 classes each with a different length
add a field prior to this field that will calculate the correct length
use the replacement token of the calculated field to include the proper class:  barsize1, barsize2, barsize3, etc


How can I add field information to an standard image?

I assume you already have image installed and a content type set up that you have an image field attached to.

You will need to install the following modules image cache actions and token
 also the following will need to be enabled "Image Effects Text" (this is part of image cahce actions)
Add an image style by going to example.com/admin/config/media/image-styles and clicking add style.
Using the select list under Effect select text and then click add
You will now be in a page where you can set all the txt setting including the actual text to overlay the image with. You can select the type of text using the select list labelled "text source" if you have token installed you can select token and browse tokens for your replacement text.


I figured out how to display the image file in the jCarousel.  In a view add the file:Name field and set the style settings to HTML and add the image source hmtl  tag to rewrite results.  Example:


Adding different auction prices for same product

As the author of this module or someone else couldn't reply this question, I'm creating new product before creating the content. Then I create the auction content and choose the related product.


Hiding fields when creating node and showing them only when editing

This is certainly without a doubt a job for hook_form_alter() and quite easy to accomplish, eg, something along the lines of:

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

  switch ($form_id) {

    case 'foo_node_form':

      if ($_GET['q']=='node/add/foo') {

        // we are creating a node of type foo so do stuff to the form one way here

      } else {

        // we are editing a node of type foo so do stuff to the form another way here

      }

      break;

   // other forms here

  }

}


call javascript function after ajax form submit

Have a look at the Ajax framework and Ajax framework commands topics in the API documentation.

Basically, instead of simply returning a single render array, you can return a number of so called ajax commands, which will be translated to javascript and executed on the client side. Replacing the specified wrapper with the returned content is just the default command that is done when nothing else is specified.

There doesn't seem to be a provided command that allows to execute any javascript method (only an invoke command that allows to execute an jQuery command on a defined selector) though. However, you can either define your own command (just have a look at what these helper functions return and the corresponding JS functions in misc/ajax.js (look for Drupal.ajax.prototype.commands = {...).

Or you might be able to replace your custom JS function with a number of the provided default ajax commands. They're pretty flexible and I'm for example using them to update the page title in userpoints.module.


Did you get drush installed on your system? Check it with the following command.

drush --version

If it is a lower version please update drush using composer, if composer already installed skip the step to install composer.

cd ~
curl -sS https://getcomposer.org/installer | php
export PATH="$HOME/.composer/vendor/bin:$PATH"
source ~/.bashrc
composer global require drush/drush:8.*
drush --version


Redirecting to a page based on the sub-domain

The linked post points in the right directions, but contains a lot of code you don't need. Use this change record https://www.drupal.org/node/2013014 instead and check $request->getHost():

  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->getHost() == '...') {
      $event->setResponse(new RedirectResponse('http://example.com/foo/'));
    }
  }

For a non-coding solution you can try Redirect Domain, a submodule of Redirect.


Content access based on on the field reference

There are plenty of node access modules available for Drupal but I honestly am not sure if there is one that would do exactly what you are looking for.

Either way, I would probably avoid a specific node access module for this and use Panels - read the Panels module - to do this since its makes this scenario easy to accomplish.

You can easily override Drupal's standard Node template and create an invariant that matches both the content/node type you want to apply this rule on and add a condition that the logged in user's ID matches the user id in the reference field defined by the node.


You do have the template files in themes/bartik*? Make sure to rebuild the theme registry.

This feature is relatively new but we've used it several times for ourself now and have multiple confirmations from other people that it works for them.

Note that the only thing that "using a theme" means is the place where Simplenews looks for the template files. Additionally, Mimemail also looks for for either the css files to embed or the mail.css (Hint: Older versions of Mimemail have their own setting, switch to the most recent dev version of Mimemail to get that fixed).

It does in no way take over the look and feel of your website, if you're looking for that, have a look at HTML Mail.

*Hint: You should not alter a core theme or add files into it, instead, create a subtheme and put that in sites/all/themes. Try Google to find more information about subthemes.


Can someone explain this behavior to me?

The render array returned by the build method in the block plugin does not have a theme or type. This means that it will default to markup (iirc). The theme/template is not being used because the render array does not specify to use it.

You can find an example of implementing render arrays on drupal.org's documentation page, Render arrays. This explains the default element properties.

How to pass variable from block and access in it twig template?

The render array should have the #theme element property set to the theme definition key.

  public function build() {
    return [
      '#theme' => 'more_topics_rollout',
      '#title' => $this->t('More Topics'),
      '#body' => 'My body',
      '#description' => 'My description'
    ];
  }


Setting up Multiple Databases on a current site

I think I figured out what to do in order to pull this off. The issue was that the documentation in default.settings.php was rather lacking but I managed to piece it together. You do have to set your tables up explicitly and your databases as well. It has not helped the issue at all, and frankly it concerns me due to the issues with Drupal 8 coming that frankly might not be usable. So I'm going to pursue a different course of action on this.


Cant find any info on this method being removed in webform or how to fix

The WebformEntityReferenceItem::getEntityWebformFieldName() static method was not removed but it was refactored and moved to the 'webform.entity_reference_manager'service.

Here is an example of showing how to use the service.

/** @var \Drupal\webform\WebformEntityReferenceManagerInterface $entity_reference_manager */
$entity_reference_manager = \Drupal::service('webform.entity_reference_manager');
$field_name = $entity_reference_manager->getFieldName($node);
...

@see \Drupal\webform\WebformEntityReferenceManager

@see \Drupal\webform\WebformEntityReferenceManagerInterface


Please check README.txt of the captcha module.

  The configuration page is at admin/config/people/captcha,
  where you can configure the CAPTCHA
  module   and enable challenges for the desired forms.   You can also
  tweak the image CAPTCHA to your liking.

Go to the configuration page - admin/config/people/captcha
Select the Default challenge type - Math or Image
In the form list, you can define which form has CAPTCHA, for example
if you want to have it on the register form, select a challenge type
(Math or Image) for the FORM_ID user_register_form

If you want to add CAPTCHA to a content type, for example, blog, add a new FORM_ID "blog_node_form" and click "Save Configuration".

By default, you will not see CAPTCHA on each form when you logged in as administrator, but you can change the option in the configuration page.


How can I unset an option from Profile2 while it is part of Registration?

Main profile fields are added through hook_form_alter.
Solution:
hook_form_alter function is executed in all modules while accessing registration form. Your custom module form_alter is executing before Profile fields get added. To solve this issue increase custom module weight. FYI : Module weight change


I think you want to use QuickTabs. I am using it on my website (check near the bottom). It seems to be exactly what you want to do. Under each quick tab, you can display nodes, views, blocks or other quick tabs.


The user ID is saved on the store when it's created. Therefore you can load it with code similar to the following one.

$store = \Drupal::entityTypeManager()->getStorage('commerce_store')->loadByProperties(['uid' => \Drupal::currentUser()->id()]);

That will load the store based on the currently logged-in user.


Div and problem locating their CSS files

1) Assuming you already have sub-themed Zymphonies theme, just add this in your sub-theme's stylesheet-

.geolocation-google-map {
width: 100% !important; }

If not, read this documentation on sub-theming and do the above. Same goes for (2)

2) You can target your div (without class or id) using :nth-child() selector

Being a title, it usually is 1st or 2nd child of the view wrapper.If so

.view-name > div:nth-child(1) {
  //styles for a div that is the first child
}

.view-name > div:nth-child(2) {
  //styles for a div that is the second child
}`

Note that the div you're targeting has to be the direct child of its predecessor


Image not found --> creates a path that doesn't exists

When you install Galleria, it creates the image style presets it requires, which you can find under /admin/config/media/image-styles.

If you view the images, imagecache will create the image types and store them in the file system under the appropriate direcory so they will not have to be re-created. If your file system does not have the correct permissions, the directories and files cannot be created, and the images cannot be found.

Check your logs for error messages (/admin/reports/dblog). If this is the case you need to make sure that the directory tree has the correct ownership (usually apache.apache) and the correct read.write permissions (664). If you have access to the server, use the chown -R apache.apache * and chmod -R 664 * commands to accomplish this.

Once you have verified the permission, galleria should work correctly.


How to remove unwanted form state values before validation

The FormState class has a method for that: FormState::cleanValues(). From its description, it's the method you should use.

  This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.

  form_id
  form_token
  form_build_id
  op

You simply call it before getting the submitted values.

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->cleanValues()->getValues();

  foreach ($values as $method => $fee) {
    if ($method != 'Free order') {
      if (!is_numeric($fee) || floatval($fee) < 0) {
        $form_state->setErrorByName($method, t('Value must be a positive integer.'));
      }
    }
  }

Since FormState::cleanValues() returns the FormState object, you can simply call it in the same line you call  FormState::getValues() concatenating the two calls.

If you need to add more keys to remove from the submitted values, you could use FormState::setCleanValueKeys(), but keep in mind that:

The array passed to the method needs to contain also the default array keys Drupal would remove
The method alters the array keys that are removed from FormState::cleanValues() for every Drupal form


Limit Taxonomy display in Term Reference based on criteria?

I achieve the behaviour described in the question with:

Entity Reference
Views

In my Entity Reference field I use these settings:

Target type: Taxonomy term
Entity selection > Mode: Views: Filter by an entity reference view
Entity selection > View used to select the entities: My custom view

In My custom view entity reference I have (most importantly):

A relationship: to the user referencing the taxonomy
A contextual filter: to grab only the terms the user "is linked to"

Related to this question - actually this is what brought me here, In some cases it easier to filter taxonomy terms using a get parameter. For example, I want my visitors to see only the cities of one country when adding a classified ad, I will have a view that produces this:

Morocco: q=node/add/ad?country_tid=1
India: q=node/add/ad?country_tid=2
Zambia: q=node/add/ad?country_tid=3

And on the entity reference view used on the ad content type I will add a contextual filter with a default value generated by this PHP code

return $_GET['country_tid'];

PS.
I tried hierarchical select, term reference tree and hook_form_alter. This solution is KISS.


Using jquery-match-height to set two blocks to equal height

Have you already tried out the Equal Heights jQuery module? This module does exactly what you want, without having to create custom code and works fine with Zen.


Regenerating images after new image style

Drupal creates derivatives images "on the fly" based on a defined image style. The act of creating a new style does not generate any images. Rather, the first time an image is requested using that style it will be generated and saved in sites/default/files/styles/{stylename}/path/to/image.jpg.

If you (for example) create a view that displays nodes with images using your newly defined image style, then as soon as you go to a page with that view the images will be generated.


If you just want to run an arbitrary PHP script through Drupal, the easiest way is probably using the Devel module

It provides a page (/devel/php) where you can copy/paste PHP code and have it run inside a fully bootstrapped instance of Drupal.


Entity reference view depending on other field

Step 1

On the field definition for the reference field that is dependent on another field you are going to change the reference method to views

Step 2

You'll need to create a reference view for this data.
Make sure to add a contextual field/relationships/etc on the reference view that takes the other value from your form that helps it pre-filter the autocomplete results.

Step 3

in a module or wherever hook into hook_form_alter and replace the reference field

/**
 * implements hook_form_alter
 *
 * @param array $form
 * @param array $form_state
 * @param string $form_id
 */
function my_module_form_alter(&$form, $form_state, $form_id) {

  if (in_array($form_id, ['node_mycontenttype_form', 'node_mycontenttype_edit_form'])) {
    // Add a wrapper around the reference field.
    $form['field_referencefield']['#prefix'] = '
';
    $form['field_referencefield']['#suffix'] = '
';

    // Add an ajax callback that replaces the contents of the wrapper.
    $form['field_triggerfield']['widget'][0]['target_id']['#ajax'] = [
      'callback' => 'mymodule_field_mycontenttype_trigger',
      'wrapper' => 'some-wrapper',
      'event' => 'autcompletechange autocompleteclose',
      'progress' => [
        'type' => 'throbber',
        'message' => t('Fetching filtered content...'),
      ],
    ];

    $field_triggerfield_value = $form_state->getValue('field_triggerfield');
    if (!empty($field_triggerfield_value)) {
      $contextual_filter_value = $field_triggerfield_value[0]['target_id'];
      $form['field_referencefield']['widget'][0]['target_id']['#selection_settings']['view']['arguments'][0] = $contextual_filter_value;
    }
  }
}

function mymodule_field_mycontenttype_trigger(array $form, $form_state) {
  return $form['field_referencefield'];
}

so what this is doing (I've assumed node edit form and node add form for a content type):

putting a wrapper around the reference field whose available values should change
adding an ajax callback to the trigger field that should cause the reference field to filter (the contextual field)
when the trigger field changes

add a new contextual value to the view reference field's view from the trigger field
replace the contents of the wrapper field in the form


How to make the cart menu display the number of items added?

Commerce Ajax Add to Cart

  Using this module you can ajaxify the add to cart operation. The
  updated cart will be displayed without page refresh and a popup
  message will be shown after you add an item to cart. You can customize
  the look of the blocks using its template files.


It seems Login with Email only should solve that. At least worth a look how they managed to do that.

  This simple Drupal 8 module allows users to log in exclusively with
  their email address from the standard login form.

  Setup:

  Just enable the module.

  Recommended Modules:

  This module is based on the Login Email or Username module:
  https://www.drupal.org/project/login_emailusername


Why doesn't my code to save an order work when invoked by AJAX?

The reason you are getting page not found is might be because of security check. In other words why any user can not access checkout page for any other user.For authenticated user drupal manages the mapping of order id and user id, but when user is anonymous drupal checks if the accessed order id is in current session or not, so while creating the order progammatically we do not need to explicitly set the order into session.
A nice example:
commerce_cart_order_new()

Creates a new shopping cart order for the specified user.

When you are on the commerce_cart_order_new() api page, check the codes after comment

// If the user is not logged in, ensure the order ID is stored in the
session.

That is how drupal cart does while creating order for anonymous user.
Reason:
Before a user a able to move to checkout page drupal checks if the current user has access or not using commerce_checkout_acess().For authenticated user it simply checks if the current user id is same as the order owner user uid if so user can move to checkout page.For anonymous user drupal checks SESSION, if in current session acsessed order id exists user can move to checkout page or access is granted to user.
Solution:
Use of commerce_cart_order_session_save() to set the session like drupal cart does.So your code will look like
$product_id = 1;
global $user;
$order = commerce_order_new($user->uid, 'checkout_checkout');
commerce_order_save($order);
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
  // If the user is not logged in, ensure the order ID is stored in the session.
  if (!$user->uid) {
    commerce_cart_order_session_save($order->order_id);
  }
commerce_order_save($order);
drupal_goto('checkout/' . $order->order_id);


Install multiple apps on a Bitnami stack

This is not a direct answer to your question. If it wasn't long I'd post it as a comment.
Since you mention configuring a server is not your forte, I'd like to recommend you and other Drupal developers at any level of expertise, an alternative development environment to manage multiple instances of Drupal, and other websites in a Vagrant virtual environment:
Laravel's Taylor Otwell also created Homestead:

Laravel Homestead is an official, pre-packaged Vagrant box that provides you a wonderful development environment without requiring you to install PHP, a web server, and any other server software on your local machine. No more worrying about messing up your operating system! Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes!
Homestead runs on any Windows, Mac, or Linux system, and includes the Nginx web server, PHP 7.2, PHP 7.1, PHP 7.0, PHP 5.6, MySQL, PostgreSQL, Redis, Memcached, Node, and all of the other goodies you need to develop amazing Laravel applications.

It certainly targets the Laravel developers, but I've been using it for most of my local development needs, whether they are Laravel, or Drupal (6, 7 or 8), or any other PHP website.
It makes it much easier to manage any number of websites with different PHP versions, different database needs, and custom hostnames in a single configuration file, to your liking either YAML, or JSON file.
I should mention that I'm not affiliated in any way with Laravel or its creator. I just really like my experience with Homestead so far, and wanted to share.
Go ahead and read its documentation, and install it globally on your machine. Set up a couple websites and give it a try. My guess is you'll have your sites up and running before you can resolve the issues with current Bitnami instance you have.


How to you add a table of contents in a pdf for a book that is exported using views_pdf?

You could write a new view that only contains the table of contents (no idea how hacky this is) and include it into your PDF view as a header. (Header -> Add -> Global -> View)


How do I add a node from a view to user profile field?

You can simply add a Global: text area in views header and input below HTML in the content.

Add Course


User roles and permission for 1 can publish and 1 can't

You are looking for Workflows and Content moderation. Those are features available out-of-box in Drupal 8 (stable form 8.4)


restrict some url access, based on user roles

You can implement hook_menu_alter in your custom module and can provide function for 'access callback' property of the menu item.

<?php

/**
 * Implements hook_menu_item_alter()
 *
 */
function custom_feature_menu_alter(&$items) {

  $items['admin/structure/types']['access callback'] = 'custom_feature_access_callback';

}

/**
 * Custom access callback
 */

function custom_feature_access_callback($arg) {

  global $user;

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

  //Adding condition for the user roles. You can change 3 to your user role. I have tested this with administrator user role
  if (in_array(3, $roles)) {

    return FALSE;
  }
  else {
    return TRUE;
  }

}


Form api AJAX, reload js in #attached 3 times

The log console prints 3 times: "aaaa" after the ajax action is over

That's correct, behaviours are re-attached after AJAX requests. That's actually the point of them - to ensure that Drupal modules can respond to changes in the DOM.

If you want to limit the effect of that, core provides once(). You'll need to add the once library separately, after which you can use, for example:

$(context)
  .find('input.myCustomBehavior')
  .once('myCustomBehavior')
  .addClass('processed');

See the JavaScript API overview for more information.

Of course you don't have to use once, if you don't need the complexity it offers you can just keep track of a boolean that determines whether or not your code should execute again.


Ability to 'mark' nodes and build a book functionality

For 'marking' nodes, you'll definitely want the Flag module.


What is the parameter $instance_id in the function Block::setVisibilityConfig?

I got it. Example:

use Drupal\block\Entity\Block;

function mytheme_preprocess_html(&$variables)
{
    $block = Block::load('sitebranding');
    $block->setRegion('content');

    $visibility = $block->getVisibility();

    if (isset($visibility['request_path']['pages']))
    {
       unset($visibility['request_path']['pages']);
       $visibility['request_path']['negate'] = 0;
       // $visibility['request_path']['pages'] = '/node/2';
       $visibility['request_path']['pages'] = \Drupal::config('mymodule.settings')->get('services_block_path_visibility');
       $block->setVisibilityConfig('request_path', $visibility['request_path']);
       $block->save();
    }
}


The actual replacement does not happen until you save the entity. There is no fancy AJAX-based form manipulation here (unlike a core file field), so there is no specific "upload" button attached to that "replace file" field.

You just need to specify your replacement file (populate that field) and then save the full form ("Save" button at the bottom) for the replacement to happen.


How can I get the checked attribute into Better Exposed Filters input type radios?

The person who does the CSS needs to design the dynamic property :checked, not the static attribute [checked]. The 2nd one is static in the HTML code and never updated after the intial page load, the first one is the currently selected input.


Can Nivo Slider change slides without any effects?

If you select fade and make the fade occur in 1ms, then it will appear to change slides without any effects.


I would use a taxonomy to tag your content.

Create a taxonomy vocabulary (E.g.: Brand), add the two terms (Green, Orange), add a new field of "term reference" to your content types and tag the content.

Then in your views, you can add a "Contextual Filter" (in the advanced options) to get term_id from the URL, so both will show the same tagged content.

Note that I've set the Path component to be 2, that's because the term_id will be passed as 2nd argument on your URL (can be anything you want).

Don't forget to validate the value to be one from your vocabulary. That's on "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED", check the option "Specify validation criteria" > "Validator" = Taxonomy Term > Check your vocabulary from the list.

Then you need to set your view URL, so you can pass the term_id by the URL:

By doing all that, you should be able to go to your page, type http://yoursite.com/brand/term_id and your content should appear.


IMCE: Prevent deletion if file is in use

I'm not familiar with IMCE but Drupal core provides a file_usage table that is for locking/unlocking files. These are the functions used to interact with it:

file_usage_add()
file_usage_delete()
file_usage_list()

Drupal's file_delete() then checks the usage table before deleting a file.


How to show a link only if a node author has a certain role

You can use menu_get_object() to easily and cleanly get information on what you looking at, eg, something along these lines:

$mgo=menu_get_object('user');

if ($mgo) { // we are looking at a user

  if (in_array('CERTAIN ROLE', $mgo->roles)) {

    // do whatever

  }

}

and if the user you are looking at, eg, user/###, has a CERTAIN ROLE, then you can do whatever.

Now, from your question, I am going to go out on a limb and assume you are creating this block from the Block UI and using the PHP Filter, so I guess it would look like this:

<?php $mgo=menu_get_object('user') ?>
<?php if ($mgo): ?>
  <?php if (in_array('CERTAIN ROLE', $mgo->roles)): ?>
    <a href="/user/<?php print $mgo->uid; ?>/menu4">MENU4
  <?php endif; ?>
<?php endif; ?>

but I would strongly urge you to consider writing a module for this as the PHP filter opens up soooo many potential holes.

Also, as @olyn has pointed out, $user points to the logged in user, not to the owner of the profile you are looking at, so you will want to look into that in your code as well for your other links, eg, $user->uid is the uid of the currently logged in user; in my code above $mgo->uid is the user id of the profile you are looking at.


Flags: flagging unflagging rules, how to check if an user has already flagged a node?

What you're trying to achieve (= allow users to flag nodes by one out of 3 flags), is by design NOT something you can implement by using a global flag. Because global flags cannot be used by individual users. So I suggest you rethink/rework the design of those flags, so that they are NOT defined as global anymore. After you do so, you should be able to implement what you're trying to do, by using the Rules module, and with no need for PHP code. Read on for more details on how to do so.

Have a look at this rule (in Rules export format):

{ "rules_unflag_related_flags" : {
    "LABEL" : "Unflag related flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "ON" : { "flag_flagged_this_is_nice" : [] },
    "IF" : [
      { "flag_flagged_node" : {
          "flag" : "this_is_bad",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ]
        }
      }
    ],
    "DO" : [
      { "flag_unflagnode" : {
          "flag" : "this_is_bad",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Some details about the above rule:

Rules Event: A node has been flagged, under "Nice".
Rules Condition: The flagged node is flagged with flag "Bad", by the flagging user.
Rules Action: Unflag the flagged node, for flag "Bad", by the flagging user.

You should be able to import the above rule in your own site, provided you first adapt the machine names of both flags (this_is_nice and this_is_bad) to fit your own machine names.

If nice is not sufficient (and it should be cool also ...)

If you want to implement similar logic for the "cool" flag, you can rework the Rules Condition and Rules Action in the sample rule above towards a Rules Component (say you name it "Disallow BAD flag"), and remove them from the rule shown above. Then clone this Rules Component towards a similar one for the "Cool" flag  (say you name it "Disallow COOL flag"), in which you change all "bad" to "cool". And finally invoke both Rules Components via an extra Rules Action (1 for each) in the sample rule above.

Or you can use the Conditional Rules module to consolidate both rules in a single rule. Here is a variation of the above rule (using flags with machine names this_is_nice, this_is_bad and this_is_cool), to illustrate how such rule would look like:

{ "rules_unflag_related_flags" : {
    "LABEL" : "Unflag related flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "flag" ],
    "ON" : { "flag_flagged_this_is_nice" : [] },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "flag_flagged_node" : {
                "flag" : "this_is_bad",
                "node" : [ "flagged-node" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_unflagnode" : {
                  "flag" : "this_is_bad",
                  "node" : [ "flagged-node" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          },
          {
            "ELSE IF" : { "flag_flagged_node" : {
                "flag" : "this_is_cool",
                "node" : [ "flagged-node" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_unflagnode" : {
                  "flag" : "this_is_cool",
                  "node" : [ "flagged-node" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

Easy, no?


How do I turn off clean URLs only for logged-in users?

This isn't possible in Drupal core because the clean url check occurs so early in the bootstrap phase, i.e. before you would be checking for permissions, settings, etc. One hacky possibility is to try and determine in your settings.php file if a session is open and then enable the clean_url settings dynamically:

$conf['clean_url'] = 0;

But even that would probably be swamped by your htaccess settings and mod_rewrite.


Check whether multiple images are uploaded to a field?

You can get it done in a few lines using the field_get_items function:

if ($items = field_get_items('node', $node, 'field_name')) {
  if (count($items) == 1) {
    // ...
  }
  elseif (count($items) > 1) {
    // ...
  }
}

It'd be best to keep this logic out of the template file itself and put it in a preprocess function though.


Check that your image has at least 200x200 as defined in the error provided by Facebook debugger.
Also use Ctrl+U in your browser to check that the og:image tag print the correct url


How to remove link to personal contact form from tabs block?

I didn't test the following example code though, but you will be able to remove tabs using hook_menu_local_tasks_alter() in a custom module (replace mymodule by the name of your custom module):

/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  // Whether the personal contact form tab is present. You
  // can fine-tune your conditions here. The tab route was
  // taken from ./core/modules/contact/contact.links.task.yml.
  if (isset($data['tabs'][0]['entity.user.contact_form']) {
    unset($data['tabs'][0]['entity.user.contact_form']);
  }
}

As mentioned before, I did not really try the above code. You might have to check the contents of the $data array to find the right plugin id and correct position of the tab definition when visiting a user's page.

Also note, that the tabs information will be cached. So you will have to rebuild your caches for the changes to take effect and the above hook to being triggered.

The functionality will be kept, as the route behind the tab is still active when you alter the local tasks array only.


Here are some advantages of using templates instead of a custom PHP field.

Templates can be naturally version-controlled just like the rest of your code.  (You could version-control the custom php field with Features, but that is an additional layer of complexity.)
Since the code for templates is in files, you can use UNIX commands like grep, etc. to search them.  You can also batch edit them easily if necessary.
If you accidentally misconfigure your site permissions and give a role access to Views administration that shouldn't have it, they still won't be able to insert PHP into your site if you're using templates (eliminates a security risk).  Consider that one of the security enhancements in Drupal 7 over Drupal 6 was hiding the PHP filter and making it harder to enable.
The Views PHP module is still in dev and thus not subject to audit by the Drupal security team.  There may be (are) bugs in the module and since it is not in widespread use they may not be found for some time (avoids another security risk).

Yes, templates might be a little inconvenient, but from a security and maintainability standpoint I think they are clearly superior.


How to hide page title based on node type using template_preprocess_page()

and my reading suggests the best practice is to handle template logic in template.php using preprocess and process functions.

Decoupling the logic from the rendering code simply means the code in template.php sets a variable that is checked in the template file. In this way, the logic is all contained in the template.php file, while the rendering code is all in the template files.

template.php

function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'concert') {
    $variables['show_title'] = FALSE;
  }
}

page.tpl.php

<?php if ($show_title && $title): ?>
<?php print $title; ?>
<?php endif; ?>

hide() doesn't work because $variables['title'] is a string, not a rendering array. hide() is always used with a rendering array, and it doesn't have any effect with a string, not even when the string is passed to render().
Actually, passing a string (or any value that is not a reference to a variable containing an array) to hide() would cause a PHP error, since the function uses this code.

function hide(&$element) {
  $element['#printed'] = TRUE;
  return $element;
}

Unsetting $variables['title'] with unset($variables['title']) doesn't work too, as template_process_page() would get the page title from drupal_get_title().

if (!isset($variables['title'])) {
  $variables['title'] = drupal_get_title();
}


Programatically get a list of node ids of a content type for a specified language

You can just add langcode to the query:

$query->condition('langcode', 'fr');


Take a look at theme_menu_tree() and theme_menu_link(). It should be all you need.

Sorry for the lack of examples, but theme_menu_tree is rather self-explanatory, and the page for theme_menu_link provides several examples.


How to unpublish a node and any related nodes?

Yes this seems perfectly possible with Rules ... In your case, the crucial part of such rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should use (at least) have a Rules Action to create a loop related to your 'related "Review" nodes' (as in your question). After you do, you should iterate over each item in that list. And for each iteration you should then perform a Rules Action to "unpublish the review being processed in the loop".

Done

PS 1: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.

PS 2: I assume this is about D7 ...


Scheduling a module to run at a specific time

Depending on how detailled your specific time is, you could still use hook_cron. For example, let's say the normal cron runs every hour, you could check date('H') in your module and only if it equals a predefined value, the cron function in your submodule will be executed.

function MYMODULE_cron() {
  if (date('H') == 3) {
    // this code will only be executed between 3:00am and 3:59am
    // do your stuff
  }
}


Render a menu block in current user's language

You don't need a custom module for this.

Drupal can have seperate language detection for interface (menu item/interface elements) and content.  There was a bug that was fixed recently so make sure you are on the latest 8.6.x version.

Assuming you have enabled all 4 core language modules and you have enabled at least 1 extra language than configure the language detection methods to accomplish what you want as I its outlined below.

Go to Configuration > Regional and language > Languages > Detection and selection and

enable Account administration pages. This will allow each user to choose their preferred interface language (there will be a new option when they edit their profile page)

enable content language detection. This will make available the language switcher (content)) block.
enable 1 detection method.  In my case I choose url (i.e. /en /fr) but you can choose any other or more methods if you like.

ΝΟΤΕ: The detection methods take precedence as they appear from top to bottom provided they are also enabled.

Go to Structure > Block layout and enable language switcher (content) (not language switcher (interface text)

Now lets say a user has chosen English as their interface language they can press on the language switcher (content) and their interface (menu, admin menu etc) will always  stay English.


How to filter by language in default search

Ah heck.. nevermind. I wasn't understanding how to get that setting. All good now. Filter by content language, and 'current user's language' is one of the checkbox options within it.


The simplest way to do this is by using a Taxonomy to define your filter. By default, the 'IDs' returned in the array will be TIDs, which you can link back to Term name.

This post provides some easy instructions on how to use a Taxonomy as your filter (you possibly need to add it as a relationship in your view)

Get your IDs (values) the same way previously:

$view = views_get_current_view();
$view->exposed_input['filter_name'];

Then simply step through the array to pick up and match the IDs to the term name:

$view = views_get_current_view();
foreach ($view->exposed_input['filter_name'] as $tid) {
  $term = taxonomy_term_load($tid);
  $name = $term->name;
  print $name;
}

Boom!


How to add a prefix - suffix to a node title from a module

You have an error in the very title. Adding prefixes and suffixes is not a job for a module. You do it in template. If you need to wrap it in html tags, do it in node.tpl.php. If you need some more elaborated logic, see template_preprocess_node().


Can't update radio button fields after ajax callback

After change type to 'select' works fine.

Drupal have this bug active

https://www.drupal.org/project/drupal/issues/2758631

Same situation with checkboxes


I would alter the exposed form and add a validation handler.

If I remember correctly, the form ID is views_exposed_form. Just do a check on the view object (which I think is in the $form_state variable) to only add the handler to a certain view/view display.


Saving default field values on node_insert

You could probably do this in hook_node_presave(), e.g.:

function MYMODULE_node_presave($node) {
  // Get a value made up of other submitted fields, e.g.
  $computed_val = $node->field_first[$node->language][0]['value'] + $node->field_second[$node->language][0]['value'];

  // Assign that value to the other field
  $node->field_computed_field[$node->language][0]['value'] =  $computed_val;
}


To alter query you should use hook_views_query_alter

Sample Code using hook_views_query_alter :

function MODULE_views_query_alter(&$view, &$query){
switch($view -> name){
    case 'products':
        if($view->current_display == 'block_1'){
            $nids = get_nid();
            $nids = !empty($nids) ? $nids : array(0);
            $query->where[1]['conditions'][2]['value'] = $nids;
            $query->where[1]['conditions'][2]['operator'] = 'IN';
        }
            break;
  }
}


Double slash in path of downloaded module

It's an artifact of how Drush builds the path. It looks at your Drupal project dir, and where it's placing the the project download, then appends it together without concern for a trailing slash in the Drupal project dir. It has nothing to do with your Drupal project file settings

Is it bug? Perhaps if you consider it a UX problem. As far as POSIX is concerned, the double slash is treated as one so it shouldn't matter in terms of referencing the directory. Whatever the case, drush pm-download is deprecated in later versions.


What limits the options in a Bulk Operations Menu (beyond their initial settings) regarding rule components?

If you are adding operations using Rules Component then you have to set the permission.

Edit your rule component and under the settings there will be Configure access for using this component with a permission., set your permission here.


How do I translate the Webform module form?

The Webform front-facing form was given the ability to be modified (and thus translated) in this issue: Make Webform multilingual (i18n) aware through contributed modules. That enhancement is already included in the latest versions of Webform, but that improvement is merely at the API-level; Webform module doesn't provide any translation abilities itself.

The add-on module that provides translation abilities for Webform is called Webform Localization, but it is currently only available as a sandbox project here: http://drupal.org/sandbox/GDrupal/1407100

The author of the module just recently (2 weeks ago) received the green-light to turn the module into a normal fully-promoted project, which will make it more easily accessible on Drupal.org.

The Webform Localization module provides two modes of translation, one that uses separate nodes and syncs certain webform settings between the nodes; and one that uses a single node and makes the strings available to translate through the i18n_strings module. The single-node approach is also what I've been advocating and I've tested that it works with this module. Only the single-node approach keeps all of the results from all languages aggregated together, with separate nodes the results are separate for each language.


NL and other languages visible, but English site not visible and showing error after translating news item

From the error msgs shown, it seems that you're using the TB Mega Menu module. So think of a way to get that module disabled (eg using the Dutch admin screens to disable a module, or using Drush if you have it available). That might possibly help to get rid of those errors again.

If you then also unpublish (or delete?) that news item where your problems started from, you may have a stable situation again. And from there continue your investigation to find the real cause (root) of your issue.

Doei!


Apply patch to the core: https://www.drupal.org/node/1927648
Install Rest UI using: drush dl restui-8.x-1.x
Go to /admin/config/services/rest and activate File /entity/file/{file}
Under /admin/people/permissions set all necessary permissions
Make sure files folder exists and has proper permissions
Encode image using command tool base64
POST to drupal.url/entity/file/

{"_links":
{
  "type":{"href":"http://drupal.url/rest/type/file/file"}
},
  "filename":[{"value":"input.jpg"}],
  "filemime":[{"value":"image/jpeg"}],
  "data":[{"value":"insert-output-from-base64-here"}] }


I recommend in the future to peruse the Module issue queue. :)

There are a number of patches in the following issue thread, one of which I've used to reset yearly (and actually modified to reset monthly): https://www.drupal.org/node/2168071


HTML / Mail System / SMTP Not sending approval in html

I believe drupal will only send text emails by default. You will need a module to help you implement HTML emails. I have used Mime Mail in the past to do this.

https://www.drupal.org/project/mimemail

From drupal.org:

  This is a Mime Mail component module (for use by other modules).

  It permits users to receive HTML email and can be used by other
  modules. The mail functionality accepts an HTML message body,
  mime-endcodes it and sends it.
  If the HTML has embedded graphics,
  these graphics are MIME-encoded and included as a message attachment.
  Adopts your site's style by automatically including your theme's
  stylesheet files in a themeable HTML message format
  If the
  recipient's preference is available and they prefer plaintext, the
  HTML will be converted to plain text and sent as-is. Otherwise, the
  email will be sent in themeable HTML with a plaintext alternative.
  Allows you to theme messages with a specific mailkey. Converts CSS
  styles into inline style attributes.
  Provides simple system actions
  and Rules actions to send HTML email with embedded images and
  attachments.


Are you sure the files are not temporary? It does sound like the files are being deleted because they are not yet permanent as Jayendra suggests.

Are you handling the file uploads yourself? Like through a custom form, because I've forgotten to save files permanently before, and I remember wasting a lot of time on it figuring it out :)

The temp files are cleaned with cron I believe, so I find it weird that altering your computer date would trigger the issue. They might however also be automatically cleaned up when you try to render an image that's not yet permanent, and that has passed it's 'lifetime'.


How to create a rule to perform a redirect if user is already logged in and visits the homepage?

Not sure if it will be your only problem to be fixed, but you seem to be using the wrong token in your condition path. Try again using either of these tokens:

[site:current-page:path].
[site:current-page:url].

Below is an example of a rule (in Rules Export format) which illustrates how to use either of these tokens:

{ "rules_redirect_logged_in_user" : {
    "LABEL" : "Redirect logged in user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node\/123" } },
          { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "something" } }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Using the path [site:current-page:path] (or url [site:current-page:url]) makes no sense for authenticated users, which is why you are redirected ..." } },
      { "redirect" : { "url" : "somewhere_else" } }
    ]
  }
}

Some more details about the above Rule:

Rules Event: Drupal is initializing.
Rules Conditions:

the user should NOT be anonymous, AND
either (or both) of these conditions must be true:
the path is node/123 (assuming your homepage is a node with nid=8, adapt to fit your case, or omit this condition if the next condition is sufficient for your case).
the url contains the text something (adapt to fit your case, or omit this condition if the previous condition is sufficient for your case). Instead of using Comparison operation contains you could also use starts with,  ends with or even a regular expression.

Rules Actions:

Show an appropriate message (adapt to fit your needs, or just omit it if you don't want such message at all, I like it for debugging purposes ...).
Perform a redirect to somewhere_else (adapt to fit your needs).

If you have the Rules UI enabled, you should be able to import the above rule in your own site. Then adapt it to fits your needs and you should be good to go.

Easy, no?


Using Ajax, how can I populate a div with Database Content from a form select?

You need to populate data in the ajax callback product_comparison_form_ajax and then return $form['results'].

Your code should be as the following:

Product comparison form

function product_comparison_form($form, &$form_state) {

  //Query DB for Rows
  $query = db_select('product_comparison');
  $query->fields('product_comparison', array('id', 'OtherCombo',));
  $query->condition('DropdownCategory', 'Exit Devices');
  $query->orderBy('OtherCombo', 'ASC');
  $results = $query->execute();

  //define rows
  $options = array();
  foreach ($results as $result) {
    $options[$result->id] = $result->OtherCombo;
  }

  $form['Exit Devices']['OtherCombo'] = array(
    '#type' => 'select',
    '#title' => t('Exit Devices'),
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'product_comparison_ajax_wrapper',
      'callback' => 'product_comparison_form_ajax'
    ),
  );

  // removed result condition

  $form['results'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => '
The results will appear here when you change the dropdown option.
',
  );

  return $form;
}

Product comparison ajax callback

function product_comparison_form_ajax(&$form, &$form_state) {
  if (isset($form_state['Exit Devices']['OtherCombo'])) {
    $row = db_select('product_comparison')
      ->fields('product_comparison', array('DesignHardware', 'DesignImg','DesignURL'))
      ->condition('OtherCombo', $form_state['Exit Devices']['OtherCombo'])
     ->execute();

    $header = array(
      array('data' => 'Design Hardware'),
      array('data' => 'Design Img'),
      array('data' => 'Design URL'),
    );

    $rows = array();
    foreach ($result as $row) {
      $rows[] = array('data' => (array) $row);
    }

    // assign result to markup
    $form['results']['#markup'] = theme('table',array('header' => $header, 'rows' => $rows));

  }

  return $form['results'];
}


I found the problem.

I was using user_load() in an earlier example, and was still using it rather than the uid.

The final access check should be...

function couples_page_custom_access($account = NULL) {
    global $user;
    $access = false;
    $node = node_load(arg(1)); // Get the nid from the URL of the CSV file.

    // If the UID of the currently logged in user matches the UID of the node author return true.
    if ($user->uid == $node->uid) {
      $access = true;
    }
    // Else check if the current user is admin so we can download what we like.
if (in_array('Admin', $user->roles)) {
  $access = true;
}
    return $access;

  }

I also added a check to return true if the current user is an Admin.

I really hope this helps someone else, and saves the time it took me to get to this!

Still, every days a school day!


Ubercart 3 check the stock before adding to the cart

Someone created a module for that already, needs some fixing IMHO, maybe you can play with that and make something better, I'll definitely be very thankful...


How can I filter nodes by term (entity reference) with jsonapi?

You were close, but your syntax was off. This is documented further down in your linked page, in the Filter Examples > Get nodes by a value of a entity reference section.
SHORT
filter[uid.id][value]=BB09E2CD-9487-44BC-B219-3DC03D6820CD

NORMAL
filter[author-filter][condition][path]=uid.id
filter[author-filter][condition][value]=BB09E2CD-9487-44BC-B219-3DC03D6820CD

So, in your example, you'd need to use:
SHORT
/jsonapi/node/my_content_type?filter[field_ref_term.id][value]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749

LONG
/jsonapi/node/my_content_type?filter[term-filter][condition][path]=field_ref_term.id&filter[term-filter][condition][value]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749


How to send a email message to specific user role when the site goes to the maintenance mode in drupal 7?

Checkout this module Maintenance mode API .

  Maintenance mode API notifies other modules when the site is switched into or from maintenance mode.

  This means that other modules can respond to this, for example:

  Alerting a list of users when the site goes into or out of maintenance mode

This module provides a hook, hook_change_maintenance_mode which any custom modules can interact

EDIT:

You can create a custom rule set with actions as send emails to your desired users. (An example guide how to create it).

Then invoke the rule set using rules_invoke_event() function inside the hook hook_change_maintenance_mode


Try this:

$form['design']['#states'] = array(
  'visible' => array(
    ':input[name="price"]' => array('!value' => 'other'),
  ),
);

though, to be honest I'm much more a fan of:

$form['design']['#states'] = array(
  'invisible' => array(
    ':input[name="price"]' => array('value' => 'other'),
  ),
);

Here are some good examples to follow. Not exactly your case, but close.


Programatically linking an image to content (Drupal 7)

You can use the l() function to wrap the image in a link. As it's HTML you'll need to pass the html option to the function so that it isn't run through check_plain():

$image = theme('image', $variables);

$linked_image = l($image, "node/$node->nid", array('html' => TRUE));

$rows[] = array(
  l($node->title, "node/$node->nid"),
  $linked_image,
  date($format, $node->changed)
);


Add a remove button to a custom unlimited value field?

there are two modules already

Multiple Fields Remove Button
Field Remove Item


Autocomplete Widget for Hierarchical Taxonomy

There is a module for that. Probably the only way to select multiple is to allow the field to have multiple values.
http://drupal.org/project/term_ref_autocomplete


module_invoke/module_invoke_all with multiple arguments

use

simplenews_subscribe_user($mail, $tid, $confirm, $source, $preferred_language);

or

module_invoke('simplenews', 'subscribe_user', $mail, $tid, $confirm, $source, $preferred_language);

module invoke is parsing all given arguements and handles them to the called function.

see php documentation regarding passing variables by reference, if that might bug you someday: http://php.net/manual/en/function.call-user-func-array.php#refsect1-function.call-user-func-array-notes


Creating a Views Search Page AND Block (not just a search block and results page)

Consider using a block with php filter to display the exposed search box in a block.

Example below is based on Search API with blocks exposed. I'm taking a guess you're using Search API based on your description.

For Search API:

$view = views_get_view('your_view_here');
$view->set_display('Page');
$view->init_handlers();
$exposed_form = $view->display_handler->get_plugin('exposed_form');
print $exposed_form->render_exposed_form(true);

For Drupal's Core Search:

$block = module_invoke('search', 'block_view');
print render($block['content']);


What is the difference between the $config and the $settings variables in settings.php?

Settings are for early-bootstrap (you can't store the database credentials in the database) and environment specific things, like the path to the public file system. Things that are not meant to be exported/deployed.

That means in almost all cases in modules, you want to use the configuration API.


Commerce Stripe and 2.0 version of library with namespace?

Download the 2.x uc_stripe version of the gateway for Stripe - it has code that works (https://www.drupal.org/project/uc_stripe) as you are seeking - the version 2.0 library uses \Stripe\Action-to-Take:: instead of Stripe_Action-to-Take::  Stripe Connect however is a whole other issue requiring a OAuth2 flow and JSON working with the Stripe Webhooks to get it working initially and THEN one can use the API for the rest of the issues for nmaintainance


In General Usage of Contributed Modules first steps to use any module is

Read Documentation of Project Page in D.O . You will find the link in the right side bar.

Readme or Install files inside Module Folder
Still if you are unable to figure out.. Visit .module file and focus on hook_menu implementation which lists menu paths as keys of $items array.. By visiting those pages you will get a chance to see configuration pages given by that particular module.

In your case

Enable i18n_menu module which has following module dependencies. I enabled using drush which automatically downloads and enabled below modules. In your case make sure below modules are present in your instance.

The following extensions will be enabled: i18n_menu, i18n_translation, i18n_string, variable, locale, i18n

Once you enable you can see "Translate" setting in any menu page. I just verified no other changes are required. Just clear cache once you enable module in case.


node_reference is just a sub-module of the References module; that's why you can't download it using Drush. Instead, download the References module.

drush dl references


I want to add user points whenever user like the page for Facebook. How can I do this?

First, you need to have your users login to your site using Facebook API. There are many modules for it, two I know and seen used are:

Facebook Connect
Facebook OAuth

That's the only real way to know "he" on Facebook is "he" on your site.

Then, Facebook will not push it's data to you. So you have 2 cases:

Button "like this page on Facebook" on your page - you can detect it being clicked and make a rule for it, as  Patrick Kenny told in his comment.
Like clicked directly on Facebook - now that's hard. It was discussed on stackoverflow with some apparently good results, and there are tutorials avaliable.

Last but not least - you need to make sure you grant this bonus only once. If not, users could fabricate points by simply repeatedly liking-unliking your page.


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

Will only append your function to the list of functions in the validation array.

I'm fairly certain using = array() won't work because that's how you define an array, not how you empty one.

Modified answer from Stack Overflow:

  Use unset, if you need the array later on just instantiate it again.

unset($form['#validate']);
$form['#validate'] = array();


Need to add meta tags in custom page created by custom module

A programmatical solution could be to use something like this. you could put it in a preprocess hook in your template.php

$path_alias = drupal_get_path_alias();

  if ($path_alias == 'thepathofmypage') {
    $meta_head_blog = array(
      '#type' => 'markup',
       '#markup' => '<meta name="title" content="My metatag title"><meta name="description" content="My metatag desc">',
);
drupal_add_html_head($meta_head_blog, 'metaHeadBlog');


How do I flag and categorize Drupal Commerce related products?

The core taxonomy module offers a flexible system for sorting content. You can easily build views based on content type and taxonomy.


As you mentioned, User protect should work well. Combine this with Role Delegation to restrict what roles they can assign.

Might also be worth keeping an eye on the Administer Users by Role module, although there is no D7 port yet (in progress here).

Let me know how it turns out as I'm going to be solving this issue on the site I'm working on soon.


The last time I added Panels to a site, I used this code to preload the required libraries on panels edit pages.

  // Panels support.
  if (module_exists('panels') && $form_id == 'panels_edit_display') {
    // Load potential editor.
    foreach (filter_formats() as $format => $object) {
      if ($profile = wysiwyg_get_profile($format)) {
        wysiwyg_load_editor($profile);
        wysiwyg_add_plugin_settings($profile);
        wysiwyg_add_editor_settings($profile, 'advanced');
      }
    }
  }

From http://drupal.org/node/356480#comment-1190907 and the patch located in http://drupal.org/node/356480#comment-4256204.

This setup worked with:

Drupal 7.0
Latest WYSIWYG 7.x-2.x-dev from git
CKEditor 3.6
Panels 7.x-3.0-alpha3
CTools 7.x-1.0-alpha4


Is it possible to cancel a delete request for a node or media item?

Have you considered the new Content Moderation module in core? It should provide the desired functionality.


The title override module utilizes drupal_set_title() to do this in Drupal 7. This function is deprecated in Drupal 8. The D8 equivalent here is to alter the _title_callback for the entity.user.edit_form route.

This is done by using an event subscriber to alter the RoutingEvents::ALTER event. This can be done through a custom module that:

Registering a new service class in mymodule.services.yml that is tagged with event_subscriber (see d.o. documentation example).
Defining the new service class to extend RouteSubscriberBase (see d.o. documentation example).
Implementing the alterRoutes(RouteCollection $collection) method within the service class to alter the entity.user.edit_form route (see example below).
A class/method that defines the title callback (see UserController::userTitle() as an example).

Within your route subscriber class:

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    // Retrieve the user edit form route.
    if ($route = $collection->get('entity.user.edit_form')) {
      // Your module will need a controller class/method defined in
      // src/Controller/CustomUserController::userTitle
      // see core/modules/user/src/Controller/UserController.php to see how this
      // is implemented by default
      $route->setDefault('_title_callback','Drupal\mymodule\Controller\CustomUserController::userTitle');
    }
  }


How to generate a list of field items using the field item name programmatically in Drupal 7?

You're pretty much on the right track. Try something like:

function blocks_preprocess_node(&$vars) {
  $node = $vars['node'];
  if ($node->type == 'portfolio') {
    $portfolios = field_get_items('node', $node, 'field_portfolio_description');
    $items = array();
    foreach ($portfolios as $folio) {
      $items['data'] = $folio['value'];
    }
    $vars['description'] = theme('item_list', array('items' => $items));
  }
}

Adding stuff to nodes like this is maybe better in hook_node_view() in a custom Module. Because you're altering the node's content before its shown (and its adding derived content to the node, not just changing some markup at the theme layer).

Code is untested and just Help. (but should mostly work)

Resources

theme_item_list function docs
field_get_items function docs
alternatively create a "Code Field" using Display suite to encapsulate this custom code field to a view_mode (aka, magic). See this tutorial on youtube on DS and custom fields.


Here's a checklist of things to look at:

Drupal simply concatenates files during aggregation. Malformed scripts may cause the entire thing to blow up. Disable aggregation first to see the code in plain so it's easier to debug.
Aggregation can also lead to some weird issues together with caching. Ensure that you've refreshed the cache for both Drupal, browser and any external file systems (i.e. S3) to ensure that you're working with updated code and content.
Malformed CSS, believe it or not, can also cause aggregation to blow up. Chrome does not show any error of this happening. However, Firefox prints a warning if it does. Debug in Firefox to see some errors not shown by Chrome.
If you're using S3 for storage, ensure that all of your resources are present. Sometimes, the file may not be accessible from S3, fail to upload to S3, or just be missing (i.e. deleted accidentally).
You already mentioned disabling admin menu caching. That has solved this problem for me in two projects.
Clear all caches (drush cc all). Always worked. :D


View to display 2 posts from 1 content type 1 and 2 posts from content type 2

I have a multipart part answer to this question:

No, there's no way to do show exactly two nodes of one content type and two of another type using only 1 view if you want them grouped in a specific order.
If you don't care about that nodes of different content types are mixed up together, you can change your content-type filter to include multiple content types. This only uses one view but may not be exactly what you want.
If you give up on using only 1 view, Kojo's comment lays out an excellent and quick way to embed views inside of another view to create the desired effect. Just to recap: create one view for each content type, and put one of the views in the header of the other view. This gives the desired effect, but gives up on using only 1 view.
You could use a SQL query like this to create a custom theme hook that would have the intended effect without using Views at all. It would require SQL knowledge to maintain it, but it would also have a lot less overhead. Here's what you'd need to do:

Inside template.php in your theme:

<?php
/**
 * Implements hook_theme().
 *
 * This registers a custom function for use with the theme() function.
 * To make your featured nodes show up in a template, add this code:
 *
 *   print theme('featured_nodes');
 *
 * Whenever theme() is called with that argument, a certain preprocess function
 * will be called. I like to write SQL in those preprocess functions to
 * find raw data from the database. Then a template will be used to display
 * the information looked up in the preprocess function. Finally, the template
 * is returned as a string wherever theme() was originally called.
 *
 * Look up hook_theme in the API docs at http://api.drupal.org/ for more info.
 */
function mytheme_theme() {
    return array(
        'features_nodes'] = array(
            // Here I define which template should be used.
            // In this case, the template will be called featured-nodes.tpl.php
            'template' => 'featured-nodes',
        )
    );
}

/**
 * Implements hook_preprocess_hook().
 *
 * This function is triggered before the template is rendered. You can
 * pass variables into the template simply by adding them to $vars.
 */
function mytheme_preprocess_features_nodes(&$vars) {
    // This is a really simple query that looks up all the fields
    // on the node table for the 2 most recent nodes of type 1,
    // then it adds all the fields of the 2 most recent nodes of type 2.
    // Learning SQL is bigger than the scope of this question.
    $results = db_query('
        SELECT *
          FROM {node}
         WHERE type = "machine_name_of_content_type_1"
         LIMIT 2
      ORDER BY created DESC
         UNION
        SELECT *
          FROM {node}
         WHERE type = "machine_name_of_content_type_2"
      ORDER BY created DESC
         LIMIT 2
    ');
    $featured_nodes = array();

    // We use db_fetch_object() repeatedly to read out each result row.
    while ($row = db_fetch_object($result)) {
        $featured_nodes[] = $row;
    }

    // Anything in $vars will be added to the templates when they are rendered.
    $vars['featured_nodes'] = $featured_nodes;
}

Then, inside featured-nodes.tpl you'll have access the $featured_nodes variable and you can display some very basic information about the nodes that you want (nid, title, author, and created date).

Here's an example of what should go inside featured-nodes.tpl.php:

    <?php foreach ($featured_nodes as $node) : ?>

<?php print l($node->title, "node/{$node->nid}"); ?>

    <?php endforeach; ?>

NOTE: None of the above code is tested and it may require some tweaking.

Here's an in-depth blog post I wrote with more information on how and why to do version 4.


There is just a module that integrates Ext in Drupal that I know of: the Ext module.

  Loads the Ext JavaScript library (version 2.2 & 2.3 for now) with Drupal. Other modules requiring Ext may use this module as a basis, or it may run on its own, simply loading the Ext library.

  Note: A new version of this module is being developed to provide relatively comprehensive integration functions with Ext 4.x (currently 4.1). For details please see http://drupal.org/node/1316616.

The module doesn't have a version for Drupal 7, though.


How to edit a node programatically after it has been created?

If you look at the Node API Hooks description here, you will see that hook_node_insert is called after field_attach_insert. That means that at the point hook_node_insert is called the fields for the node are already written to the database. If you keep your code in top_node_insert, then add field_attach_update('node', $node) to update the fields with the new data. It might look something like this:

function top_node_insert($node) {
  $top = views_get_view_result('top_3');

  $found = false;
  foreach($top as $key => $value) {
    if ($value->nid == $node->nid) {
        $found = true;
        break;
    }
  }

  if ($found) {
    $ranking = $key + 1;
    $node->field_hoogste_ranking[LANGUAGE_NONE][0]['value'] = $ranking;
    field_attach_update('node', $node);
  }
}

Alternatively, you can try and use hook_node_presave.


How do I show the number of nodes using a taxonomy term?

The following worked for me in Drupal-8.0.6.

Note that for some reason 'Content NID' is not offered as a field for the 'Content with term' relationship, so I used UUID instead and it worked.

Create a Taxonomy Term view (with a field Taxonomy term: name, usually linked to the term page)
Relationship > Taxonomy term: Content with term (will be called node).
Advanced: Use aggregation: Yes
Add Field > Content: UUID with relationship node
Aggregation type for UUID = Count

You may have to play with COUNT vs COUNT distinct

If you want tbe count to appear in brackets like this:

linked_term (count)

On UUID field use Rewrite results:

({{ uuid }})

Note that it is using the new Twig template language notation.


REST API OAuth Authorization and Authentication

Actually, I got the solution. It was my mistake, that I was trying to use OAuth2 3-legged authorization, but I am actually need OAuth 2-legged authorization.
More Details on oAuth Flow and Grant Types: oAuth Grant Types


You could cache the content and displaying it cached would ideally take stress off your database. Check out module "Boost" it can help.

Ideally optimization of the site is what is needed along with better hardware and maybe Varnish.

If you are using views consider using views built in cache with time based expiration to take stress off database.

Update

If you already have Varnish, APC and memcache then the only other think you can really do is get some better hardware.

We have servers that get about double what you have and they run on a quad core processor with 32GB of RAM.

We also split Web and DB server so we can utilize APC for Web Server and memcache for DB server.

Have you checked your APC stats? Varnish probably won't do much unless you configure it to cache Authenticated traffic which by default bypasses Varnish.

What are your server stats?


Change Ubercart shipping/billing layout & logic?

You can change the order here:

admin/store/settings/checkout/edit/panes

But you cannot dynamically determine whether the shipping is required. (at least not without tweaking the code.)

Do you really need to offer both anyway? (how often person A buys tickets that need to be sent to person B?)


You can use hook_views_query_alter(&$view, &$query)
here you can pass extra sorting more sorting fields

http://www.chrisfree.me/2010/12/use-hookviewsqueryalter-handle-special-sort-cases
please check this link


Main Navigation Menu: Throwing out the old and making a new

Search for a module called nice menus.

Another option is to create a custom block and inside it query the db yourself for the main menu links.
You can also add the contextual list links button to your block.


How to keep Views argument results in panels display

Ok, I think I have this sorted out but wouldn't mind some advice if I went about it the wrong way.  To recap, the goal was to have a list of previous programs sorted by year and have that results page stay within the layout set in Panels.

Within Views

Create a Content Pane to filter out only the programs content type with the Argument set to display a 'Summary, sorted descending' based on the year of the program.  This will be used to display just the years of the previous programs in a list and will be added to main Programs page.
Create a Page to filter out only the programs content type with the same Arguments.  Set the path of this page to 'programs/previous'.  This will be used to view the actual results of the list created above.

Within Panels

Create a new Page with the Path set to 'programs/previous/%view'.  In the Arguments section, set it to Managed Page.  In the Content section add the page created within Views and make sure the Send Arguments option is checked.
Within Node Template (which controls the main layout of the entire site), add the Content Pane to the Programs page.

Therefore, when a visitor goes to the main Programs page ('/programs'), they will see a list of the previous programs in the right hand corner and clicking on each one will bring them to the appropriate page (such as '/programs/previous/2001') while keeping everything in Panels.

I'm a little confused as to how all works (for instance, how does the Content Pane inherit the '/programs/previous' path from the Page?) but am glad it works as planned.  Hope this helps others and please don't hesitate to let me know if I could have achieved this in a simpler way!

Bob


How to show user profle edit tab as a default tab on user profile page?

You could use the Redirect module to redirect users from /user/* to /user/*/edit. This could cause problems when other users are trying to view other user's profiles.

You can also do this with Rules. This would allow you to redirect users conditionally.


Method #1: (No subit button, requires JS, loads all views at once but shows conditionally)

<?php
function MYMODULE_my_custom_form($form, &$form_state) {
  $options = array();
  $options['view_one'] = 'view_one';
  $options['view_two'] = 'view_two';
  $options['view_three'] = 'view_three';

  $form['chooseview']=array(
    '#title' => t('Choose a View'),
    '#description' => t('Which View do you want to display?'),
    '#type' => 'select',
    '#name' => 'chooseview',
    '#required' => TRUE,
    '#options' => $options,
  );
  foreach ($options as $view_name) {
    $form['display'][$view_name] = array(
      '#type' => 'markup', // Not necessary - just to be clear.
      '#markup' => views_embed_view($view_name, 'block_1'),
      '#states' => array(
        'visible' => array(
          ':input[name="chooseview"]' => array('value' => $view_name),
        ),
      ),
    );
  }
  return $form;
?>

(short, eh)

Method #2: (Submit button, JS-independent, loads only view when necessary)
Note we pass $form_state to the form builder function by reference.

<?php
function MYMODULE_my_custom_form($form, &$form_state) {
  $options = array();
  $options['view_one'] = 'view_one';
  $options['view_two'] = 'view_two';
  $options['view_three'] = 'view_three';

  $form['chooseview']=array(
    '#title' => t('Choose a View'),
    '#description' => t('Which View do you want to display?'),
    '#type' => 'select',
    '#name' => 'chooseview',
    '#required' => TRUE,
    '#options' => $options,
  );
  $form['show_me'] = array(
    '#type' => 'submit',
    '#value' => t('Show me, please!'),
  );
  if (!empty($form_state['values']['chooseview'])) {
    $form['display'][$view_name] = array(
      '#type' => 'markup', // Not necessary - just to be clear.
      '#markup' => views_embed_view($form_state['values']['chooseview'], 'block_1'),
    );
  }
}

function MYMODULE_my_custom_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}
?>


Show block on specific pages URL attribute

You can use PHP visibility on your block settings to achieve this. Drupal block's visibility does not provide the functionality to display blocks based on parameters after ? (aside from ?q= of course) so you need to do this with custom PHP.

Set your block visibility to use PHP as the markup and place this in your code:

<?php
// Show the block if the 'showblock' attribute is available
if (!empty($_GET['showblock'])) {
  return TRUE;
}
return FALSE;

?>

Happy Programming!


You can use the Embedded Google Docs Viewer module for that

  Drupal 8

  This module provides a formatter for the File field type. This
  formatter presents the file as a fully rendered object within a web
  page - i.e. it displays the contents of the file as appropriate to its
  filetype (Adobe Acrobat .pdf, Microsoft Word .doc/.docx, Microsoft
  Excel .xls/.xlsx, Microsoft Powerpoint .ppt/.pptx), using the Google
  Docs embedded rendering engine.

There are some other modules but those are in Dev version. Have a look at the Comparison of PDF viewer modules


What is the best way to pass values from one form to another with fapi?

You can do a multistep form, there is a clear usage example in the Examples module. Here is an excerpt about it from the module's project page:

The Examples for Developers project aims to provide high-quality, well-documented API examples for a broad range of Drupal core functionality.
The Examples project contains many modules which hopefully illustrate best practices for implementing various Drupal APIs. These modules can be enabled individually, and will typically add menu items to your site, which should guide you through their features. You can then look through the code to see what they are doing.
Developers can learn how to use a particular API quickly by experimenting with the examples, and adapt them for their own use.
Note also that these modules demonstrate internals for Drupal development in PHP (and some JavaScript). Not all Drupal users will need these examples. There are many contributed modules which will do the majority of what a Drupal site-builder could need. Be sure and explore other contributed modules to see if you can find one that meets your needs.


Displaying a standard picture when user has not uploaded a picture

Basing on the code used by template_preprocess_user_picture(), I would suggest the following code.

if (!empty($user->picture)) {
  if (is_numeric($user->picture)) {
    $account->picture = file_load($user->picture);
  }
  if (!empty($user->picture->uri)) {
    $filepath = $user->picture->uri;
  }
}
elseif (variable_get('user_picture_default', '')) {
  $filepath = variable_get('user_picture_default', '');
}
if (isset($filepath)) {
  $alt = t("@user's picture", array('@user' => format_username($account)));
  if (module_exists('image') && file_valid_uri($filepath)) {
    $user_picture = theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
  }
  else {
    $user_picture = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
  }
}

If you didn't need to use a specific style, but you could use the one set in Drupal settings, the code would simply be the following one.

$user_picture = theme('user_picture', array('account' => $user));

Keep in mind that there are some places where Drupal already shows the user's picture. If you just need to change the image style used for the user's picture, that is possible from Drupal settings (see this other answer). If you need to show the user's picture in a page where Drupal doesn't show them, I would set the default image style for the user's picture in Drupal's admin settings, and use the following code.

$user_picture = theme('user_picture', array('account' => $user));


How can i set the value of first field to the second in same form

I finally got an answer and would like to post it here, to help someone who may run into this problem as well.

public function buildForm(array $form, FormStateInterface $form_state) {

     //SET THE VALUE HERE
     $form_state->setValue('store_value', 'The stored value is: Angeline
     Mnene');

     $form['container']['#tree'] = TRUE;
     $form['container']['#type'] = 'container';
     $form['container']['show_value'] = [
         '#type' => 'markup',
         '#markup' => 'The stored value is: ' . $form_state-
          >getValue('store_value'),
     ];

     return $form;
}


How to theme regions in non-standard themes like Consilium?

regions are normally defined in the [theme_name].info file in the theme directory. Here is an example from the Bartik theme:

  name = Bartik

  description = A flexible, recolorable theme with many regions.

  package = Core

  version = VERSION

  core = 7.x

  stylesheets[all][] = css/layout.css

  stylesheets[all][] = css/style.css

  stylesheets[all][] = css/colors.css

  stylesheets[print][] = css/print.css

  regions[header] = Header

  regions[help] = Help

  regions[page_top] = Page top

  regions[page_bottom] = Page bottom

  regions[highlighted] = Highlighted


Is there a callback for the managed_file form element, called on succesful upload?

For the PHP side, use #upload_validators as described in Form API docs. They are fired after upload, just like you want them to be. In Drupal everything that's supposed to happen between user's input and actual form save, happens in validators. Pretty weird, but that's the way it is.

For an JavaScript part, element's description says:

  The #managed_file element is expanded into a set of FAPI elements including two '#submit' buttons one for Upload one for Remove, a '#file' element and a handful of '#hidden' and '#markup' elements to handle progress indication and displaying of already uploaded files.

Thus, while it does not have any '#ajax' property, you can try to access it's internals with your own custom code. Notably, successful file upload makes delete button visible. But internals can be refactored without notice, so be careful about that.


What is the purpose of drush entity-updates?

drush entity-updates is a developer tool. If you change entity/field definitions in your custom module you can quickly apply this.

In production this should not happen. If you update a module between official releases, then the update code in the module should handle this.

But in your case you are mentioning that your site is in developing. So there are a lot of things, which could have caused this. Either in your own code or in dev or alpha versions of contrib modules.

I found this example from the CR Write update functions for entity schema updates, automation removed (where there are further examples):

/**
 * Add 'revision_translation_affected' field to 'node' entities.
 */
function node_update_8001() {
  // Install the definition that this field had in
  // \Drupal\node\Entity\Node::baseFieldDefinitions()
  // at the time that this update function was written. If/when code is
  // deployed that changes that definition, the corresponding module must
  // implement an update function that invokes
  // \Drupal::entityDefinitionUpdateManager()->updateFieldStorageDefinition()
  // with the new definition.
  $storage_definition = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Revision translation affected'))
      ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
      ->setReadOnly(TRUE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('revision_translation_affected', 'node', 'node', $storage_definition);
}


How can i create theme's block width should be configured from dynamically

You could use a theme thats already done this...

http://drupal.org/project/adaptivetheme

http://drupal.org/project/omega/


How to call a function in template.php through ajax from a page?

I would recommend using the Ajax Framework in Drupal 7 core: http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7.

You will need to create a callback through hook_menu which will return the html you want to load.

See the examples module for how to do this. The two functions show adding a link and using the 'use-ajax' class and creating a link using a render array:
http://drupalcode.org/project/examples.git/blob/refs/heads/7.x-1.x:/ajax_example/ajax_example_misc.inc

They both link to 'ajax_link_callback' which calls the other function ajax_link_response().

'ajax_link_callback' is defined in hook menu like so:

 180   // A menu callback is required when using ajax outside of the Form API.
 181   $items['ajax_link_callback'] = array(
 182     'page callback' => 'ajax_link_response',
 183     'access callback' => 'user_access',
 184     'access arguments' => array('access content'),
 185     'type' => MENU_CALLBACK,
 186     'file' => 'ajax_example_misc.inc',
 187   );


how to alter only one set of specific forms?

In the case you need, so you can easily use control flow in your hook_form_alter

You know that the hook runs everytime a form is willing to be rendered, so you can easily do something like

hook_form_alter(&$form, &$form_state, $form_id){

if($form_id == 'A_node_form'){...}//alter form A

if($form_id == 'B_node_form'){...}//alter form B

if($form_id == 'C_node_form'){...}//alter form C

}


Is there any way to adjust the items per block options?

Thanks to the answer @Berdir provided, I've been able to replace the restrictive select field with a more flexible number field.
In mymodule.module
The form_id is block_form (andpanels_edit_block_form and panels_add_block_form for Panelizer). Change the #type to number to make it so that you can input a number. Unset the #options to avoid validation errors (Invalid choice).
/**
 * Implements hook_form_alter.
 *
 * Changes the input type of the "Items per block" setting of
 * a view-block in Blocks/Panelizer from 'select' to 'number',
 * so that amounts other than 5, 10, 20 and 40 can be chosen.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (in_array($form_id, ['block_form', 'panels_edit_block_form', 'panels_add_block_form'])) {
    if (isset($form['settings']['override']['items_per_page'])) {
      $form['settings']['override']['items_per_page']['#type'] = 'number';
      unset($form['settings']['override']['items_per_page']['#options']);
    }
  }
}


This was very strange issue, now solved, but can't texactly the point that solved it, as i ran extensive code/config sweep both on code / server side. (Including Apache restarts, MySQL restarts, module maintance (many unused gone with the wind), APC configs, and running registry rebuids.