How to set the link in a view slideshow?

You just need to make a little change in the slideshow view: Just link the image field to the content and save. Go to Configure Field > Link Image to > Select Content.


You need to download the Full Package of the CKEditor library.

You can download it at the official website.


If you don't want to wait for the port of the Less CSS Preprocessor module to run the less compiler at run time, you can execute the command line tool from settings.php

exec('lessc themes/mytheme/less/style.less themes/mytheme/css/style.css > /tmp/less-debug 2>&1');

This is only for development, remove this from the production settings.php.


I think the latter is true, and you're misunderstanding what Features does.

Features takes any database-stored configuration (Views for example), and exports it to code.  The generated module is essentially just a package that then contains the code version of your configuration.

For example, if you create a Feature containing a Blog content type, and a View that show all Blog articles in a list - the generated Feature is simply a module with that configuration stored in code, and exposed to Drupal.

If you want all of the modules packaged, you are looking more towards a distribution - which is a completely different kettle of fish.

To cut a long answer short, Features is a module builder - so as with any other module, dependencies must be retrieved seperately.


Cannot bind delegate onClick event on .use-ajax elements

Thanks to Clive, I've found one way to make it work : wrap the code into a drupal behavior.

It look like this :

(function($) {
  Drupal.behaviors.refresh_views = {
    attach: function () {

        var view_identifier = '#view_id';

        //attach the on click handler to all links of class 'use-ajax'
        $('a.use-ajax').on('click',function(){
            $(view_identifier).trigger('RefreshView');
        });
    }
  };
})(jQuery);

I'm attaching an handler with my first version of the onclick function :

$('a.use-ajax').on('click',function(){
    foo();
});

So without the delegate part (does not work when an element is created after the script execution). In my case, I'm reloading the view with an ajax request. And in drupal 7, each time a request finishes the ajax behavior is called again. So the code is executed and it bind the on click event into the new elements.

I'm leaving a little warning here :
This script is executed on every ajax request (if you open a modal popup in the ajax way, it will add an event into the click handler). So it might bind a lot of time the same event ! So don't forget to control the amount of events that your are adding to the same handler.


PDOException: SQLSTATE[42S02] on cache_block after module install

can I use the live production system to export the cache_block table structure and then import it into my localhost?

Yes, that's exactly what you should do. Core cache tables have a common structure so you could even just duplicate cache_bootstrap or another from your local and rename it.

Don't bother importing the data as you'll want to clear caches after recreating the table anyway.

Personally I'd be tempted to also go and find out what caused it in the first place to make sure it can't happen again (and so the site can stay up to date).


its this one:

$field->getFieldDefinition()->getType()


How to group taxonomy and node flags together?

You could use the Views Contextual Filters OR module. Excerpt from its project page:

  ... provides a views plugin which modify query to support OR conditions for contextual filters.

Create a view using 2 contextual filters (=both of the filters you already have for your 2 views), and combine them with an OR.


You can't (without reflection). Protected members of a class are available only to the defining class and its subclasses - it's the whole point of using access modifiers in the first place - if you can get access to a protected value directly from the object, then the language has failed. Miserably.

If a method doesn't exist to expose that data already, you'll need to extend the class that represents that object to provide getter methods for the protected properties.


Think your looking into this a bit too deep for what it is.

For your fields you use the following:

Summary: Default field with any content type
Embed: http://drupal.org/project/youtube (not sure if theres something for
vimeo)
Notes: Create a field that accepts PDf file extension

You then have loads of options for how you can present your content type. How about just creating a template file for that content type so...

node--type.tpl.php

You can then manipulate the output of the fields, for example...

    print render($content['youtube_field']);

    print render($content['pdf_field']);


How do I set the value of a date and time field with Behat?

I haven't been able to find a way to do this, so for now, I rewrote my CI configuration so that I can use Standalone Chrome with Pantheon/CircleCI instead of the Behat Chrome Extension.


How to create a view with a list of items and item clicked?

Views does have an Ajax option in the advanced setting, although it may or may not be appropriate or have enough features for what is being described above.

See the previous answers https://stackoverflow.com/questions/3016747/drupal-use-ajax-to-update-views-content and How to load and display a view with Ajax in Drupal 7? and Using AJAX to access the content of a view .

Any solution may or may not require customization.


Basic page still showing in view that filters out basic page content from view

I never found out why this was happening, but I found a workaround for it.
Add another filter that says content cannot be of type: Basic Page.
It's not pretty and I would prefer to not have to use that and fix the problem instead, but if you're pressed for time this will work.


A PDF field open in a new window of Drupal

If you're looking for a quick fix for ALL pdf links on your site you could use a little bit of javascript to accomplish this as well.  This snippet finds all URLs ending in .pdf and sets the target attribute to be _blank (new window).

(function ($) {
    $(document).ready(function() {
        // Open PDF In New Window
        $('a[href$=".pdf"]').attr('target', '_blank');
    });

}(jQuery));

Since you're looking for just files of your field type you could certainly use a less generic selector, such as .field-name-field_pdf a[href$=".pdf"].  Best of luck!


Durpal 8 on install new module, insert data in new created table

To run tasks when your module is installed, use hook_install(), e.g.

function module_install() {
  \Database::getConnection()->insert(...)->execute();
}


Create a block with hook_block_info and embed your custom form within a block using hook_block_view. Assuming module's name to be example, this module creates a "My block" with the form.

FYI, in the below code drupal_render(drupal_get_form('MYMODULE_form')); is the one rendering your form in the block where MYMODULE_form is the form ID.

 <?php
    /**
     * Implements hook_block_info().
     */
    function example_block_info() {
      $blocks = array();

      $blocks['MYBLOCK'] = array(
        'info' => t('My block'),
        'cache' => DRUPAL_NO_CACHE,
      );
      return $blocks;
    }

    /**
     * Implements hook_block_view().
     */
    function example_block_view($delta = '') {
      $block = array();

      switch ($delta) {
        case 'MYBLOCK':
          $block['subject'] = t('My block title');
          $block['content'] = drupal_render(drupal_get_form('MYMODULE_form'));
      }
      return $block;
    }


Add site details to be used as tokens throughout site

I think you could achieve this by altering the site information form in a custom module to add a custom submit function which would use the Token API to add desired values in tokens.

I found a good post explaining the token part for 6/7 here and a good post for altering the form here.

The module developer's guide is handy too.


There are several method to clear the cache_form automatically.

Use optimizedb module

  There is well-known issue with fast-growing table cache_form. This
  table stores Drupal form cache and it isn’t cleared when you flush all
  cache or run cron. Also you can struggle with problem of fragmentation
  with InnoDB tables on active delete/insert operations. This module
  provide functionality to solve this problem. Also its provide
  additional tools for maintenance database.

  Module OptimizeDB provide such features:

Ability to clean **cache_from** in administrative page or do it by cron.
Ability to optimize all database’s tables and display its sizes.
Configuration of notification about necessity to perform maintenance tasks.
Perform check and repair operation with tables.
Prevent crashing tables when perform all maintained actions.

If you have drush access  Safe cache_form Clear module

  Safely remove a limited number of items from the cache_form table.

  This module provides a drush command drush safe-cache-form-clear that
  can be run at a high frequency, keeping the table at a reasonable
  size. It requires that you use the database cache back-end for the
  cache_form table.

  Drupal's core cron can have problems clearing out the cache_form table
  when it grows extremely large. This module works around this by
  limiting the number of items expired from the cache in a single run,
  dealing with a manageable chunk each time.

  You can configure the number of items deleted in a single run by
  setting the $conf['safe_cache_form_clear_limit'] persistent variable.

for automatically clear the Drupal cache use  Cleaner module (it's not clear the cache_form table).

  The Cleaner module allows the admin to set a schedule for clearing
  caches, watchdog, and old sessions.

and another solution is create a custom route in your module something that not predictable by others (some hash url), on call back function truncate 'cache_form' table (or equivalent Drupal ) then on your server or your Cpanel create  a crontab,schedule it to run the code periodically.


Would be Drupal a good choice for my web app?

Both codeigniter and drupal are php frameworks. Can you elaborate more on what exactly you are looking for? Drupal is capable of doing everything a php can do. Also Drupal 7 has built in ajax support for forms. With additional modules like ctools, you can extend ajax functionality to any DOM elements.

There is Rules module that is more powerful and extended version of triggers. Its the GUI version of if-else-then php statements.


How to set default values for daterange widget in baseFieldDefinitions

I think the problem is just the date format. If you look at the DateRangeItem class's generateSample method, it uses the DateTimeItemInterface::DATETIME_STORAGE_FORMAT format to prepare both value and end_value. You probably just need to do the same:

$rangedefaults['value'] = $rangedefaults['end_value'] = (new DrupalDateTime())->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);

As an aside, since you're using the current time it feels like you might want the default value to be the time at which the entity is created. By setting it in the field definition, the default will always be the time you installed the field.

That might be what you want, but in case not, use setDefaultValueCallback instead, and add a method to the entity class which returns the default value.


How do you use drupal's devel krumo ddebug_backtrace()?

This bug was quite annoying to solve. What I did was:

