Send php variable to js in drupal 8 block

This is from the documentation how to attach libraries to a render array of a block plugin and send php variables to js:

  Attaching to a render array of a Block Plugin

  To give another example of attaching a library to a render array, If
  you are building a block plugin in your module, you can attach the
  libraries to the render array in the build() function of your class
  extending the BlockBase class (as of Drupal 8 beta 6).

return array(
      '#theme' => 'your_module_theme_id',
      '#someVariable' => $some_variable,
      '#attached' => array(
        'library' =>  array(
          'your_module/library_name'
        ),
      ),
    );

  Attaching configurable JavaScript

  In some cases, you may want to add JavaScript to a page that depends
  on some computed PHP information.

  In this case, create a JavaScript file, define and attach a library
  just like before, but also attach JavaScript settings and have that
  JavaScript file read those settings, via drupalSettings (the successor
  to Drupal 7's Drupal.settings). However, to make drupalSettings
  available to our JavaScript file, we have to do the same work as we
  had to do to make jQuery available: we have to declare a dependency on
  it.

  So that then becomes:

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

and

$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

https://www.drupal.org/developing/api/8/assets


How do I get 2 separate displays of a view in one page that are displaying contents from two different content types?

If You are not comfortable with Panels, then

Create one of the required views, a view page (for Content-type A) with proper contextual filters.
Create the other view (Content-type B) as an attachment (attachment Views).

Select INHERIT contextual filters while creating it.
Basically, both the views should have the same contextual filters.

Attach it to the first view created for Content-type A.

This might be an alternate solution.

For overriding the default taxonomy term paths check this tutorial -
Overriding the default taxonomy page with a view in Drupal 7

Hope you are able to manipulate the contextual filters properly in the views.


Usually, you should control join type using views Advance relationship options. By enabling "Require this relationship" you are telling Views to use "INNER" Join instead of using "LEFT" Join. If this option is somehow not working here is how I would solve this problem.

use \Drupal\views\ViewExecutable;
use \Drupal\views\Plugin\views\query\QueryPluginBase;

function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
   // check your view ID:
if ($view->id() === 'id') {
 //Get your table info object;
  $table = $query->getTableInfo('table');
if (isset($table['join']->type) && $table['join']->type === "INNER") {
//Change your Join type;
 $table['join']->type = 'LEFT';
   }
 }
}


fields with Image styles only showing placeholder

Here is an overview of how file permissions should be set on a Drupal installation: https://www.drupal.org/node/244924

If you scroll down there is a shell script that you can install on your server and it will fix all file/folder permission errors.

Your issue is definitely a folder permission error, Drupal has to be able to write to the /files folder. It makes new directories for each style, each image, each size so one folder may exist but the others may not be able to be made.


No, the browser needs to download the markup and stylesheet to do its job, and you shouldn't try this kind of thing, It doesn't work and is annoying to site visitors.

Please read the answers on this similar StackOverflow question: https://stackoverflow.com/questions/6597224/how-to-hide-html-source


Could you get what you want from the Custom Breadcrumbs module?

  Allows administrators to set up parametrized breadcrumb trails for any
  node type. This allows CCK-style node types to have "Home > User Blog
  >2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases.
  Breadcrumb visibility can be customized via a php snippet.


Deleting feature[]=logo from .info file, enlarged the whole website font-size?

@codenext: Can you paste the screenshot of the css in chrome devtools. So that we can see which css code is creating that problem?


how to add the radio button intead of checkbox in tableselect drupal 7

As per Adding checkboxes to a table, you need to set #multiple on the element:

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#multiple' => FALSE,
);


Dependent Dropdown based on Database Queries

use FF or Chromes console.log function and be sure your Ajax is being called properly. Or use dd() from the devel module to log whats going on when the change event or other JS actions are called.


error with phpunit execution: how to set PHP Test class path in phpunit.xml?

You must point in the phpunit.xml file to drupal's bootstrap.php file. See a working phpunit.xml file example for Drupal 8 here: http://cgit.drupalcode.org/permissions_by_term/tree/tests/phpunit.xml.dist


Solved!

Instead of trying to change the maxDate using Drupal.settings.datePopup[id].settings, pass it as options to datepicker using the jQuery Datepicker syntax $( ".selector" ).datepicker( "option", { name: value } );

Here is the solved JavaScript code:

(function($){
Drupal.behaviors.meh_profile = {
attach: function (context, settings) {
    $('#edit-profile-main-field-profile-date-of-birth-und-0-value-datepicker-popup-0').attr('disabled', 'disabled');
    $('input:radio[name="profile_main[field_profile_gender][und]"]', context).change(function(){
        var genderVal = $('input:radio[name="profile_main[field_profile_gender][und]"]:checked').val();
        if (genderVal == Drupal.settings.gender_options.gender_female) {
            $("#edit-profile-main-field-profile-date-of-birth-und-0-value-datepicker-popup-0").val('').removeAttr('disabled').removeClass('hasDatepicker').datepicker({
                changeMonth: true,
                changeYear: true,
                yearRange: '-75:-18',
                maxDate: '-18y'
            });
        } // if female
        if (genderVal == Drupal.settings.gender_options.gender_male) {
            $("#edit-profile-main-field-profile-date-of-birth-und-0-value-datepicker-popup-0").val('').removeAttr('disabled').removeClass('hasDatepicker').datepicker({
                changeMonth: true,
                changeYear: true,
                yearRange: '-75:-21',
                maxDate: '-21y'
            });
        } // if male
    }); // gender change handler
}
};
})(jQuery);


Node post date in views exposed filter as a select list

You can start with Views, dealing with Combined filters. Try it with option Grouped.


Depending on the purpose of that dropdown, you should have a look at the entity reference module. Here is an excerpt about it from the module's project page:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

  Two implemented on top of the Options module (Select and Radios/Checkboxes),
  Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

  Two formatters:

  A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.)
  A "Rendered entity" formatter, that renders the references entity using a configurable view mode

  Integration with Views (for both forward and backward references)
  Integration with Entity Metadata (and as a consequence with Search API and the like)
  Integration with Devel generate
  Integration with Feeds and Migrate (>= 2.3) for painless data import


"The form has become outdated. Copy any unsaved work..." when saving/deleting content

Take a look at the answer provided by warwickshaw on D.O https://www.drupal.org/node/2241311#comment-8791165

  To fix the error message: 'The form has become outdated. ...' try
  moving the 'drupal_private_key' in to the Drupal 7 settings.php file.

  The Issue See
  https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_ge...
  drupal_get_private_key() is not a safe function.

  When variable_get() doesn't return a $key (some outage, maybe a
  memcached restarted) you suddenly and silently get assigned a new
  drupal_get_private_key.

  If you are using multiple server Drupal system where each server has
  it's own MySql database replicated from a Master DB, a Slave DB can
  end up with it's own key (which Master doesn't see) and when the slave
  gets it's key cached in memcached the fun begins.

  Mean while back in the D7 Admin, forms and menus that once worked
  start failing!

  The Fix The only safe place in D7 whether using a single or
  multi-server setup is to move 'drupal_private_key' value to the
  settings.php file.

  Add $conf['drupal_private_key'] = '...';

  To get the value execute on the Staging server (MySql master) drush ev
  'print drupal_get_private_key();' and assign the value above.

  You should have something like this (these are example values, don't
  use) $drupal_hash_salt =
  'j8lnCx-XF3gq_2NmnnHZ61Q3xlbKHFSzZ9EmUouPwKU';
  $conf['drupal_private_key'] =
  'Fnll-1ZETTb03CgO6PW4COWT7CjTBeRSAQzXqerq6FA';

  Check the hash_salt is behaving correctly (should match
  $drupal_hash_salt) drush ev 'print drupal_get_hash_salt();'

  Copy these setting to all other servers in the same Drupal cluster.

  On Stage update 'drupal_private_key' row with value used in the
  settings.php file. This will replicate and reset any MySql slaves out
  of sync. update variable set value = '[drupal_private_key]' where name
  = 'drupal_private_key';

  On Stage execute drush cc all

  Clear your browser cache.

  You are good to go!

  New D7 Projects When ever you create a new Drupal project make this
  the first task after installation.

  Other Symptoms of the Same Bug Multiple Save, Cancel buttons appears
  after clicking Save or Cancel in Page layouts.


Facet API : How to change some behaviors like having input radio instead of checkbox

What you're doing to change the markup should just work, here's a working example I have from a project that does just that:

function foo_facet_items_alter(&$build, &$settings) {
  if ($settings->facet === 'my_facet') {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_ucfirst($item["#markup"]);
    }
  }
}

I can confirm that it works as expected.

As far as switching the select for a radio, the error you get is pretty common and you're probably not removing/adding extra Form API options that aren't allowed for one of the types.

Radio buttons behave a bit different than selects, you might not be able to just switch the #type and have it work, if this is still relevant, please post the code you're using to alter that form... thanks!


Remove drupal parameters from form submitted via POST

You can make a call to external website using drupal_http_request in form submit handler.. Define extra submit handler using hook_form_alter and

$form['#submit'][] = 'YOUR_FORM_SUBMIT_HANDLER';

For Example

// Adds a submit handler/function for your form

function YOUR_FORM_SUBMIT_HANDLER($form, &$form_state) {

    $options = array();
    // Array keys are matching the key that the remote site accepts. URL encoding will be taken care later.
    $options['data'] = array(
        'firstName' => $form_state['values']['firstName'],
        'lastName' => $form_state['values']['lastName'],
        'email' => $form_state['values']['email'],
        'name' => $form_state['values']['name'],
        'phone' => $form_state['values']['phone'],
    );
    $options['data'] = http_build_query($options['data']);
    $options['method'] => 'POST';
    $url = 'https://[url path to external site]';

    // Put your additional headers here. Cookie can be set as well.
    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');

    $options['headers'] => $headers;

    // Submits data to the remote server from the drupal server. User will remain in the Drupal form submission chain.
    $response = drupal_http_request($url, $options);

}


