Let the user set the target of the link in a link field

You can use https://www.drupal.org/project/link_attributes for that. No, it is not in core.


How to create a message with message stack when user becomes a member of a group module group?

It looks like the membership relationship is stored as a GroupContent entity, so in theory you would use something like hook_ENTITY_TYPE_insert()as your event:
function MODULE_group_content_insert(\Drupal\group\Entity\GroupContentInterface $group_content) {
  // This will fire for all types of group content so make sure to filter
  if ($group_content->getContentPlugin()->getPluginId() == 'group_membership') {
    $account = $group_content->getEntity();
    $group = $group_content->getGroup();
    // Create the message
  }
}

This is untested so may need tweaking, but it should be close enough to get going.


Auto-collapsing fieldsets on user_profile_form

You want to use hook_form_alter here.

THEME_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_profile_form")
    {
        $form["FIELDSET"]["#collapsible"] = true;
        $form["FIELDSET"]["#collapsed"] = true;
    }
}


How to use Tokens [current page arguments]?

If you want to use tokens with taxonomy terms urls you have to enable token, pathauto and Chaos tools module. You can do it by runing drush command
drush en pathauto -y
After these modules are enabled go to admin/config/search/path/patterns

Hope this is what you asked about.


7 - Sorting a Views exposed filter options alphabetically

J. Reynolds suggestion was the answer.

Creating a new function for the sort code and using $form['#after_build'] to call it resulted in the select box being sorted alphabetically.

function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {
    $form['#after_build'][] = '_sort_alphabetically';
  }
}
function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}


How do I revert all of my DB tables from MyISAM back to InnoDB?

The easiest way is to take a backup with Backup and Migrate, open it in an editor and search/replace "MyISAM" to "InnoDB".  Then restore it.

Personally, I would restore to a new catalog, and then switch the database in settings.php.  This way, you can test before making the new version live.

Otherwise, this is a dup of How do I convert a database from MyISAM to InnoDB?


How do I limit access to a custom field type I have created so that it can only be attached to certain bundles of content?

It is not possible to define field types which are only applicable to certain bundles. I think you need hook_form_alter for the form where the fields are chosen for a bundle to achieve that.


Migrations dependencies: run one by one?

First of all, you only need two yaml files, one for the default language and one for the translations.

If you are migrating for example a content type of bundle pages and your default language migration is eg. my_website_migrate_node_page, then in the my_website_migrate_node_page_translation define your dependencies as follows

migration_dependencies:
  required:
    - my_website_migrate_node_page
  optional: { }


Can I use Pathauto with additional url values?

The Sub-pathauto module is for exactly that purpose.

  The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.

  For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.


I would install both module, set the Lightbox field format in your view, and then try to replicate the output used by the hover_preview module. If you use the browser inspector you will notice that you need two images in top of each other and some classes assigned to them in order to work.

In your view, add those images fields and rewrite the results. See image attached. I hope it helps.


Undefined index $base_path in include(), line 7 of page--front.tpl.php

$base_path is a global variable which should definitely be available in your theme's page template files.

I would guess your theme is doing something to remove that var (perhaps in a preprocess function). You can easily solve the problem using one of the following:

Using a call to the base_path() function instead of $base_path.
Using $GLOBALS['base_path'] in place of$base_path`.
Adding the line <?php global $base_path; ?> to the top of your page template file(s)


First install Fieldable Panels Panes module. This module allows you to create different fields for Panels pane. Then go to admin/structure/fieldable-panels-panes, Click on Manage Fields of Panes Pane

Add an image field, It is going to be like this

Now click on Add Entity tab and create a new entity. You must also create a Category in Reusability, This Category will be displayed in the Panels Content menu, I called it My own Panels Pane

Now save it.

If you open a Panel and click on Add content the My own Panels Pane is available, click on it and select the content you created.

From the list of Panels Pane in Fieldable Panels Pane there is a direct link to edit this image. I mean this (for testing I created 3 entities ):

Now you can easily edit the image and use it's direct link.


How do you access custom user information added from: Configuration » People » Account settings

try $account = user_load($user -> uid) after global $user and then dsm($account) or print_r($account);,
global $user get only basic data of object I think


Assuming that Your Drupal 7 site is a new site (not upgraded from a D6 installation), I think the best approach is to use the Profile 2 module (dependent on Entity API) and add a file field to the user profile.


The item of an unregistered user's cart is shown a different unregistered user

The reason for the behavior described above is that in Views I changed the advanced option context filter - order id - for "if there is no value for the context filter" from: "static" (the option after installation, which had the effect that no cart was shown at all) to "show all results" (with the effect described above).

I found this link https://www.drupal4u.org/howtos/how-hide-empty-shopping-cart-drupal-commerce saying the correct value would be "Current user's cart order ID", but this was not available. I'm not sure if this is a bug, if things changed for Commerce 2 or if I configured something wrong.


Get image's URL as a token for use in Views' replacement pattern

I ended up using a module to create a custom formatter.  Image URL Formatter http://drupal.org/project/image_url_formatter .  It created a new formatter option called "Image URL," and I can use that as a token.


Translate text on the front page with t()

You need to activate the locale module.

Under "Admin >> Configuration" you find a section regional and language.
Add a new language, and set it as default language; after that, you can use the 'translate interface' to translate the strings wrapped in t() for your new language.


You can change this setting directly in the settings.php. You've a line that looks like that :

ini_set('session.cookie_lifetime', 2000000);

Change 2000000 to 0 and you will get what you want.


Go with CCK.

I've done this in Drupal 5, and I'm doing it again for Drupal 6.  It's really not that hard to get this going.  You gets all kinds of things for free both with CCK and Views.  You already mentioned the benefits for Views, but it's the same for CCK.  You simply create everything you need from the UI, and then export it to a file that gets read during your install hook.

Also, why write your own CRUD?

I'm doing something very similar.  Take a look at my code over at Syndeploy.

I haven't exported the Views code yet, but I'll get there.


Add Object in json file generate by services module drupal

The JSON is generated by the RESTServerViewBuiltIn class in the services/servers/rest_server/includes/rest_server.views.inc file, specifically the render_json member function.

Services does provide a way to override this.

Firstly in a custom module implement hook_rest_server_response_formatters_alter and change the View class that's used to render the output to a custom one:

function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['json']['view'] = 'RESTServerViewMYMODULE';
}

Then add your custom View class (I'd keep this in the module file to avoid having to load includes):

class RESTServerViewMYMODULE extends RESTServerView {
  public function render() {
    $new_data = new stdClass;
    $new_data->some_key = $this->model;

    $json = str_replace('\\/', '/', json_encode($new_data));

    return $json;
  }
}

Hope that helps


Views - Add a wrapper DIV around a Group

I needed to do this same thing recently. You can create a template file:

Find the template under /modules/views/themes/views-view-unformatted.tpl.php.
Copy it into your /sites/all/themes/<your-theme> folder and rename to views-view-unformatted--<nodetype>.tpl.php.
Edit the file adding a div around the entire template. The
 tag is the group name.

Here is what the modified template file might look like.

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>


Why doesn't a cloned theme work as the original theme?

In template.php the functions that begin with the template name e.g. themename_preprocess_page need to be renamed to have the new theme name in them e.g. newthemename_preprocess_page.


As I am always against adding PHP code in the UI may I suggest a different approach?

Add a relationship to your view "Content: age group", which is the relationship from your term reference field to the taxonomy term.

Then add a contextual filter "Taxonomy term: Name", using the relationship you just added.

Then the argument will be the term name without you having to add custom PHP code.


You query is looking for nodes that are tagged with a term that has an empty label. Obviously that's not what you want. What you're looking for is notExists():

$query = \Drupal::entityQuery('node')
  ->condition('type', 'mycontenttype', '=')
  ->notExists('field_grade_level');

$nids = $query->execute();
return $nids;


Yes.  How you fix this depends on what you built and what you did.   You did not say if you built a Drupal 6 or 7 site.  It makes a big difference.  You also did not say what mods you made to the settings.php file if any when you uploaded this new site.

Your
$base_protocol
$base_url

AND a $conf statement as to HTTPS will need to be properly set - depending on which version of Drupal you are using

You may need to modify the DNS zone to accept a wildcard for the domain depending on what kind of site and content it already has and the

$cookie_domain may need to be properly addressed or Drupal (depending on which one you have ) may drop sessions and log people out by dropping the session if they switch between secures pages classes.  See the issues que of secure pages for examples - and make sure you are looking at the issue that has to do with whichever version you have installed - Drupal 7 and Drupal 6 respond completely differently to SSL and HTTPS issues  See https://www.drupal.org/project/issues/securepages?categories=All

See https://www.drupal.org/https-information for a head start and pointers

As to getting the admin pages to work - usually creating and setting $conf['https'] = FALSE;  should allow http access again by forcing the entire site to non-secure


Verify if you have enabled “Count content views” within Statistics module configuration.
(admin/config/system/statistics for D7)


Add this to your theme's template.php file:

function THEME_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-views-portfolio-view-block")
    $variables['block_html_id'] = "portfolio";

}


Here you go:

    if(isset($content['product:field_course_no_']['#object']->field_pd_number['und'][0]['safe_value'])){
     $my_field_value =  $content['product:field_course_no_']['#object']->field_pd_number['und'][0]['safe_value'];
} else {
        $my_field_value = '';
}


Noob question about private files and Content Access

I believe that this issue was fixed in SA-CORE-2012-002 - Drupal core multiple vulnerabilities instead of being posted to a public site like this. In the future something like this should be reported to the security team. And, if upgrading Drupal core doesn't fix your bug let's discuss more details by having you submit a new Core security issue where we can figure out what's going on in private and then, if appropriate, release a patch that fixes the bug.


Is it possible to configure read count from Statistics module?

You can add a count field to your blog content type, ban access of editing or creating this field using Field Permissions for other users (they just can read) now you can set its starting value.

Then using Rules module you can create an action in a way that with each viewing of blog posts this fields value increase by one.


How to import a live Drupal site into Acquia Drupal Dev Desktop?

First, use the Backup and Migrate module to create a copy of the database. Then download all the Drupal site files to your machine as well.

You can set up a local version by using the import option Acquia Drupal Dev Desktop instead of creating a new site and importing the Drupal files you just downloaded.

Then use the Backup and Migrate module again on the local site to synchronise the database.


Is there a way to clear the cache without dropping tables?

As Kevin correctly points out in the comments, the cache clear is issuing a TRUNCATE command rather than DROP, but TRUNCATE does require the DROP permission.

If you look at the manual installation method in the install guide, you'll see that DROP is one of the permissions that is granted as part of the setup process:

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES ON databasename.* TO 'username'@'localhost' IDENTIFIED BY 'password';

That's followed shortly after by:

  Note: Unless the database user/host combination for your Drupal installation has all of the privileges listed above (except possibly CREATE TEMPORARY TABLES, which is currently only used by Drupal core automated tests and some contributed modules), you will not be able to install or run Drupal.

So DROP is simply a required permission for Drupal to work.


The base theme should be set to the machine name of the Base Theme. The machine name is the same as the name of the directory that contains it. Yours starts with a capital letter. I imagine that the folder is just master (all lowercase).

Because the .info file is cached, you must clear the cache before any changes are displayed in your site.

Writing theme .info files


Node reference + i18n - How to display only referenced nodes for the current language?

If it would be an option for you to switch from using node reference to entity reference, then you could try to use the Translated Entity Reference module. From its project page:

  ... brings better i18n support to Entity Reference field selection widget.


The Umami demo: Content module is not found from Drush, nor is it visible in the list of modules, because it is set as hidden in demo_umami_content.info.yml. If you change the hidden: true line in hidden: false, you will be able to uninstall the module, and re-install it. This will execute again demo_umami_content_install(), which imports the content.

/**
 * Implements hook_install().
 */
function demo_umami_content_install() {
  if (!\Drupal::service('config.installer')->isSyncing()) {
    \Drupal::classResolver(InstallHelper::class)->importContent();
  }
}

If that doesn't work, the alternative is re-install Drupal using Unami as installation profile.


Show related Content type content in block filtered by category

At first, category and sub-category should be in Drupal-terms. Taxonomy vocabulary, taxonomy terms etc.

Assuming your related content block is created with contextual filters.

You can add these contextual filters to your views:

Content: Has taxonomy term ID (with depth)

Display content if it has the selected taxonomy terms, or children of the selected terms. Due to additional complexity, this has fewer options than the versions without depth.

Content: Has taxonomy term ID depth modifier

Allows the "depth" for Taxonomy: Term ID (with depth) to be modified via an additional contextual filter value.


Complicated content/node access scenario, input wanted

Well, just for anyone who stumbles upon this in the future, DO write your own content access module. Once you grasp the logic it's quite simple and it will solve your problems while allowing you to keep the logic of other modules involved in your project. Simply copy their code/logic and set it along with the rest of your requirements with higher priority.


How can I build a view that shows other nodes that reference the same node the current node references?

You should be able to do this with a relationship. Add the neighborhood node reference field as the relationship.  Add NID as your argument and apply the neighborhood relationship that you just created as the relationship to that NID argument. This will tell views to use the NID of the node reference field as the argument.


If you want to update the content of existing entity than you may use field_attach_update($entity_type, $entity): this saves field data for an existing entity.

Example:

$art = node_load($node->nid);
$field_language = field_language('node', $art, 'field_intro');
$art->field_intro[$field_language][0]['value'] = $record->intro;
field_attach_presave('node', $art);
field_attach_update('node', $art);

Note: field_attach_update() always expects all fields (like we are [passing the complete node object as $art), but If you just pass it the fields you actually want to update it will drop others like image or file fields.


When you get fatal web server/PHP error it is very useful to check the logs. Usually Apache logs are placed in /var/log/apache2/error.log but it may differ.

  Owner and Group of all files are www-data

I must warn you that www-data should not be an owner for most PHP files. www-data usually needs only read permissions. But it is not directly related to this question.


Drupal 6 Apache Solr Search Problems with result ordering & fields

I would suggest you look into the Views module and/or Apache Solr Views. This blog post http://blog.hsl.virginia.edu/drupalpress/apachesolr-views-drupal-6/ might also be useful.


Does node_delete() function deletes the attached media files as well?

It depends.

If the file has no references left to it in the file_usage table, then yes, it will be deleted.

If there are remaining references, it won't be deleted.

Either way, file_delete() is definitely invoked for the file.


How to hide 'add to cart' button on content type full view?

You could use devel_themer module. After enable the module, a checkbox appear on left bottom of the window then, select the checkbox now you could find the template name after click the add to cart button...


How to print correct path to file in .tpl.php?

It appears $base_path is empty, which would suggest your code isn't in page.tpl.php (where that var is commonly available, having been added in template_preprocess_page()).

To make it available to your current template, implement a preprocess hook like the following, which is for a region.tpl.php template file:

function MYTHEME_preprocess_region(&$vars) {
  $vars['base_path'] = base_path();
}


Services: Getting error 406 Node type is required - but I have specified the node type

try to observe the order of fields like: type > title > body > fields
that is the widget type of "field_link"?
add "und" to this field

{"title":"Sample post ",
"type":"article",
"body":{
"und":[{
"value":"comments about something"}]},
"field_link":{
"und":[{
"url":"http://www.google.com",
"title":"My title"}]}}


How can I get the taxonomy tree by the vocabulary ID?

You can load terms using the entity query,

$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
     $term_data[] = array(
      "id" => $term->tid,
      "name" => $term->name
     );
    }


Views won't display unpublished nodes when explicitly told to

Since drupal 7.15 drupal injects node_access conditions into queries - these can be disabled with the query tag DANGEROUS_ACCESS_CHECK_OPT_OUT but views' query tag entry doesn't accept uppercase tags (Yay)

The only solution to remove node_access checks is to disable query rewriting entirely in Other > Query Settings


How do I make a single page use ssl in Drupal 7?

Take a look at the Secure Pages module. The module enables you to:

A small process which will redirect the required pages to a SSL version of the page.

To make use of it, take into account though that your webserver / webhost will need to support SSL and it should be configured for your site.


How to capture URL from a webform without using token value?


Go to the path alias, set your path to what you want, then from admin/config/search/path/delete_bulk delete all taxonomy path , then from admin/config/search/path/udate_bulk rebuild them.(this is is pathauto mdoule)if your menu link not worked rebuild them ( with taxonomy menu module)


What do you mean by "in Drush"?

If you are working in a Drush commandfile (e.g. writing your own Drush command), then you can get environment variables via php using the getenv function.

If you are calling Drush from bash, then you can use bash to expand environment variables (e.g. drush dl --destination=$HOME/.drush)

If you are wondering what to do because you have set up your web server to define environment variables that you are using in settings.php to bootstrap Drupal, then you cannot read these from Drush or bash, because they are only defined by your webserver.  Try defining equivalent variables in your .bashrc.


Trying to show multiple relationships with Drupal view

I would have used references to start with.

You would create a manufacturer (e.g BMW). Now BMW will have a picture/logo description etc.

Then you would create a CAR (e.g 320i). Now the car will have all the fields you want and most importantly the reference to the manufacturer.

You will then need to create a block view of content type CAR.

Fields will be picture and title(320i).

Filters will be "Content: Type (=Car)".

Contextual filters will be "Content: Nid".

Then in Structure->blocks you move the newly created block view into the Content section under "Main page content".

When visiting the BMW node the view should display the car + title.


How to get hook_install() to run all hook_update_N()?

You shouldn't get your install hook to run updates. When a module is installed for the first time no updates should be necessary.

Updates are used when the module already is installed (the database or variables have been created). In that case, you don't want to reinstall the module as it will wipe all data, instead you create update_N hooks. Drupal will detect which updates are needed and those will be run going to update.php. In Drupal 6 it will auto select which updates to do, but you can change it, while this is not possible in Drupal 7.

Drupal detects which updates are needed by saving the number of the last run update. This can be changes in the database, which will allow to rerun updates in Drupal 7. Rerunning updates is usually a bad idea and will most often cause errors and can in some cases mess up your data.

Always remember to backup your database before running updates.


LDAP Role Mapping - Working, but not Assigning

Ok so I found the solution - which made me kick myself :p

In order to get the role mapping working the role names have to start with a lower case letter - so in my example I changed the role name from Delegate to delegate and it is all working now.


Having trouble adding a custom js file to my Drupal 7 site

I was able to solve the problem by changing the document.ready function on the first line of my js file from: $(document).ready(function () { to: jQuery(document).ready(function ($) { I found the answer here:


Populate dropdown with data from database in Drupal7 using jQuery

By default, hook_menu's delivery callback is set to drupal_deliver_html_page(), therefore it delivers content wrapped in a page template. You will need to modify the delivery callback.

To output page content in ajax

function MYMODULE_menu() {
  $items['search/data1'] = array()
  'title' => 'Add data', //page title
  'description' => 'form',
  'page callback' => 'search_data1',
  'page arguments' => array('access content'),
  'delivery callback' => 'MYMODULE_ajax_deliver',
  'access callback' => TRUE
}

function MYMODULE_ajax_deliver() {
  if ($page_callback_result) echo drupal_json_output($page_callback_result);
}

To output naked page content

function MYMODULE_menu() {
  $items['search/data1'] = array()
  'title' => 'Add data', //page title
  'description' => 'form',
  'page callback' => 'search_data1',
  'page arguments' => array('access content'),
  'delivery callback' => 'MYMODULE_custom_deliver',
  'access callback' => TRUE
}

function MYMODULE_custom_deliver($page_callback_result) {
  if ($page_callback_result) echo $page_callback_result;
}

To learn more about a custom delivery callback function, see my other answer.


Enable the module display suite extras
Define a display suite layout. Once the layout is specified you get the 'custom classes tab'.
Enable Field Templates in the display suite configuration screen admin > structure > Display Suite. Then select "Field Templates". Check "Enable Field Templates. URL is admin/structure/ds/list/extras
Define some classes. Using the "CSS classes" tab in the display suite settings define some "CSS classes for fields". URL is admin/structure/ds/classes
Ensure that the view mode that you are using is managed by display suite. Under "Manage display" accessed either via the node editing screen or admin > structure > content types check the box next to the view mode being used. In the format column the 'Field template' text should now be shown.
Using the cog icon on the right, edit the field template setting. Select the CSS style chosen in #4

With images the process is
1. enable display suite extras
2. Define a display suite layout

Enable field templates

Define classes

Manage the view mode

Select the classes


Fatal error: Call to undefined function _ds_inception_get_overrides()

When Drupal runs its cron tasks, it runs also every implementation of hook_cron() made from every module, including the core ones. Those implementation can then invoke other hooks, even the ones implemented by modules not implementing hook_cron().

The error you are showing is caused from the module whose machine name is ds_inception. Whenever it is implementing hook_cron() or one of the hooks invoked from hook_cron(), you need to disable that module.

I cannot tell you the name of the module you read in the page listing all the enabled modules, since I didn't find any third-party module with that machine name hosted on drupal.org. I thought it was a sub-module of the Display Suite module, but the 7.x-1.x branch doesn't contain such module, nor does the 7.x-2.x branch. It could also be a custom module developer for that site.
You can still find the readable name of the module in the ds_inception.info file, if you find one. It's the one following name = in that file.


How to load Node and Paragraphs using target_revision_id?

The second line probably should be:
\Drupal::entityTypeManager()->getStorage('paragraph')->loadRevision($target_revision_id)

It is recommended, though, to load the referenced entities through the field:
The first paragraph:
$paragraph = $node->{$field_name}->entity;

The second paragraph:
$paragraph = $node->{$field_name}->get(1)->entity;

All paragraphs:
$paragraphs = $node->{$field_name}->referencedEntities();


Php libchart with value from my custom table

Looking at the error msg, I think the code needs to be adapted, so that the current string (as it is now in the error message) like BETWEEN 01-10-2014 18:39:52 AND 01-10-2014 19:39:52 is replaced by BETWEEN "01-10-2014 18:39:52" AND "01-10-2014 19:39:52". So basically prepend and append a " to the variables $prev_date and $next_date ...

What isn't clear to me in this question though:

What is that 'libchart' in the title of this question?
What's the purpose of the $chart in your code? If it is because you're using some charting module, it'd be interesting to know which module you're using, and you might want to add the charts tag to this question also ...


Implement hook_page_attachments_alter() like so:

function MODULE_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'drupal.ajax';
}

The same hook can be implemented in a theme if that makes more sense.


Resolving mysql error Integrity constraint violation: 1062 Duplicate entry '' for key 'uri':

You can check whether the file is being used by another part of the system with the file_usage_list() function:

$file = file_load($fid);
$usage = file_usage_list($file);

If the returned array is empty, you can probably assume that it's an orphaned record, and safe to delete. But take a backup first, as always.


Views: Display only first value from content field in a staff directory

I am assuming you are using Drupal 7 and Views 3. If that is true, then you could use the below -

Quoting from the comment here - http://drupal.org/node/1024158#comment-5064416

  Under fields, when you add your image field, one of the configuration options is "Multiple Field Settings". Under that make sure you check the box for "Display all values in the same row". The last line under this will ask how many items you want to display. Type "1". You can also specify which number to start with if you like. Hope this helps.


check mark disappear after moving to new ip address

Thank you for all your help.
I found out the reason for a long time searching. Cause I moved an existing complicated website to a new ip address. The Advanced CSS/JS Aggregation module does affect images, css and js.

Here are some solutions that I found might be useful:

Check $base_url in setting.php file (might be set as old url/ domain name/ ip address)
Uncommend "#RewriteBase /" in .htaccess file then flushing the cache (Do not try this unless you know what you are doing)
Unable Advanced CSS/JS Aggregation Module (It will compass your js/css, this might cause some problem. Just unable it, use your
original css file) -- This works for me.

Here are some references I used here:

Need help changing domain/url on existing drupal site...
images not showing / displaying after moving to localhost (Wamp
Server)


Images not loading until the page is refreshed

Have you tried  the Image Allow Insecure Derivatives module?

  Provides a user interface to allow Drupal to bypass the token security check when generating image derivatives.

  Details

  Drupal 7.20 comes with a security fix that changes all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)

  s an example, links that previously pointed to a URL like: /sites/default/files/styles/thumbnail/public/field/image/example.png

  will now point to a URL like: /sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD_VaCaD

  For more information on the security improvement, visit the release notes.

  This is a fantastic security improvement, but in certain cases, has some ramifications. This module provides a configuration setting in order to toggle whether or not Drupal bypasses that token check.


Entire site broken because of one custom module! No pages found anymore. How to fix?

I'm not sure why your menu item above took over all paths, it should have only responded to paths that start with '/MyModule_view'. Maybe someone else can see what the problem is. However, I believe it's still causing problems because the menu registry hasn't been rebuilt. You'll need to clear that out to actually remove the menu item definition. Normally this would happen when you disable the module from 'admin/build/modules', but because you did this manually by altering the database that process didn't happen. If you use Drush (which I highly recommend) you can rebuild the menu registry with

drush cc menu

If you don't have Drush, then you can write a simple script to rebuild the menu even though you can't really access your site. The script is explained in an answer over on StackOverflow: https://stackoverflow.com/a/6912110/318158


Adding a Custom Solr Search Block that restricts search to one content type

Once i stumbled upon Custom Search module I found this was easy to achieve. Install the Custom Search module and when configuring the module click on the 'search blocks' tab. Change the number of blocks to the number of additional search blocks you require. I needed two - each one searching by an different content type.

Now go to manage your blocks. Find the new search blocks within the list of block. Click 'configure' for search block to set the options and which content type to restrict to. Note that if you choose more than one content type you can choose whether to add radio buttons, or a drop down etc to allow the user to select what they will search for. This module also has some other interesting features which are outside the scope of this question - check it out.


Showing previous and next pager links regardless of the page one is in

Probably not, to do this you would have to use theme_views_mini_pager().

Reference: http://drupalcontrib.org/api/drupal/contributions%21views%21theme%21theme.inc/function/theme_views_mini_pager/7

Example:

if (empty($li_previous)) {
   $li_previous = "&nbsp;";
}

That is whats doing it...


Drupal automatically ensures that a user has a session, so your script can simply read and write to the $_SESSION superglobal array.


How to get order information on the checkout complete page?

I've managed to complete this task.
First, you must get the order id from session or database using query.
Second, you must create an $order object like this

$order = commerce_order_load($orderId);

Define a new order sdtClass

$myOrder = new stdClass();

Wrap the order

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

And then you can get various order info like this:

// Get order number
$orderNumber = $order->order_number;

// Get user's e-mail address and encode properly encode it
$orderMail = drupal_json_encode($user->mail);

// Prepare an array to store products
$orderPurchasedItems = array();
// Create a foreach to loop through all the products and get the products info
foreach ($items as $item) {
    // Checks if the value is equal to product
    if ($item->type->value() === 'product') {
        // Get the unit price value per product
        $commerceUnitPrice = $item->commerce_unit_price->value();
        $entity = $item->value();
        if ($entity) {
            $orderPurchasedItems[] = array(
                "id" => $entity->nid,
                "quantity" => $item->quantity->value(),
                "price" => commerce_currency_format(
                    $commerceUnitPrice['amount'],
                    $commerceUnitPrice['currency_code']
                ), // this will result in $10
            );
            // Store all the ordered products in a new variable so we can use it later
            $myOrderProducts = $orderPurchasedItems;
        }
    }
}


Try using the Taxonomy Creation Date module. It adds creation and updated date rows to the database, so you should be able to use it in view.


views_pre_render add class item to a row

Because you do not want to alter some data, you should use a preprocess function for this. Check this out:

function MYMODULE_preprocess_views_view_unformatted(&$variables) {
  $view = $variables["view"];
  $viewId = $view->id();
  if($viewId == 'my_view_id'){
    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {
      $important = $row['content']['#row']->_entity->get('field_result_value')->getString();
      $custom_row_class = 'views-row-' . $important;
      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }
  }
}


Is there a way to manually run cron with Drush?

You can try drush core-cron

  $ drush help core-cron
  Run all cron hooks in all active modules for specified site.

  Aliases: cron


How do I track if a user is logged in on multiple devices and computers?

Check Session Limit module.

Session Limit allows administrators to limit the number of simultaneous sessions per user.
Max session is configurable, no database tables needed.
By default, a session is created for each browser that a user uses to log in. This module will force the user to log out any extra sessions after they exceed the administrator-defined maximum.
Assuming the session limit is 1, if a user is logged in to a Drupal site from their work computer and they log in from their home computer, they would be forced to either log off the work computer session, or abort their new login from home.


See system_settings_form and system_settings_form_submit for implementation details. In Drupal 7 Reset to Default button is removed from System Settings form .

function system_settings_form($form) {
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save configuration'),
  );

  if (!empty($_POST) && form_get_errors()) {
    drupal_set_message(t('The settings have not been saved because of the errors.'), 'error');
  }
  $form['#submit'][] = 'system_settings_form_submit';
  // By default, render the form using theme_system_settings_form().
  if (!isset($form['#theme'])) {
    $form['#theme'] = 'system_settings_form';
  }
  return $form;
}

System_settings_form :

Add's save configuration Submit button and submit callback to system_settings_form_submit function.

system_settings_form_submit:

function system_settings_form_submit($form, &$form_state) {
  // Exclude unnecessary elements.
  form_state_values_clean($form_state);

  foreach ($form_state['values'] as $key => $value) {
    if (is_array($value) && isset($form_state['values']['array_filter'])) {
      $value = array_keys(array_filter($value));
    }
    variable_set($key, $value);
  }

  drupal_set_message(t('The configuration options have been saved.'));
}

Iterates through all form elements and sets variables for each form element with key as form element key and value as user submitted form  element value read using $form_state['values']

So, it's just a form with submit handler that sets variables for all form values using variable_set function.


SimpleTest: How to make multiple Ajax posts and then save the data?

On subsequent tests of a form that has already been loaded and posted, this call will submit the form to the same URL with the field values resulting from any previous activity:

$this->drupalPost(NULL, NULL, t('Save'));

The $edit argument is only to submit new field values. And, passing NULL for $path uses the currently loaded page. So, to test my AJAX button that adds items to the form:

$this->drupalGet('path/to/my/form');
$this->drupalPostAJAX(NULL, NULL, array('op' => 'Add Item Button'));
$this->drupalPostAJAX(NULL, NULL, array('op' => 'Add Item Button'));
$this->drupalPost(NULL, NULL, t('Save'));

I was able to verify after this that two items had been added to the form as expected.


BaseFieldDefinition change DB column type

You can use BaseFieldDefinition::create('string_long') to get a LONGTEXT type field without the extra__format column.


What is the difference between "Limit allowed HTML tags and correct faulty HTML" and "Correct faulty and chopped off HTML"?

"Limit allowed HTML tags and correct faulty HTML" does not correct unclosed tags in HTML.  SO it doesn't REALLY fix "faulty HTML" at all.

You also need "Correct faulty and chopped off HTML".


Create destination directory with drush archive-restore?

Try --destination=./newdir.  Drush always uses --flag=value; without a value specified, the default is 1.


I checked your css file and it shows because of below css line, That arrow is activated for last li item, just delete or comment the lines.

#leftNav ul ul ul li.last a {
    background-color: rgb(190, 205, 222);
    background-image: url("img/blue/icon-leftnav.gif");
}

Probably you have to edit under themes folder or modules menu folder.

Go to your themes folder sites/all/themes/yourtheme/blue.css and search for url("img/blue/icon-leftnav.gif") or line 13 and comment the line and then clear the cache.


Are there any issues with installing memcache on a VPS running multiple Drupal sites?

Make sure your settings.php file has a unique prefix for each site that has memcache enabled.  I got tripped up by this, and everything went berserk. This thread fixed it for me.  Basically, this is the only issue you would have as far as conflicts.

http://drupal.org/node/1416102

Like APC, memcache works indepedently of your sites.  Make sure you have enough memory for it to function correctly.  You can get a rough idea idea by seeing how much disk space all of your drupal databases take up.  Not all tables in each database will be cached of course, but so long as you have that much memory to dedicate to memcache, you are good to go.

Said differently, as an example I have 12 sites on my VPS 4 gigs of RAM total with 1 Gig dedicated to memcache.  I have never had a problem. Total size of databases on disk is around 400 mb.


Router can't find route in LanguageNegotiation plugin route name

Okay, the problem was not in either of these two files.

As suggested by @Berdir I checked the router table and found that my route was not there. However there is nothing wrong with the file.

So the problem must be somewhere else. What if a bad class/method reference could cause this?

As an experiment I replaced the '_form' property with one that was known to work and cleared the caches. Suddenly the route was there in the table.

Checking my Drupal\doublespeak\Form\NegotiationApiUrlForm file I discovered that in my copy/paste haste I hadn't changed the namespace so the form class effectively did not exist. And the route was not loaded into the table.

Fixed. (Phew.)


How can I safely move a module to another folder?

Just restart apache. The APC cache will be rebuild then.

You can also try to hit rebuild.php or run drush cr. Those all attempt to explicitly clear the APC cache.


Make use of the contextual range filter module to create a filter range on your field 1 and field 2 and expose the filter

is a simple plugin for Views that adds the option to contextually
filter, not just by a single value, but also by range.
Numeric, alphabetical (string) and list ranges are all supported. Node
ids, user ids and even taxonomy term ids are all special cases of
numbers so will work also. Range-filtering on the "created" (posted)
and "updated" (last modified) node properties is also supported,
provided you use the correct format as dictated by Views. So, YYYYMMDD
for full dates or one of the shorter year+month, year-only,
month-only, week-only and day-only formats.

UPDATE:
Once you have installed the modules. Go to the views display you are working on, and under the filter category, select add.
Choose the field1 you created with an integer field and click add to display

Check the box expose filter to visitors. In the operator drop down, select is between and two text box should appear(min and max). Click on apply and you should see the form on top of your display. Do the same for field 2


Is it possible to get render a field for a paragraphs field in the parent twig template

in your node.html.twig file you can traverse up the element array like this

{{node.field_parent.entity.field_paragraph.entity.field_text.value}}

where

field_parent.entity is the parent paragraph
field_paragraph.entity is the child paragraph attached to parent
field_text is a text field attached to child paragraph

OR inside your paragraph.html.twig

{{paragraph.field_paragraph.entity.field_text.value}}

NOTE: its actually better to put this code in a paragraph--parent.html.twig file otherwise this template is going to be used also for the child text paragraph which does not have field_paragraph and its going to lead to error.


form_set_error Not displaying error after invalid form submission

I  made a  quick test module using your code, and I was also not getting any error messages.  The error message problem was solved when I added '#title' fields to each of the elements in your form array.  Drupal is using those to figure out what messages to display.

The reason form_set_error message isn't getting set is because drupal displays at most one error message per field, and it is already detecting that the user_email field is required and setting its own error message because of that.  If you want additional validation, you'll have to check for more than just the existence of the field, and also pass in some malformed data.


How to render a @FormElement in Views area plugin

You can create block Form first. And from View UI, add a view object to your header or footer. And from View object configuration choose the form block you created.


You should read the page about Drupal 7 Template suggestions - you would see that the proper template suggestions for Drupal 7 nodes are :

node--NODEID.tpl.php
node--NODETYPE.tpl.php

I'm unsure from your question whether you want a template for a particular node (in which case you should use the node id, not the node title - node--NODEID.tpl.php) or for all nodes of your content type "our locations" (in which case you want to use the second form, which depends on the node type, not the node title, node--NODETYPE.tpl.php)
Note that NODETYPE is your content type's machine name - on your site you will see this next to the content type name when you go to "admin/structure/types", and that hyphens should be replaced by underscores. So if your content type machine name was our-locations, the template file you want is node--our_locations.tpl.php)
Finally remember that once you've added the new template file, you must clear your cache before it gets noticed. You can do this on the performance page on your site at "admin/config/development/performance".


In a custom module, implement hook_form_FORM_ID_alter(). In there, the $form['#submit'] element is an array of all the functions that will handle a valid form submission. You can add your function to that array to have it executed on (valid) submission. Submit handler functions are executed in the order of the array, so the best is probably to append yours at the end. If the array is empty, you need to create the array and it must contains default submit handler in addition to yours, otherwise your will loose the default behavior.

To open a popup, you will need some custom JavaScript to the page trough drupal_add_js() (which you would call from your submit handler). In your custom JavaScript, you can use jQuery UI Dialog library bundled with Drupal 7. To have the library available on the page use drupal_add_library('system', 'ui.dialog'). You can use drupal_add_js() to pass data from your validation handler to your JavaScript code using the setting type.


How to alert views output using custom module

hook_views_pre_render() gets the $view object passed by reference. This means that if you change the $view object inside your hook_views_pre_render() function, it doesn't need to be returned or saved or re-executed or anything. The view object itself, the same one that is rendered, is the one you're altering.


Database error: Lost connection to MySQL server at 'reading initial communication packet'

To share a bit more detail: the reason for this is generally that your MySQL GRANT is configured as user@localhost.  Therefore, connecting over the external IP address does not match the @localhost portion, and your connection is rejected.  Specifically, because no users in the mysql.user table match the external address in their host column, the connection is rejected immediately.  You can see this by the simple expedient of telneting to the port:

$ telnet example.com 3306
Trying 255.0.0.71...
Connected to example.com.
Escape character is '^]'.
FHost '255.0.0.70' is not allowed to connect to this MySQL serverConnection closed by foreign host.
$

As you can see, before authentication is even attempted, the connection is killed.  If you had a host entry that could have satisfied this request, you would have gotten an authentication failed message, instead.  But in this case, the connection died before authentication was even requested or sent, thus the lost connection at "reading initial communication packet"; the very first packet sent included a disconnection!

To resolve this, either use a hostname value in your databases array for which there will be a corresponding host column entry in the mysql.user table, or add an explicit grant that covers the use case, e.g.:

GRANT ALL ON drupal.* TO 'drupal'@'255.0.0.70' IDENTIFIED BY 'YjbW7dUT';
FLUSH HOSTS; FLUSH PRIVILEGES;

Note that you can also use '%' as a wildcard, as in:

GRANT ALL ON drupal.* TO 'drupal'@'255.0.0.%' IDENTIFIED BY 'YjbW7dUT';

or even:

GRANT ALL ON drupal.* TO 'drupal'@'%' IDENTIFIED BY 'YjbW7dUT';

Don't use this last one unless you have a firewall in front of your MySQL server.  (Which you already have anyway, right?  Right.)

Bonus Section

MySQL treats localhost specially.  Specifically, localhost means to use the UNIX socket, whereas 127.0.0.1 means to use TCP/IP networking.  Therefore, you can run into the strange case where the two are not interchangeable, despite the fact that in every other part of the *NIX world, they are.  This can commonly happen when you have skip-name-resolve specified in your my.cnf; your GRANTs for localhost now don't cover access over TCP/IP, and vice versa.

To fix, either add a localhost GRANT for each 127.0.0.1 one (and vice versa), or change all host columns in the user table to %—which, at the risk of repeating myself from earlier, should only be done if you are behind a firewall in which you are eminently confident.


How do I remove the ellipsis button in the pager?

GO to the menu /admin/config/user-interface/pagerer and edit your pagerer

and in Separators -> Configure separators text. remove the (...)


$node contains all the content-type in your application as value. So, you need to set your node access based on the $node value.

function hook_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if($type == 'forum') {
    //set your permission based on $op value.
  }
}


Shared Database With Domain Access and Multiple Accounts With Same Email

You should not use Domain Access unless you are planning on sharing users and content between the different domains.  In your instance, you do not want to share users -- and yes, you would have problems if you tried to have duplicate user entries sharing the same email address.  You are therefore better off creating multiple independent Drupal sites, and replicating shared content (if any) via other means.


How can I restrict libraries to attach to my custom controller only?

Your render array can return the #attached property:

$build = [
 '#title' => 'My Controller',
 '#plain_text' => 'Here is some text.'
];

$build['#attached']['library'][] = 'mycontroller/mylibrary';

return $build;

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/group/theme_render/8.2.x


Is there a better way to create an alternative URL Alias Pattern?

I'd create a token for that specific data; I'm not sure it's necessarily better (or worse) than using the alter hook, but it has the advantage of being reusable elsewhere in the site.

A simple (untested) example:

function MYMODULE_token_info_alter(&$data) {
  $data['tokens']['node']['field_type_or_title'] = array(
    'name' => t('Field type or title'),
    'description' => t('Value from field_type if available, node title otherwise.'),
  );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $sanitize = !empty($options['sanitize']);
  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    if (isset($tokens['field_type_or_title'])) {
      if ($items = field_get_items('node', $node, 'field_type')) {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($items[0]['value']) : $items[0]['value'];
      }
      else {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($node->title) : $node->title;
      }

    }
  }
  return $replacements;
}


The datetime value stored in DB is the UTC value. Any built in date formatter should give you the correct local time on the page. However if you need to manually get it from DB you'll have to convert the timezone yourself.


multiple sites use one apache solr server

apachesolr_multisite allows you to tenant multiple Drupal sites in one Solr search core, allowing searching across sites, or on single sites, but it must be configured. Go to admin/config/search/apachesolr/settings, click "Edit" on the Solr search environment, and examine the settings at the bottom of the form:

These must be configured properly for your use case.


Fixed. Had a configuration issues with Dates


path alias for 'edit' not loading correct page under 'admin/'

It happens because paths defined through hook_menu() implementations have the precedence over path aliases. The System module defines the admin menu item, which is a catch-them-all, since Drupal, for a non existing path like node/1/not-defined-from-any-module, will show node/1. This also happens for not existing path aliases that partially match a path defined from a module; if you try to access admin/not-existing-alias, Drupal will return the page at admin.
Notice that in the case of a non existing alias that partially matches an existing one (e.g. path-alias/sub-path-alias/not-existing-sub-path versus path-alias/sub-path-alias), Drupal will not show the page at the path for the existing alias (in my example, path-alias/sub-path-alias).

Also, the Pathauto module doesn't define path aliases for node/1/edit; for that, you need the Sub-pathauto (Sub-path URL Aliases) module.

  The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.

  For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.


How to send html/plain-text mails based on user settings?

If we are talking about hardcoding (not interface), you have to loop through the
addressee list, load that user, and based on his preferences send html, or plain text.


This is because you're not filtering the users when you grab them using db_select. This will also grab the "Anonymous" user (uid 0). When you try to save that user, this error happens most likely. Putting a simple if(!empty($dude->uid)) within your foreach loop should fix this issue. Or excluding uid 0 from your db_select query using the NOT EQUALS condition like so:

$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->condition('uid', 0, '<>')

Or by using the NOT IN condition:

$updateAllDudes = db_select('users', 'uu')
  ->fields('uu')
  ->condition('uid', array(0), 'NOT IN')

See here

  if you need to edit all users (I am setting a default value for a custom field), you need to strip uid=0 from the list and deal with it as a special case.


Views sort criteria setup by number of fields

It should be something like this. (It is not the exact code, but it will help you.)

function findNodesByUser($userID) {
$result = $query
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('status', 1)
  ->propertyCondition('type', $type) //Where $type is the type of node
  ->propertyCondition('uid', $userID)
  ->execute();
}

function createArray() {
    customArray = array();
    $users = entity_load('user');

    foreach ($users as $user) {
        $user_nodes = findNodesByUser($user);
        foreach($user_nodes as $user_node) {
            customArray[$user . $user_node] = count(field_get_items('node', $entity, $field_name));
        }
    }
}


Difference between create new and edit node in form alter

If you look at the code of node_object_prepare(), which is called from node_form() (the form builder for the node edit/create form), you will see it contains the following code.
  // If this is a new node, fill in the default values.
  if (!isset($node->nid) || isset($node->is_new)) {
    foreach (array('status', 'promote', 'sticky') as $key) {
      // Multistep node forms might have filled in something already.
      if (!isset($node->$key)) {
        $node->$key = (int) in_array($key, $node_options);
      }
    }
    global $user;
    $node->uid = $user->uid;
    $node->created = REQUEST_TIME;
  }

In an implementation of hook_form_BASE_FORM_ID_alter(), it is enough to use code similar to the following one.
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];

  if (!isset($node->nid) || isset($node->is_new)) {
    // This is a new node.
  }
  else {
    // This is not a new node.
  }
}

If the node is new, then the form is creating a node; if the node is not new, then the form is editing an existing node.
In Drupal 8, every class implementing EntityInterface (including the Node class) override the EntityInterface::isNew() method. Checking if a node is new becomes as easy as calling $node->isNew(). Since in Drupal 8 there isn't $form_state['node'] anymore, the code becomes the following.
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state->getFormObject()->getEntity();

  if ($node->isNew()) {
    // This is a new node.
  }
  else {
    // This is not a new node.
  }
}


How to create a filter in Views for filtering dates by day, month, or year?

I ended up creating a module that made three new fields - month, day, and year - and then processed the date field to populate these new fields. Then it was simply a matter of adding a view with exposed filters for month, day, and year.


Just add a new parameter in the constructor declaration, and get the service from $container.

public function __construct(QueryFactory $query_factory, EntityTypeManagerInterface $entity_type_manager, CustomServiceInterface custom_service) {
    $this->entity_query = $query_factory;
    $this->entity_type_manager = $entity_type_manager;
    $this->custom_service = $custom_service;
  }

public static function create(ContainerInterface $container) {
   return new static(
       $container->get('entity.query'),
       $container->get('entity_type.manager'),
       $container->get('custom.service')
    );
}

Notice that all the parameters the constructor gets are the ones passed in new static(). I removed $param1 and $param2, since there aren't equivalents in the static() call.

As for passing parameters to the custom.service service, you cannot with $container->get('custom.service') nor \Drupal::service('custom.service') since both the methods accepts only the service ID as parameter. The service needs a method to set its properties; in that case you could use the following code.

public function __construct(QueryFactory $query_factory, EntityTypeManagerInterface $entity_type_manager, CustomServiceInterface custom_service) {
    $this->entity_query = $query_factory;
    $this->entity_type_manager = $entity_type_manager;
    $this->custom_service = $custom_service;
    $custom_service->setParam1($param1);
    $custom_service->setParam2($param2);
  }

public static function create(ContainerInterface $container) {
   return new static(
       $container->get('entity.query'),
       $container->get('entity_type.manager'),
       $container->get('custom.service')
    );
}

You could also use the following code.

public function __construct(QueryFactory $query_factory, EntityTypeManagerInterface $entity_type_manager, CustomServiceInterface custom_service, $param1, $param2) {
    $this->entity_query = $query_factory;
    $this->entity_type_manager = $entity_type_manager;
    $this->custom_service = $custom_service;
    $custom_service->setParam1($param1);
    $custom_service->setParam2($param2);
  }

public static function create(ContainerInterface $container) {
   return new static(
       $container->get('entity.query'),
       $container->get('entity_type.manager'),
       $container->get('custom.service'),
       'param1 value',
       'param2 value',
    );
}


How to set an exposed filter to enable current user to view nodes that he has not commented

As I understand it, this is impossible with just the views module by itself.

You can easily filter for nodes that the user has commented on, but filtering for nodes the user hasn't commented on is difficult for reasons I'll go into later, so you're going to have to install additional modules or write your own code.

First of all, to get the nodes the user has commented on, you've already added the correct relationships ("Comment: Comments of the node" and "Comment: Author"). However, the filter you actually need to use is "User: Current" with your author relationship selected and the option "Is the logged in user: Yes". You probably also want to use the "Distinct" option in the view's "Query Settings", otherwise you'll get duplicate rows if the user has commented multiple times on the same node.

Now, the reason you can't easily get the nodes the user hasn't commented on is because you can't just change the filter option to "Is the logged in user: No".

Why not?

Because that will go through every comment on the node, and if any of the comments are not authored by the current user, the node will be included in the results, even if it has other comments that were authored by the current user.

So, what you'd actually need to be able to do is take the list of nodes which the current user has commented on, and then exclude them from the results of the view, which simply can't be done in the standard views UI.

Without writing your own module to modify this behaviour, the best option seems to be the OtherView Filter module.

With that module, you can create a second view of nodes, which excludes the results of the first view I described above, using a "Content: Other view result" filter. For usability you'd probably want to set this up as a grouped filter to avoid having the operator and view names exposed to the user.


Can't run drush from within website folder configured with IIS on Windows Server 2012

Drush Launcher solved the issue for me.

Step 1 Download drush.phar and put it in project root folder

Step 2 Create drush.bat file in project root folder and put following content (it will run phar in window)

@echo off
php "%~dp0\drush.phar" %*

Now it will use local drush.


why &drupal_static is getting used with refernce?

function drupal_static

  Provides central static variable storage.

  All functions requiring a static variable to persist or cache data
  within a single page request are encouraged to use this function
  unless it is absolutely certain that the static variable will not need
  to be reset during the page request. By centralizing static variable
  storage through this function, other functions can rely on a
  consistent API for resetting any other function's static variables.

More with examples: https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_static/7


Just looking at the query, the obvious culprit is the recently_read module. The join that is added to the query is fully unindexed:

LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id

The query doesn't really make sense, so I assume the Views integration for this module needs work.


JS/CSS aggregation not creating css folder

I believe this issue is due to incorrect permission. Can you check the permission on the folders. It will also be helpful if you print the related error/warning/notice logs with the question.

Thanks


Allowing a user role to edit only their own content

Your best bet would be to create a view that duplicates this functionality but only references content to the currently logged in user. You could then add in View Bulk Operations to add the edit/delete links usually found on that page.

You could give the view a path of /admin/content/node/self maybe.


How can I create correct breadcrumbs when using Views arguments?

Check out the Custom Breadcrumbs module which has support for Views. Here is a quote about it (from the module's project page):

Custom Breadcrumbs 1:
Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home > User Blog > 2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.
Custom Breadcrumbs 2:
Many new features have been added including support for Views, Panels, Taxonomy vocabularies and terms, paths, and a simple API that allows contributed modules to enable custom breadcrumbs for module pages and theme templates. These are implemented using optional, independent submodules that depend on the main Custom Breadcrumbs module.
In addition to breadcrumb visibility, this version provides an option permitting PHP code snippets to be used in forming the breadcrumb titles and paths. Multiple languages are also supported.


Finally, the view has

• a path taxonomy/term/%/%

• a second contextual filter Content: Has taxonomy term ID depth modifier

and this solves problem 1 : with a parent tid as an argument the view produces every content that is tagged with one of its child terms.

But problem 2 remains.


confirm_form() is a form builder; as such it should be called from a menu callback or another form builder function. From the code you shown, I take you are calling it from a form submission handler, and that is not how you should use that function.

As example of code that shows a confirmation form, you can look at system_modules(), the form builder associated with the "admin/modules" path. The function contains the following code.

  // If the modules form was submitted, then system_modules_submit() runs first
  // and if there are unfilled required modules, then $form_state['storage'] is
  // filled, triggering a rebuild. In this case we need to display a
  // confirmation form.
  if (!empty($form_state['storage'])) {
    return system_modules_confirm_form($visible_files, $form_state['storage']);
  }

The form submission handler for the "admin/modules" path, system_modules_submit(), then contains the following code.

  // Redirects to confirmation form if more modules need to be enabled.
  if ((!empty($more_required) || !empty($missing_modules)) && !isset($form_state['values']['confirm'])) {
    $form_state['storage'] = array(
      'more_required' => $more_required,
      'modules' => $modules,
      'missing_modules' => $missing_modules,
    );
    $form_state['rebuild'] = TRUE;
    return;
  }

Settings $form_state['rebuild'] to TRUE tells Drupal to call again the form builder which (basing on the value of $form_state['storage']) shows the confirmation form, rather than the form listing all the modules found for the Drupal site.


the function you need to hook is:

themename_status_messages()

where themenameis your theme's name. You can see the status message theme docs here.

What specifically are you trying to restyle? Most of it can be done with CSS, without introducing a theme hook.


How to create a view that shows a Managing User all content of their members?

First of all create a view of all content.

Next, add a relationship to the author of the content. Call the relationship author. Check 'require this relationship'.

Next, add a contextual filter on the entity reference field to the manager, using the author relationship. Under 'When the filter is not available' select 'Provide a default value', and choose 'User ID from logged in user'.

Let me know if it works for you.

I've added an image of my view for you:

And here is an export of my view - you should be able to import this and it will just work:

$view = new view();
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: CA reference (field_ca_reference) */
$handler->display->display_options['arguments']['field_ca_reference_target_id']['id'] = 'field_ca_reference_target_id';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['table'] = 'field_data_field_ca_reference';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['field'] = 'field_ca_reference_target_id';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['relationship'] = 'uid';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test';


In order to load the template based on the content type, inside the template.php file of your theme you need the following code:

function your_theme_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

if the content type is "mycontent," create the page--mycontent.tpl.php file.

For template files that are based on the page path, create the page--front.tpl.php, page--node--7.tpl.php, page--node--58.tpl.php or page--node--nodeid.tpl.php files. Please note that between the page and node templates are different from what they used to be in drupal 6.


You should implements hook_theme_suggestions_HOOK_alter() to add a suggestion for 'select' element. Then create a new twig template in THEME/templates folder with the name 'select--$view_id.html.twig'.

Example code:

function HOOK_theme_suggestions_select_alter(array &$suggestions, array $variables) {
  $routeObject = \Drupal::routeMatch()->getRouteObject();
  $view_id = $routeObject->getDefault('view_id');
  $display_id = $routeObject->getDefault('display_id');

  if (!empty($view_id)) {
    $suggestions[] = 'select__' . $view_id;

    if (!empty($display_id)) {
      $suggestions[] = 'select__' . $view_id . '_' . $display_id;
    }
  }
}


How to exclude product variations from product teaser display?

Fortunately I got the answer, by looking at the solution described in a comment to View of products with multi-value product reference field show multiple rows per product node. Here is a summary of it:

  I created a view of product display nodes. Added the relationship to products. Added two fields "Content: Title" and "Commerce Product: Image".
  Got a row for every display node and product (so a node that references two products gets two rows). This is what I expect to happen.

  Possible solution A:

  I click on "Query settings" in the third column, and in query settings enable "Distinct" (it's a checkbox).
  That kills the duplicates.

  However, DISTINCT is usually a bit stupid, so it might not work in all cases. In those cases, you can try the next possible solution.

  Possible solution B:

  I enable Aggregation (again, it's in the third column). I make sure to have a "Content: Nid" field added at the top of the fields list, so that it groups by that first. Might need to apply "MIN' to the title (by setting: Aggregation type to "Minimum" in "Aggregation settings" for that field).

  Note that once you do that, the image will stop displaying. The solution for that is to go into "Aggregation settings" for the image field, and change the "Group column" from "fid" to "Entity ID". That makes it display again.


How to index created field in baseFieldDefinition?

The way to do that at the moment is a custom storage schema handler, see NodeStorageSchema for example:

protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
  $schema = parent::getEntitySchema($entity_type, $reset);

  $schema['node_field_data']['indexes'] += [
    'node__frontpage' => ['promote', 'status', 'sticky', 'created'],
    'node__title_type' => ['title', ['type', 4]],
  ];

  return $schema;
}

And then you register it with:

"storage_schema" = "Drupal\node\NodeStorageSchema",

as a handler.

To update existing installations, you need to drun drush entup or write an update function.


How to split and link date field to view (imdb style)

Use module and code in your theme:

/**
 * Override theme_date_display_single().
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 */
function theme_date_display_single($variables) {
  if($variables['dates']['format'] == "d F Y"){
    // In this case i keep only start date. For keep end date use value2.
    $date = $variables['dates']['value']['formatted_iso'];
    $timezone = $variables['timezone'];
    $attributes = $variables['attributes'];

    $day = format_date(strtotime($date), 'custom', 'd');
    $month = format_date(strtotime($date), 'custom', 'F');
    $year = format_date(strtotime($date), 'custom', 'Y');

    // Wrap the result with the attributes.
    return '' . '' . $day . '' . '' . $month . '' . '' . $year . '' . $timezone . '';
  }
}


Select Panel Node Layout on Node edit form

It sounds like you are using Panels (presumption based on the column names), so this is very easy to achieve.

In Page Manager, enable and edit node_view. Create a new panel variant. Enable Selection Rules for the variant. Add the selection rules "node_type = product" and "field_layout = 2 column".

Then carry on through the rest of the config, ie choose 2 column layout and put in your fields/blocks/etc. You will then have to create 2 more variants (or clone and edit the current variant), changing the selections rules and layout to suit.


Node Reference, and Entity Reference are great; I need “Menu reference”

I have never used the module, but in theory, Block Reference should be able to solve your problem. If needed, I assume you can combine it with Menu Block to set up the menu blocks you need.


How do I check whether a node is flagged when it is being deleted?

That code works, but if the module that implements hook_nodeapi() is executed before Flag; differently, it will be executed after flag_nodeapi(), which removes any reference to the deleted node from the database tables used by Flag.

case 'delete':
  foreach (flag_get_flags('node') as $flag) {
    // If the flag is being tracked by translation set and the node is part
    // of a translation set, don't delete the flagging record.
    // Instead, data will be updated in the 'translation_change' op, below.
    if (!$flag->i18n || empty($node->tnid)) {
      db_query("DELETE FROM {flag_content} WHERE fid = %d AND content_id = %d", $flag->fid, $node->nid);
      db_query("DELETE FROM {flag_counts} WHERE fid = %d AND content_id = %d", $flag->fid, $node->nid);
    }
  }
  break;

If the short name of the module starts with any letter after the f, then that module needs to change its weight to a number lower than 0; it is usually done in the implementation of hook_install(), or hook_update_N().

db_query("UPDATE {system} SET weight = %d WHERE name = 'mymodule' AND type = 'module', -1);


So I got my answer by myself: I ran clear cache and it performs everything perfectly. @Andrew Morris: I haven't used Rules before but I think it can't be performed by that. The generate function creates 2 xls files via PHPExcel and gets all files uploaded by user in a period of time. Then it compresses all the files into a zip archive via ZipArchive and saves the data for the zip file. Then it returns the fid of the saved file.


How to redirect all variations of a domain to https version?

example.com is the naked version of www.example.com. In the settings for the domain, add an A name pointing to IP of your server.

Add a C Name that points to the www version at the same IP.

If you are running Apache, in the virtual host settings add both Servername and ServerAlias.

<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com

This will make sure that your server listens both the naked domain and normal domains and points them to you code folder for execution.

Make sure the .htaccess file contains the following lines.

  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

This code just sets a flag called protossl, if you have visited using https. This will ensure that you don't have infinite redirections between http and https as mentioned in the comments.

Comment out all other settings related to http and https redirection, and add the following lines.

#
# Rewrite http(s)://example.com to https://www.example.com
#
RewriteCond "%{HTTP_HOST}" "!^www\." [NC]
RewriteCond "%{HTTP_HOST}" "!^$"
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#
# Rewrite http://www.example.com to https://www.example.com
#
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This code was provided by https://www.drupal.org/u/mdrescher on
https://www.drupal.org/forum/support/post-installation/2018-04-15/forcing-to-https#comment-12723535.

These changes will make sure that all six variations example.com, www.example.com, http://example.com, http://www.example.com, https://example.com, https://www.example.com are redirection https://www.example.com


How can I show just one content with 5 images

This can be solved by using aggregation

Change the No to Yes.


How to check if current page is a group entity?

You can get the object for the current page in Drupal 7 using menu_get_object().

if ($group == menu_get_object('group')) {
  // do something with $group
}


Displaying multiple referenced nodes' fields through Views, using Views Slideshow

I don't know if it's possible to do this with views_slideshow but I just created a patch for the field_slideshow module. It will be committed once I have tested it a little more or there is some feedback.

The Field Slideshow module page.

The issue with the patch.

And the documentation page: drupal.org/node/1495622

So once you have installed the dependancies and libraries here is how to download and apply the patch:

git clone --recursive --branch 7.x-1.x http://git.drupal.org/project/field_slideshow.git
cd field_slideshow
wget http://drupal.org/files/entity_reference_support-1634412-3.patch
git apply entity_reference_support-1634412-3.patch

Then enable the module and go to your content type display setting page ( something like admin/structure/types/manage/article/display ). Here you should be able to define the format of the reference field to be a slideshow.


A quick search with "drupal ajax username checker" points me to the Username originality AJAX check module. There is a dev version available for 7.
Some more details about this module (from its project page):

This very simple module allows visitors to check username originality quickly using AJAX request during registration (completing registration form). This makes registration process more convenient as you don't need to submit your registration form to find out whether this username is already taken or not. This module is sensible to standard Drupal username validation as well as Access Rules validation.
username_check module provides two ways of user name checking:

Manual (5.x and 6.x) — a "Check availability" button appears on the form and a visitor can press it to verify whether his name is available or not.
Automatic — check is performed automatically when you finish typing and on leaving username field.


How to create different Filter Criteria which works indipendently for every views (one is "For All" the other is "For this page")

You can't influence all Views that way at one go, that wouldn't make any sense because you can have various Views types (content, user, taxonomy term).

What you can have is a Master display within one View that can be used as a template for creating new displays. But that isn't what you're asking for.

You're asking for partial Filter handling, some Filters applied to all displays, and some Filters overridden for particular displays. But that isn't available AFAICT, at least not without complex code interventions.

But I think you might be helped with Contextual filters. Usually they are used when you need to Filter according to each taxonomy term, for example. It's tedious to create a new display for each term, instead, you let Drupal calculate that on the fly.

The same with the Date, you can use a Contextual filter on Authored on field to show only the ones from a particular year.

Automation is key when dealing with a large number of data.

Here's a couple of quick tutorials about Contextual filters: Using Drupal Contextual Filters in Views, How to use Contextual Filter in Drupal 8


How can I pass the filter parameters of one view to a different view on the same page?

Yes, it's possible to have 2 different views on the same page sharing the same exposed filter query parameters.

The trouble you're having is, by default, a block display doesn't show any exposed filters. The only way to enable this is by enabling the Use AJAX setting on the block view under the Advanced section in the admin UI. Once set, both the block & page Views will pick up on the same location[postal_code]/location[distance]/location[search_units] query parameters.

Of course this means, you'll have 2 different form filters on the same page but you can kludge your way around it with a style rule to hide it (e.g. #block-views-my_block_machine_name-block div.view-filters { display: none; }) or some other means of hiding the form.


Adding Google Map via iframe with CKeditor in an article

Please see dev.ckeditor.com/ticket/11688 for more details.

  If you are using latest CKEditor for Drupal module then please go to Modules->CKEditor->Configure and edit your profiles. Each of them has ADVANCED CONTENT FILTER setting which can be disabled/enabled or extended.

NOTE: durring checking it has turned out that relase version for drupal OS module hasn't been updated thus you can't see this setting. For now please use development release which has this feature and is fully stable.


Couldn't get setErrorByName to apply error class

Setting errors outside of validation isn't supported any more. From a related change record:

  In Drupal 7, form validation functions could use either form_set_error() or form_error() to set errors for an element, and form_get_errors() to retrieve the errors for a given form.
  These were global functions, which just set or retrieved errors from the current form being processed. This worked fine for form validation functions, but could produce unexpected results when called from non-form functions (like a theme function).

  In order to ensure that errors are associated with the correct form, you must now call the form error functions on $form_state.

Even if you got a reference to the form state in your controller, setting errors on it wouldn't do anything as the form wouldn't be validating (see this change record)

The best alternative is probably to use hook_form_alter and a validation method to the form which contains your logic.


How to reorder nodes in Drupal 7 using Drag and Drop feature?

Create a view to list your nodes and use Drupal draggable views module to order your nodes.

  From the documentation page,

  Order any type of entity
  Set different order for different set of arguments
  Create one view that sets the order, and create as many views as you like that shows that order
  Use core tabledrag.js or jQuery UI draggable javascripts to set the order

Steps to use this module and views to order nodes:

Download draggable views and views module and enable in your site.
Create a view to list your nodes say field will be node title and choose Format as Table.
Add draggable fields as additional field in Fields section. You can use submit as well as ajax submit once you ordered your nodes.
Add Draggable weight as ascending order in sort criteria.

Save the view and view it in the page.
My list will be like this:

Drag and drop the pointer to order the nodes and hit submit.


By using the Views slideshow module.

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.


You should put your facet blocks into a regions and also you should be sure that they are rendered after the search is executed.


How to create a view of unread comments on own nodes for the user's profile page?

The Flag module only keeps rows in the database for content where a flag is set. I.e. when something is not flagged, there will be no corresponding row in the database.

The problem is, that views will generate a query which looks something like this (for a user with uid=12 and a flag with fid=1):

SELECT cid FROM comment AS c
INNER JOIN node AS n ON c.nid = n.nid
LEFT JOIN flagging AS f ON c.cid = f.entity_id AND f.fid = '1'
WHERE n.uid = '12' AND f.uid = '12'

However in order to select all comments for a given user excluding those which are not flagged, you need an SQL subquery:

SELECT cid FROM comment AS c
INNER JOIN node AS n ON c.nid = n.nid
WHERE n.uid = '12' AND c.cid NOT IN (
    SELECT f.entity_id FROM flagging AS f
    WHERE f.fid = '1' AND f.uid = '12'
)

AFAIK Views has no built-in support for subqueries. I therefore recommend you to reverse the logic and implement the following:

Add a comment-flag is_new
Whenever a new comment is posted, execute a rule which sets this flag on behalf of the content author.
Whenever a node is viewed by its author, execute a rule which removes all is_new-flags on the associated comments (this is essentially the same rule you already have, except that you need to reverse the flagging-logic).
Configure the view just as you did before but remove the flagged=false filter, instead configure the flag-relationship such that only flagged content is included.


You can use BETWEEN like this:

$query->condition('myfield', array(5, 10), 'BETWEEN');

In your case:

$query->condition('paiddate', array('2017/03/01', '2017/03/30'), 'BETWEEN');

For more information see the Conditional Clauses documentation.

It depends on how your dates are stored as to what min and max values you should pass in.

For example it could be a unix timestamp or it could be an actual date.
I would recommend doing a more generic select on the data to find out the format of the dates and then replicate that format in the values that you are passing in.


How can I alter variables sent to a paragraph bundle template within a module?

Drupal 7

I don't know if this will help you directly, but I found this code snippet on DropBucket and it helped me do something similar:

/**
 * Implements hook_preprocess_entity().
 */
function wwvs_slices_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    $edge = field_get_items('paragraphs_item', $variables['paragraphs_item'], 'field_edge');
    if ($edge && $edge[0]['value']) {
      $variables['classes_array'][] = 'slice--edge';
    }
  }
}

In my usecase I wanted to augment the paragraph entity with an ID using the url-safe version of the title field used in that paragraph. Here's my implementation:

/**
 * Implements hook_preprocess_entity().
 */
function foo_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    if(isset($variables['elements']['pp_title']['#items'][0]['value'])){
      $title = $variables['elements']['pp_title']['#items'][0]['value'];
      $title = strtolower(drupal_clean_css_identifier($title));
      $variables['attributes_array']['id'] = $title;
    }
  }
}

I hope this is helpful!


You can user Omega without Drush but I do recommend to try to install the Drush. Even if you do not want to use Omega you need to have Drush for serious Drupal projects. It makes your life easy.


How do I change a field description using hook_form_alter()?

I found a solution.

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['field_myfield']['widget'][0]['value']['#description'] = \Drupal\Core\Field\FieldFilteredMarkup::create(t('My custom description'));
  }
}


How to upload image or video from mobile device to content

That's a mobile OS issue. But in general, documents will open a list and show file managers at the bottom.


How do I import entity related fields using drush migration?

You can achieve this via a custom migration module, this way you have full control over what will be migrated, note the bold text:

  Create the migrations using drush migrate-upgrade --configure-only as discussed in Upgrade Using Drush
  Make sure you have aconfig/syncdirectory, to which the next step will write
  Export the migrations using drush config:export
  Create your custom migration module
  Copy only the YML files you want to use from the config/sync directory into the config/install directory of your new custom module, editing them to remove the uuid values and to edit the id, group, label, and other values as needed
  In the config/install directory of your new custom module, make a new migrate_plus.migration_group.your_module.yml file for your new migration group.

from official handbook: https://www.drupal.org/docs/8/upgrade/customize-migrations-when-upgrading-to-drupal-8

You can also rename the fields. Further processing can happen in hook_migrate_prepare_row(), hook_migration_plugins_alter(), or even a custom process plugin.

update

Please note that you will not be exporting configuration from a site and moving it to other site. Config export is a bad name here. Read it as generate migration template.

When you generated your template (aka, exported), you handpick those fields, entities and configuration that you want from all the available generated files, put them in a custom module, say my_custom_mig, enable it, and run it's migration.


Auto Import facebook comments into Drupal website

You can fetch comments on a post using graph API. But you must know the Facebook post id of the corresponding node.

https://graph.facebook.com/<postedid>/comments

Try this - https://stackoverflow.com/questions/11043527/how-to-get-all-comments-and-likes-for-a-facebook-post


Writing a patch on a sandbox/dev install using a git branch

Go to the module you want to patch and do a:

git diff original_branch final_branch > /path/to/file.patch

Test it by applying the patch to the initial module:

patch -p1 < /path/to/file.patch

or

git apply --index /path/to/file.patch

More info:

http://linux.about.com/od/commands/l/blcmdl1_patch.htm

https://drupal.org/node/707484


Get node url alias/path when loading the node using node_load()

No, the URL alias is not a field nor entity property, and it doesn't get added to the node object when it's loaded.

It would be trivial to add that data though, using hook_node_load()

function MYMODULE_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->url_alias = url("node/$node->nid");
  }
}


If the data about a product are not available when processing a "line item", you can make them available. To do so, use a technique similar to what is explained in my answer to "How to access commerce_product field of line-items using Rules to flag the Commerce Product?", which includes a Rules Component that looks like so:

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

Here is a blueprint of what you need to do:

Create a Rules Component, similar to the above Rules Component. Just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
Rework the Drupal Message shown via the last Rules Action in the Rules Component (Starting with "Some details about this product"), e.g. by also using any of the available tokens that fit your needs.
Execute that Rules Component inside your Rules Loop of the rule in which you want to loop over all line items.
Improve the Rules Component from Step 1 by creating whatever additional Rules Action(s) you need. Make sure to place these Rules Action(s) AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID".


In Drupal 8, you cannot anymore disable modules. You can only uninstall a module, but in the case of the Comment module, you first need to remove any Comments field. In fact, on /admin/modules/uninstall you will see the following message:

  The following reason prevents Comment from being uninstalled:

  The Comments field type is used in the following field: node.comment

By default, the Comments field is added to every content type.

Once you remove that field from every content type, you will be able to uninstall the Comment module from a Drupal 8 site, if there isn't any module that depends from the Comment module. Otherwise, you first need to uninstall first those modules.

As for updating Drupal, updating Drupal doesn't install the core modules you previously uninstalled, not even the ones the profiles you used to install Drupal would install.