Isolate the variable that was causing the issue.
Setup a conditional to detect this variable when it happens.
Add drupal's ddebug_backtrace() to the conditional.
Trace back to where the function was being called up.
Find out how that problematic variable is being passed in.
Keep following the backtrace to the point where that variable is assigned and not just passed along to another function. In my case it was in theme() that assigned the blank variable $template_file.
From there I needed to know when theme() was being called. The original backtrace didn't leave any clues to which module was calling it aside from views, but views gets called all over the place. Now I needed to find the module that was calling views.
In theme() there were a bunch of hook variables that gave the hint of where it was coming from. I dpm() all the $hook and $hooks variables and it showed the error was happening when a "display suite" hook was being called.
In the end all I needed to do was uncheck this box. I still don't know why it caused the issue randomly... -_-

My debug code to get the output I needed:


How does the global variable $user work?

I would check to see that the block is not getting cached, or that you are not using something like Boost (static caching).

Sounds like the block contents are being cached to me.


Retrieve a field value without loading the entire node?

I don't think there's anything built in to the API but in a pinch you could just query the database directly:

$entity_type = 'node';
$bundle = 'page';
$nids = array(1, 2, 3);

$field_values = db_select('field_revision_FIELD_NAME', 'f')
  ->fields('f', array('entity_id', 'FIELD_NAME_value'))
  ->condition('entity_type', $entity_type)
  ->condition('bundle', $bundle)
  ->condition('entity_id', $nids, 'IN')
  ->condition('deleted', 0)
  ->execute()
  ->fetchAllKeyed();

After running that you should have an array of field values, keyed by their respective node's nid.

It's worth remembering the column name won't necessarily be FIELD_NAME_value; for example a node reference field would have a column name of FIELD_NAME_nid. Which one you use will depend on your field type.

UPDATE

It seems there is a way to do it with the API, but it's not pretty and still involves a manual query:

// Get the field meta data for the field_id.
$field_name = 'field_something';
$field_info = field_info_field($field_name);
$field_id = $field_info['id'];

// Load up the properties from the node table.
$nids = array(1, 2, 3);
$sql = 'SELECT * FROM {node} WHERE nid IN (:nids)';
$nodes = db_query($sql, array(':nids' => $nids))->fetchAllAssoc('nid');

// Attach the single field to all nodes.
field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

That method takes advantage of the $options parameter in field_attach_load() by specifying a field ID to load data for. It's worth noting, per the docs:

  Note that returned entities may contain data for other fields, for example if they are read from a cache.

So the code might have appeared to load extra field data, but anything other than the field you've specified will come from cache.


Does Drupal 7 support connecting to DB using MySQLi?

No. Drupal 7 does not come with Mysqli support. It only comes with PDO based drivers for MySQL, pgSQL and SQLite.

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

https://www.drupal.org/requirements/pdo

See the files :

INSTALL.mysql.txt
INSTALL.pgsql.txt
INSTALL.sqlite.txt

to find out more about how to install using each option.

There are also many community provided solutions for connecting to other databases including MsSQL, Mongo and Oracle.

Have a look at the Drupal modules page for more information on database drivers

The core advantage of PDO over MySQLi is in its database driver support. PDO supports 10+ different drivers, opposed to MySQLi, which supports MySQL only.

If you are interested in the comparison between PDO and Mysqli there are many articles around including this one.


The directory sites/default/files does not exist

Your perms should (arguably) never be 777 on anything, but your exact situation will dictate that. 755 is often more appropriate for writeable folders, 644 for writeable files, but it depends on how your server is configured, and who owns the files.

You do need to create the sites/default/files folder manually, before the web-based installation can proceed, and your web server user must be able to write to that folder. You also need to create sites/default/settings.php, make it writeable, then remove those write perms once installation has completed. Drupal's status report will tell you about this if you haven't already done it.

There's not a lot more to it, just make sure the perms on all your files and folders are sensible for all the users that can interact with them. Securing file permissions and ownership has the full details, I'd recommended reading and fully understanding that page before going any further.


Available tokens in the Filter Section of Views

I don't see any way in the Views UI to do this, but you certainly can with a hook:

function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='THE_VIEW_YOU_ARE_LOOKING_FOR' && ($node=menu_get_object())) {

    $filters = $view->display_handler->get_option('filters');

    $filters['nid']['value']['value'] = $node->nid;

    $view->display_handler->override_option('filters', $filters);

  }

}

which would set the value in the node nid filter to that of the node nid the View is displayed on.


You can use Views module http://drupal.org/project/views.

With Views module, you will have a flexible method to pull content according fields of your content that you want to show, and with Exposed Filters feature of Views module (or with modules like Better Exposed Filters), you can search/refine by field of your content.

here is a documentation about Views: http://drupal.org/documentation/modules/views

here is an example: I want to filter and search by Title of my content. Then I can add to my View a filter to search by Title, then in Filter Criteria I can select Title and expose that filter to use, for example, a text field for search Titles:

this screen shot is about where is located the Filter Criteria area, and where is the option to add filters:

this screenshot is about where you can select if you want expose a text box to search/filter, in this example, by Title. The operator is very important to filter. In this case I will select Contains that seek a word that is part of title:

Also remember that you can add another filter, the filter by content type, to filter results by list of content type desired. This filter can be not exposed, or if you want, can be exposed to allow to users filter and search, according content types:

And finaly this screenshot have the View with a text field for filter and search by titles of my content:

I hope information be useful.


This problem occurred for me when building an 8.0.0-beta6 test site on my Ubuntu 14.04 laptop.  I have an Apache web server running locally, with the test site defined using a VirtualHost directive.  I add the domain name of the test site ("example.com") to my /etc/hosts file, pointing to 127.0.2.1, to bypass the need to use real DNS entries.

After installing the site, everything looked fine.  However, I noticed a warning message on the Status Report page about not having trusted_host_patterns set, so I went into my /sites/default/settings.php file and added these lines:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^www\.example\.com$',
);

Upon saving the file and reloading my browser, I got a very generic error page and, after commenting-out the new lines, noticed the Untrusted Host "localhost"... log message.

It appears that because I'm web-browsing from the same computer on which the web server is running, the Host is at some point getting converted to localhost, and thus is failing to match the set of patterns I had specified.  I was able to fix this issue by changing these lines to:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^www\.example\.com$',
  '^localhost$',
);

On a site that is intended to be put into production, you might want to utilize a settings.local.php file to specify ^localhost$ as a valid host pattern for testing purposes only.  Note that if you want to do this, you'll need to uncomment these lines in the default settings.php, and move them to the bottom of the settings.php file:

if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

In this case, the settings.php file would only contain the actual domain names:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^www\.example\.com$',
);

and settings.local.php would contain:

<?php
$settings['trusted_host_patterns'][] = '^localhost$';

to append localhost to the list of valid hosts.  With this configuration, you would not copy the settings.local.php file when copying the site to the production server.


What makes a maintenance mode message display, when a site is not in maintenance mode?

If not in Maintenance it could also be an uncaught PHP exception as suggested here: "The website encountered an unexpected error. Please try again later." so check your Drupal logs (Reports > Recent log messages), or a problem with your database service.

You can test whether it's a database offline situation by using a special theme template based off of maintenance-page.tpl.php called maintenance-page--offline.tpl.php where you put your own HTML and text instead of printing the $content variable:

Connection to database lost!

[Suggestions about what to do...]

You can test what the page looks like (on your local dev environment) by disabling the mysqld temporarily and visiting your local site. Don't forget to clear the cache to get the new template to register before trying to test it.


I was able to add a Views footer with some code in a custom module.

use Drupal\views\ViewExecutable;
function YOURMODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'view_machine_name' && $display_id === 'view_display') {
    $options = array(
      'id' => 'area_text_custom',
      'table' => 'views',
      'field' => 'area_text_custom',
      'relationship' => 'none',
      'group_type' => 'none',
      'admin_label' => '',
      'empty' => TRUE,
      'tokenize' => FALSE,
      'content' => ‘Footer content is great.’,
      'plugin_id' => 'text_custom',
    );
    $view->setHandler('view_display', 'footer', 'area_text_custom', $options);
  }
}

Reference: Drupal 8: Programmatically Adding a Views Footer


Drupal 7 clearing validation error messages

The reason being after you enter the value the form needs to be submitted for the error to clear out. So if you want the validation removed as the user starts entering values you should look into the Clientside Validation module.


setErrorByName not working properly if field is in #details

Answer provided by Clive in comment is the correct one.

$form_state->setErrorByName('person2][lastname2', $this->t('This field is required.'));

Though if you just want to make the field required it would be better to do:

$form['person2']['lastname2'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Last Name'),
  '#size' => 32,
  '#default_value' => $this->store->get('lastname2') ? $this->store->get('lastname2') : '',
  '#required' => true,
];


How to enable click-sorting for views table display based on Search API index?

As it turned out, it was my stupid mistake - search index field can be added to views (as a views field) in 2 ways, with one of them having (Indexed field) appended to the field label.

When I added field with (Indexed field) appended, I can set that field a Sortable.


Seems the Time Spent  module is what you're looking for

This module tracks, by Ajax, how long a registered user took to read a page and the amount of time he spent on the entire site.
You can configure which content type and role should be tracked and view the report, exhibiting the total hours (or minutes/seconds) a user spent reading a page and at the entire site.

Similar module -Time Tracker

Features

Track Time on any entity and or comments
Activities and Time Entries are now both fieldable entities.
Track time using time intervals (start and end times) or durations    (admin/settings/time_tracker)
Integrated Timer to track time as you go
Time estimating
User Time Sheets to display weekly logged time (user/%uid/time_sheet)
View for reporting on tracked time (time/report)


How to Extract Label of a Field, which is inside FieldCollection?

This should do it:

$entity_type = 'field_collection_item';
$bundle_name = 'field_some_field'; // Field name the collection is attached to
$field_name = 'field_some_other_field'; // Field name within the field collection

$info = field_info_instance($entity_type, $field_name, $bundle_name);

if ($info) {
  $label = $info['label'];
}


You can 'connect' both views through the (hidden) node ID:

add the field Content: Nid to the fields list of your first view and check Exclude from display on the next screen.
also add the field Content: Nid to the fields list of your first view and check Exclude from display on the next screen.
add Draggableviews: weight to the sorting criteria of both views.
in your second views sorting settings choose your first view under Display sort as to connect both.


Two things that might be causing the problem:

You need to execute the query: $result = $query->execute();
The id you gave is HUGE, and I don't know if it would ever work. Drupal comes with the nid column set to a length of 10.  Even if you've accounted for that, the max INT column size in MySQL is 4294967295 and your ID is 195755377227337728.  Theoretically you could use BIG INT instead of INT.  See: MySQL column type sizes

Also, try this Static Query instead of db_select():

$result = db_query("SELECT nid FROM {table} WHERE nid = :nid", array(':nid' => $nid,));


Out of the box, Drupal only stores the salted hash for the current password. No previous passwords are stored without the help of a contrib module such as Password Policy.


Can we use Deployment Module with multi DB Drupal Site or Cross DB Connection Drupal Site?

I tried and got this solution, sharing with you all

While using hook_update_N() in your deployment module - .install file, you have to active the DB for which you want to deploy the changes.  I tried it on my server and it works, I am sharing a piece of code, have a look:

function hook_update_N(&$sandbox){
db_set_active('dbsourcekey');
variable_set('clean_url', 0);
variable_set('site_403', 'access-denied');
db_set_active('default');
}


If you start chasing the code in cache_get you will eventually end up in DrupalDatabaseCache::getMultiple.  If you look at the code, you will see a call to DrupalDatabaseCache::garbageCollection at the top.  This will handle cache expiration before cron runs.

As part of system_cron you will see that cache_clear_all get called with NULL as the first parameter which

  $cid: If set, the cache ID to delete. Otherwise, all cache entries that can expire are deleted.

This cleans up the cache tables every time cron runs.

The Drupal 6 plumbing is different for pruning the cache (start reading cache_get, but the end result is essentially the same.

TL;DR, your cache TTL will always be honored when you get values, it's just the cache table cleanup that may not happen exactly when the TTL is up.


Using the entity_field.manager service, you are able to get an array of BaseFieldDefinition classes. This service is injectable as well, but for copy-paste working code, you can do the following:

$bundle_fields = \Drupal::getContainer()->get('entity_field.manager')->getFieldDefinitions($entity_type, $bundle);
$field_definition = $bundle_fields[$field_name];
$catalog_id = $field_definition->getSetting($setting_name);


Set $form_state['redirect'] = false in the submit handler.


Geting values for multipart form elements using Twig

I think you are just overlooking something simple here. The 'multi part form elements' is called a composite element. And it holds an array of values of its subfields.

Let's say the composite parent is called 'name', and it has a subfield called first_name, then you can use {{ data.name.first_name }} to get the first name in twig.

As for webform submission token, you can try something like [webform_submissions:values:name:first_name]


Execute jquery function if Ajax callback form complete

I think if found the answer at :https://drupal.org/node/171213.

Section: JavaScript on your AJAX form

"Attach jQuery to Drupal.behaviors, that way it can be run anytime new DOM elements are inserted. One example, if you're using AJAX in Views, each time a section of the page reloads, it will reload/run jQuery."

Didn't test it, because i don't need it anymore :), but still good to know!


Upload an image to filesystem, rename it and set it as Profile Picture for current user

I agree with @Clive you can do it that why, and also you can download the image directly with the full_name.
To do so just change the line:

$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures", TRUE, FILE_EXISTS_REPLACE);

by

$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures/$full_name.jpg", TRUE, FILE_EXISTS_REPLACE);

and remove the line:

$picture->setFilename("$full_name.jpg");


What I did for one of my client in order to get the webform in two columbns, was to create two "Fieldset", containing the fields for column 1 and column 2.

Then with css, I added to my webform this property :

.webform-component-fieldset {width:50%; float:left;}

Of course, there are other ways of doing it, like display:inline-block, and maybe you need to be more precise with the css so you don't mess up other webforms.

And if you don't want the title of the fieldsets, you can do a simple:

.webform-component-fieldset legend {display:none;}

I think that's the easiest way of doing it.


To export a view, go to http://example.org/admin/structure/views/view/your_view/export
Then wrap it into a module using hook_views_default_views() and export that module.

Not the easiest way, but reliable.


Create a content type node programmatically

Try this Code in MigrateContentController:

<?php

namespace Drupal\migrate_contents\Controller;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;

class MigrateContentController extends ControllerBase {

 function migrateContent() {
 $updated = 0;
 $data = array(
   'type' => 'ip_range',
   'title' => '192.168.7.100/24',
   'field_ip_range_gw' => '192.168.7.100',
   'field_ip_range_hidden' => '',
   'field_ip_range_blocked' => '192.168.7.200',
   'field_ip_range_access_type' => 'Blocked',
   'field_ip_threshold' => '20',
   'field_ip_range_sec_zone' => 'C2',
   'field_ip_range_vlan_name' => 'Network58',
   'field_ip_range_vlan_tag' => '4054',
   'field_ip_range_comment' => 'Ip ranges from 192.168.7.100 to 192.168.7.255',
 );
 $node = Node::create($data);
 $node->save();
 $updated++;

 return array(
   '#markup' => $updated,
 );
 }
}

  Inside your_module.routing.yml

migrate_contents.migrate_node:
  path: '/migrate-contents'
    defaults:
    _controller: 'Drupal\migrate_contents\Controller\MigrateContentController::migrateContent'
    _title: 'Migrate Contents'
  options:
    _admin_route: TRUE

Note: Clear the cache before proceeding.


http://drupal.org/project/embed_views  "This is a views display based on the default views display that does not have any additional features or "cruft" that you can use to create embed views for your site."


In Views, display additional fields from an entity reference

Many solutions for this but to pick one :)