Programmatically showing the summary of a post

You can use teasers from node. In node.tpl.php you can use $teaser variable to print it.
In other templates, you need to use node_load().

$node = node_load(211); // 211 is the Node ID
print $node->teaser;


Hide block on specific page through custom contextual link

You can use context module which has good number of contextual filters that can be used dynamically to display/hide a block.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.


How to migrate Ubercart Shop (drupal 6) to another CMS / Shop system as Commerce, Magento, etc?

How to migrate Ubercart Shop (drupal 6) to another CMS / Shop system as Commerce, Magento, etc...

A typical approach to migrate such site to D7 is to use the Migrate module.

  Is there any easy way to migrate a Drupal 6 Ubercart store to another CMS or shop system?

Using the Commerce Migrate Ubercart module will pretty sure simplify things. Some details from its project page:

  Commerce Migrate Ubercart is a migration using Commerce Migrate and the Migrate suite that can migrate 6.x and 7.x Ubercart stores from either the existing Drupal database or an external database on the same machine.

Since this includes D6 and Ubercart, you should definitely have a look at this module if you go for Drupal Commerce

  What would you use instead of Drupal Ubercart?

Going for the Drupal Commerce module is definitely an option you should consider, and the modules mentioned above should help (a lot?) to get you there.


How to use the managed_file field in a custom form plugin

I think the issue we had was understanding the data that the form was sending back to us when using the 'managed_file' type. This creates an entity of File and stores the image information directly into the table called 'file_managed' in your database, but also saves the file to your directories based upon where you send it. So take this code for example:

$form['mainslider_slide_one']['image_dir'] = [
    '#type'                 => 'managed_file',
    '#upload_location'      => 'public://module-images/home-slider-images/',
    '#multiple'             => FALSE,
    '#description'          => t('Allowed extensions: gif png jpg jpeg'),
    '#upload_validators'    => [
      'file_validate_is_image'      => array(),
      'file_validate_extensions'    => array('gif png jpg jpeg'),
      'file_validate_size'          => array(25600000)
    ],
    '#title'                => t('Upload an image file for this slide')
];

For the '#upload_location' we are telling the file to be stored in our public folder under the specified directory (sites/sitename/files/ directory). So now we have the actual file stored where we want, as well as data stored in the database.

When we receive the information back (under validation for instance) we have the following code:

public function validateForm(array &$form, FormStateInterface $form_state) {
    $managedFileId_imageOne = $form_state->getValue(['mainslider_slide_one' => 'image_dir']);

    if (empty($managedFileId_imageOne)) {
        $form_state->setErrorByName('test', 'No image found for image one');
    }
}

The result of $managedFileId_imageOne will either be an empty array (whereas I am sending an error message back) or an array of fid's.  The fid is the location in the database.  This is the information that we ended up saving into our settings file data. So when we pull the information into our program we are querying for the 'fid' located in the 'file_managed' table using the Entity::load method.

NOTE/UPDATE:

Don't forget that files uploaded in this manner are currently, by default, set to be temporary (status column in the "file_managed" table). You need to set the file to permanent to manually set status to 1 so they are not temporary. I believe this is functionality that is currently a bug and they are looking into possibly updating this in future releases.

Sample from Jasodeep

   $image = $form_state->getValue('image');
   $file = File::load( $image[0] );
   $file->setPermanent();
   $file->save();

Hope this helps at least get you on your way!


Use hook_user_insert() to take action on the user account after creation:

function mymodule_user_insert(&$edit, $account, $category) {
  //@TODO: use $account->uid & $account->status to do stuff
}


Syntax highlighting for admin-side text areas (during node or block editing)

I use the BUEditor module, for which you can add syntax highlighting with some additional configuration.  You can specify to only allow administrators access to this interface via the module's options page.

Step-by-step instructions

Install the BUEditor module (I used 1.6).
Download bue.highlight.min.css and bue.highlight.min.js from this page.  I placed these files in a bueditor directory inside the directory for my custom theme.
Go to the BUEditor config page: /admin/config/content/bueditor.  Edit the settings for the relevant version(s) of BUEditor (probably default, but it depends on which you assign to each role-- if you want, you can configure different BUEditor options per role, but then you will need to set up syntax highlighting for each.)
On the Editor settings screen, click the Editor paths tab and then add the following Editor specific library files (My example assumes that you put the JS in your theme directory.):

  %THEME/bueditor/bue.highlight.min.css
  %THEME/bueditor/bue.highlight.min.js

Then, scroll down to the bottom of that page (under Buttons) and add tpl:syntax along with this code:

js:
BUE.postprocess._turnOnHlight = function(E, $) {
  setTimeout(function(){E.highlight('html')});
};

Then save the configuration and you should be good to go.


logging in after exiting website under maintenance

Are you logging in as Admin (user 1) or a site administrator?  They are the only ones who have the rights to login while the site is in maintenance mode.  The URL should be http://www.example.com/user/login or http://www.example.com/index.php?q=user .

KMT


How do I add certain Fields to a View (not all fields are showing in Add list)?

Is there some way to associate the View with a certain group of Fields

Yes, this is done by adding a relationship.

For example, if you create a content view and add a relationship of Content: Author, you will now be able to add user fields, such as User: Picture or User: E-mail to name a few.

Therefore, look if the already built in view is using a relationship. (It's under Advanced, located on the far right of the View's settings).


Modifying the node-form in domain module

I found my solution: I set the respective values in the node save events, which didn't require to use the interface provided by Drupal. I didn't have concerns on the form and its settings.


Assuming these are normal image fields, you can go to Structure > Content types, then select manage display for your product node type.

There, click on the settings button on the right side of your image field. A settings form should be expanded now, where you can configure in which image style you want them to show up and to what they should link. If you choose link to file, clicking on it will link directly to the original file (only).

An alternative is provided by the Colorbox module, which allows to display the images in a popup-like overlay. The same settings form should have more options to choose from once you installed that module.


How do I target Ajax Loader Throbber in CSS?

To target the overlay you can use .ajax-progress and to target the throbber you can use .ajax-throbber.

Something like this would position the throbber on the center of the screen:

.ajax-progress {
  position: fixed;
  z-index: 99999999;
  background: rgba(255,255,255,0.6);
  text-align: center;
  width: 100%;
  height: 100%;
  top:0;
  left:0;
}

.ajax-throbber {
  left: 0;
  position:absolute;
  right:0;
  top: 50%;
  transform: translateY(-50%);
}


Form - Prepopulate and hide field with given argument

There appears to be a dev version of the Prepopulate module for Drupal 7:

The Prepopulate module allows fields in most forms to be pre-populated from the $_REQUEST variable.
For example, the following URL,
http://www.example.com/node/add/blog?edit[title]=this is the title
will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets. For examples on usage for all of these cases, please read the USAGE.txt file that comes with the module or you can read the online handbook page.

So you would just have to craft that button on your City node page to include the additional variable for your city field.
If for whatever reason this doesn't work exactly to your liking, eg, I am not sure if it allows for hiding of the prepopulated field, it would be fairly trivial to craft the functionality in a form_alter() hook in a custom module.


If you want to import a lot of different content types

you might want to check the Migrate Module out

It supports Organic Groups.

Migrate Documentation

// Maybe this can help you some of the way

Migrate Classes: Location CCK to Address Field

Migrate Extras

This might also give you a clue on how to do it. I know its

Migrate OG


cannot create taxonomy terms using hook_enable solved!

$vid remains FALSE throughout the entire first run. You need to set it after the vocabulary object is saved:

...
taxonomy_vocabulary_save($vocab);
// Add this next line
$vid = $vocab->vid;


How do I dynamically change the $GLOBAL['base_path'] variable?

I don't think base path is what you need here.
Once the user's page is loading it is too late to change their URL, unless you redirect them them to the /members or /guests url with drupal_goto().