Download and enable Display Suite https://www.drupal.org/project/ds
Go to admin/structure/ds/fields and a token field (see screenshot #2 for values, adjust according to your field names)
Go to view mode of your Url content type and create a seperate view mode, e.g. called entity_reference_url_view or something (I just picked teaser for this example) . Make sure to select One column layout so Display suite will make your custom token field available to you (see screenshot #1)
add the custom token field you added earlier to the visible section
Now go to your other content type view at e.g. admin/structure/types/manage/your_content_type/display/full and select Rendered Entity as the format and choose your previously created view mode of the URL content type (see screenshot #3
Now view your content type and the entity reference fields should show up in the format you defined in your custom Display suite field

Screenshot #1

Screenshot #2

Screenshot #3


How to replace the search submit button with a Font Awesome character?

In order to add the new form button, I used hook_form_FORM_ID_alter in my template.theme file in my theme folder (Notice:replace ThemeName with the name of your theme in below code):

ThemeName.theme:

**
 * Replace the Search Submit Button with a Font Awesome Character.
 */
function ThemeName_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'search-button';
}

Remeber use html_entity_decode() to parse the Unicode code.
and CSS:

.search-button input[type="submit"]{
    font-family: FontAwesome;
    color: #fff !important;
    display: inline;
    font-size: 18px;
}


Load view with ajax and contextual/exposed filters

If you call a display_id of block_1 the block does not have the exposed_form created to be evaluated by default in Views (views blocks cant have exposed forms out of the box) -- so your AJAX views calls knows nothing about any exposed form.

You need to either call a Views Page url where the exposed form is set on the page. Or, you need to use Views hooks to create/attach the exposed form to the View when your Ajax call is made.


How can i move a secondary level Tab to the parent Tabs

Well, for each page, the type of tab is decided my a parameter 'type'. So you can do a hook_menu_alter() on the specific page to change that. Please have a look at the "Rendering Menu Items As Tabs" section of the documentation for hook_menu() to gain idea of what options do what.


Create a 'taxonomy term' view
Add 'Taxonomy term: Content with term' as a relationship (don't make it required, otherwise unused terms won't show up)
Add two fields, 'Taxonomy term:Name'(mark this excluded from display since we will group them in the next step) and 'Content:Title'
Go to Format settings: set 'grouping field Nr.1' to 'Taxonomy term:Name'
Now you get the data you want, you can use your preferred approach to style them.


This answer is for future reference

Checkout the WYSIWYG Filter

  The WYSIWYG Filter module provides an input filter that allows site
  administrators configure which HTML elements, attributes and style
  properties are allowed. It also may add rel="nofollow" to posted links
  based on filter options. It can do so with no additional parsing on
  user input. That is, it may apply nofollow rules while parsing HTML
  elements and attributes.

  The filter is based on whitelists that can be defined from the filter
  settings panel. Rules for HTML element and attributes are defined
  using the same syntax of the TinyMCE valid_elements option.

  HTML attributes related to DOM events (on*) are not allowed for
  security reasons (to prevent XSS, etc.).

  The following elements cannot be whitelisted due to security reasons,
  to prevent users from breaking site layout and/or to avoid posting
  invalid HTML. Forbidden elements: applet, area, base, basefont, body,
  button, embed, form, frame, frameset, head, html, iframe, input,
  isindex, label, link, map, meta, noframes, noscript, object, optgroup,
  option, param, script, select, style, textarea, title.

Please refer to the project page for more details.


How to modify a term reference autocomplete field

There's a GREAT module for this type of configurations called Hierarchical Select

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!

This module has a lot to offer, but as for your need, it also does the trick.
Also you might want to consider Taxonomy Term Reference Tree Widget as well, the main functionality is a different thing but you can define a permission via views to do what you are after too with this module.


You always start with a base-theme.  Let us call this Theme A.  If you introduce a sub-theme (e.g. Theme B as a sub-theme of Theme A), it inherits everything from Theme A.  You can introduce minor (or major) tweaks in Theme B.

If you set Theme B as the default, then you get Theme A + Theme B.

If you set Theme A as the default, then you get Theme A (with nothing from Theme B).

In other words, if you've set Theme A as the default, then Theme B is not supposed to work.   To get Theme B to "work", you must set Theme B as the default.

This also works if you cascade with more sub-themes.

For instance, if you introduce another sub-theme (e.g. Theme C as a sub-theme of Theme B), it inherits everything from Theme A and Theme B. You can then introduce minor (or major) tweaks in Theme C.

If you set Theme C as the default, then you get Theme A + Theme B  + Theme C.

A theme need to be enabled to be set as default, but works fine as an inherited theme even when it is not enabled.


How do I render a table with a checkbox on each row?

The form element type "tableselect" is available in Drupal 8

  Description: A table created with a far left column of radios or
  checkboxes. Build the table headings and columns with the #headers
  property, and the rows with the #options property.

https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/8#tableselect

More info on "Adding checkboxes to a table" can be found in the handbook documentation here: https://www.drupal.org/node/945102


Change the content of a node programmatically with hook_node_view

If you are trying for home page then your node should be set as front page content. Otherwise this hook would not do any thing for your home page.

However any node view can be expanded by this hook:

$node->content['additional-text'] = array(
   '#markup' => 'TEXT TO GO BEFORE NODE VIEW',
   '#weight' => -10, // Set as lower as to bring this markup upper
);


Why we use dependencies keyword in {theme}libraries.yml ? and not just include the file?

A library is a set of files (CSS or JavaScript) which could be local or loaded from another site. Declaring a dependency from another library has the vantage of not requiring to know:

Which files need to be loaded
Where those files are located
Which dependencies that library has

Using a library and declaring its dependencies also means that:

A file is loaded only once
There is only a copy of a file for all the modules
A module that depends from a library doesn't need to update the list of files (which are part of that library) when the library changes its files


Add roles to user during create and save account

Found the answer: hook_user_presave() will do the trick.

I.e you add what you want to the user object (and don't save). Drupal will do the rest.


How can I get the date_popup module to display AM/PM in the time selector?

I remember having a similar issue - I fixed it using a custom module like this, the possible cause was probably that Drupal and jQuery returned different formats...

$GLOBALS['locale'] = $locale = 'fr';

/* [...] */

function x_form_alter(&$form, &$form_state, $form_id){
    // Fix date format in some exposed date filters (cck date)
    $date_format = 'd/m/Y'; /* Should be same as in "sites/all/js/jquery.datepicker/$locale.js" */
    foreach($form as $key => $value){
        isset($value['value']['#date_format']) && $form[$key]['value']['#date_format'] = $date_format;
        isset($value['min']['#date_format']) && $form[$key]['min']['#date_format'] = $date_format;
        isset($value['max']['#date_format']) && $form[$key]['max']['#date_format'] = $date_format;
    }
}

I guess you can adapt this code to your situation and even better, suggest a cleaner solution.


How to dynamically change the path to store commerce files depending on some product variables?

You need to use the Token with File (Field) Paths and Pathauto modules.

  Note: File (Field) Paths extends the token module by adding Node tokens, without this module, you will not be able to use the node fields as tokens.

Then edit your file field.

We then use Pathauto to fix names with spaces. Ex: If the album name is "Hello World" the path/folder name will change to /hello-world/


how to get list of field names by select its node type in drupal?

To get a list of field names for each content type,, stored in a variable "list", given an array of bundle names, you could do:

$list = array();
foreach($bundle_names as $bundle){
   $list[$bundle] = array_keys(field_info_instances('node', $bundle));
}

Hope that helps.


Unable to get my ContentEntity base field definition to appear as checkboxes

Try with options_buttons because this is the ID if the OptionsButtonsWidget widget.

$fields['content_display'] = BaseFieldDefinition::create('list_integer')
  ->setDisplayOptions('form', array(
    'type' => 'options_buttons',
    'weight' => -4,
  ))
  ->setSetting('allowed_values', $values)
  ->setDisplayConfigurable('form', TRUE);


hook_inline_entity_form_table_fields_alter add custom field

Add the checkbox field to the referenced entity. Also, as an alternative you could use ief_table_view_mode module instead of hook_inline_entity_form_table_fields_alter and then set the fields that should be displayed in the table on the referenced entity in the Entity form table view mode.


To move things around like that you will either need to use the CSS top property within your CSS or SASS file(s), or move it around with Javascript.


Background

So I have an entity reference field on a node, the widget is a
select-box.

You (Risse) have already done this, but to make this clear for other users, this involves adding an entity reference field to a content type and in the field settings changing from the default 'Simple..' to 'Views..':

Now the select list used to choose a referenced entity (in this case a node), will use views to create the select list, allowing us to customise the nodes listed. In the example above I have created a view (and added an 'Entity Reference' display) and called it entity_reference_select.

I want so that an user can choose one of their own authored nodes as a
reference OR if an admin is logged in, they can choose any content. So
admins should be able to bypass this restriction (with a permission,
role or something).

It is easy enough to list only nodes by the current author using the filter "Content: Author uid" in the view (as per @molot above). Unfortunately this does allow us to differentiate the results for admin users.
An appropriate response might initially seen to involve an OR statement in the views filters to allow admin user to see all nodes in the select list, and other users to only see their own nodes. Unfortunately there are two issues with this:

There is no way to create a views Relationship to the current user in order to evaluate the current user's roles in the filters section
An OR conditional in the filters will remove options, not add them, so would  remove non authored nodes from an admin role user anyway

Solution
Provide a default value for a contextual filter which is defined by PHP. This means we can specify which user(author) we are going to filter the results by, which would be the current user (fetched from the global $user object) unless the current user has the 'administrator' role, in which case we list nodes authored by all users.


For bugs like this, it's best to do a quick search of the module's issue queue. There are two issues, one with a patch that appears to do the job!

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


How to create a list of FULL Nodes without titles (Views)

To create a view of just comments,  Remove the Node:Title field (and all other fields), and add Comment: Body

To have the node title not a link, uncheck 'Link this field to its node'


How to alter file upload description text

I used hook_field_widget_form_alter as suggested by DannyEnglander and leymannx.

8.8.x hook_field_widget_form_alter

Replace MYMODULE with your custom module's name and alter the element array to suit your needs.

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if (get_class($context['widget']) === 'Drupal\file\Plugin\Field\FieldWidget\FileWidget' && !empty($context['form']['#attributes'])) {
    $element['#description'] = '
File must be less than 15 MB.
Allowed types: txt csv tsv xls xlsx sav sas7bdat
';
  }
}


You can make an RSS feed of the digest and then use Mailchimp to make a newsletter of that RSS feed.
This has to be setup one time and the rest is automated.
Mailchimp module synchronizes Drupal user groups with the mailing lists and groups.


\Drupal::l is deprecated.
Maybe this case will be useful for somebody

  use Drupal\Core\Url;
  use Drupal\Core\Link;
  $url = Url::fromRoute('entity.node.edit_form', array('node' => NID));
  $project_link = Link::fromTextAndUrl(t('Open Project'), $url);
  $project_link = $project_link->toRenderable();
  // If you need some attributes.
  $project_link['#attributes'] = array('class' => array('button', 'button-action', 'button--primary', 'button--small'));
  print render($project_link);


I would do that with a little code in a custom module...

For the purposes of this example my module is called misc, but replace everywhere is says misc with the name of your your module.

First create a block:

function misc_block_info() {
    $blocks['next_four'] = array(
        'info' => t('Show the next 4'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return $blocks;
}

And then define where it's content comes from:

function misc_block_view($delta = '') {
    switch ($delta) {
        case 'next_four':
            $block['subject'] = '';
            $block['content'] = next_four();
            break;

    }
    return $block;
}

And then define the content of the block:

function next_four() {
    $output = '';
    if(arg(0)=='node') {
        $node = node_load(arg(1));
        $query = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('n.type', $node->type)
            ->condition('n.status', 1)
            ->condition('n.nid', $node->nid, '>')
            ->range(0, 4)
            ->orderBy('n.nid', 'ASC');
        $nids = $query->execute()->fetchCol();
        $nodes = node_load_multiple($nids);

        $output .= '
';
        foreach($nodes as $node) {
            $output .= '
nid).'">'.$node->title.'
';
        }
        $output .= '
';
    }
    return $output;
}

What this code does is:

Take the nid of the current node
Does a query to get more nodes of the same type with an nid height than the current page.
Loads each node and outputs the node title, with a link to the node.

This will work for any content type. If your HTML is going to be any more complex than this then I would suggest using the hook_theme function to create a template file for your block.


Can I downgrade to drush 5.x using homebrew?

Homebrew install specific version of formula? - this answer on drupal.stackexchange might help you to get the overview of how specific formulas can be installed via homebrew.

Short version related to your specific question:

Update homebrew with brew update.
Get all the versions available for drush formula with brew versions drush
You will see a list of commits that point to specific drush versions, e.g.,

6.1.0    git checkout a188056 Library/Formula/drush.rb
6.0.0    git checkout 1264aaf Library/Formula/drush.rb
6.0-rc4  git checkout 39b2450 Library/Formula/drush.rb
6.0-rc2  git checkout 2a61472 Library/Formula/drush.rb
6.0-beta1 git checkout 54ba68d Library/Formula/drush.rb
5.9      git checkout 81108ad Library/Formula/drush.rb
5.8      git checkout 91cb127 Library/Formula/drush.rb

Go to the base brew directory by typing cd $( brew --prefix )
Uninstall your current drush installation with brew uninstall drush (this won't affect your settings in ~/.drush directory).
Checkout the drush formula for specific commit that you are interested in. If you want to have drush version 5.9, type git checkout 81108ad Library/Formula/drush.rb and you will have a brew formula available for this particular version.
Install drush (version 5.9) with brew install drush
Type drush --version to make sure you have the correct version installed.


“Structure->Block” showing when permission is not given to user

You've probably given them the Administer blocks and Administer views permission as well. Withdraw these permissions and the links should disappear.


Is your submit function getting called to begin with?  Just put a dsm in the beginning of your submit function and make sure it is being called.  If it is, then, dsm your form_state['values'].  If you can see all the values in form_state, then, make sure your table name and column names are spelled exactly the same as they are case-sensitive.


Both Feeds and Migrate are modules purpose-built for what you'd like to do. Migrate requires a little more coding at this point, but I like its ease of use a little more than Feeds.

Simply upgrading the site, using CCK for Drupal 7 to migrate your fields and content types, might be a better solution, though. I would create a backup copy of your site and at least give it an hour's worth of trying before resorting to a full-on content migration.


Given the way things are heading on the internet now, and Google making statements about weighing HTTPS sites higher than HTTP in the past couple of months, you might as well make it totally HTTPS.

You don't want to log in on HTTPS then redirect back to HTTP, you'll have issues with people being logged in and out intermittently. People have tried to address this issue over the years, but I don't think it has ever been solved.

I would set HTTPS always on and handle it in .htaccess, redirecting any non HTTPS traffic to HTTP. (to clarify, you do not need a module to do any of this - just follow the instructions in .htaccess and work with your hosting provider to provide an SSL cert).


Filter a view based on an attribute of a user?

Finally found an answer, described in detail here. Confusingly, it starts with creating a view for displaying users. Use a contextual filter to limit it to the currently logged-in user. You can then create a relationship to bring in information about the custom user field, and a second relationship to find nodes that share the value from that field. I tried this and it worked for me!

A more straightforward method is described a few comments earlier, but I haven't tried that one.


I was able to use Context Debug All to determine that the context is actually being loaded.  The error is related to a different issue.


How to fix error Undefined index: parent in taxonomy_form_term_submit()?

There's a couple of ways you could go about the problem:

Patch Core: If there's no outstanding issue for the problem, alter core, create a patch & bug report, and submit your patch. You can manage your patch in your deployment process until the patch is accepted upstream.
Custom Module: Looking at the comment above the code you posted, it was authored with the intention that someone might need to alter the form ("Contrib modules can then intercept before hook_form_alter to provide scalable alternatives."). You can use a HOOK_form_taxonomy_form_term_alter invocation to alter the submission handler or the form array to mitigate the warning introduced.


I would go with the migrate module, it's no syncing but export and import in two steps. But i cannot tell you if existing users will be replaced, skipped or doubled ..

Maybe account_sync does what you want.

Also have a look here How to sync users profiles and user tables in 2 drupal sites.


How can I correctly include a (non-fragment) # in a URL?

You are correct ... it is invalid to use the "#" for anything other than a fragment. That does not mean that someone doesn't have their web servers setup in such a way that "#" can be used in the URL itself.

  I'm guessing this is a problem with hash segment handling. Is there a right way to handle a URL like this?

To be clear, there is no problem with how Drupal is handling URLs ... Drupal is following the spec. I think your best bet in this case (short of yelling at whoever is giving you this URL for doing so) is to extend the Url class and replace the formUri method to handle your weird case.

Your other option is to do something really hacky like putting an easily replaced string in the URL and then doing a string replace at the last minute before displaying it.


Does change of .info file need reinstallation of module to take effect?

No, it doesn't. It needs a cache clear though.


How declare my service via dependency injection in construct?

Both code snippets work indeed, the second one uses type declaration:

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

You can use type declaration to force specific arguments in your methods parameters. If, for instance, someone should create a new class from your first code snippet and inject something other that your Paybox class your class will not throw errors. In the second example you are enforcing the first parameter to be of type Paybox. If something else is passed PHP will throw errors. If you make your code available as an API for other people they can see what kind of parameters are required without checking the full logic of your encapsulated code.

Furthermore, your IDE will play nice with type hinted parameters providing you with suggestions and better doc block generation.


How do I resolve missing content type references from uninstalled modules?

this probably is happening because you've deleted the module from sites/all/modules before uninstalling it correctly via drupal / or the module you have installed did not provided the code to uninstall it from database. Based in this, you can try to install the module again and then, disable it first, then uninstall it, and then delete it from the sites/all/modules. And don't forget to clear the cache

If the problem persist, i think you can always delet the tables individually from phpmyadmin.
Let me know if the problem persists. So, then i can analyze it with you


'"entity_test" entity type does not exist' on attempted module uninstall

Sounds like you installed the entity_test module accidentally and then disabled test modules afterwards.

Set that flag to TRUE, clear cache, uninstall search and the entity_test module (look for other enabled _test modules too) then set that flag to FALSE again.


Change the default selection for a Views 2 exposed filter

So, I tried the way that @David Lanier suggested, but couldn't quite wrap my head around it. So I went back to Drupal basics and tried it from the hook_form_alter() approach. After some troubleshooting, I also found a post about changing default Views filter values. I took the same approach and got it working. Below is the code a used, with a couple of modifications to take out my site-specific stuff. As always, be sure to replace "modulename" with the name of your module.

function modulename_form_alter(&$form, $form_state, $form_id) {
 // is this the right form?
 if($form['#id'] == 'name-of-the-views-form-displayed') {
   if (empty($_GET['label-of-the-filter']))  {
    $form_state['input']['label-of-the-filter'] = 'default-value-for-filter';
   }
  }
}

Just replace name-of-the-views-form-displayed with, you guessed, the name of the views form you want to change. The easiest way to find this is to inspect the source of the View in the browser (I love Firebug for this) and find the form element, then grab it's id attribute. To find the name of the filter and the value you should set, change the filters and perform the "search". Look in the address bar and you'll see the values you need to use here as parameters in the url.

Hope this helps get others around this issue too!


How do I get a textarea form field to use a full HTML WYSIWYG editor?

You want to use the TextFormat form element: https://api.drupal.org/api/drupal/core%21modules%21filter%21src%21Element%21TextFormat.php/class/TextFormat/8.4.x

Note that this will give you a value and a format in a nested form structure, you need to store both (or lock to a specific format) and then render the content with that format to avoid security issues.


How to add a display format for the field

Here is an example on how to create custom field formatters

https://github.com/npinos/drupal8-field-formatters

You can directly specify the markup like this extending the FormatterBase class:

<?php
/**
 * @file
 * Contains Drupal\drupal8_field_formatters\Plugin\Field\FieldFormatter\MainHeadingFormatter.
 */
namespace Drupal\drupal8_field_formatters\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
/**
 * Plugin implementation of the 'main_heading_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "main_heading_formatter",
 *   label = @Translation("Heading 1"),
 *   weight = "10",
 *   field_types = {
 *     "string",
 *     "text",
 *   },
 *   quickedit = {
 *     "editor" = "plain_text"
 *   }
 * )
 */
class MainHeadingFormatter extends FormatterBase {
  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];
    foreach ($items as $delta => $item) {
      // Render each element as markup.
      $element[$delta] = [
        '#type' => 'markup',
        '#markup' => '<h1>' . $item->value . '</h1>',
      ];
    }
    return $element;
  }
}


I have this problem using things like Views Slideshow and NiceMenus.  You can perhaps fix it by changing the CSS of the menu to include the following: z-index: 99. If you post a link to the site I can give you a more detailed answer.


How do I programmatically save "2019-11-04 07:30:00+01"?

There is no DateTime class in Drupal\Core\Datetime you should use DrupalDateTime class instead try with.

    use Drupal\Core\Datetime\DrupalDateTime;
   //$userTimezone = new DateTimeZone(drupal_get_user_timezone());
    $gmtTimezone = new DateTimeZone('GMT');
    $myDateTime = new DrupalDateTime($item['start_date'], $gmtTimezone);
    $dateTime = $myDateTime->getPhpDateTime();


How do I retain the query string after login?

I think, my suggestion is :-

alter login form
add a hidden field for destination URL.
add submit handler  like $form['#submit'][] = 'destination_redirect_handler'
use drupal_goto('destination_redirect_url') in this destination_redirect_handler


Show comment link function based on node comment settings and not user privilege

If you look at https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7.x

and click View source

and scroll down a bit, you will see that there is a variable that you can use:

  $comment: State of comment settings for the node.

So my guess would be that the value is either 1 (TRUE) or 0 (FALSE).

Using Devel module you can use Devel's dpm() function, so put:

dpm($comment);

to dump and see it's value.

If my guess is correct, then you would need to do something like this:

 if ($comment == 1) {
    print 'Comment';
 }


feeds importer tamper double importing image

I was having a similar problem using the standard feed tamper modules, so in the end I installed the Feed Tamper PHP module alongside it. Here's some example code I've used to split a string and import multiple values into a field using the Feed Tamper PHP module.

if (is_array($field)) {
  $value = implode($field);
}
else {
  $value = $field;
}

$field = explode('|', $value);

foreach ($field as $key => $value) {
  $field[$key] = trim($value);
}

return $field;


Put it in html.tpl.php also it work in page.tpl.php but I think you did not clear cache , please dont forget this, clear cache after templates changes.

also you can use conditional css
this link help you

https://drupal.org/project/conditional_styles


Uninstall core forum.module while keeping content type and taxonomy

The problem is that there is no simple thing like "content type ownership". There is module column in {node_type} table, but simply changing it to "node" (as set for handmade content types) might not be enough. Forum module implements node-related hooks, and integrity of forum data might be endangered if you will simply turn them off and change module in database.

Safer option would be to export data you need to some neutral format, like XML, and then use Feeds or similar module to import it again, to the content type created with your new needs in mind.


Okay, it can be a few things...

If that twig template is the node, you would not use {{ page.content }}, but rather just {{ content }}. {{ content }} is the entire render array for the node.

If you wanted to split the fields up within the node twig template, you can use the format {{ content.field_foo }}.

It is already set to render the paragraph entity - so this should be all that is needed.

Another thing to check, if {{ page.content }} is totally blank, ensure that the Main page content block is set to output in the Main Content region of your theme.


Drupal 7: Is hook_update_N() called when a module is updated between minor versions?

hook_update_N is only invoked when:

The update process is running (via /update.php, drush, etc).
The current schema version for the module is less than the update hook's schema version (The N in hook_update_N).

No updates are run when you visit the modules admin page, the process will always be invoked by an administrator (or perhaps an automated task, but never silently/automatically by Drupal itself).

As an aside (in case it comes to bite you at some point), no update hooks are invoked when installing a module, only for already-installed modules during the update process. The update hooks are only for getting older installations up to speed with what the current release offers upon installation anyway.

As another aside, your schema numbering looks a bit suspect if you want to stay within common practice; have a read through the hook_update_N docs for more info, but your numbering should probably be in the 7100s at this point.


Rule fetches only single taxonomy term from multiselect values

What you included n your question (with "Rule is"), does nto really look like a rule to me, rather something that is part of your rule. However, since you're trying to process a multi value field, a crucial part of a working rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should (at least) have a Rules Action to create a loop related to your field that holds the list of taxonomy terms. After you do, you should iterate over each item in that list. And for each iteration you should then perform the desired Rules Actions.

Done

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


Can I take a list of Titles from a Content Type and turn them into a Taxonomy list?

Yep, it looks like I can with Node Auto Term [NAT]

  Node Auto Term or NAT is a helper module used to facilitate node-node
  relationships through the use of the Taxonomy module; i.e. when a node
  is created, a taxonomy term is also created automatically using its
  title and body in any associated vocabularies. Other nodes can now be
  tagged with terms from these vocabularies thereby establishing
  node-node relationships.


I have used very successfully used honeypot and Mollom together with very positive effects.

I am not sure about lowering the sensitivity of Mollom however or improving its ability to recognise a quality post. I can only assume they have increase the strictness to ensure they maintain there high number of correctly classified ham messages.
for more information check out: https://mollom.com/blog/spam-vs-ham


Where do you put your template override files?

When creating new templates for your theme you need to name it to match your theme.

You'll want something like:

YOURTHEMENAME--commerce-order--customer.tpl.php


how to replace title field with some other field in entity reference field list?

Create a view and add the Title and Code fields.
Add an Entity Reference display to your view. In the View edit page, under the Settings for the Format: Entity Reference list, check one of your fields.
On your City content type, under the Country reference fields settings, change the target type on the Mode field under Entity Selection to View: Filter by an entity reference view. After selecting, the fields in that fieldset should update making your newly created view available under the View used to select the entities field. Select your view and save the fields settings.

Your dropdown should now have your Title and Code fields.


Yes, magic methods afaik can't be mocked.

You can use get('field_foo')->entity which does exactly the same as __get(), at least in this case. And then make that return a stdClass object with a ->entity property. That's not exactly the same as what really happens, but it will work in the same way for your code.


The Drupal 7 system table data is now stored in the config table in Drupal 8 against the core.extension parameter.

Solution 1: Update configuration

You can run the following code using drush eval or may be using the Devel module's provision to Execute PHP Code.

// Read the configuration.
$module_data = \Drupal::config('core.extension')->get('module');

// Unset the modules you do not need.
unset($module_data['MODULE_NAME']);

// Write the configuration.
\Drupal::configFactory()->getEditable('core.extension')->set('module', $module_data)->save();

You can do this all in a quick one-liner with drush.

drush eval "\$module_data = \Drupal::config('core.extension')->get('module'); unset(\$module_data['MODULE_NAME']); \Drupal::configFactory()->getEditable('core.extension')->set('module', \$module_data)->save();"

Solution 2: Edit config table if you cannot execute PHP

If the site is broken because of the problematic module and you can't even run PHP code, then may be you can edit the config table directly.

In the row in the config table where name = "core.extension" and edit the BLOB column data. The data is a serialized PHP array where you have to remove the module you want to get rid of from the module key of the configuration.

Solution 3: Fast and dirty solution

Remove the module from the file system
Truncate the table cache_config

However, this solution might result in messages saying the module does not exist in file system which mean something is wrong. But at least the broken module gets disabled and you can access your site in most of the cases.

Clearing Cache

Sometimes you might have to clear cache after following the above steps. Read this handy documentation on how to clear cache.


Is there a drupal hook that I can use to redirect a user to an interstitial page for the first page view? If not then how can I accomplish this?

Your suspicions are correct. If you want to do this server side on a cached page, you'll need to use hook_boot() and you won't be able call most Drupal functions because Drupal hasn't been bootstrapped at the stage that hook_boot() runs.

It seems to me that this is much better suited to client side. I would move this to a small js file (put it in the head if you're worried about the the redirect happening too late).


Using Drupal 7, modules can easily handle tokens similar to [node:author:name], where the part of the token after node:author is referring to a user token. Differently from the Token module for Drupal 6, the code that in Drupal 7 handles the tokens allows the creation of dynamic tokens. This is because on Drupal 7, modules implementing tokens can replace any token, not just the tokens they defined. The normal loop used in hook_tokens() is the following one.

foreach ($tokens as $name => $original) {
  // Check the value of $name, and generate the replacement that is assigned to
  // $replacements[$original].
}

Using the following code, you could get what you are trying to achieve. Tokens have a specific format, which is different from the one you are describing, though. The code has not been tested.

function mymodule_token_info() {
  $type = array(
    'name' => t('Anchors'),
    'description' => t('Your description'),
  );

  return array(
    'types' => array('anchor' => $type),
  );
}

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

  if ($type == 'anchor') {
    foreach ($tokens as $name => $original) {
      list($file, $title) = explode(':', $name);
      if (!empty($title) && !empty($_GET[$title])) {
        $title = $_GET[$title];
      }
      else {
        $title = '';
      }

      $replacements[$original] = "$title";
    }
  }

  return $replacements;
}

The replacement for the tokens is so specific that I don't think you will find a module that does that. Your only possibility is a custom module you write.


Is it possible to integrate Zoho CRM with Drupal Webforms?

Please checkout http://www.drupal.org/project/zohocrm. There isn't a submodule in there to specifically syncronize webforms, however, when you have zohocrm set up properly, it's pretty easy to use it with some custom code to send webform data to zoho. In the code below, we are inserting a Case into Zoho. You could easily modify to insert a Lead or Contact:

/**
 * Implements hook_webform_submission_insert().
 */
function my_module_webform_submission_insert($node, $submission) {
  $components = $node->webform['components'];

  // Get all submission values.
  $form_values = array();
  foreach ($components as $key => $component) {
    $form_values[$component['form_key']] = $component['type'] == 'textfield' ? check_plain(trim($submission->data[$key]['value'][0])) : $submission->data[$key]['value'][0];
  }

  switch($node->nid) {
    case '234':
      $notes = 'Phone: ' . $form_values['phone_number'] . "\n";
      $notes .= 'Message: ' . $form_values['message'];

      // Build Zoho data for Case.
          $data['records'][] = array(
            'Request Type' => $form_values['topic'],
            'Subject' => $form_values['subject'],
            'Description' => $notes,
          );

          // Send case data to Zoho.
          my_module_send_record($data, 'Cases', NULL, TRUE);
    break;
  }
}

/**
 * Send record to Zoho to insert or update.
 */
function my_module_send_record($data, $module, $record_id = NULL, $workflow = NULL) {
  $zoho = zohocrm_get_client();
  if ($zoho === FALSE) {
    return;
  }

  zohocrm_log($data, 'ZOHO DATA');

  $zoho->setModule($module);

  // Trigger Zoho workflow rules
  if ($workflow) {
    $params = array('wfTrigger' => 'true');
  }

  try {
    if (!empty($record_id)) {
      zohocrm_log('UPDATE RECORD');
      $response = $zoho->updateRecords($record_id, $data, $params);
    }
    else {
      zohocrm_log('INSERT RECORD');
      $params['duplicate'] = 2;
      $response = $zoho->insertRecords($data, $params);
    }

    watchdog('zohocrm', t("Successfully sent data to Zoho CRM. Zoho module: @module"), array('@module' => $module), WATCHDOG_INFO);
    zohocrm_log($result = $response->getResponse(), 'ZOHO CRM RESPONSE');

    // Let other modules process their tasks.
    module_invoke_all('zoho_record_sent', $data, $module, $result['recordId']);
  }
  catch (Exception $e) {
    drupal_set_message(t('Sending data to Zoho CRM failed. Error message: @message', array('@message' => $e->getMessage())), 'error');
    watchdog('zohocrm', t("Sending data to Zoho CRM failed. Zoho module: @module. Error message: @message"), array('@module' => $module, '@message' => $e->getMessage()), WATCHDOG_ERROR);
  }
}


Multilingual websites- one menu for each language or one menu for all languages?

You have a lot more flexibility when using one menu for each individual language. It's a bit more work to setup but it definitivly pays out in the long run.These are the points that are blocking me for using one translatable menu:
You're not able to reorder menu items for only one language.
You can't deactivate one particular link in one language, the content needs to be disconnected from the link.

Bottom line is when you're sure that you have a fixed menu that doesn't need flexibility it's OK to use i18n_menu.
When building a site that could be expanded in the future and has differences between language content avoid the use of i18n_menu and set up a menu for each language.
(You can set a fixed language in order to do some ajax magic and only show the menu items available for each language when creating new content.)


Multi-site vs Large Single site for Intranet

Another alternative you may want to consider is to start using the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

Group is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various types of roles used by the Group module, refer to my answer to "What are the various roles supported by the Group module?".

And because Group also integrates with the Rules module, you could probably transform your workflows related rules toward Group equivalents.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Can I use multiple if statement in with with same validation?

What's jumping out at me is this line:

elseif page.footer_first or page.footer_first or footer_third

It's checking page.footer_first twice, and footer_third, which based on the code you've shown is not a valid variable, it should be page.footer_third. I'm guessing this should be more like:

elseif page.footer_first or page.footer_second or page.footer_third


How do I create a download link from data in memory?

My approach is to use a Symfony Response obejct as explained here: The HttpFoundation Component: Serving files.

Firts setup the routing:

mymodule.download_item:
  path: '/myitems/{item_id}/download'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyController::downloadItem'

So the controller looks like:

class MyController extends ControllerBase {
 public function downloadItem($item_id) {

    $fileContent = functionToObtainExternalContent($item_id);
    $response = new Response($fileContent);

    $disposition = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'foo.txt'
    );

    $response->headers->set('Content-Disposition', $disposition);

    return $response;
  }
}


what POST values are required to update nodes containing CCK Date fields via cURL?

All the CCK fields has access rights settings in actions-roles permission matrix. Normally the access is restricted. Please confirm the permission on date field for your role.

An illegal choice has been detected. Please contact the site administrator. is normally reported when some extra fields are added to the form which are not originally the part of form. It is a security measure from Drupal core.

I do not know how cURL request cycle maintains user session that should be associative with proper role that is allowed to edit date field.


How to combine four text fields into one column in a view?

TL;DR: Add the four fields, hide them from the view. Add a custom text field, use it to custom-render the earlier four.

What you need to do is add the four fields into your view. For each, click and check the Exclude From View setting. Then add a fifth field, a Custom Text field, and arrange it so that it comes after the four fields earlier. Click on it to edit, and configure it to output the fields earlier using token replacements.


I eventually traced back the issue as being caused by the rules module not RNG. Removing the rules enabled me to save the event.


Add a prefix to all path with hook_url_outbound_alter and/or hook_url_inbound_alter

I finally made it but not without the help of a sympathetic module: PURL.

And here's my final solution:

Create a custom module
In the mymodule.module file create 3 functions:

/**
 * Implements hook_purl_provider
 */
function mymodule_purl_provider() {
  return array(
    'mymodule_provider' => array(
      'name' => t('My module provider'),
      'description' => t('Sets a prefix for URL.'),
      'callback' => '_mymodule_prefix',//I didn't really use this callback and I don't really know how to :-)
      'example' => 'my-prefix',//anything you want. only for UI I think
    ),
  );
}

function mymodule_purl_modifiers() {

  $mymodule_events = _get_all_events();//custom function to get some data

  foreach ($mymodule_events as $kid => $e) {
    $modtab['mymodule_provider'][] = array('value' => $e['alias'], 'id' => $e['nid']);//this array must be structured like this!
  }
  return $modtab;
}

function _mymodule_prefix(){
  $event = _get_one_event();//custom function

  if ($event) return true;
}

then you can go in /admin/config/search/purl to configure PURL with your data you've just created with mymodule.

In /admin/config/search/purl/types you select the type you need (I checked only "Path")
In /admin/config/search/purl/list you should see your modifiers you've created with mymodule.
And in /admin/config/search/purl you can select witch type you use for your provider

I am a bit sad because I didn't manage to use the 2 hooks (like purl does :-) but the good news is that "it works"

Cheers.


RE 1: If the block no longer appears in the hook_block_info(), then yes, the block's config will eventually be removed. I'm a little unsure of the timing (clearing cache / cron operation). You can use _block_rehash() to force an update of the available blocks.

RE 2: Not a nightmare, no. Keep an eye on your entities to ensure the list doesn't get out of control, but that's all you need to worry about. hook_block_info() doesn't get called on every page load, but rather only when:

the cache is cleared
the blocks administration page is loaded
another module calls _block_rehash().


How can I create a custom view other than content types?

You need to implement hook_views_data to tell Views about your tables and how the data in your tables relates to other tables defined to Views (if it does).  Here's a good tutorial to get you started:
http://www.grasmash.com/article/demystifying-views-api-developers-guide-integrating-views

Depending on the nature of your data, you may, alternatively, consider defining your custom data as a custom entity type.  If you do that through the Entity API module, then it will provide Views integration "for free".


You should use either static declaration or drupal_static(), but not both for the same variable. The issue here is that the reference is lost because references are not stored statically.

From https://www.drupal.org/node/619666#comment-2211696

  So unfortunately this is not possible (declarations of static variables don't accept expressions):

static $implementations = &drupal_static(__FUNCTION__, array());

  An this neither (it'll lose the reference):

static $implementations;
if (!isset($implementations)) {
  $implementations = &drupal_static(__FUNCTION__, array());
}

  But this is:

static $cache = array();
if (!isset($cache['implementations'])) {
  $cache['implementations'] = &drupal_static(__FUNCTION__, array());
}
$implementations = &$cache['implementations'];

So you should do this:

static $cache;
if (!isset($cache)) {
  $cache['registry'] = &drupal_static(__FUNCTION__, array());
}
$registry = &$cache['registry'];


You probably don't see a message because the results of the hook you're implementing are cached; you need to clear the cache to get the code to run. You'll want to clear it from within the browser so the message is put in the right session.

Perhaps the easiest method for this is to install the Admin Menu module, which gives you a direct link to flush the caches. When the page reloads after the cache clear, you should see the checkout pane details.

I'd recommend sticking with dpm() (assuming you have Devel installed), that's the best of the three methods in your code for inspecting vars.


Which is the best way to create an entity?

The Entity Construction Kit (ECK) is a module to assist developers with creating their own entity types. If you want to export your entity types to code for version control and deployment use the Features module. If you don't want to do this (i.e. take the long way) write your entity type code using Model module as an example to follow (essentially the same thing).


On node view page show a link or button that executes an action?

You can use the Flag module to put that "button" on the node. Then using Rules you could execute a VBO or simply use rules to create that content. Don't forget to look at Rules Bonus Pack for more goodies.


Trouble with implementing contextual links

After one day of research I got a solution:

$build[1] = array(
    '#theme' => 'filteredusers_object',
    '#object' => $object,
    '#contextual_links' => array(array('', array())), // replaced by dummy data
    '#marker' => 'marker',
);

And adding this new hook:

function filteredusers_contextual_links_view_alter(&$element, &$items) {
    if(isset($element['#element']['#marker']) &&
             $element['#element']['#marker'] == "marker") {
        $element['#links']['custom-link'] = array(
            'title' => 'Some title',
            'href' => url('node/42', array('absolute' => TRUE)),
        );
    }
}


I imagine the question is about using check_plain(filter_xss($string)), or filter_xss(check_plain($string)).

check_plain() and filter_xss() have two different, and in contrast, purposes:

check_plain() encodes special characters in a plain-text string that is then displayed as HTML.
filter_xss() filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities. In particular its purpose is:

Removing characters and constructs that can trick browsers
Making sure all HTML entities are well-formed
Making sure all HTML tags and attributes are well-formed
Making sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

If you use check_plain(), the string passed to the function is supposed to be used as plain text; in such case, filter_xss() is not necessary.
If you use filter_xss(), then the string passed to the function is supposed to be HTML, and check_plain() is not necessary.

If the question is about using check_plain() and filter_xss() on different parts of the same string then, as greggles pointed out in his comment, you can use (for example) check_plain() on the content of tag attributes, and filter_xss() on the entire HTML tag.


Paging a view based on a grouping field?

Download the Date module at and be sure to active its Date Views submodule. That will add a Page by date option to the pagers listed in your Views config page. Here is a nice writeup by Richard Schulte on how to configure the date pager.


I managed to work this one out, to get the block ready to be displayed I used preproccess_region (see code below)

function THEMENAME_preprocess_region(&$variables){
    $site_search_block = module_invoke('search', 'block_view', 'search');
    $variables["site_search_block"] = render($site_search_block);
}

Then in in my region .tpl file (region--menu.tpl.php for me) I put the following code to display it.

<?php if($site_search_block){ print $site_search_block; } ?>

As an additional bit of information if you want to edit the output of the form as I did, although I didn't ask about it here, this function should help you:

function THEMENAME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['#id'] = 'siteSearchForm'; //Set form element ID

    //The form elements (I think)
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#size'] = 10;  // define size of the textfield
    //$form['search_block_form']['#default_value'] = t('SEARCH'); // Set a default value for the textfield

    //Submit button element values
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/img/search-icn.png');

    //Add extra attributes to the text box
    //$form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'SEARCH';}";
    //$form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'SEARCH') {this.value = '';}";

    //Prevent user from searching the default text
    //$form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='SEARCH'){ alert('Please enter a search'); return false; }";

    //HTML5 placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('SEARCH');
}


Views will always only return the results for the current page of results.

That is a benefit of paging, since you aren't retrieving all the data if users may only want to see some results.

If you want to sort after the results come from the database then you have to turn paging off and return all results. Then you can sort all the results and display them as you like.

[EDIT]

You mention in your comment potentially using hook_views_query_alter() to alter the paging out of the query but (without having actually tried) I don't think that would work without removing the paging all together, because PagerDefault::execute() does its thing to the SQL after you are altering.

If you want to pursue that idea though, what might potentially work though is you doing Query alteration (tagging) by adding an alter tag in hook_views_query_alter() and then implementing hook_query_TAG_alter(), which would run on the preExecute(), which should be after the pager has acted.

For example:

/**
 * Implements hook_views_query_alter().
 */
function MODULE_NAME_views_query_alter(&$view, &$query) {
  if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    // Add a query alteration tag so that we can alter the completed query before execution.
    $query->addTag('CUSTOM_TAG_NAME');
  }
}

/**
 * Implements hook_query_TAG_alter().
 *
 * Alter queries with the CUSTOM_TAG_NAME tag.
 */
function MODULE_NAME_query_CUSTOM_TAG_NAME_alter(QueryAlterableInterface $query) {
  // Alter the $query object here.
}


If I click "Run cron" in the admin menu I'm redirected to another URL.

You have a node using the PHP filter, and calling drupal_goto(). That node is then indexed, the PHP code is executed, and you are then redirect. Don't do that ;)

  I can't run cron; see the video capture I created.

You need to specify a cron key when accessing cron.php directly. You can find a link with the key on your Status report page (admin/reports/status).


Duplicate nodes returned from a module's SQL query

I just took a quick look at the calendar_block module. From what I can tell, hook_calendar_block op alter is called for every single day in the calendar. I guess this makes sense at it allows you to alter the appearance of any day.

My guess is that the calendar on your site has 35 days in it which is why your query is run 35 times.

You could make use of a static variable to only do your stuff once or save the query etc.

Something like this could work:

function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {
    case 'alter':
      static $events;
      if (empty($events)) {
        $sql = "SELECT DISTINCT node.nid AS nid
              FROM {node}
              INNER JOIN term_node term_node ON node.vid = term_node.vid
              WHERE (node.status <> 0) AND (term_node.tid = 5)";

        $results = db_query($sql);

        while ($node = db_fetch_object($results)) {
          $events[] = node_load(array('nid' => $node->nid));
        }
      }
      ....
  }
}

The above code doesn't catch the case where there is no result and is just meant as a proof of concept.

Update:
If you only want to run the entire code once, you could do something like this:

function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {
    case 'alter':
      static $code_executed;
      if (!$code_executed) {
        ...
        $code_executed = TRUE;
      }
  }
}


Unlimited text field type and unordered list with links

I found out a perfect module to do just what I wanted called Link.


How do I store custom block content as configuration?

Then don't use custom block types because they are stored in content entities.
Use blocks storing only configuration. You can build a custom block plugin, even with a body field. See Custom block build function to display wysiwyg body text
There are also some contrib options like Simple Block which is implementing a config entity for blocks.


Drupal is not saving any changes made through administrator, Drush works fine

Problem is fixed.  Late last night I tried investigating why my attempts to enable Mod Rewrite were not working properly, and when I figured out how to enable it natively in WAMP instead of manually in .htaccess, it fixed the issue.  Apparently I was having the exact same problem as the linked post, just with slightly different symptoms, and I must have been attempting to enable it wrong so I didn't feel it was the same issue.

For other users in the same situation, you can't enable Mod Rewrite in .htaccess to fix it, you have to enable it through the WAMP server interface.  It's under Apache > Apache modules > Rewrite_modules.


What is the significance of dumping the tablespaces?