Base path is also not what you need because base path is telling drupal where your files are in the web root, so changing the $base_path global is likely just going to break your site unless your files are in /var/www/yoursite/members and /var/www/yoursite/guests (I'm assuming your web server setup here for the paths).

The main thing here is that you need to make sure your users are actually hitting the paths www.example.com/members/path and www.example.com/guests/path and then you have to make drupal handle those paths appropriately or you will just get page not found errors.

This is how the drupal multilingual (locale) system works.
It rewrites urls that appear on the page to point to www.example.com/langcode/path so the user is actually navigating to those pages. If there is no langcode part drupal just assumes the default language.

In drupal 6 this is ingrained into the url() function, which calls language_url_rewrite().
In drupal 7 the local module has an implementation of hook_url_outbound_ater() (local_url_outbound_alter()).

You could replicate this by implementing custom_url_rewrite_outbound() (read the docs for that, it is not a normal hook).
Or use the url alter module and implement its hook_url_outbound_alter() hook.

That's not all though, because users are going to paths like www.example.com/langcode/path those paths have to be valid drupal menu system paths or else drupal won't know that functions to call for that given page.

For the multilingual system drupal core handles this in the bootstrap phase, before any menu handling has happened.

See _drupal_bootstrap(), which for the DRUPAL_BOOTSTRAP_LANGUAGE phase calls drupal_init_language(), which in turn calls language_initialize().

language_initialize() has code in it that detects the language from the url and then removes that language portion of the url from the $_GET['q'] variable so everything from then on just sees www.example.com/path and the page loads as normal.

If you were to use this same approach for your path then the system would try to load the menu item for www.example.com/members/path and it would likely not exist and you would get page not found errors.

However you could the also add an implementation of hook_boot() that does something similar to language_initialize() and save a global variable of your user type (member or guest) and then removes that part of the url from $_GET['q'] before the menu handler runs.

From then the $_GET['q'] variable doesn't have your user type anymore but you will be able to use the user type global you created from your other custom code if you need to.

This system relies on there being a default user type for when guests or members are not present (which can easily happen, for example the user can just type in the url manually instead of clicking one of your altered links).

So your system would have to assume the user type or work it out in some other way (easy because you have user_is_logged_in() or global $user to determine the user type). It just means in these cases the user doesn't get to see that url scheme you want with the user type in it.

As you can see this is a complex requirement and the solution doesn't have 100% coverage so i it was me I would reconsider doing this at all.

Alternatively you may be able to just have a members area, full of pages like views and nodes that do really have urls like /members/something, but not change the url for the whole site (although I'm just making assumptions on your requirements now).


Try clearing cache and then visiting login page again, that should show Form ID. It will be hidden again when you refresh login page.

use \Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function [MODULE_NAME]_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  echo $form_id;
  switch ($form_id) {
    case 'user_login_form':
      // Do your code here to alter login form.
      break;
  }
}


Can i attach a views grid of images in a carousel

Views Slideshow
You could use the Views Slideshow module for this. Here is a quote from its project page:

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

News item slideshow (such as the title, image and teaser of the last 5 news articles submitted).
The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).
Rotate any image, based on any filters you can apply in views.
Hottest new products for any ecommerce drupal site.
Rotate contact links, share links, etc.
You could rotate entire nodes, categories, image galleries, etc. I wouldn't suggest it, but you have that power.
It's also a great space saver. Places where you had multiple images or multiple items such as RSS feeds or category listings can now be presented in a slideshow.

The possibilities are really endless, as the more ways you can think of to categorize and add to views, the more you can rotate.

Further enhancements
Possibly you may want to further extended this with related modules  (there are dozens of modules to further enhance views) such as Views Slideshow: Galleria. Here is a quote from that module's project page:

Integrating Galleria with Views Slideshow.
Galleria is a JavaScript image gallery framework built on top of the jQuery library. The aim is to simplify the process of creating professional image galleries for the web and mobile devices.

jCarousel
Another option is to consider the jCarousel module. Here is a quote from its project page:

... This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.
Features:

Built-in Views support.
AJAX-loading of additional items as needed.
Carousel pager/navigation to jump between multiple pages.
Circular wrapping of items.
API for direct usage of jCarousel without Views.


How do I prevent a form from being cached for anonymous users?

To update:

In order to prevent a form from caching at all, you can include the following #cache key in your form:

$form['#cache'] = ['max-age' => 0];


Found the answer here:
https://drupal.org/node/1051320

Create your view as normal.
Add your image field as normal.
Go to relationships
Add Relationship "File Usage"
Go back to fields section
Under groups, a new option "File" will appear
Selecting file will output the path for every file field on your site. If you want it just for one particular image field follows these steps:

Add the new "File" field
In file field, select "exclude from display".
Go back to your image field (created in step 2)
Select "Rewrite the output of this field"
Under tokens, use the token for the file field (created in step 6). (NB the file field must come before the image field, or else the token will not appear).

Hope this helps somebody!


how to add .js programatically when in an entity list

The correct approach is doing it using a custom list builder, assuming you are using that and not a view.

class MyListBuilder extends EntityListBuilder {

  public function render() {
    $build = parent::render();
    $build['#attached']['library'][] = 'yourmodule/library';
  }
}

Then specify it in the annotation of your entity type.see Node/User or so on how to do that, most entity types specify either the default or a custom list builder.

If it's a view then you can implement one of the many views hooks, if it's not your own entity type then I'm not exactly sure why you need to add a JS there and you should explain in more detail what kind of list it is and what your JS does.


Search API Views - Show search string in text


How to make Drupal 8 forget an old deleted field?

Execute this to remove deleted field(s), pending deletion:

drush php-eval 'field_purge_batch(1000);'


How to properly call dependency classes (Class not found)

Yes this is right the onlything is never try to composer require X in a modules directory even though you can include a composer.json file in the module its self
always make sure you are in the site root. then the paths will be correct.


By using form_alter hook you can alter the type of field. I am assuming you are using Drupal 7. The below code will alter the field_working_as List (text) profile field in user_register_form in to checkboxes.

And the same field will show as selectbox in profile edit page. I hope this will help you.

function mycustommodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    unset($form['field_working_as']['und']['#options']['_none']);
    $form['field_working_as']['und']['#type']='checkboxes';
  }
}


How to set a Rules Condition "Does this node with date field use repeating functionality"?

I'm not aware of any Rules Condition to check for repeating attributes. However you may possibly get it to work by using a loop within your Rules Actions, to actually check how many repeating values you actually have.

To do so, have a look at the rule included in the answer to "How to add up all items of a field collection field using Rules?". You could use a similar set of Rules Actions (combined with whatever Rules Events/Conditions you want) to simply calculate how many values you have.

For that, all you need to do is to initialize some counter to zero (before the loop starts), and then add "1" to that counter for each list item. And after the Rules Loop is finished, you invoke a separate Rules Component to which you pass the counter (= result of your calculation) as a parameter. Within that Rules Component, you can add any Rules Conditions you'd want. And in its Rules Actions you perform the actual Rules Actions you want.

It might be worth to pass your date field also as an extra parameter to the Rules Component, so that possibly you can get access (whatever you mean by that) to that "repeat rule" also.

Note (about your comment): Using node:field-time:1:value might also work, but you'd first have to do some testing with that "data field is empty". I doubt a bit what happens in the case where you only have 1 value (= node:field-time:0:value), while you would be referring to node:field-time:1:value ... In that case it might cause some type of data exception or so (not sure though, to be verified). How about some data comparison related to node:field-time:1:value, or (more "safe") using a text comparison with an appropriate RegEx?


How to define custom date format in page.tpl.php?

You are right using the correct API format_date(). What you need to do is passing correct value to it.

<?php print format_date(time(), 'short'); ?>

According to the API doc, the function signature is:

format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)

And it explained how you should handle the translation.

  $langcode: (optional) Language code to translate to. Defaults to the language used to display the page.

$langcode is handled automatically if you keep it as default value.


Copy contents from an field entity reference

Using Entityreference prepopulate and Entityreference prepopulate token

Once installed, you will need to create a link for the Child on the Parent page's template that includes tokens for the fields you want prepopulated. The answer here shows how to string multiple values together.

If it needs use a Node Reference rather than an Entity Reference, then Node Reference URL Widget and Prepopluate will do approximately the same thing.


User group / user access to files Drupal 7

Drupal supports this natively.

Use private file access and content_access to support granular access to your content.

Due to some bugs here and there I had to rebuild the permissions (/admin/reports/status/rebuild) after configuring content_access a usual clear cache wont work here.


How to create a Category Article listing with subcategories?

Drupal Taxonomy is used to Categorize Content... Please have a look @ detailed tutorial here how to use taxonomy concept in Drupal to create categories and tag contents with categories.

You need to use views module to display the content by category.

Hope it helps.


If you begin to add nodes and never edit them, like you would do when migrating data to a new Drupal installation, then the nid and vid would increment at the same pace, and would happen to be the same. After first edit though, assuming you have revisioning on, the new vid would be what ever is the next available number for all revisions.


menu block or view that shows only siblings and parents

It seems this question has an ongoing patch at https://www.drupal.org/node/2811337 (which i found just after offering the bounty! :)


How to list custom navigation menu with submenu?

You can use below function to render your custom menu your way

function _custom_menu_overview_tree_form($tree) {
  $output = '';
  foreach ($tree as $data) {
    $item = $data['link'];
    if ($item && $item['hidden'] == 0) {
      if(strtolower($item['title']) == 'about us page condition'){
            $output .= '
';
      }else{
            $output .= '
';
      }
      (0 == $item['plid']) ? ($class = 'parent') : ($class = 'child');

      if(isset($item['options']['attributes'])) {
        $attributes = array('attributes' => array_merge($item['options']['attributes'], array('class' => array($class))));
      } else {
        $attributes = array('attributes' => array('class' => array($class)));
      }

      $output .= l($item['title'], $item['href'], $attributes);

      if ($data['below']) {
        $output .= '
' . _custom_menu_overview_tree_form($data['below']) . '
';
      }
      $output .= '
';
    }
  }
  return $output;
}

And use below code in your html.tpl.php or where you want to render your menu

$menu_items = menu_tree_all_data('your menu name');
echo '
' . _custom_menu_overview_tree_form($menu_items) . '
';

Please try this and let me know if any issues.


I don't think there is, weirdly enough I've just been looking for pretty much the same thing...I couldn't find one so I just wrote a helper function:

function _lightbox_link($image, $style_name) {
  $image_style = theme('image_style', array(
    'style_name' => $style_name,
    'path' => $image['uri'],
    'alt' => $image['alt']
  ));

  $url = image_style_url($style_name, $image['uri']);

  $link = l($image_style, $url, array(
    'html' => TRUE,
    'attributes' => array(
      'rel' => array('lightbox-gallery')
    )
  ));

  return $link;
}


If you are using the Drupal Console, you can use the command :

drupal router:debug

This will print all the routes on your site including routes from core.

The other solution is to use the Devel module and going to "devel/routes".


You can declare the script file inside mymodule.info with

scripts[] = myscriptfile.js

This way it's gonna be included in every page of your site, exactly the same result you obtain adding it manually to hook_init.

In case you want it only when you render a form, add this to the form declaration