Tablespaces are used to define the physical file location of one (or more) tables - chances are if you were using them for something beyond the default innodb space, you'd know about it. It's likely safe to ignore.
The error will have started when MySQL was updated to 5.7.something, they introduced a breaking change in a minor version because it addressed a security flaw, and world + dog was greeted with this error message.
There's a way around it:
drush sql:dump --extra-dump=--no-tablespaces


You can find fid under the table name file_managed.
It is unique id for files. In files you can include images, .txt, .pdf etc extension files.
This fid is unique for the site and auto incremented
By using file_load($fid) function. Where $fid is file id.

Fid is only valid for managed files. Files uploaded as unmanaged does not have records in database, so no fid.


How can I set a reminder for a specific user to be triggered on a specific date?

Rules module
Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the 3 steps below. These steps are based on a date field which is added to the user profile, so that for each user you can indicate an appropriate date.
Step 1: Create a field to store the appointment date
Add a field to the "user" entity with machine name (say) field_next_appointment. Allow only 1 date (to store the "next" appointment), but don't make it required.
Step 2: Create a Rules "Component"
Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at admin/config/workflow/rules):
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Friendly reminder about your upcoming event",
          "message" : "This is a reminder about the upcoming event that you have an upcoming event on [user-to-notify:field_next_appointment] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other From eMail ID.