$form['#attached']['js'][] = drupal_get_path('module', 'mymodule).'myscriptfile.js';


On your view page,  click on the 'Field settings'. i.e.

Format:
Show: Fields | Settings

Click on the 'Settings'. You will see a popup window. And select the 'RAW OUTPUT' for the respective field. Also, you can provide ALIAS for the field.
I guess you were looking for this option.


Is it possible to turn on/off two layers at once with the openlayers_plus module?

I think the best way to do this would be to create a function that uses setVisibility()

For example (without toggle logic):

$('.my-button').click(function(e) {
  e.preventDefault();
  var ol = $('.openlayers-map').data('openlayers');
  ol.openlayers.getLayersByName('myLayerName1')[0].setVisibility(false);
  ol.openlayers.getLayersByName('myLayerName2')[0].setVisibility(false);
});


Remove library from page based on node field value

Drupal has dedicated theme hook, hook_page_attachments_alter, for this scenario. Your theme can hook into it, check the rendered route (for your node type), and take action on the $page['#attached']['library'] render array accordingly:

function MYTHEME_page_attachments_alter(array &$page) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if (!is_null($node) && $node->getType() == 'page') {
    //@TODO: remove the appropriate library items from $page['#attached']['library']
  }
}


How to make CKeditor format code indenting elements and adding line breaks?

Finally I found a solution, thanks to the post CKEditor with well-formatted html source code.

I just added to a custom module the following code:

function mymodule_editor_js_settings_alter(array &$settings) {
  foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
    if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
      $settings['editor']['formats'][$text_format_id]['editorSettings']['customConfig'] = base_path() . drupal_get_path('module', 'mymodule') . '/ckeditor_config.js';
    }
  }
}

to include a configuration a file called ckeditor_config.js that contains the code:

CKEDITOR.on('instanceReady', function(ev) {
    // Sets indentation of source code
    ev.editor.dataProcessor.writer.setRules( 'div', {
                indent: true,
                breakBeforeOpen: true,
                breakAfterOpen: true,
                breakBeforeClose: true,
                breakAfterClose: true
            });
});

Doing this, CKEditor will keep the indentations in the source code, and a well formatted code easy to read.


How do I display category items in a view content pane?

Try this...

In your view that displays movies and plays, add the term id (tid) to the list of fields.
Rearrange your fields so that the tid field is above the term name field.
In the tid field settings, check Exclude from display.
In the settings for the term name field, check Rewrite the output of this field. In the text box underneath, enter this:

[placeholder2]

Expand the Replacement patterns section of the dialog box to see what to insert in place of placeholder1 and placeholder2. Click Apply to close the dialog box, then save your view.

Now, in your content pane view, you simply have to match up the contextual filter with the tid. One way to do that is in your contextual filter settings, click the Provide default value radio button, select Raw value from URL from the dropdown, and set the path component to match where placeholder1 appears in the link generated in your other view.

This is the simplest way to do it and it has some limitations (e.g. a non-intuitive Url) but hopefully is enough to get you on the right track. One you're comfortable with it you can experiment with different arguments and different ways to pass them. The link below has a good description of how to use contextual filters:

https://www.metaltoad.com/blog/using-drupal-contextual-filters-views


How to use "content entity" type in a View?

Add a views_data handler to the entity type. Either the core standard EntityViewsData
content_entity_example/src/Entity/Contact.php
  *   handlers = {
  *     "views_data" = "Drupal\views\EntityViewsData",

or a custom handler:
content_entity_example/src/Entity/Contact.php
  *   handlers = {
  *     "views_data" = "Drupal\content_entity_example\Entity\ContactViewsData",

content_entity_example/src/Entity/ContactViewsData.php
<?php

namespace Drupal\content_entity_example\Entity;

use Drupal\views\EntityViewsData;

/**
 * Makes the content_entity_example entity available to Views
 *
 * @ingroup content_entity_example
 */
class ContactViewsData extends EntityViewsData {

  /**
   * {@inheritdoc}
   */
  public function getViewsData() {
    $data = parent::getViewsData();

    // $data from the parent is enough to make it work but modify as required.

    // Give it a more description name in the dropdown when creating a new view.
    $data['contact']['table']['base']['title'] = $this->t('Content Entity Example Contact');

    // Make the Name field appear to Views as Last Name
    $data['contact']['name']['title'] = $this->t('Last Name');

    return $data;
  }

}

To apply this code to the example module use the patch from this issue https://www.drupal.org/project/examples/issues/2725833


I am not sure if that is available by default (found no result on searching), but one thing that you can do is declaring your own Drush command in 3 easy steps:

Creating the Command File:

  ( Give the right name to the command file and place it into a folder that Drush will look, That name must end with .drush.inc (in our case it will be publish.drush.inc) and must be placed either in the folder of a custom module on your site (will work for that site if the module is enabled) or in the .drush folder in your server’s root directory).

Declaring the Command Function: To declare a new Drush command you have to invoke hook_drush_command() in the file you created above and below the php opening tag. Example as below:

  function publish_drush_command() {
    $items = array();
    $items['publish-content'] = array(
      'description' => 'Publish content',
      'aliases' => array('pc'),
      'arguments' => array(
        'type' => 'Nodes of this type will be published',
      ),
    );
    return $items;
  }

Note: This command is declared in a file that has been placed in the .drush folder that resides in the VPS’s root folder.

Here we have declared a new command called publish-content (a new key in the $items array). The description and what’s included in the arguments key is what you will see when you run the drush help publish-content command. What’s actually helpful here is that you can also specify an alias (or shortcut) that can be run instead of the longer publish-content version. In this case, drush publish-content will equal drush pc.
3. Declare the Command Callback Function: Now you need to write the code that you want Drupal to perform when you run the custom command. The name of the function needs to be in the format: drush_command_name. (Note: dash in the command name becomes an underscore in the function name).

function drush_publish_content($type) {
  $nodes = node_load_multiple(array(), array('type' => $type));
  $count = 0;
  foreach ($nodes as $node) {
    if($node->status == 0) {
      $count++;
      $node->status = 1;
      node_save($node);
    }
  }
  if($count > 0) {
    drush_print($count . " nodes of the " . $type . " content type have been successfully published.");
  }

  else {
    drush_print("No nodes of the " . $type . " content type were published.");
  }
}

This callback function takes as argument the machine name of the content type of all the nodes we want published. This gets passed as a command argument like so (Example: pulish the contents of blog content-type):

  drush publish-content blogs

Drush will then print out how many nodes have been published (displaying only the number of nodes that have been in fact affected by the command).

References:
https://www.digitalocean.com/community/articles/how-to-declare-your-own-drush-commands-with-your-vps
https://github.com/edvillan15/node-tools/blob/master/node_tools.drush.inc


Having issue with multiple calls of same view

Yes, this issue arises because you have a current copy of view and you not destroy it. Kindly use below code for multiple use (suggested to be every-time).

$viewname = "profile_match_with_job";
$display_id = "block_3";
$view = views_get_view($viewname);
$view->set_display($display_id);|
$view->set_arguments(array(138,80)); // views Contextual filter parameters
$view->pre_execute();
$view->execute();
$myresult =  $view->result;
$view->destroy();


Undefined index errors only on one subdomain

Since you don't say anything about any debugging effort, it's hard to say, but one thing repeatedly stands out as clearly wrong

$node->field_X['und']['0']

which should always be

field_get_items($node, 'field_X);

Since your domains are foo.com, www.foo.com, foo.fr and www.foo.fr, this might indicate that you use more than one language, which is exactly when ['und']['0'] is likely to break for you. Notice that field_get_items() will return an array instead of a single value, so you will need to amend your code to deal with that.


Import configuration in CI/CD script does not work

After running composer install, you need to add a drush cr before you run drush cim. All together:
composer install
./vendor/bin/drush cr
./vendor/bin/drush config-import -y


two changes i made

form .field-multiple-table td.field-multiple-drag { width: 30px; padding-right: 0; position: absolute; left:0px; /*LTR*/ } form .field-multiple-table td.field-multiple-drag a.tabledrag-handle { padding-right: 0em; position: absolute; left: 520px; /*LTR*/


How to translate custom content block title?

To use the title from the custom content block entity (not the title from the block placement config):

function mymodule_preprocess_block (&$variables) {
  if ($variables ['elements'] ['#base_plugin_id'] == 'block_content') {
    $variables ['label'] = $variables ['content'] ['#block_content'] ->label ();
  }
}

This also respects translations and does not require access to block placement for translators.


Yeah, I think your guess is good.

Create a block programmatically: Create a custom Block. This means to create an own module with this block.
The created block should appear (when the module is activated) in your block settings, there you can add it.
The content of your block appears where you added it.

Another option, easier but not so beautiful, could be to hook in your THEME.theme. As an example you can add the menu in the  template_preprocess_html:

function template_preprocess_html(&$variables) {
    $variables['my_own_menu'] = $my_own_menu;
}

Then you can use the variable {{ my_own_menu }} in your html.html.twig and do whatever you want to do.


Is caching certain parts of a page possible?

If you use the Page manager together with Panels, then yes, this is trivial. Each "Pane", in a Panel can have it's own cache settings, and they can also be set on a per user basis, meaning you can cache things, even if they include data that is unique for the logged in user.

If you also add Cache actions on top of that, you can add some really aggressive caching that will be cleared only, and exactly, when the relevant data updates.


You can use the SQL operator LIKE in an entity query and append the wildcard % to the string:

$result = \Drupal::entityQuery('taxonomy_term')
  ->condition('name', 'david%', 'LIKE')
  ->condition('vid', 'tags')
  ->execute();

$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadMultiple($result);


Migrate file field paths not the actual file

Say I drag and drop files from a source site into the folder structure of a new site (destination site) that I'm migrating content to.

Dont do this. Migrate D2D has file handling classes to move the files for you. In the UI it's super easy, in code you select the correct file handing class.

Read the documentation on migrating files for D2D. There are 4 cases it supports, depending on how the remote file needs to be fetched.

In the D2D UI you just want to be sure to setup the File_class value for your migration ok. Typically the Files are migrated (moved) to Drupal as 1 of the 1st auto-generated migrations. Then in Node content that relates the migrated files to the (migrated) Node you set file class to FileFID and select the previous Source Migration that moved the file into the new site.

EDIT

So for example with a website with existing image fields in a content type. On the destination Drupal 7 side of the migration I tell it the legacy field and tell the configuration to use MigrateFileFID this will map just the file ID between the 2 drupal instances:

See field_ofellow_photo above for an example of this configuration for D6 -> D7.

Then Migrate will see the information for the migration steps:

If you use MigrateFileFID then Migrate doesnt (necessarily) move the files I believe if you leave off the destination information, it just moves FIDs. See the documentation on MigrateDesinationFile and MigrateFileFid.


You can try Mime Mail module.

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

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


When you access the field on your node you will get the file id. This can be passed to file_load which will return the file object. One of the properties is filepath which holds the path to the actual file. I'm guessing that's what you are after - images doesn't use href <a> tags do.


Advance search between two content types that are linked by entity reference fields

In Views this called "Relationships".

Create view that show "Type A", then in filters add "Type B" to be also allowed.
Then add relation on field that you use for entity reference and made this relation required.

Now "Type B" content will be also displayed in view if related "Type A" is match search criteria.


How to use entity form in pop-up window?

Make sure you have 7.x-1.4 of the entityform module installed or this won't work.
Install the Modal operations module.
Install the Modal forms (with ctools)
Enable the Modal entityforms module that came as part of the modal module.
Create a link to your modal popup like this:

Open Entity Form in Popup!

I found this blog post very useful for figuring this out and getting it working.

If you cannot use version 7.x-1.4 for some reason then there is a patch here that some have had success with however I could not get it to work this method.


How do I fix missing input fields in panels

Just a reference for those who come along after this.

Try to find out if anyone else has touched your code specifically .js or .CSS and CSS was the issue here.  ONe of the content editors added some css into a block: fieldset{display:none;} well that closed the fieldsets in that popup window and I am sure in other places on the site that we had not run into yet.


When can uid 1 get an access denied page?

After trying to fix this for an hour, I tumbled on the solution right after I posted this.  Apparently, it is possible to set a theme as "default" but not have it "enabled", and have a site function normally.  Enabling the theme fixes the problem.


How to display legal link on registration page in colorbox node?

You will have to add the class colorbox to the Terms and Conditions link generated by the Legal module.

This is easily setup through a theme_ function override.
Use the following code in your theme's template.php file:

    function YOUR_THEME_legal_accept_label($variables) {
      if ($variables['link']) {
        return t('Accept Terms & Conditions of Use', array('@terms' => url('legal')));
      }
      else {
        return t('Accept Terms & Conditions of Use');
      }
    }

Note: you might have to tweak the output in the popup, but that's outside of the scope I guess.


So you just need to place 1 contextual filter for nid and one relationship with referenced entity, and use that relationship in fields.
See the attached screenshot of a demo view.


how to generate view data from sql query?

It looks like you're selecting 30 nodes of type 'post' and grouping them by user.  This view would be pretty easily built using the views UI. Once you've created the view, you should be able to add an author uid as a grouping field.  This will group the post fields by author.

Let me know if you have questions.


I'd recommend installing and using Drush with GIT instead of only GIT when it comes to security or any other updates. It's really easy to update with drush.

drush up

will update everything

drush up modulename

will only update a module of your choosing

drush up drupal

will only update drupal core.


Tax rate select missing from product price in commerce 8

Try these 3 references:

1) Need to modify tax type based on user field in Drupal 8 Commerce 2

Here you can see an example of creating your own service in a custom module to interact with the default TaxOrderProcessor or writing a simple module to override the tax order processor service at all.

2) https://www.flocondetoile.fr/blog/apply-vat-rate-product-drupal-commerce-2

Here you can see how "to vary an applicable VAT rate according to a product, or a product type, we just need to implement a service that will declare the trade_tax.tax_rate_resolver tag with a priority at least higher than the default TaxResolver provided by Drupal Commerce."

3) https://www.rapiddg.com/blog/modifying-product-prices-drupal-commerce-2-drupal-8

Here you can see another example of application of "resolvers", the concept that do the work done bu Rules at Commerce 1, which is the key of the previous comment (link 2).

Ps: At the moment, poor documentation about this stuff, and no UI to manage this BASIC feature :-(


Filedepot - Where is the file management interface?

Looking at the hook_menu() implementations for Drupal 6 and 7 these two paths stick out:

Filedepot ( http://mysite.com/filedepot )
Filedepot Settings ( http://mysite.com/admin/settings/filedepot )

The rest of the paths defined are variations on the above, or AJAX callbacks, so I think one of those is the path you're looking for.


How can i make a Slide Show for my Home Page with the following requirements

Views slideshow has solutions to be responsive, see:
http://drupal.org/node/1510526

You can also embed a custom slideshow navigation using views and a global counter in the view, using Tokens you can replace the counter text with whatever you want. An example of this can be found here:
http://blog.urbaninsight.com/2012/01/03/building-slideshows-with-navigation-based-views

All of your criteria are met by Views Slideshow I believe, you just have to get crazy with CSS. I have made the following slideshow with Views Slideshow using the navigation tutorial above, Views, Views Slideshow and Nodequeue.

example view slideshow config

default rendering of ViewsSlideshow in Admin area, an un-themed slideshow

Final themed slideshow with custom navigation

In my case I overlay the navigation into the view, I had to use jQuery to achieve some of the dimensions at runtime and CSS3 stuff for opacity of my overlay div.


How to show the user badges in my tpl.php file?

The first thing that you need to do is add the php tag to the code:

<?
if (module_exists('user_badges')) {
 print user_badges_for_uid($uid);
}
?>

But for to that this code works you need to pass the uid = User Id

This code should do the job:

<?
// Getting the actual user.
global $user;

if (module_exists('user_badges')) {
 print user_badges_for_uid($user->uid);
}
?>


How I can include Commerce SKUs in search result?

Add a field or attribute to your index

Most likely, you need to add the SKU field to your index. Since most search api implementations of Commerce index display nodes AND their connected products, you will need to use: https://www.drupal.org/project/commerce_search_api for connecting referenced product properties with your display nodes.

Then, you will need to add the SKU field to your product display index. A good step-by-step for this is here (search for "define index fields" on the page): http://www.webwash.net/drupal/tutorials/intro-search-api-part-1-how-create-search-pages

Add an indexed field or attribute to search results

Finally, if you want to managed the fields that appear in search results, you will need to modify the view and/or the display mode being used to render the results.

Commerce allows "field injection" for display nodes that allow you to inject default product properties on display. But note that if you search for "Red Shirt" and the display node that has this product is by default "Blue Shirt" then, when that node is rendered, it's likely going to render the "Blue" and not "Red" SKU.

Probably need to create a hook_form_alter() that can determine if the add to cart form is being generated inside search results and trying to make it understand which SKU should be a part of the result.


this worked! found the answer here https://www.drupal.org/project/drupal/issues/2923723#comment-12343660
 field_blog_post_date:
        plugin: iterator
        source: field_blog_post_date
        process:
          value:
            plugin: substr
            source: value
            start: 0
            length: 10


How to create a map like the one used on the drupal.org homepage?

Perhaps this is useful: How the Drupal.org home page map works

This is the actual module: HTML5 user geolocation


How to populate an Entity Reference field from a modal AjaxResponse?

Figured out it was the InvokeCommand i needed and to set "val" to the referenced entity title with id in ().

  $nid = $form_state->getValue('nid');
  $node = Node::load($nid);
  $value = $node->getTitle() . ' (' . $nid . ')';

  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $response->addCommand(new InvokeCommand('#edit-field-ref-to-bundle-a-0-target-id', 'val', [$value]));
  $form_state->setResponse($response);


I was able to get it to work, but I'm not entirely sure why it works. What I did was after saving the duplicated subqueue I loaded it once again then applied the items before saving for a second time.

    $subqueue_clone->save();
    $newsubqueue_clone = \Drupal::entityTypeManager()->getStorage('entity_subqueue')->load($clone_id);
    $newsubqueue_clone->set('items', $clones);
    $newsubqueue_clone->save();


Add a Résumé content type. Add your text fields and a file field to this content type. Set your permissions accordingly, allowing whichever user roles you want (or anonymous) to create this content.

This will allow people to upload their resumes.

Get the Rules module and create a rule a bit like follows

Events

Node - After saving new content

Conditions

Node - Content is of type:  Résumé

Actions

System - Send mail

You can use Token to put content fields into the email, but I'm not sure if you can put links to the file.  If not, you can at least put a link to the content that contains the file.

Lastly...use Views and create a simple view that shows Résumé content -From here, get  sorted however you want.

For extra points, you could also use the Flag module to flag résumés (e.g. follow up, spam, not useful and so forth), and then create more views based on those flags (so you can only see useful résumés for exampleetc).


How to use rendered file entity in view header as background image for view

Is there something the Background Images Formatter module can do for you?

The module allows you to set a background to any CSS selector(s) you can think of. Combine it with a selector built with NID-token (NID field in Views, excluded from display, and its token used in the selector you assign the background-image to), and it will probably save you some templating headaches.


Check out the nodereference url module. It's designed exactly for this use case.


Block/mosaic type homepage with heavily interactive menu

There is a module to do that, but you have to customize it. It have the animation option using filter, probably you can try to use that filter as menu or change that filter like menu using CSS.

Views Quicksand see the Demo and website using Drupal.

  Quicksand is a JQuery Plugin that provides a nice animation for
  filtering or reordering lists of content. Views Quicksand integrates this effect into Views. Therefore it provides a views style-plugin, which allows you to alter most settings the quicksand plugin provides.


How do I schedule a reminder email with Rules to users that have flagged an event?

Sounds like you know how to set up the Flag. Triggering a Rule with Flag is piece of cake and NodeOne has an create 15min tutorial covering all the details. They also have all the needed training on Rules if your fuzzy about Rules in general. Once your ready to set up your rule and you have the event to trigger it, you can set up the email action following a recipe similar to this other answer. In your case you have the future event. Lullabot has a tutorial specifically on the Rules Scheduler.


TB Mega Menu is a pretty awesome module, but we've been using it for a few years and occasionally run into issues where the rendered menu doesn't appear to reflect the menu's structure. It gets "stuck." Here are a few things that have worked for us, in various combinations:

Clear your site's cache.
Rebuild your site's menus (use devel for this).
For the items that aren't showing, create a new parent menu item and move the child items to under the new parent and delete the old parent menu item.

From our troubleshooting, we've determined that TB sometimes seems to "lose track" of the menu and basically all of these efforts are intended to get TB to re-sync.

Hope it helps!


After logging in the user is not directed to the homepage

It is a default option.
But you can redirect user to any page by using hook_form_FORM_ID_alter
Example:

 /*
* Implements hook_form_FORM_ID_alter
*/

     function YOUR_MODULE_OR_THEME_NAME_form_user_login_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      // Alter login form and add own custom submit handler.
      array_push($form['#submit'], '_custom_user_login_form_submit');
    }

 /**
 * Custom submit handler for login form.
 */

    function _custom_user_login_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
        $parameter = 'some_value';
        // Set redirect to login form.
      $form_state->setRedirect('custom_page', ['parameter' => $parameter]);
    }

For the front page default front page name is view.frontpage.page_1. So it should be

 function _custom_user_login_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {

          $form_state->setRedirect('view.frontpage.page_1');
        }


You can try these modules.

https://www.drupal.org/project/form_mode_control https://www.drupal.org/project/form_mode_manager

I prefer form_mode_control. Form_mode_manager create a view form mode for all content types.

These modules can be restricted with permissions. But I prefer https://www.drupal.org/project/field_permissions; it is more acurated by field.


Adsense tokens "[adsense:XxY:SlotID]" in node content aren't being replaced by ads

Wow, finally solved. Since pages are rendered via Panels the solution was to check "Clean" option from Panel content manager to the node body which removes "dangerous" markup.

In other words it seems like node body doesn't respect text format settings when rendered via Panels. Or at least not all of it without checking this option.


How change views exposed filter drop down format?

It appears currently that you have the select box as multi-select. Do you want the user to choose 1+ values or only 1 value? If you want it as a dropdown in the more classic sense, then limit that to one value. BEF would allow you to modify some of the aspects of the select box, as well as allow you choose to use checkboxes instead of a dropdown.


After the field has been created you will see the field on retrieve user resource (not index), and you will be able to send data on crud operations.


Error after transfering process to a new host

These kinds of problems (after transfer to a new host) might be caused by some type of permission problems. At least if we may assume that the table in the error message does actually exist (if not that needs to be addressed of course).

So I'd verify that the userid specified in the settings.php file, has the appropriate access to the Drupal database (also specified in settings.php).

Another option is to verify the various items mentioned in https://www.drupal.org/node/1308308


You can try using Premium content  Module..

Project Page Says

  This is useful on a news or membership site where teasers are
  available to the general public but the full body is only available to
  privileged users. Premium nodes appear in listings with full title and
  teaser available to anyone. If a user does not have adequate
  privileges, the default behavior is to show a simple message, but you
  can use Panels or theme overrides to do more custom things.

Found this article in D.O which will be useful for your issue.


You may setup different VCL configurations for your environments.

It can be easily done with wrapping them by host condition:

sub vcl_recv {
if (req.http.Host ~ "^example.com")
 {
 ...
  if (req.url ~ "^/something") {
   return(pass);
  }
 ...
}
}

Please, take a look on my blog post http://blog.tenya.me/blog/2011/12/19/varnish-simple-virtual-hosts/, it describes how to do configuration separation.


How to manage and delete orphaned node references?

This situation is exactly like deleting comments which are entities when deleting the node they are attached to. So I looked at the code in comment.module to see how it is handled there. Here is my solution:

/**
 * Implements hook_node_delete().
 */
function helper_node_delete($node) {
  if ($node->type == 'product'){
    $nids = db_query('SELECT entity_id FROM {field_data_field_review_reference} WHERE field_review_reference_nid = :nid', array(':nid' => $node->nid))->fetchCol();
    node_delete_multiple($nids);
  }
}

This also means that I can test to see if the node type is a review so all node types that reference the review can be handled too since hook_node_delete is recursive in this instance.


D7 bug with db_select, 'addExpression' and 'having' conditions?

Sounds like the problem is the paging, because it's the count query that gives you the error. For debugging, try to disable the paging.

If it works without paging, it means that the automatically generated count query doesn't work and you need to create one manually and then set it with $query->setCountQuery() after doing the extend('PagerDefault').

The automatically generated query removes all selected fields, which then causes the error when you are trying to access it in the having condition.


Cycle comments on field--comment.html.twig

You can try something like this:

   {% set pre_render = comments['#pre_render'] %}

   {% for key, item in comments if key|first != '#' %}
     {% if key != 'pager' %}
       {% set item = { '#pre_render': pre_render, 0: item } %}

{{ item }}

     {% else %}

{{ item }}

     {% endif %}
   {% endfor %}


Access submitted form data in custom callback before hook_mail_alter()

Why do you need a submit callback at all? The built contact message is available in hook_mail_alter(), you can just access the submitted data there?

This is from a custom project where we did something similar:

/**
 * Implements hook_mail_alter().
 */
function yourmodule_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];

    if ($contact_message->bundle() != 'feedback') {
      return;
    }

    $recipient_address = $contact_message->get('yourfield')->value;
    if (\Drupal::service('email.validator')->isValid($recipient_address)) {
      $message['to'] = $recipient_address;
    }
  }
}