Step 3: Create a "Rule" using the Rules Component
Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at admin/config/workflow/rules):
{ "rules_on_new_user_event_registration" : {
    "LABEL" : "On new user event registration",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_appointment" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_email_notification",
          "task" : "[account:name]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-appointment",
            "date_offset" : { "value" : 259200 }
          },
          "identifier" : "[account:name]",
          "param_user_to_notify" : [ "account" ]
        }
      }
    ]
  }
}

Note that the above rule refers to the Rules Component from the previous step.
Also note the machine name of field_next_appointment in this rule, which is the field's machine name created in Step 1 (if in step 1 you used another machine name, then also replace the machine name field_next_appointment in this rule with the machine name of the field created in Step 1 (if you don't have such field yet, or the field names don't match, then the import of the above rule might not work).
The schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).
Step 4: Further tuning and enhancements

The date_offset (=259200) in the above rule corresponds to "3 days in advance", which may need review / tuning.

If needed, you could also use the Field Permissions module to set field-level permissions to edit, view and create fields on any entity.

Instead of just sending an eMail (as in the Rules Component), you could replace that by a more advanced option using the Message module (which has great integrations with the Rules module also). Here is an quote about that module (from its project page):

... enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Note: Using Rules to send an email X days after a user registers also contains quite some details that may help you.
Date Reminder module
There is also the Date Reminder module. Here is a quote about this module (from its project page, bold markup added here):