How to change line-wrap length on Drupal 6 Blog?

hi you can use the module maxlength to achieve it, it can be used to set the charecter limit to any of the cck field like body, summary, title etc.


How to Embedd youtube video in body field (converts URLs into embedded players)?

I’ve found and tested this module which do excaly what I want :

Url to Video Filter

  This module adds a new input filter that automatically converts URLs
  for various video sharing websites into embedded players into the
  text.

Here is a screenshot of the CKEditor filter :

I’ve tested this module on multiple sites and it works very well.

Currently this module supports the following services : YouTube / Vimeo

EDIT
Now, It also supports Youtube URL with parameter like ?rel=0 (rel=0 is used to disable related videos shown at the end of a video)


Child menu items not displayed in drupal

Try this:

<?php
$menu_name = variable_get('menu_main_links_source', 'main-menu');
$tree = menu_tree($menu_name);
print drupal_render($tree);
?>

Also Drupal doesn't make things hard, you just don't understand it yet.

It is just a tool suited to specific tasks. If you just want to make a blog then don't use Drupal, just use Wordpress.

If however you want a very powerful CMF (Content management framework, not system) to create complex systems with lots of inter-related entities then continue to learn Drupal - I think it's the best tool for the job.


How to alter tabs that have wildcard in bartik main menu

Solve this by page preprocess function. Not sure is this correct way or not.

function mobitek_custom_preprocess_page(&$vars) {
  $nid = arg(1);
  $node = ($nid && arg(0) == 'community' && is_numeric($nid)) ? node_load($nid) : FALSE;
  if (!$node) {
    return;
  }
  $main_menu = &$vars['main_menu'];
  $mobitek_menu_items = array(
    'communities',
    'reports',
    'administrators',
    'users',
  );
  // Remove links by this.
  foreach ($main_menu as $key => $menu_array) {
    if (isset($menu_array['identifier']) && in_array($menu_array['href'], $mobitek_menu_items)) {
      unset($main_menu[$key]);
    }
  }

  ....

  foreach ($community_links as $title => $community_link) {
    $new_tab = array(
      'title' => $title,
      'href' => $community_link,
    );
    array_unshift($main_menu, $new_tab);
  }

  // Add link by this.
  if (arg(0) == 'community' && arg(2) == 'profiles-roles') {
    $on_roles_page = (arg(3) == 'user-roles');
    $profiles_item = menu_get_item('community/' . $nid . '/profiles-roles/user-profiles');
    $vars['tabs']['#primary'][] = array(
      '#theme' => 'menu_local_task',
      '#link' => $profiles_item,
      '#active' => !$on_roles_page,
    );
    $roles_item = menu_get_item('community/' . $nid . '/profiles-roles/user-roles');
    $vars['tabs']['#primary'][] = array(
      '#theme' => 'menu_local_task',
      '#link' => $roles_item,
      '#active' => $on_roles_page,
    );
  }
}


with the same views you can use filters in global variables and this module https://www.drupal.org/project/views_autocomplete_filters you can make this


Update failed on Metadata module, any easy fix?

So the solution here was that the backup (done by my ISP) did not fully restore.  I think they forgot to recursively restore and just did the main Drupal root.  Once I asked them if they were sure they restored recursively and there was a long pause (a few hours, at which point the site started working again) they came back and said they'd missed a few files.

So luckily that solved it.  I did not need to configure anything or run any update.php or such.  Just restored the entire Drupal directory and all subdirs and such, and a database restore to match.  That fixed it.  Whew!


Be sure that the string you sent by mail is already translated in the target language. Otherwise it will not work. You can check it here http://youwebsite.com/admin/config/regional/translate


You want the Field Permissions module, it does exactly that:

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

It gives you granular access control based on role for every field, e.g.:


Add taxonomy terms to search autocomplete

Default search can either display users or content. Apart from this it won't show you any results.


View with Page display won't show menu tab for an alias

Create your views as follows:

Challenges -

path: node/%/challenges

tab: menu tab with title Challenges

filter criteria: type = group

Contextual filter: nid, and in section WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED specify validation criteria: Validator Content, Content types group

Members-

path: node/%/members

tab: menu tab with title Members

filter criteria: you con't need any as you are displaying users (you have a view of users)

relationship: add a relationship to the node table such as: User: Content authored. This will bring in the related nodes.

Contextual filter: nid, in the section rlationships nodes must be selected. Specify validation criteria as Validator Content, Content types group

And these two tabs will now show up only for node type group. If you need it on other content types as well then adjust your views filter criteria and contextual filter validation as required.


To enable error messages, add the following to your index.php:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


Dynamic select list in the form (dependent dropdown)

You can use Ajax to accomplish this. Drupal 7 has good Ajax support now. On your first select list (city) you'll need to add Ajax information. Then, the second select list can be populated based on the information in the first. You can also even hide the second select list until an option in the first is selected, and I'll explain how to do that in a bit.
First, to set up the basic form:

$form['city'] = array(
  '#type' => 'select',
  '#title' => t('City'),
  '#options' => $options,
  '#ajax' => array(
    'event' => 'change',
    'wrapper' => 'squadron-wrapper',
    'callback' => 'mymodule_ajax_callback',
    'method' => 'replace',
  ),
);
$form['squadron_wrapper'] = array('#prefix' => '
', '#suffix' => '
');
$form['squadron_wrapper']['squadron'] = array(
  '#type' => 'select',
  '#title' => t('Squadron'),
  '#options' => $squadron_options,
);

This is just the basic setup of the elements. Now you'll need a way to determine what options should go in squadron. First you need to make your Ajax callback identified in 'city' select list. In most cases you can just return the element that wraps the ajax element, in this case $form.

function mymodule_ajax_callback($form, $form_state) {
  return $form;
}

Now, when the 'city' select list changes it will rebuild the squadron-wrapper part of the form. Your 'city' value will now be in $form_state['values']. So, when the form is rebuilt we need to determine what options to give to the select list based on the value of 'city'.

// Get the value of the 'city' field.
$city = isset($form_state['values']['city']) ? $form_state['values']['city'] : 'default';
switch ($city) {
  case 'default':
    // Set default options.
    break;
  case 'losangeles':
    // Set up $squadron_options for los angeles.
    break;
}

// If you want to hide the squadron select list until a city is
// selected then you can do another conditional.
if ($city !== 'default') {
  $form['squadron_wrapper']['squadron'] = array(
    '#type' => 'select',
    '#title' => t('Squadron'),
    '#options' => $squadron_options,
  );
}


AJAX callback inserts empty div with large amounts of data - Whats happening?

Turns out there was some UTF8 encoding in a field that was causing the output to not be rendered. Appears to be something in the output buffering that caused this and not drupal. Adding a utf8_decode when the fields print has resolved the issue.


Is it possible to show taxonomy terms in a views filter sorted alphabetically?

Upgrade taxonomy and views to the latest version and select the following options.

And when the filters terms are being listed, they will be listed in alphabetic order.

You can confirm that there is hierarchy in terms and they are not alphabtic in order.


Yes. We can use the Mimemail + SMTP Authentication Support. Plz check the link http://drupal.org/node/1200142 and check the part : Alternative Approach: Mail System + SMTP + Mime Mail


How to see #default_values in multiselect form

The default value needs to be the key of the options array, so assuming the rest of your code is correct, this should work:

$form['group_config']['tematicas'] = array(
  '#type' => 'multiselect',
  '#title' => t('Temáticas'),
  '#options' => $options3,
  '#required' => TRUE,
  '#multiple'=>TRUE,
  '#default_value'=> $term2->tid,
  '#prefix' => '

',
  '#suffix' => '
',
  '#size'=>20,
);


"Variants" are typically used / related to "Page Manager", which is part of the CTools module. The "simplest explanation***" is ... not "simple" to provide. However there is an interesting (amazing?) video intro about it: refer to Learn Page manager! Part 3: Variants and selection rules.
While you're at it, you may want to look at the entire (impressive) video series around there, i.e. Learn Page manager!. Here is a summary of the entire set of videos about this topic:

Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
The screencast series is targeted at experienced Drupal developers.
Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Some more recommended (free) tutorials that you may want to consider, and which will help a lot to understand the typical Drupal terminology in your question:

The 32 (!!!) great video tutorials Learn the Rules framework, organized in 7 chapters, about the Rules module.
A similar set of 8 video tutorials about the Flag module.
The set of 30 video tutorials about the Views module.

In Drupal 8, Page Manager has become a separated module, while formerly (up to Drupal 7), it was part of the CTools module. Here are some more quotes from the (D8 related) project page:

It supports the creation of new pages, and allows placing blocks within that page.
Like Drupal 7's Page Manager, it provides a concept of "page variants", each with their own selection conditions.
Additionally, it can be used to take over an existing page, like overriding /node/% to change what is displayed when viewing a node.
It utilizes the core Conditions, Context, and Blocks APIs to accomplish this.

So that's part of the changes coming up in the CTools module in D8.


The first snippet doesn't work because Drupal doesn't use any 'gitlab_refresh_token' array index, and it doesn't know any field with that name. If you were trying to change the value of a field added with the field UI, the array needs to have a different structure, to be saved.

The second snippet works because Drupal effectively uses that array index, as also said in the documentation.

  Key / value pairs added to the $edit['data'] will be serialized and saved in the {users.data} column.

// Prepopulate $edit['data'] with the current value of $account->data.
// Modules can add to or remove from this array in hook_user_presave().
if (!empty($account->data)) {
  $edit['data'] = !empty($edit['data']) ? array_merge($account->data, $edit['data']) : $account->data;
}


Why variable_get() returns all values of checkboxes list, even if checkbox is not selected?

Because Drupal doesn't actually filter out empty checkboxes values, it sets them to zero. I think this is so you get an accurate representation of what options were available when the form was submitted, and what was actually chosen by the user.

It's easy to get the filtered array though, using array_filter():

$values = array_filter(variable_get('mymodule_menu_perm_menus', array()));


How are values passed from the database to the templating system?

The function that does the job is theme_render_template(), which contains the following code.

  // Extract the variables to a local namespace
  extract($variables, EXTR_SKIP);

  // Start output buffering
  ob_start();

  // Include the template file
  include DRUPAL_ROOT . '/' . $template_file;

  // End buffering and return its contents
  return ob_get_clean();

The function is called from theme(), which uses the following code.

// Default render function and extension.
$render_function = 'theme_render_template';
$extension = '.tpl.php';

// The theme engine may use a different extension and a different renderer.
global $theme_engine;
if (isset($theme_engine)) {
  if ($info['type'] != 'module') {
    if (function_exists($theme_engine . '_render_template')) {
      $render_function = $theme_engine . '_render_template';
    }
    $extension_function = $theme_engine . '_extension';
    if (function_exists($extension_function)) {
      $extension = $extension_function();
    }
  }
}

// In some cases, a template implementation may not have had
// template_preprocess() run (for example, if the default implementation is
// a function, but a template overrides that default implementation). In
// these cases, a template should still be able to expect to have access to
// the variables provided by template_preprocess(), so we add them here if
// they don't already exist. We don't want to run template_preprocess()
// twice (it would be inefficient and mess up zebra striping), so we use the
// 'directory' variable to determine if it has already run, which while not
// completely intuitive, is reasonably safe, and allows us to save on the
// overhead of adding some new variable to track that.
if (!isset($variables['directory'])) {
  $default_template_variables = array();
  template_preprocess($default_template_variables, $hook);
  $variables += $default_template_variables;
}

// Render the output using the template file.
$template_file = $info['template'] . $extension;
if (isset($info['path'])) {
  $template_file = $info['path'] . '/' . $template_file;
}
if (variable_get('theme_debug', FALSE)) {
  $output = _theme_render_template_debug($render_function, $template_file, $variables, $extension);
}
else {
  $output = $render_function($template_file, $variables);
}


Which user does the Rules module execute as?

And here is a module that could assist:

Rules switch user

  This module adds two new Rules actions:

  Switch to another user
  Switch back from another user

  These actions could be useful when you have an operation that you want
  an unprivileged user to use but it fails because the user doesn't have
  sufficient permissions.

Create a fictitious user with sufficient permissions and switch to this user when performing the Rules action and switch back again when done.

EDIT This answer is just a workaround and does not speak to the question directly, namely why the current permissions doled out are not allowing the Rule to execute successfully.


There is a feature request for the Migrate module: Export migration configuration as code. Beware that this is highly experimental! Here is the summary of the issue:

Apply this patch to the Migrate module and be sure to clear cache. This patch makes your configuration exportable as a Feature.
You can now create a new Feature on the source site and select your configuration inside the Migrate fieldgroup. Check all options that apply and download/export your Feature.
Copy the Feature to your target site, enable it and then revert it to copy all your settings.


Forms are manipulated in Drupal 8 predominantly by using services, twig templates and yaml files, rather than hooks. Hooks are still used, but the code in the hooks is limited in comparison with Drupal 7.

On the other hand, new D8 concepts such as Services and Event Subscribers have become much more important.

Here's a good tutorial showing how to alter the Drupal 8 login form:

https://www.foreach.be/blog/how-manipulate-forms-drupal-8

Follow the steps in the tutorial to create a simple form_overwrite module.

When you get to the step where you create the src/Routing/RouteSubscriber.php file, you'll diverge slightly from the tutorial.

Instead of altering the routeSubscriber for user.login, you'll want to alter the one for node.add:

<?php

/**
 * @file
 * Contains \Drupal\form_overwrite\Routing\RouteSubscriber.
 */

namespace Drupal\form_overwrite\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // This is the one from the linked article
    if ($route = $collection->get('user.login')) {
      $route->setDefault('_form', '\Drupal\form_overwrite\Form\NewUserLoginForm');
    }
    // This is the one you want to write
    if ($route = $collection->get('node.add')) {
      $route->setDefault('_form', '\Drupal\form_overwrite\Form\NewNodeAddForm');
    }
  }
}