... allows a registered user to request an email reminder to be sent at a specified time before an event. Generally these would be calendar events, but any node type that has a CCK datetime can support reminders.

However I think that module is not going to answer your question, because:

it's the user who has to request such reminder (in your question you want to set a reminder to a specific user).
these reminders are related to some node, while your question is related to a user. You might possibly work around this by creating some extra node type (like "Appointment"?), though that seems like overhead.


How to use Vertical Tabs on ConfigEntity Form

Use the vertical_tabs form element. There is an example shown in the API documentation for this form element: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21VerticalTabs.php/class/VerticalTabs
In short, instead of using nested fieldsets, create a 'vertical_tabs' form element as the container then put multiple 'details' form elements inside it. Each of the 'details' elements will serve as the container for one vertical tab. See the example in the API documentation for the exact syntax.


Install custom module into modules/custom folder

As I know Drupal web interface will always install modules to sites/all/modules.
Placing modules in subfolders like sites/all/modules/contrib, sites/all/modules/custom, or sites/all/modules/dev is a task for Drush and Drush Make; you can manually place the module in the right folder.

You can move your module folder with the PHP rename() function, or implement your own Updater instead of core ModuleUpdater. In your case, these solutions look improper.


Well, you need to say that what you want to display is global as well:

<?php
global $base_root;
print $base_root;
?>


How to apply an image style based on a condition (a date for ex.)?

Yes you can do it with rules module with the help of Field formatter conditions module

  Adds conditions to field formatters. Configuration happens on the
  "Manage Display" screens of every entity type on a per field basis
  when clicking on the cogwheel on the right.

Supports

Rules
Field API fields
Display Suite fields (only branch 2)

Simple conditions and actions

Hide source field when target field is empty.
Hide source field when target field is not empty.
Hide source field when current user has specific roles.
Hide source field on specific pages.
Hide source field when target field contains a specific string.
Hide source field when target field doesn't contain a specific string.
Hide link field if title is empty.
Hide date field if from/to has expired.

Rules actions

Hide a field.
Change image style.

Rules should always be a 'A field is rendered' event before they can be selected in the conditions dropdown on the "Manage Display" screens per field.