Armed with this knowledge, you should be able to adapt the linked tutorial to suit your needs. Good luck!


When the update manager reports 'no release found', it typically means you installed from a git (formerly CVS) checkout. If you did do this, you'll need to run the Git deploy module to properly track module versions.

If you didn't use direct git checkouts, but rather, downloaded normal releases from Drupal.org, it may be a bug, which should be reported with as much detail about your setup as possible in the Drupal 7 issue queue.

Edit: you may also be experiencing this Drush issue.


Is this the correct way to complete aliases.drushrc.php in order to avoid messing with other accounts?

"when I try to access ssh using one of my site´s credentials (not the
  root user, but one of the site´s admin), it doesn´t recognize drush
  commands."

The only requirements for using Drush from another user (than the one that installed it) is a) the drush directory should be readable, and b) drush should be in your PATH.

It is okay to install Drush once per user.  I use a custom move-in script to accomplish this, but in my case it's rare for me to have more than one Drush-using user on one system.  Setting the PATH in your bashrc to include the Drush directory of the root user is also fine.  [Aside: it is best to avoid calling Drush using the root user, for security's sake.  Any Drupal module can define code that runs during the execution of any Drush command.]

You aliases file looks okay, except that you only need to define remote-user for remote aliases.  The aliases you are defining are local, so remote-user will be ignored.  The alias file should go in the ~/.drush directory (inside the home directory of the user that is calling Drush).

You can download the Drush chapter of DGD7 for free; it is one of the book's sample chapters.  It does a pretty good job at describing alias files and configuration.  Although it was written for Drush 4, most of what it describes is unchanged in Drush 6 and Drush 7.  Be sure to also read all of the Drush README.

Update: Forgot to mention: to use your aliases, type drush @site1 status.  If your settings.php file is in a folder called default, then you may also access your site via cd /home/site1username/public_html && drush status.


sf Smallscreen menu button reverts to full desktop menu when scrolling down

I can't say for sure without seeing your code, but I wonder if this is maybe because you have some Javascript that does an add/remove class or changes the structure of the menu in order to make sticky nav items take up less space when you scroll. This symptom could only be caused by Javascript detecting the scroll behaviour, and as far as I know, Superfish does not have this feature natively (though I could be wrong, I am not overly experienced with this specific module).

If this is the case, right click and inspect code, then look for things that change dynamically on scroll. Any names of classes that are added might give you a clue as to which module is causing this. It does sound like a conflict, though, and not Superfish itself.

If that is not helpful, do you have a dev site up that we can take a look at?

Good luck!


This question is not exactly related to drupal.

Still you can use jQuery to make it work.

Just get the wrapper class of parent element

jQuery('#edit-field-hobby-und .form-checkbox').click(function(){
  jQuery("#edit-field-hobby-und .form-checkbox").each(function(){
  jQuery(this).attr('disabled',true);

  });
  jQuery(this).removeAttr('disabled','disabled')
})

Here form-checkbox is the class of the checkboxes and edit-field-hobby-und is the id of its wrapper.

Hope it will help!


User's homepage depending on their organic group

There is a module (Frontpage) that allows to set a different front page for anonymous users, and authenticated users.

The module allows third-party modules to alter the page to which the users are instead redirected, or to alter the structure array used to render the page.

As alternative, you can create a custom module that, using code similar to the one used by Frontpage, redirect users to a specific page, basing on specific criteria.

The module should implement hook_menu() and associate a menu callback to, for example, http://example.com/frontpage; the page callback of that menu item should simply verify a condition is verified, and then redirect the users to a specific URL.

The code skeleton could be something similar to the following:

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  $items['frontpage'] = array(
    'page callback' => 'mymodule_frontpage_view',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function mymodule_frontpage_view() {
  // These variables can be useful to redirect the users
  // to specific pages, basing on the language currently set for
  // the content, or on the fact the user is logged in.
  $langcode = $GLOBALS['language_content']->language;
  $logged_in = user_is_logged_in();
  $usergroups = og_get_groups_by_user($user);
  $group = og_load($gid);
  $groupnode = $group->etid;
  $redirectpath = 'node/'.$groupnode->nid;
  drupal_goto($redirectpath);

}


Using the service file.uses you get the file media object:

Example:

$file is a loaded file object.
$file = \Drupal::entityTypeManager()->getStorage('file')->load($fid)
$result = \Drupal::service('file.usage')->listUsage($file);

$result should now contain an array like so:

$result['file']['media']['4372'] = 2;

Where 4372 is the media id. and 2 the times the file is used.

From the docs of listUsage:

@return array
   *   A nested array with usage data. The first level is keyed by module name,
   *   the second by object type and the third by the object id. The value of
   *   the third level contains the usage count.


How do I set up an entityreference entity base field to show as a link to the target entity?

->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'entity_reference_label',
        'settings' => [
          'link' => TRUE,
        ],
      ])

and optionally to allow it to be configured in the UI:
      ->setDisplayConfigurable('view', TRUE)


Panels on the front page get invalid $user variable

Ok, got is. Panels have its own caching that was switched on.


connecting words with a integer field in a content type

It's quite simple, really. Create a content type for parts. Use title for part name, remove body, add integer field for price.

In your "maintenance" content type, create Entity reference to parts. That's all. Views are able to use Entity references ad views relationships, so sum of prices will be doable.


Is there a module to show a quick message to a user or role?

See the User Alert Module. This module provides a simple way to show a short-term urgent message on the website. Think of CNN Breaking News, when they show a short message the top of the site (or the 'Welcome!' style messages at StackExchange websites). This module works for both anonymous and authenticated users by using a cookie, and recording actions in the database. This solves the need to show messages independent of the users authenticated status. With User Alerts, you can: Alert users about breaking news, or a special same-day sale for ecommerce. You can also set expiration timers for alerts (1 hour, 3 hours, Never, etc) (Drupal 6 Only, D7 requires Scheduler).


How can I change the search form placeholder value?

You don't alter a TranslatableMarkup object: You replace it with another TranslatableMarkup object you obtain from t('The new placeholder') or
new TranslatableMarkup('The new placeholder') (or a method returning a TranslatableMarkup object).

function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['title'] = t('The new placeholder');
}

The result of this code is the following (on Google Chrome running on OS X El Capitan).

What you are showing is not the placeholder, but the input title. To change the placeholder of a form element, you should use code similar to the following one.

function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['placeholder'] = t('The new placeholder');
}

Using this code, you get the following result.


How to fined the fields biggest weight in form

the solution is in this code:

  $elements = Element::getVisibleChildren($form);
  $weight = 0;
  foreach ($elements as $el) {
    $check = strpos($el, 'field_');
    if ($check !== FALSE && $form[$el]['#weight'] >= $weight) {
      $weight = $form[$el]['#weight'];
    }
  }

  $form['register'] = [
    '#type' => 'submit',
    '#value' => t('Register'),
    '#submit' => array('NAME_OF_A_FUNCTION'),
    '#weight' => $weight + 1,
  ];


file_unmanaged_copy - Any service alternatives?

This changed in Drupal 8.7.0
See https://www.drupal.org/node/3006851
try {
  \Drupal::service('file_system')->copy($source, $destination, $replace);
}
catch (\Drupal\Core\File\Exception\FileException $e) {
    // Log or set message or doing something else.
}


Drupal add class to body if page is unpublished

in your theme's template.php:

function mytemplate_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    if ($node->status) {
      $vars['classes_array'][] = 'published';
    } else {
      $vars['classes_array'][] = 'unpublished';
    }
  }
}


If you use Meta tag module, you can use following method. From this method you can get Meta tag title and other Meta tags for view section also.

my_module.services.yml

services:
my_module.route_subscriber:
class: Drupal\my_module\Routing\RouteSubscriber
tags:
  - { name: event_subscriber }

my_module/src/Routing/RouteSubscriber.php

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    protected function alterRoutes(RouteCollection $collection) {

        if ($route = $collection->get('entity.node.canonical')) {
            $route->setDefaults(array(
                '_controller' => 'Drupal\my_module\Controller\MymoduleController::view',
            ));
        }
    }
}

MymoduleController.php

namespace Drupal\my_module\Controller;

use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Entity\Node;
use Drupal\node\Controller\NodeViewController;

class MymoduleController extends NodeViewController {

    public function view(EntityInterface $node, $view_mode = 'full',
    $langcode = NULL) {

        $elements = getRequiredDetails($node);

        return [
            '#theme'    => 'your-theme',
            '#contents' => $elements,
            '#attached' => [
                'library'=> [
                    'my_content/my_content',
                ],
            ],
        ];
    }
}