Check if administration toolbar is visible

I think using the user_access function to see if they have the "access toolbar" permission should work.

Some example code:

if (user_access('access toolbar')) {
  // Your logic here.
}


In your views sort settings, make sure your Date sort is the first one, because it seems that there is another sort by entity title applied first

UPDATE
After checking the view export:
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['granularity'] = 'month';

You are sorting the results using "Post Date" of the node, not the date field, you should remove this and add the date field instead


how to setup cron to run everytime when new file is generated in drupal files folder

I want cron to run everytime text file is generated

I think you're misunderstanding what cron is. Cron is

  a command to an operating system or server for a job that is to be executed at a specified time.

It doesn't respond to file system triggers, it's a scheduled task.

If a file is created as part of the normal Drupal content add/edit, you can just implement hook_file_insert():

function MYMODULE_file_insert($file) {
  if ($file->uri == 'foo') {
    // Do something.
  }
}

If you want to start the scheduled jobs running in that hook you can use drupal_cron_run(), but it would probably make more sense not to involve cron in this.


Programmatically Render a Node Edit form with a custom Form Display Mode

The error message says you did not specify a form class, but what it really wants to say is, that you did not specify a form operation with the name of the form mode:

mymodule.module:

function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('my_custom_form_display_mode_id', 'Drupal\node\NodeForm');
}

The form operation needs a form class. This can be the same as for default, which you find in the handlers section of the annotations in the Node class.


Add to Cart Forms Buttons disables Boost Module Caching

I solve the solution by using the following module:

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

One issue I had to was getting these links to display in a Views output as this module turns the add to cart input fields into url links. There was no option in views to change this:

I did a work around to get this to work. Apparently you can just append the product id to the form of this link:

/cart/add/nojs/[product-id]/random-token-variable

I'm not sure what the token is for, but you can just put anything in there and it will still add it to the cart. It works for anonymous, but when your logged in, the link will hit you to an access denied page. I had to do the following to get it to work for authenticated users by commenting out 3 lines in commercie_cart_link.module:

I'm not sure what the token is for.


If this is a contextual filter, you can specify AND or OR logic for the multi-values.

Views says:

  Allow multiple values

  If selected, users can enter multiple values in the form of 1+2+3 (for
  OR) or 1,2,3 (for AND).

So your querstring would have &state=CA+NY+TX to OR California, New York, and Texas states.


How to force rules configuration to load

Your question is a bit confusing, because the default Rule in question is defined by the Payment module in commerce_payment.rules_defaults.inc, not by the PayPal module. It sounds to me like a general case of cache trouble, though in my testing and development of the PayPal module I've never seen any issues with it. If what you mean is simply that the payment method rule is disabled by default, that's just how we've built the modules - enabling it like you show with your custom code will just be a necessary step.


"Content Id from URL" is indeed what you want. The preview box doesn't care for the rest of the url (the /node/*/edit part) and takes everything entered there as an argument.


Yes, the bundle entities themself are not fieldable.

But bundle config entities in the end only exist to manage bundles for the content entity type, and as far as content entities are concerned, bundles are basically just a string (and a bit of metadata like a title). It's even possible to have bundles based on plugins or other things.

Per-bundle fields (usually configurable fields defined only in config, but it would be possible to define them in code as well, currently not trivial) are then attached to a content entity type + specific bundle. Fields actually consist of two definitions: field storage, which is tied to the entity type and defines name and storage-level settings, and the field, which is for a bundle and has bundle-level settings, label and so on. Base field definitions defined in the baseFieldDefinitions() method are exposed as both the field storage and field definition.

Haven't yet read it in detail, but http://www.daggerhart.com/drupal-8-custom-entities-bundles/ is a recent (as in, ~1h old) extensive resource on how to build entity types with bundles.


views preview is different from actual view

This happens because Views UI is a part of administrative interface and uses the admin theme to render previews.

If you would use the same theme for admin and front end - you'd see the same style for your View. Although, you should be aware that not all front-end themes render administrative interface good enough - that is why there is an option to use separate themes for admin and end user interface.

To sum it up - there is nothing wrong with how your View's preview is rendered, because preview and the end result are using different themes.


Verifying that Webforms Hooks are firing

Hook functions are run only when they are put inside a .module file.

So you should move your function into your pvfk.module file. Then visit your /admin/build/modules list so Drupal will refresh hooks list.


taxonomy_term entity loadByProperties depth not found

What is the way to find attributes I can use on loadByProperties()?

I guess with Devel's Kint, loading one and then looking at the "iterator contents" tab
  $entity_manager = \Drupal::entityTypeManager();
  $entity_storage = $entity_manager->getStorage('taxonomy_term');
  $term = $entity_storage->load(1);
  kint($term);


As per my understanding, there are custom modules from which it is updating.

Try searching hooks like hook_user_insert(&$edit, $account, $category) and hook_user_update(&$edit, $account, $category) from custom modules. I hope they might have written a piece of code to update the roles.


Custom theme doesn't show up in Blocks section

If you want to skip the full story

Search for any "*.info" file in your drupal repo that has no line similar to "name = xxxx".

My problem was due to a file named "lcov.info" in a grunt module (grunt-svgmin) in my theme.
I happended "name = lcov is not a theme" at the beginning of the file and the issue fade away.
I'll check svg-min later.

Full story

I had the same notice problem for few days.

The notice was a pattern of 3 lines :

in block.module :

line 146 :

'title' => check_plain($theme->info['name'])

and line 165

'title' => check_plain($theme->info['name']),

in system.module line 647 :

'title' => $theme->info['name'],

This pattern is replicated a variying number of times depending on the pages.

I've tried switching theme in vain.

I first tried to cleanup - hence the last part may apply.
It worked at first (which explains my first response), but came back.

*What I did : *
Open system.module and go to line 645

  foreach (list_themes() as $theme) {
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],

insert these two var_dump lines :

 foreach (list_themes() as $theme) {
    var_dump("-----------------");
    var_dump($theme->info['name']);
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],

Visit your site. It should show something like

string '-----------------' (length=17)
string 'A Theme' (length=5)
string '-----------------' (length=17)
string 'Bartik' (length=6)
string '-----------------' (length=17)
string 'Garland' (length=7)
string '-----------------' (length=17)
null
string '-----------------' (length=17)
string 'Seven' (length=5)
string '-----------------' (length=17)
string 'Stark' (length=5)
string '-----------------' (length=17)
string 'Zen' (length=3)

See this empty line where it is written null ????
This is the F....g theme.
So I looked up to the admin theme to find the culprit and got rid of "engines" folder
...But discovered engine is not a theme, so added it back.
I then went

drush pm-list --type=Theme

And found a disabled theme named *lcov (lcov) *

Believe it or not : it is not a drupal theme !!

it is a file named lcov.info in a node module -- grunt-svgmin -- in my theme

*TADA !!! *

First attempt

The sub theme I heritated was based on ZEN, but zen was not inclued any longer.
Also, theme name included numbers abc123

On a another instance of the local site I :

Added a fresh version of zen and activated it

ran drush zen "My human readable Theme name" mymachinethemename
/* the latter will generate a clean version of your ZEN subtheme */

Adjusted the subtheme.info file for regions, assets and optins

Moved the badly named theme to another folder outside of the site

started adding back assets from the old theme, then templates and includes, piece by piece,
renaming functions to match the theme name

No need to say you need to backup and work on a dedicated branch and database.
You might have to reposition blocks in admin.

Not sure it was the most efficient but as I'm roughly new to drupal it was a great way for me to dig in this legacy theme.

Charles


How to use presave hook to save a field value as node title?

You need to implement the hook_entity_presave()

/**
 * Implements hook_entity_presave().
 */
function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  switch ($entity->bundle()) {
    // Here you modify only your day content type
    case 'day':
      // Setting the title with the value of field_date.
      $entity->setTitle($entity->get('field_date')->value);
     break;
  }
}


In drupal 7 I want to crop same image for different device ratios. How can I do this?

You can use picture module combined with breakpoints module. Worked perfect for me.


How to easily find whether the contibuted modules have been updated or not?

If you are going to attempt an upgrade from D6 to D7, you really should consider using Drush.  Really strongly.  The Drush Site Upgrade command will save you a lot of time, and as a bonus, it will tell you the upgrade status of your D6 modules, and will recommend alternate modules for some modules with no upgrade path, but for which alternatives exist.

If you really don't want to use Drush, you can use the Upgrade Status module.  It also has an upgrade assist block that will help you walk through the upgrade process manually.


Is it possible to filter content  displayed by the  Views module using a regular expression?

Set up a Contextual Filter (previously know as Arguments in D6), they're hiding under the "Advanced" menu of you view. There you can put some PHP code to return a list of arguments.

Here is an example from one of my views, my PHP code return ID for a field regarding the roles of a user, it returns a string separated by "+" like 1+2+3 which is the separator for "OR" so I can select various node which have these values in this field.

This is the configuration to provide multiple arguments.


Before returning response to api you should load field collection using field collection ID, then you can get fields value of field collection.

entity_load('field_collection_item', array($item_id))

Source: How to load field collection


Instead you can use Wysiwyg Media Embed module to embed videos.

  This is an integration of the CKEditor MediaEmbed plugin for the
  Wysiwyg module.


Well, solution was to remove "fake" label and wrapper div which was moved upper to wrap "control-label". All done in THEME_NAME_checkbox(&$variables){}.

            <input type="checkbox" id="edit-submitted-payment-methods-1" name="submitted[payment_methods][1]" value="1" class="form-checkbox checkbox require-one-edit-submitted-payment-methods">

            In cash (to a member or representative)

    In cash (to a member or representative)


Form Submission values in Hook Form Alter method

You'll find submitted values in $form_state['values'], eg

$foo = $form_state['values']['bar'];


How to change a Textfield into a Select list in a Views Exposed Filter

Okay, figured out a solid solution using hook_form_alter.
function MODULENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

    if ($form['#id'] == 'EXPOSED-FORM-ID') {

        $nids = \Drupal::entityQuery('node')->condition('type','CONTENTTYPE')->execute();
        $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
        $options = ['' => 'All'];

        foreach($nodes as $nid => $node) {
          $value = $node->get('FIELD_NAME')->getString();

          if (isset($value)) {
            $options[$value] = $value;
          }
        }

        if (isset($form['FIELD_NAME_value'])) {
          $form['FIELD_NAME_value']['#type'] = 'select';
          $form['FIELD_NAME_value']['#options'] = $options;
          $form['FIELD_NAME_value']['#size'] = 1;
        }
      }
    }

}


Show jCarousel if number of items are more than 3

You can use JCarousel views as block display and then set a visibility condition by executing custom php condition test code (This will require to enable PHP Filter module)

$result = views_get_view_result('view-name', 'display_id');

Then you can analyze the $result and count the number of results.
Most probably you need to do ....

if(count($result)<3)
    return FALSE; //Would not let to show that block
else
    return TRUE; // Would let to show


Site gone offline after aborted mysql restart

It sounds like your database is broken. Drupal can't work without a database, and will display site offline if it can't connect to the database. If you fix your database, (And the data is still intact) Drupal should work fine.

For questions about databases you should go to dba.stackexchange.com


Drush 8x working from directories above web root, but not in web root

Fixed: we figured out that composer and drush were using an older version of PHP which wouldn't work w/ Drupal 8. I still don't understand how the webserver can run one version (phpinfo.php showed the site running the expected 5.6 version) while Drush is set to another. Anyway, finding and aliasing to the proper version fixed the issue. The fix was adding this to .bashrc: (your path might be different).
    alias php='/opt/php56/bin/php'
    alias composer='/opt/php56/bin/php ~/bin/composer'
    export DRUSH_PHP='/opt/php56/bin/php'


Have you tried using Menu Block?

  provides configurable blocks of menu trees starting with any level of any menu.

It does exactly what you're looking for. If you still want to write a custom module I reckon looking through the code for that module would be the best place to start.


Why does drupal_add_css and drupal_add_html not always work?

It turns out that it's a known problem that core provides a generator metatag without an option of replacing or disabling it. The metatag module will do this, or removing it in a custom module via hooking html_head_alter.

I'm not quite certain why drupal_add_css would not work, but adding it with drupal_add_html_head worked.


No administrative CSS for arabic language

By default, many themes have a separate RTL template or CSS. Depending on what theme you are using, you may have to create RTL CSS or change the behavior of which CSS files it's looking for. Try searching for a *-rtl.css file (where * is some name that comes before the suffix.)


How to distinguish radio and checkbox type in drupal

I got the solution, I've used field_info_field function, In the return array  I found the difference in cardinality.

The cardinality for checkbox is -1 and for radio button is 1. Similarly for select is 1 and multi select is -1

I found it myself, is there any better solution than this?


How to add JS Confirmation popup when clicking an #AJAX button in custom module?

I could have sworn it was on so somewhere. But I could not find it quickly. You can try this using the form API in your button. Found here

 '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}')

You can of course use JS as you were. I think you were missing the return false;


Simple:

Twig:

<ul>
  {% for key, icon in icons %}
    <li{{ item.attributes.addClass('pos' ~ key, icon) }}>
  {% endfor %}
</ul>

Source:
http://twig.sensiolabs.org/doc/tags/for.html


How do I use the geoip_language_redirect module?

As the project page says, after you installed the module, you need to set up the geoip_redirect_mapping persistent variable with an array that associate the ISO country code with the language.

variable_set('geoip_redirect_mapping', array(
  'GB' => 'en',
  'FR' => 'fr',
  // …
));

For example, put the following code in setup.php, and save it in the same directory where Drupal has its cron.php and index.php.

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
variable_set('geoip_redirect_mapping', array(
  'GB' => 'en',
  'FR' => 'fr',
  // …
));

Visit http://example.com/setup.php, and the variable will be setup. After this, you can delete the file.

If you have Drush, then you can alternatively execute the following command from the site directory (from the terminal).

php -r "print json_encode(array('GB' => 'en', 'FR' => 'fr'));"  | drush vset --format=json geoip_redirect_mapping -

For the rest, the module automatically redirects the users.

Please note the following

The project page is a little confusing. It's not clear if the persistent variable is geoip_mapping or geoip_redirect_mapping. I didn't find in the code any reference to that variable, so I cannot confirm which one is correct. I would try geoip_redirect_mapping, since that is the one used from the example code; if that doesn't work, I would try geoip_mapping. If neither of them works, I would open a support request for the module, if there isn't one already, asking to change the project page to make it clearer.


Image widget stopped working after core update

Got it - the AJAX form was not being cached by memcache, and so it was failing out every single time. Restarting memcache did the trick.


You can try iTweak Login module to customize the login page. This module have so many settings to customize login form page as well as login block.

You can also try FreshLogin module. It will provide a complete different template.It  can customize as you want.


How do I iterate over values of a multivalued field with entity_metadata_wrapper?

The problem is in this file: /sites/all/modules/entity/includes/entity.wrapper.inc

Whenever a field_foobar->value() is called, and the field isn't set, then the class throws an Exception.  That is just silly, because having an empty field isn't an error.

Inside that field, when checking to see if a field is empty, it uses this code:

$data = $this->dataAvailable() ? $this->value() : NULL;

But using "if ($wrapper->field->foobar->dataAvailable())" before each echo of the value is aggravating.  Sigh, why can't things in Drupal ever be simple?


Display Date field in email body with rules module

i had a wrong date field. It should be entity-fetched:field_event_date. Now its working.


Just checking the node's type should be enough, and you can default to returning the standard deletion form:

function my_node_delete_function($node) {
  // If the node is of your custom type, delete it straight away.
  if ($node->type == 'my_type') {
    node_delete($node->nid);
    // ...
    drupal_goto();
  }
  else {
    // Otherwise, serve the standard node delete page.
    module_load_include('inc', 'node', 'node.pages');
    return drupal_get_form('node_delete_confirm', $node);
  }
}


Unable to add new OpenID identity in Drupal 7

Thanks to Mołot's comment, I was able to figure it out.  The problem was the administrative overlay.

Using the Chrome Developer Tools console (Chrome Menu/View/Developer/Developer Tools) I was able to see the request history.  The last request included:

referer:http://mysite.com/user/1/openid?render=overlay&render=overlay

The response from Google also contained a header that looks like an error, although it may not have been relevant:

p3p:CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."

I don't know if the referrer header was the actual problem, or if it just reflected a problem caused by including "render=overlay" in the request going on in the background between my server and the OpenID provider.  In any case, by turning the administrative overlay off (Admin/Modules/Core/Overlay), I was able to add and use my new OpenID.  It worked for both Google and Yahoo.

I would also add, as noted elsewhere, the URL to use to set up the OpenID for Google is:

http://www.google.com/accounts/o8/id

That initially confused me because that does not appear to be a unique ID.  However, using that ID both to add the OpenID for Drupal, and to log in using OpenID, works.  The string stored as my "OpenID" is different, and has what appears to be a unique identifier, but the user never has to enter that long, unique string.

Not only did the Administrative Overlay prevent the OpenID from being added, it also prevented me from seeing the error message when I used the wrong string to add the OpenID.


Picking image from server: FileField_Sources not working

I just found the answer myself.

If anyone else would come into the need for something like this:

Download the 3 modules that I had typed in my question
Go to the Manage fields of your content type & click edit next to the Field
Scroll down and click Allow users to select files from IMCE File Browser for this field.

I forgot 2 & 3 :)

I do have to say that it's not 100% what I wanted, as I have different image fields in different nodes, and it only finds the image fields of the nodes that it's in. But I guess I should have used the references instead to make that work...

If anyone still has an answer for my secondary question, it would be much appreciated though, but I'll try to fix that myself tomorrow.


Drupal 7

drush eval "print_r(array_keys(entity_get_info()));"

Drupal 8

drush eval "print_r(array_keys(\Drupal::entityTypeManager()->getDefinitions()));"

as per Jason suggestion,

or:

drush eval "print_r(array_keys(\Drupal::entityManager()->getDefinitions()));"

as per @RaisinBranCrunch suggestion. Note \Drupal::entityManager() is being deprecated in 8.x.


Error messages aren't displayed when submitting the form

this works for form messages (in a regular ajax form callback):

    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];
    $response->addCommand(new ReplaceCommand('#yourFormWrapperElement', $form));

but using drupal_get_messages() screw's things somehow up .... sometimes. plus you need enable showing messages here: /admin/config/development/logging

So - your second try should also work !

$status_messages = array('#type' => 'status_messages');
$text = \Drupal::service('renderer')->render($status_messages);
return $text;

Maybe the mentioned settings are needed ..


Using Automatic Entity Label how to add number if title is already used (unique)

You can add node id to the label. It will make labels unique anyway.
For example

[node:field_first_name] [node:field_last_name] #[node:nid]

Please note, that there is an issue in module that prevents [node:nid] token from working.
https://www.drupal.org/project/auto_entitylabel/issues/2920695

But there is simple patch available in this issue to fix this. So this should be resolved soon I hope. Until that you need to apply patch manually.
https://www.drupal.org/files/issues/2018-11-11/auto_entitylabel-support_entity_id-2920695-31.patch


Getting the source URL of image in Media Gallery Module

The link you're looking to override is hard coded into the template_preprocess_media_gallery_media_item_thumbnail() function in the Media Gallery module.

Fortunately, as it's a preprocess hook for a theme function, you can yourself override it in your site's theme. It does mean having to duplicate some code from the original preprocess function, and also another theme function so you can add the rel attribute, but it's not too much. You'll also need to implement hook_js_alter() to remove the colorbox js the the Media Gallery module adds by default.

Place the following code in your theme's template.php file and replace all occurrences of THEMENAME with your theme's name:

function THEMENAME_preprocess_media_gallery_media_item_thumbnail(&$variables) {
  $element = $variables['element'];

  // Only make the changes for images, no other media type.
  if (strtolower($element['#bundle']) != 'image') {
    return;
  }

  $format = $element['#media_gallery_entity']->media_gallery_format[LANGUAGE_NONE][0]['value'];
  $lightbox = is_numeric(strpos($format, 'lightbox')) ? TRUE : FALSE;

  /*
   I'M PRESUMING HERE THAT YOU'RE ADDING THE SHADOWBOX SCRIPT USING ANOTHER
   METHOD (PERHAPS IN THE THEME'S .info FILE). IF THAT'S NOT THE CASE JUST
   UNCOMMENT THE FOLLOWING LINE AND CHANGE THE PATH TO ADD IT HERE

   if ($lightbox) {
     $element['file']['#attached']['js'][] = drupal_get_path('theme', 'THEMENAME') . '/path/to/shadowbox.js';
   }
  */

  // Get the rendered file without annoying DIV wrappers.
  $element['file'] = array('#theme' => 'media_gallery_file_field_inline', '0' => $element['file']);
  $image = drupal_render($element['file']);

  $gallery_id = $element['#media_gallery_entity']->nid;
  $media_id = $element['#file']->fid;

  // Add a class that is a more targeted version of what template_preprocess()
  // automatically adds for this theme hook, to enable per-type (e.g., video vs.
  // image) styling.
  $variables['classes_array'][] = drupal_html_class('media_gallery_media_item_thumbnail_' . $element['#file']->type);

  // Add a class for the wrapper.
  $variables['classes_array'][] = 'media-gallery-item-wrapper';

  // Create an array of variables to be added to the main thumbnail link.
  $link_vars = array();
  $link_vars['image'] = $image;

  // THIS IS WHERE YOU MAKE THE CHANGE TO THE LINK PATH. YOU MENTIONED THAT
  // YOU'VE ALREADY MANAGED TO ADD THE 'rel' ATTRIBUTE THAT YOU NEED SO I WON'T
  // ADD THAT HERE
  // Old code: $link_vars['link_path'] = "media-gallery/detail/$gallery_id/$media_id";

  // New code:
  $style_name = 'media_gallery_large'; // Name of the image style for the full sized image you want to link to
  $url = image_style_url($style_name, $element['#file']->uri);
  $link_vars['link_path'] = $url;
  $link_vars['rel'] = 'shadowbox'; // The rel attribute
  // End new code

  $link_vars['classes'] = array('media-gallery-thumb');
  $link_vars['title'] = $element['#bundle'] == 'image' ? t('View larger image') : t('Watch video');
  // Add the image as a link to the detailed view
  $variables['media_gallery_item'] = theme('media_gallery_item', $link_vars);

  // Set the variables to theme the metadata.
  $meta_vars = array();
  $meta_vars['location'] = $element['#media_gallery_entity']->media_gallery_image_info_where[LANGUAGE_NONE][0]['value'];
  $meta_vars['title'] = isset($element['media_title']) ? $element['media_title'][0]['#markup'] : '';
  $meta_vars['link_path'] = $link_vars['link_path'];

  // Theme the metadata.
  $variables['media_gallery_meta'] = theme('media_gallery_meta', $meta_vars);
}

function THEMENAME_media_gallery_item($variables) {
  $image = $variables['image'];
  $link_path = $variables['link_path'];
  $attributes = array();
  if (!empty($variables['classes'])) {
    $attributes['class'] = $variables['classes'];
  }
  if (!empty($variables['title'])) {
    $new_image = str_replace(array('title=""', 'alt=""'), array('', ''), $image);
    $image = str_replace('/>', ' title="'.$variables['title'].'" alt="'.$variables['title'].'" />', $new_image);;
  }

  // Below is the only change to this function, just to add the rel attribute.
  if (!empty($variables['rel'])) {
    $attributes['rel'] = 'shadowbox';
  }

  // Add sliding door top div and wrappers
  $item = '

';
  // Create a link around the image
  $item .= empty($variables['no_link']) ? l($image, $link_path, array('html' => TRUE, 'attributes' => $attributes)) : $image;
  // Add sliding door bottom div and close wrappers
  $item .= '

';
  return $item;
}

function THEMENAME_js_alter(&$js) {
  // Remove the media gallery colorbox js. It interferes with the rel attribute.
  if (isset($js['sites/all/modules/media_gallery/colorbox-display.js'])) {
    unset($js['sites/all/modules/media_gallery/colorbox-display.js']);
  }
}

I've added some comments to the code to explain what's happening so it might be worth giving the code a quick glance over.

After you've cleared Drupal's caches you should get exactly what you're after :)


How to automatically populate /node/add/ form fields via simple logic?

Module Conditional Fields does the job.

It lets you assing values, visibility etc. of fields depending on other fields in the same form.

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


How to configure Trusted_Host_Settings for subdomains?

It's actually documented in settings.php file as in examples:

Drupal 8.5.x
https://cgit.drupalcode.org/drupal/tree/sites/default/default.settings.php?h=8.5.x#n712

<?php
$settings['trusted_host_patterns'] = array(
  '^example\.com$',           // Matches naked domain only.
  '^.+\.example\.com$',       // Matches any subdomains.
  '^subdomain\.example\.com', // Matches a specific subdomain.
);

You can easily define any naked or sub-domain, as long as defined regex pattern matches them correctly.


You have to iterate over all nodes in $result to do that. array_pop() only returns the last item in $result. So you'll have to do something like this:

$paths = array();
if (isset($result['node']))
{
  foreach($result['node'] as $key => $node) {
    $paths[$node->nid] = drupal_get_path_alias("node/$node->nid");
  }
}

After this $paths will contain an array of keys that map to each node id with a value that corresponds to its alias path.


The trouble with this approach is that there are block definitions and block instances.  A block definition is the code or custom block that defines the block's behavior.

A block instance is what you create when you place a block onto your theme and defined its settings (e.g. nodes to display it on, values for custom fields).

To have different banners for each class using this method you would need to create a different block instance for each class.  (and set the display rules appropriately).

To use a single block, you will need to define a location outside the block that has the needed information.  Probably on your course page.  Then you can use either a view block as mentioned in the comments or write a custom block to pull the info.  If it is only needed on the main course page, you could probably just use a custom content type twig file and add it when the page is rendered.

If you need the block on subpages, e.g. secondary pages of a course, you will probably have to write a custom block that knows how to relate the subpage to the main course page. E.g. get the course information from a course entity reference field on the subpage and then get the banner info from the main course page).

Note that with both views and custom blocks, you will need to define the cache tags appropriately so that the content is cached per page and not overall.


Set default value with PHP on a node field.

I don't know if there is an UI for it, but fields allows either an array as allowed values or an callback.

This means that you most likely will need to create a function in a module instead of hardcoding the php which then would be saved in the database. IMO this is a good thing.

In your field config array you want something like this:

....
'settings' => array(
    'allowed_values' => array(),
    'allowed_values_function' => 'callback_function',
),
...

If you are new to this, take a look at field_create_field and field_update_field.


Getting taxonomy name from entity for computed fields

If you have taxonomy id, I'd suggest to do this:

$term = taxonomy_load_term($tid);
$node->your_field_name[your_language_specifier][your_value_index]['value'] = $term->name;

if you don't have taxonomy term id you can get it like so:

 $field_name = 'term'; //or what ever your field is named
 $entity_id = 4;//or what ever your entity id is
 $query = db_select("field_data_field_" . $field_name, $field_name);
 $query->addField($field_name, "field_" . $field_name . "_tid", "tid");
 $query->condition("entity_id", $entity_id, "=");
 $result = $query->execute()->fetchAssoc();
 $tid = $result['tid'];


fixed... always, REMEMBER!! always shutdown block in block UI. if not do it, this piece of shit gives something like:

  {"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"a94bccf7913b478becb33a3a27ec903d","pager_element":"0"}

in page header and your ajax may work not so clear :)


How to make each header in a table clickable and add a chart to it?

There's no drag-and-drop solution. You would either have to create a custom module yourself that would do what you want, modify a module that gets close to what you want or use one of the solutions out there that makes you enter things in manually.


Strategy to consolidate multiple fields across content types?

I can't say which is better, because it depends on what customization you intend to do in the future.

That said, generally speaking, if you have different content types that use the same field for the same purpose, you should choose to re-use the field across content types in the design stage; doing so would've saved you the trouble you face now.

How to consolidate multiple fields

First, create a new field on one content type.

Next, re-use the field on all the other content types you want to use it on.

Then, see this question on renaming fields for information about how to use SQL to copy the data from the old fields to the new fields.  ALWAYS make a backup before doing this; if you make a mistake in this step, you can break your site.

Now, you will have to fix your views, twig templates, and anything else that might be broken.  You can go to your exported config folder and search for the field names of the old fields, but I wouldn't change the config directly; I would use the config folder as a hint of what to change, and then update the values in the UI.  I'd do this because sometimes one setting changes another, and if you do it in the UI, everything should get changed properly.


Image upload fields and drag & drop tables are two separate elements that you can combine in your module by using a form callback function to declare your fields and a theme function to theme the upload fields in a drag & drop table.

D7 Form API provides an upload field named 'managed_file'. The documentation provides a clear example:

<?php
// Use the #managed_file FAPI element to upload an image file.
$form['image_example_image_fid'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
  '#default_value' => variable_get('image_example_image_fid', ''),
  '#upload_location' => 'public://image_example_images/',
);
?>

Then you can have a look at the documentation to setup the field with your desired settings. This element does not have a #multiple setting. So you can either generate many fields, either add new fields using ajax as in cck in D6.

Finally you can check this documentation on how to use drupal_add_tabledrag();


how to display/hide block on homepage depending the value in user profile field?

I would use the PHP visibility settings to display the block if user has requiredvalue. Once you've created the block that you want to display (or not display) add the following code to the "Page specific visibility settings" in the block configuration menu:

 <?php
    global $user;

    If($user->your_profile_field_value == 'requiredvalue' && drupal_is_front_page()) {
    return TRUE;
    }

    return FALSE;

    ?>


please check the permission in "admin/people/permissions" under the node section check View published content has been enabled for anonymous user


Migrating Only DRUPAL7 DATABASE from Microsoft SQL to MYSQL

A possible approach for this is to use the Drupal-to-Drupal data migration module (aka "migrate_d2d") for this. Quote from its project page:

  ... provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed.


No, results of node_load_multiple() are in the order in which the node IDs were passed to it in the first place. There are no other sorting options through that function.

The weight module doesn't appear to have an API for this, so you'll need to create a query that joins the node and weight_weights tables to get the nids in the right order, then pass them to node_load_multiple().


For count the number of term in a vocabulary you can use this method : taxonomy_get_tree($vocabulary_id). It will returns all the terms of the vocabulary in an array. After that, you only have to get the size of the array.

Example :

$terms_array = taxonomy_get_tree(9); //9 is the vocabulary ID.
$terms_nb = sizeof($terms_array); // $terms_nb = your number of terms.


Is there a way to have two aliases to a user's profile page?

Assuming you don't want to manually maintaing the second alias - since pathauto only allows you to generate a single automatic alias - then perhaps the easiest way is to use Rules, instead of pathauto. It's been a few years since I did this, and it was for node aliases, not user page aliases, but I don't see why it wouldn't work.

Setup a Rule with multiple steps to create the aliases you need - you can use all the same token substitutions in Rules as you can in pathauto
Run the rule when a user is created


Assuming your site is a Drupal 7 site

Make sure you have .htaccess in your project root. You can get it here - this should fix the access denied errors
If you have drush, run: drush cc all - this should fix the missing CSS (Drupal doesn't really serve pages directly, it makes cached versions of them. I'd say you caches are empty to they need to be rebuilt.

(If you aren't able to clear / rebuild the cache with drush, please try some of the alternative steps outlined here)


How to find unused or old twig template files?

It's difficult to find a deterministic method, so you probably need some kind of usage statistics.

A simple statistical method would be to clear the twig php cache:

\Drupal\Core\PhpStorage\PhpStorageFactory::get('twig')->deleteAll();

Then run the site for some time and check the twig php cache (/sites/default/files/php/twig) for twig files not having a compiled php template.


Not quite clear on the question actually. So you're saying you want to get the settings value from webform element "Category" list before it's submitted and set it as your form wrapper?

Here's some tip I recently learned, hope it helps.

// get all webform submissions id from my_webform
$query = \Drupal::entityQuery('webform_submission')->condition('webform_id', 'my_webform');
$result = $query->execute();

// load all submission data from webform submission storage
$webformStorage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $webformStorage->loadMultiple($result);

If you want to get the submission values form webform, then you can use WebformSubmission class.

If your want to get the element settings value that user sees from your category list, then you'll need Webform class to load the options array from the webform element.

use Drupal\webform\Entity\WebformSubmission;
use Drupal\webform\Entity\Webform;

// get sid from your preprocess or elsewhere
$webform_submission = WebformSubmission::load($sid);

// This will return the data array of submitted values from sid given.
$data = $webform_submission->getData();

// Load webform with bundle type id, normally it's your webform machine name
$webform = Webform::load($sid->bundle());

// Get element definition in webform element
$select_list_element = $webform->getElement('key_name');

// for options in Select list. this may vary depending on what element type you're using
$select_list = $select_list_element['#options'];


It's very open structured, and adaptable ..

Think of it like this: You sell variations of a product to a customer.
Where attributes handle the actual variation.
Products and variations can be arranged by types (like content types)

  Different types can have different properties (ie. fields) a variation
  can be referenced to a product no matter of their types. So here the
  attributes come into place and should available for all variation
  referenced to a instanciated product.

A product field can be on a content type to show your product on a regular node. (and is a referenced entity)
Otherwise products can be shown with the search api.

The variations are also referenced entites on the product. But provide already good AJAX and add to cart functionalities out of the box.

Regarding display:
Fields can be everywhere ... and are in the end displayed. (a basic drupal concept: fieldable-ness)
Forms are only used in the backendfor composing the content.

Maybe the doc from the commerce guys gives you the point (it's d7):

Product Types. (and variation types for d8)
A product type is a specific bundle based on a custom product entity. Each bundle can have fields attached to it, including pictures and other kinds of information.

Product "Informational" Fields. (and variation fields for d8)
Any field on a product can be a simple "informational" field. Typical informational fields include an image of that specific configuration of a product. For example, if you sell a tshirt with a cool print in multiple colors, each product with a different color could have an image field that, when displayed on the product display node, will change when you select different attributes (like color).

Product "Attribute" Fields. (actually variations attributes for d8)
Any field on a product type with a defined list of options (list of text options, list of taxonomy terms, list of colors). The attribute fields are special because of the way they turn into selection widgets on a product display. Often you will pair an attribute field (like a color dropdown) with an information field (like an image field) to let the user "select" the blue tshirt and the Drupal Commerce system will quickly load the picture associated with the blue product.

Product Displays.
If needed at all, these are groupings of products. You can reference any type and number of products on a product display. In order to make use of product displays, we recommend only showing one type of product per product display. The product display is where you typically see the product with drop downs to "configure" or "order" the right kind of product.

taken form here https://drupalcommerce.org/user-guide/product-attributes-variations


Why are some of my modules reporting missing inter-module dependencies after migration?

Are those missing modules in your sites/all/modules folder? I'm not sure why they would have been left out of a file migration, but anything's possible.

Modules do not 'create' other modules (except possibly Features, I haven't used that in awhile) in the sense that you're referring to w/ the cTools example, though there are modules that exist as part of the parent module package.


I completed this in hook_update_n:

function MODULE_update_7201(&$sandbox) {

  // get all field names
  $field_names = array();
  $fields = field_info_instances('node');
  foreach ($fields as $node) {
    foreach ($node as $node_field => $field) {
      $field_names[$node_field] = TRUE;
    }
  }

  // load schema to update
  $columns = array();
  MODULE_field_schema($columns);

  // load all fields and check for type
  foreach ($field_names as $field_name => $junk) {

    // load field info
    $field = field_info_field($field_name);
    if ($field['type'] == FIELD_NAME) {

      // loop schema and check fields for existance
      foreach ($columns as $db_field_name => $db_field_schema) {
        if (!db_field_exists('field_data_' . $field_name, $field_name . '_' . $db_field_name)) {
          db_add_field('field_data_' . $field_name, $field_name . '_' . $db_field_name, $db_field_schema);
        }
        if (!db_field_exists('field_revision_' . $field_name, $field_name . '_' . $db_field_name)) {
          db_add_field('field_revision_' . $field_name, $field_name . '_' . $db_field_name, $db_field_schema);
        }
      }
    }
  }
}


Is it possible to run a module written for drupal 7 in drupal 6?

No, it's not generally possible without back-porting the code.

The API is very different between Drupal 6 and 7. A few things have remained the same, so it's theoretically possible that a module for one version might work as-is in the other version, but generally speaking, it's not possible.

For a proper idea of the task ahead of you, take a look at Converting 6.x modules to 7.x. Not a trivial task, unfortunately.

I just had a quick look and the specific module you've mentioned definitely won't work in Drupal 6, it would need to be re-written.


You could override the theme_form_element() function in your theme's template.php so that the label does not output:

// Remove  from output

function THEMENAME_form_element($element, $value) {
  // This is also used in the installer, pre-database setup.
  $t = get_t();

$output = '\n";
  $required = !empty($element['#required']) ? '*' : '';

if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required));
    }
    else {
      $output .= '$t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required));
    }
  }

$output .= " $value\n";

if (!empty($element['#description'])) {
    $output .= ' ' . $element['#description'] . "\n";
  }

$output .= "\n";

return $output;
}

Alternatively, you could target the form id > label and set it to display:none without modifying the theme function.


How to set an existing database field to auto increment

I found the solution I was looking for here. Below is the relevent part.

For example, suppose you have:

$schema['foo'] = array(
  'fields' => array(
    'bar' => array('type' => 'int', 'not null' => TRUE)
  ),
  'primary key' => array('bar')
);

and you want to change foo.bar to be type serial, leaving it as the primary key. The correct sequence is:

db_drop_primary_key('foo');
db_change_field('foo', 'bar', 'bar',
  array('type' => 'serial', 'not null' => TRUE),
  array('primary key' => array('bar')));


How do I remove product duplicates in a view?

Drupal Commerce has duplicate entities because a product is referenced from multiple variations, any field you add to a variation type will find multiple duplications in your view most notably in images but could be any field in example t-shirt size.

An easy way to remove these is to set in your view:

FILTER CRITERIA
Product: Variations:delta (= 0)


What are the limitations of the theming system?

Theming hooks (templates and theme functions) defined in hook_theme() implementations are always overridable. But they have to be used properly, always use theme('foo', $bar), never theme_foo($bar).

In Drupal 6, (pre)process functions are only available for templates, not theme functions. Also, the templates must be be overriden in the theme otherwise the preprocess function from the theme is not used. So to have your THEME_preprocess_node(&$variables) function used, you need to have the node.tpl.php in your theme folder.

Another limitation (actually a bug) is that for a template to be overridable in a theme, the file name (without the .tpl.php extension) must be exactly the same as the theming hook name except for the _ that are replaced by -:

function MODULE_theme() {
  return array(
    'overridable_template' => array(
      'template' => 'overridable-template',
    ),
    'non_overridable_template' => array(
      'template' => 'nonoverridable-template',
    )
  );
}


Allow a user to select where to save an uploaded file

You could use a text input with select list, allowed values list will be generated with php code reading the directory you created, then using File (Field) Paths you will save the upload on the select list input.


It can be something wrong with File system settings. You may check it here admin/config/media/file-system


Authenticated users must be able to flag webform submissions

Navigate to /admin/structure/flags/add/node and create a flag (do not check the "global" checkbox). For "Bundles" (on the same form, check "webform").

On that same form, review any of the various other options available to define/refine the flag to be created, such as:
- Flag Access,
- Display options,
- Link type,
- Etc.

Then use the "Save Flag" button.

A few other questions that may help to get you going (which are like variations of this question):

Any way to flag users who previously submitted a webform on revisit?
Adding a "processed" flag to a Drupal Webform, that admins can use to indicate whether or not they've dealt with a particular submission?

Note: The Webform Flag Submissions sandbox is for D6 only (I'm assuming this question is about D7, is it?).


Help with #text_format and field widgets

Good luck with that. What a head-scratching nightmare. See Missing hook_field_widget_form_submit()? for an idea of how to make this easier.

I got this to work once in a module, but then had to remove it for other reasons. The code is still there, look at this older version of flashcard.install and flashcard.module, especially flashcard_field_widget_form() and flashcard_field_formatter_view().


How to access date value from a datelist form element for validation?

Yes, to compare the date it's better to use the unix timestamp. You can get it by using the method getTimeStamp() and compare it to the current date:

      $value = $form_state->getValue('date_field');
      if ($value->getTimeStamp() > REQUEST_TIME) {
        drupal_set_message('Time is in the future');
      }


The Drush logs are emitted only to the console.  Use --debug to get more information about what is happening.

Your ISP is probably deciding that your Drush command is taking too long, and are killing the process.  Ask support at your ISP to determine if this is the case, and whether there is a way to increase the limit.   Drush does not have any support this sort of limitation; it assumes that it is running in a shell with no time limits.

PHP can also be configured to apply a maximum timeout to your requests. To find out what php.ini Drush is using, run drush status. One of the lines will provide the full path to your php.ini file.  Ideally, you should use a different php.ini for Drush than you do for your web server.  Set the environment variable PHP_INI to point to the php.ini file that Drush should use. Copy your webserver php.ini to serve as a starting point, and then customize to suit.

The variable you are looking for is max_execution_time.


How do I modify and then render the Drupal login form in a page template in Drupal 7?

1 )
Create the login and password empty page files and place them in your theme "templates" folder.
The name of the files are page--user--login.tpl.php and page--user--password.tpl.php. There's no need of all those steps of "hook", "alter", blablabla... Drupal will use those files automatically without any call or whatever.

2 )
Put this code inside your files.

page--user--login.tpl.php

<?php print $messages; ?>
<?php print drupal_render(drupal_get_form('user_login')); ?>
Request new password"

page--user--password.tpl.php

<?php print $messages; ?>
<?php print drupal_render(drupal_get_form('user_pass')); ?>
Go back

3 )
Done!
In thee steps. Now style your css as much you need and pimp your new fancy login page. "Inspect" your html output of your new login page and see how clean it is now. ; D

Afterwords )

I just spent this last hour reading posts and questions about this all over the internet, and the work around in some cases are simply crazy like using the dpm(get_defined_vars()); function, copying html and paste all of those input forms and attributes, blablabla.
I didn't found a concise post like this. It's crazy!!!

Also, you will need (if you still don't have it and if you want it) to disable "label/description" and enable "placehover" for the inputs. You can do it all together like this:

<?php
/*
 *  Remove labels and add HTML5 placeholder attribute to login form
 */
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if ( TRUE === in_array( $form_id, array( 'user_login', 'user_login_block') ) )
    $form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
    $form['name']['#title_display'] = "invisible";
    $form['pass']['#title_display'] = "invisible";
}
/*
 *  Remove login form descriptions
 */
function THEMENAME_form_user_login_alter(&$form, &$form_state) {
    $form['name']['#description'] = t('');
    $form['pass']['#description'] = t('');
}
?>

PS )
Do you have the "header", "footer" and "sidebar" visible and want to remove them too? No problem.
Go to admin/structure/block and click "configure". Scroll down and include this on "Show block on specific pages" option:

user/login
user/password

Done!
Drupal it's incredible powerful. I think people complicate things a lot and if you see it in a simple way it will be more efficient... Most of the things you can do it inside Drupal environment.

source: https://www.drupal.org/node/1195754


How to override formatting for a CCK field?

Depending on the type of the field you are using, there are template files for those as well e.g. a number field (field--number-decimal.tpl.php). that way you would only have to override the field template, rather than the node template.


Drupal 8. Imce module show thumbnails instead of a filename

Short answer: No

Long answer: This seems like it existed in the 6.x branch of the module as a "Box View", but in 7.x it looks like it's been dropped. See here for the 6.x discussion. And there's a ticket for 7.x too, with 0 activity.

Edit: Serhiy found out that for D7 there's a template file which can be modified to display thumbnails instead of a list.


How to put a node in a menu using an URL parameter?

hook_node_insert() is probably the best place to do this. You'll want to call menu_link_save() to create the menu item, using the $_GET superglobal to retrieve the plid parameter:

mymodule_node_insert($node) {
  $item = array(
    'link_path' => 'node/' . $node->nid,
    'link_title' => $node->title,
    'plid' => $_GET['plid'],
  );
  if (!menu_link_save($item)) {
    // menu_link_save() returns the mlid of the new item. Handle a failure here,
    // which will occur if the plid supplied is invalid.
  }
}


How to change menu item URL in menus for Drupal 7 multiiste

Try to add menu links as "Relative Paths", then a domain name will be added automatically depends on sites.

E.g. use /test , not one.example.com/test.


You can refer the following tutorial for the same, it's well explained.

https://www.ostraining.com/blog/drupal/d8-multi-lingual/

https://www.drupal.org/docs/8/multilingual/choosing-and-installing-multilingual-modules


I think you can do this by Drush.
Install drush

1. drush up drupal  ->> it will update only core drupal
2. drush pm-update --no-core <modulename>   ->> it will update only mentioned module.


valueCallback in custom form element is not invoking itself?

It doesn't invoke itself when #value is already set to element. I didn't notice that I set it in theme function. After removing #value key from $element array it is working fine.


Permission settings for Edit Node Link to show up?

go to:

  admin/people/permissions

and check:

  Content type name: Edit own content.

if you want that this role can edit ANY content of this type, not only their own conent, then check:

  Content type name: Edit any content.


custom views slideshow tpl from unformatted list of views drupal 7

Butterfly

you can use very options:

Create view with the slider content and theming tpls adding slick.js fe. as block or node to display only in frontpage
Add carousel module (there are many modules..carousel bootstrap, flexslider...) and create new view of this type with the slider content as block and display this block in frontpage .

Regards,
Iván.


Can FileTransfer be used to target remote FTP servers?

What used for the $jail parameter is the directory for which the operations are limited; if you try deleting a file outside that directory, the operation is not allowed.

If you want FTP access to a directory on a remote site, you should use the FileTransferFTP class, and create an instance with FileTransferFTP::factory().


how to assign different Text formats for each Long Text fields?

Use the better formats module. The module allows you set text formats per field.

  Better formats is a module to add more flexibility to Drupal's core
  input format system.


I believe I've resolved this issue; least it looks good so far.  Super thanks to Alauddin's response to "how to create rules to send email notification for node reference content?"

EVENT
After saving new content of Car Review

CONDITION

Entity has field
data selector: node:field-car-review-node-reference
value: field_car_model_tag

ACTION

Fetch Entity by ID, with value: node and data selector: node:field-car-review-node-reference:nid
Set a data value, with selected data (that I want to change): node:field-car-review-node-reference:field-car-model-tag

I think I have this right, here is an export of my Rule:

{ "rules_term_ref_4" : {
"LABEL" : "TERM REF 4",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : {
  "node_insert--car_review" : { "bundle" : "car_review" },
  "node_update--car_review" : { "bundle" : "car_review" }
},
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "node:field-car-review-node-reference" ],
      "field" : "field_car_model_tag"
    }
  }
],
"DO" : [
  { "entity_fetch" : {
      "USING" : { "type" : "node", "id" : [ "node:field-car-review-node-reference:nid" ] },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "node:field-car-review-tag" ],
      "value" : [ "node:field-car-review-node-reference:field-car-model-tag" ]
    }
  }
]
}
}


You probably want to use Drupal behaviors which is a wrapper of sorts for JQuery. With JQuery you can make it so that everytime your textfield gets edited your Javascript code gets executed. Behaviors/JQuery is a big subject and will take time if you're not familiar. You can start here

The Drupal JavaScript API

JQuery tutorials


How to solve tput problem when installing drush on Windows?

Ashlar seems to have found a solution to the tput problem in his own bug report 'by adding the add-on gygwin command tput from the cygwin installation program "setup.exe". The actual command i not on the list. Look for the "ncurses" package which includes the Tput utility.' ... see http://drupal.org/node/1361510#comment-5327144


Ok here is what you can do:

Attach a Five Star field to the user
Create Views block that shows the users. Select to show fields and only show the Five star field.
Use a contextual filter in the View to filter by User Id(uid). Select "Provide a Default Argument" -> "User id from URL" -> "Also look for a node and use the node author"
Place this block on the page. Restrict it by content type if you want.
When someone Views a node then they will see the Views block also and can rate the user.

You could put Header text area in text in the View to give the user instructions. You could also display the user name, picture or other information if you wanted.

This is way I could think of with the least amount of modules. If you were already using Panels you could use Panels to place the Five Star field on the node page but I won't suggest installing Panels just for this use case.


Body Class, Drupal 7, change language name programmatically

sites/all/modules/i18n/i18n.module

Line:267:  $variables['classes_array'][] = 'i18n-' . $language->language;

You can create your own small module mysmallmodule.module and put this in it:

/**
 * Implements hook_preprocess_html().
 */
function mysmallmodule_preprocess_html(&$variables) {
  global $language;
  $variables['classes_array'][] = 'lang-' . $language->language;
}

Which wont get rid of the i18n class but will just add your own version :)

EDIT: Step by step to create a small custom module.

Create a new folder in the sites/all/modules folder called custom, in here you can keep any custom modules you may need.
Create another folder in the custom folder and call it something suitable like customclasses.
In the customclasses folder create two files, customclasses.module and customclasses.info.
In the customclasses.module file paste the code above but call it "function customclasses_preprocess_html" instead of "mysmallmodule".
In the customclasses.info file paste

name = Custom Classes

package = Custom Stuff

description = Custom class to get "lang-" in the body class.

core = 7.x
Finally, go to the modules page and enable your first custom module.


You want a Relationship on your View.

If you're displaying nodes, add a Relationship on the User Reference field that your node has. Then add a Filter for User = Current User, using the relationship you just created.


display the entities that are referencing the current entity with views

You create a View that lists all reservations and then add entity_reference_field as the context.

If you use Panels, you should create a content pane and require a node id as context.

If you don't use panels, you should create a block and provide a default value to the context being the node id from the url. (When you insert the block on the node page, views will grab the node id from the url and use it in the query to display only reservations for that room).


How to open the view and edit page inside the colorbox?

You need to specify more precise which html elements of the destination page (the page containing the event) should be rendered.

i guess changing the id selector to

#content .content

will do the job.


Is it possible to post a file with drupal_http_request?

All you need is to set correct header information.
I'd do it like so:

$boundary = 'A0sFSD';
$headers = array("Content-Type" => "multipart/form-data; boundary=$boundary");
drupal_http_request('some/url/you/want/to/post/file/to', $headers, 'POST', multipart_encode($boundary, $params));
if ($request->error) {
    watchdog("ipaper", "Request failed - ". $request->error .' - '. http_build_query($params));
}

...............

function multipart_encode($boundary, $params){
    $output = "";
    foreach ($params as $key => $value){
    $output .= "--$boundary\r\n";
    if ($key == 'file'){
        $output .= multipart_enc_file($value);
    }
    else {
        $output .= multipart_enc_text ($key, $value);
    }
    $output .="--$boundary--";
    return $output;
}

function multipart_enc_text($name, $value){
    return "Content-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n";
}

function multipart_enc_file($path){
    if (substr($path, 0, 1) == "@") {
        $path = substr($path, 1);
    }
    $filename = basename($path);
    $mimetype = "application/octet-stream";
    $data = "Content-Disposition: form-data; name=\"file\"; filename=\"$filename\"\r\n";
    $data .= "Content-Transfer-Encoding: binary\r\n";
    $data .= "Content-Type: $mimetype\r\n\r\n";
    $data .= file_get_contents($path) . "\r\n";
    return $data;
}

You might also consider using cURL for this purpose.


drupal 6 status report, automate via drush?

If you want to use drush, drush -n up will show the available module updates.

Getting the status report (really "requirements" from the API's perspective) is a bit more convoluted, and can be output with

drush php-eval 'include_once DRUPAL_ROOT . "/includes/install.inc"; drupal_load_updates(); print_r(module_invoke_all("requirements", "runtime"))'

Other options are Nagios, Update Status Aggregator, Droptor, or the Acquia Network.


You should be able to add a prefix or suffix with the field. See Field Suffix in the Form API, So your code might be:

$form['copy'] = array(
'#type' =>'checkbox',
'#title' => t('my taxonomy term.'),
'#field_suffix' => '<img src="myimg.png" />',
);

You can use field_prefix if you want it to come before.


Views suggestion preprocessor template.php and views-view-field--suggestion.tpl.php working in harmony?

I think what you are looking for is:

function MY_THEME_views_view_field__frontpage_fold__page__field_video_background_files_preprocess(&$variables, $hook) {

Note the addition of _preprocess at the end of your function name.

https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess/7


Is there a way to call "access callback" with parameters?

If I understand your query right the access callback needs to accept a parameter based on which it decides whether or not to return TRUE for the menu path. This should be achievable using access arguments, like

'access arguments' => array($experimentID),

quoting from the hook_menu API documentation

  "access arguments": An array of arguments to pass to the access
  callback function, with path component substitution as described
  above. If the access callback is inherited (see above), the access
  arguments will be inherited with it, unless overridden in the child
  menu item.

The passed argument, in your case the $experimentID could be either from any custom computation like a value from the user object or even a part of your query parameters.


How to get the context node in a custom block inside a views list?

When placing the block you have to choose from where the block will get the node value.

Select a node value

Node from URL

Ah! I found my own issue on DO. You also might have to unrequire the context like following:

 *   context = {
 *     "node" = @ContextDefinition(
 *       "entity:node",
 *       label = @Translation("Current Node"),
 *       required = FALSE,
 *     )
 *   }


How to remove title 'Navigation' from Navigation menu in Drupal 7?

You can click "edit block" or go to the Blocks administration page and enter '<none>' for block title for the Navigation block.


Constraint doesn't attach from BundleFieldDefinition, but does from entity_bundle_field_info_alter()

Yes, both are different. In core the system to define bundle fields in code is broken from the beginning. Commerce did implement their own system (entity traits), but although it looks like the fields are defined in code, in reality they are not. Commerce adds them to config and doesn't transfer constraints in this process.


how to create a page.tpl.php without $page['content']?

You have asked simple question & there is very simple answer for that --

Yes, you can create page.tpl.php without <?php print render($page['content']); ?>. You just have to remove this snippet from the TPL file & it will work.

But then you have explained your issue about comment.

So if you go through the structure of tpl files at theme, you will understand that <?php print render($page['content']); ?> is responsible to print node.tpl.php & that one contains <?php print render($content['comments']); ?>.

So without fetching the things of node.tpl.php you won't get comments. Anyway, how a comment can be associated to a page when there is no node.


The easiest and simplest way to integrate drupal with magento is using magento API. http://www.magentocommerce.com/api/soap/introduction.html. Magento API provides all the functions necessary for e-commerce operation. You can get the list of all categories, products, product reviews, shopping cart feature etc.


Views: output item fields grouped by field instead of item?

Look at Views Attachments. Set up your first View w/ just titles. Then Add display > Attachment, override your Fields to get body and use Attachment settings to position it after the first. Should be a few tutorials out there if this is confusing. Hope it helps.


Node creation PHP – menu item under proper parent

It looks like you need to set $node->menu['plid'] = "961"; to set the parent node.

You can have a look through the menu_link_save doco to get an idea of what is going on, or there is a smaller code snippet on this blog that explains in a simple, fast way.

As a side note, you can use node_object_prepare($node); to set default values after setting your node type, which should take care of your default menu parent. I've found this guide helpful with programmatic node creation.


How to fix "Hook implementations should not duplicate @param documentation."?

The problem is that if you're implementing a hook and you don't need to write more than this:

/**
 * Implements hook_field_widget_form_alter().
 */

Because you will have all the information in the hook_field_widget_form_alter() definition, so just write always in the hooks implementations only this:

/**
 * Implements hook_hook_name().
 */

In your case:

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, $form_state, $context) {
  if ($context['widget'] instanceof \Drupal\text\Plugin\Field\FieldWidget\TextareaWidget) {
    $element['#after_build'][] = '_mymodule_remove_textarea_help';
  }
}


How to write test cases for custom ajax functionality using simpletest in drupal7

You cannot test custom javascript with simpletest because it simply ignores them. Simpletest can simulate the ajax behavior (via xpath) only if you add that to the form with the #ajax property. http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax

To test custom js you might want to have a look at Selenium.


Do I need to run Captcha and Mollom simultaneously?

If you're satisfied with the Mollom module, then I don't think it makes sense to also leave the Captcha module enabled/installed.

However, if you're looking for some kind of extra protection/layer but without those double captcha forms, then you may want to consider replacing Captcha with the Honeypot module. Because of the technique used by Honeypot, you don't risk to have double captcha forms in that case.

Some more details about the Honeypot module (from its project page):

  ... uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site (read more here). These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which Punish the user.

Note: even if you don't want to consider using the Honeypot module (for whatever reason), keep "the message" in mind about what that link quoted from its project page (Punish the user) is trying to explain whenever your researching similar modules.


Preventing redirects from being cached for anonymous users

Solution ended up being an event subscriber with a cacheable response:

<?php

namespace Drupal\news_redirect\EventSubscriber;

use Drupal\Core\Routing\TrustedRedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class NewsRedirectSubscriber implements EventSubscriberInterface {

  public function redirectMediaCoverage(GetResponseEvent $event) {

    $node = \Drupal::routeMatch()->getParameter('node');
    if (isset($node) && $node instanceof \Drupal\node\NodeInterface) {

      $nodeType = $node->getType();

      if($nodeType === 'news'){

        $typeID = $node->news_type_of_content->target_id;

        if(isset($typeID)){

          $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($typeID);
          $name = $term->getName();

        }

        if(isset($name) && $name === "Media Coverage" && isset($node->news_source_url->value)){

          $url = $node->news_source_url->value;

          if(isset($url)){

            $response_headers = [
              'Cache-Control' => 'no-cache, no-store, must-revalidate',
            ];

            $response = new TrustedRedirectResponse($url, '302', $response_headers);
            $response->addCacheableDependency($node);
            $event->setResponse($response);
          }

        }

      }

    }

  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirectMediaCoverage',30];
    return $events;
  }

}


I believe you want to change your listings_menu()

function listings_menu() {
    $items = array();

    $items['site/listings/%'] = array(
        'title' => 'City Listings',
        'page callback' => 'business_listings',
        'access arguments' => array('access content'),
        'page arguments' => array(3),
    );

    return $items;
}

Then you need to change your listings to accept that argument

function business_listings($states){
  $states = listing_states($states);

  $dbquery = db_query("SELECT DISTINCT CityName FROM {zipcodes} WHERE StateName = '".ucfirst(arg(2))."' ORDER BY CityName ASC");

  $cityname = '';
  $cityname .= '
';
  foreach ($dbquery as $dbrow) {
      $cityname .='
';
      $cityname .= 'CityName)).'">'.$dbrow->CityName.'';
      $cityname .= '
';
  }
  $cityname .= '
';

  return array('states' => $states, 'city_names' => $cityname);
}


You can give drop down menu using Filter Criteria option.

In Filter Criteria in the field which you added for filtering Check the checkbox called

  Expose this filter to visitors, to allow them to change it


Sounds like you need the register with picture module


Adding optional insurance service to existing shipping service

You'd probably add this using a combination of Rules (module) plus an additional custom field for Shipping line items.


How do I add an field containing image links?

In the field formatting/rewriting options, you can check "Output this field as a link" and then enter your third party external link.


Drupal doesn't queue AJAX requests, no. If it's causing a problem, you might want to implement some JS to disable the form while a request takes place.

Alternatively, as it doesn't appear your fields are required, you could use #states instead. They don't require an AJAX call, but (depending on your ultimate requirements of course) will give you the same effect as your current code.


Is there any way to display an image as background?

You can use Background Images and Background Images Formatter modules to achieve this. Note in the Background Images Formatter description that it can take images from a field and add it to the background.

Otherwise you can create your own module that generates the appropriate css and adds it to the page with drupal_add_css


I might think about using a login mechanism like OAuth (with its Connector module) or an LDAP instance so that your global admin can login to any site with the same login.

To distribute the content, I would try using a REST API from the regional sites via the Services module which supports login if content or views needs access control.

Good luck!!


If you want to add the Javascript to a single node, you might also implement hook_node_view:

<?php
function my_module_node_view($node, $viewmode, $langcode)
{
  if ($node->nid == MY_NODE_ID) {
    $node->content['#attached']['js'][] = array
    (
      'type' => 'file',
      'data' => drupal_get_path('module', 'my_module') . 'js/add_property.js',
    );
  }
}
?>

(Solution adapted from https://www.drupal.org/node/1993228).


When "drush updatedb" is executed, are scripts cached by OPCache invalidated?

Updated response to address the questions as asked.

Yes, either the web server need to be restarted or the web-server's OPCache needs to be cleared. Drush cannot clear the web-server's opcache as it is a CLI application. Instead of restarting the web server a php script with following content can be added to next to Drupal's update.php
 <?php
 opcache_reset( );
 /*
 Following measures should be taken to safeguard this file from malicious use
 a) Set filename with a long random string as a name (like 100+ characters).
 b) Check the IP address of the requester so the script can only be called from trusted networks.

 To clear cache visit this file at
 siteurl/random_long_string_eiquooR3.php
 or use curl siteurl/random_long_string_eiquooR3.php
 Check the IP address of the requester so it can only be called from trusted networks.
 */

Neither Drupal core nor Drush invalidate OPCache.

Yes, setting opcache.enable_cli to 0 is a fine, it is anyways off by default. Unless you are really explicit in your configuration of opcache to enable it on the cli and also use a file based caching mechanism, the opcache exists in memory and is reset on each command line invocation. Therefore you only need to worry about clearing opcache by restarting any long-running PHP command line jobs.

Original Answer by @greggles

Restarting the webserver works, but takes quite some time. A more efficient solution is to have a way to call opcache_reset.
Opcache must be reset by calling opcache_reset from within the web process. If you call it inside drush then it will not clear the opcache for the webserver so it won't help the problem.
Unless you are really explicit in your configuration of opcache to enable it on the cli and also use a file based caching mechanism, the opcache exists in memory and is reset on each command line invocation. Therefore you only need to worry about clearing opcache by restarting any long-running PHP command line jobs.

If you want to clear opcache as part of a deploy process, I suggest adding a file that contains opcache_reset and then you have to protect access to that file so malicious users can't easily call it:

Give it a long random string as a name (like 100+ characters).
Check the IP address of the requester it can only be called from trusted networks.


Drupal Gardens Template builder: Can I have this feature on my site

Fusion theme + Skinr module will get you part of the way there.  DG may have some customizations that are not available outside of their walled garden.


Adding a link with nid in Global: results summary in Views

Because the header uses the default Drupal PHP interpreter, Views variables aren't available there like they are in the arg php code. You can get them by doing something like this:

<?php
global $current_view;
print $current_view->args[0];
?>

Update: If you want to use PHP in views header, you can go to configure header, select "Global: Text area" and have to change text format to PHP code; you have to first install the PHP filter module.

Also if you use Global: Text area with PHP filter enabled this should work:

@total


According to the WYSIWYG Filter module page it follows TinyMCE valid elements syntax. From that page:

  ! Makes attributes required. If none of the required attributes are
  set, the element will be removed. For example, "!href".

It looks like your attribute string uses the exclamation mark to make the 'href' attribute required but the <a> tag you're putting in your content does not have that attribute so the element is being removed.


How to customize Number of posts on front page in drupal 8

As the front page is a view now, you can find its settings under /admin/structure/views/view/frontpage.


Using custom functions in Views template files = not good practice?

This should be just fine, however, The REAL Drupal way to do this, would be for your module to provide a field formatter to views that calls this function. There are many modules which do nothing but provide functions. CTools, for example.

Having a field formatter removes your site's functionality from the "view". Which is a best practice with any kind of software. You'll be able to change the theme in the future without worrying about your youtube IDs. Creating a formatter isn't hard to do, here is a great tutorial on how to do it.

Once you have a formatter, you can simply select it from the drop down in the View's UI and you're done!


D8 - Access Webform submission values programatically

You need to apply the patch from this issue.


Load scripts in the head AND bottom of the page?

You have to add additional libraries: https://ffwagency.com/blog/managing-css-and-javascript-files-drupal-8-libraries

So in my theme.info.yaml

libraries:
  - THEME-NAME/global
  - THEME-NAME/custom

In my theme.libraries.yaml file:

global:
  version: 1.x
  css:
    base:
      /ui/style.css: {preprocess: false, minified: false}
  js:
    /ui/application.js: {preprocess: false, minified: false, weight: '-99'}

custom:
  version: 1.x
  header: true
  js:
    /ui/head.js: {}


Can I show email Id entered by user to the visitors?

Check out the following modules
User Field Privacy

A successor of Profile Privacy for Drupal 7 that works with standard Field API (ie. non-profile) user fields.
In easier-to-understand terms:

All the user fields should have an "alterable privacy" checkbox.
If this checkbox is ticked, the user should be presented with an
additional checkbox for the privacy-enabled fields on user edit forms
to be able to make that fields' values private.
If this second checkbox is ticked for a field of a user, only the
site administrators (members of roles with the "Access private
fields" permission) and the user herself should be able to view that
field's value.

Profile Privacy

This module allows users to set privacy options for their profile fields when using the core profile.module. It does not create any settings pages or configuration screens, and it integrates seamlessly with the existing profile module.


How to add google_tag script to header with custom environment variables?

The recommendation for adding javascript is to use an external file

That is not always the case and it is more of a guideline than a hard rule.

There is a way to do what you ask, but you shouldn't because the google_tag module does exactly what you to want to do. It also allows you to include the GTM snippet inline or as a file.


I'm not sure if there are template hints that work exactly with this, but you can place block.tpl.php and region.tpl.php (in modules/block/ and modules/system/ respectively) in the theme directory, and then use conditions to sort through which areas you want to be marked up the default way and regions you don't want to be marked up that much.


Displaying Webforms on Content Types in Page Manager/Panels


Entity Reference, references dont display

Okay, found it. I had changed the language for my user session on the frontend.  Content wasn't yet populated in that langauge, therefore it didn't display.


Cron has been running for more than an hour and is most likely stuck

It seems that cron is locked, hence the semaphore variable needs to be deleted before running cron again. In your includes/common.inc file, on line 2755 you need to delete the variable from drupal_cron_run(). You can use the following code:

function drupal_cron_run() {
  //The following line will delete the semaphore variable.
  variable_del('cron_semaphore');
  // Try to allocate enough time to run all the hook_cron implementations.
  if (function_exists('set_time_limit')) {
    @set_time_limit(240);
}

Then visit http://yoursite/cron.php and check the logs for errors.
Note: You should comment out the line variable_del('cron_semaphore');, after cron runs successfully.
I know it is not recommended to hack the core, but this was the only solution I found useful. If there is any work-around to this solution, please let me know.


What do all these problem have in common (can't find the origin)?

So the problem was the dhtml-menu module with the "Expand on bullet option"


Make page.tpl.php and page--front.tpl.php share same html

The theme system works by looking for templates that are a precise matches for the current path and then falling back to looking for less and less precise pages.

If you

delete your page--front.tpl.php
clear the cache

Then phptemplate should use page.tpl.php for your front page.


After many unsuccesful tests, I have finally found the solution through
Set the "from" header in the email to be in the format "Full Name" <email@address.com>.

In your module, you must use the following code, which can be customized via the ID of the email or other parameters which are contained in the variable $message (which is passed by reference, so can be modified by the hook):

function my_module_mail_alter(&$message){

    $from = "user-account@domain.name" ;

    $message['from'] = $from;
    $message['headers']['From'] = $from;
    $message['headers']['Sender'] = $from;
    $message['headers']['Return-Path'] = $from;

} // function


Is there a way to upload files to the theme directory

It doesn't look like the file module places any restriction on the upload path, so in theory it should be as simple as:

'#upload_location' => DRUPAL_ROOT . '/' . drupal_get_path('theme', 'MYTHEME') . '/images/backgrounds';

However, having your theme folder writable by the web server would usually indicate that permissions are not set correctly. It would be a better idea to fix those, and save your images in the proper location (i.e. sites/default/files); see Securing file permissions and ownership for full details.


try this module "Nice Menus" and this "Menu Attributes".

You can follow these tutorials for more informations:
http://codekarate.com/daily-dose-of-drupal/drupal-7-menu-attributes-module
http://codekarate.com/daily-dose-of-drupal/drupal-7-nice-menus-module

I hope it helps you out. Thank you


How to show 404 page for not found images

While @Shawn Conn's answer does work it does cause issues in Drupal because of image cache. If you go to a page that doesn't have the image style created yet it won't create the image because of the .htaccess rule.

The best way to display a 404 page on bad images is to use the Fast 404 module and create a static html page.


How to programmatically check a view to test if it has any results?

Your options:

Trim down the "view" to return only 1 row of possible results.
Attack the problem from the other side. Use a Rule or a Hook to track the condition of your event (eg, "is there new content of type X") in a site variable and check that value instead of your View.

... etc ...


Allow users to edit their own content and admin-generated content

You can give the 'Authenticated user' role permission to 'Edit any <content type> content'. If you configure that content type to create a new revision by default, the user will be registered as the author of that revision (and if you don't give them the 'Administer nodes' permission, they can't uncheck the option to make a new revision). The original author of the node will however still be listed. I can't think of an easy way to change that automatically. But the users can already edit all nodes of that type anyway, so it would only be relevant if you use the node author for some listing or so - in that case, you can probably use Rules to do assign latest revision author as node author.

Edit: OK, so in that case this doesn't help. You can investigate if something along these lines works (I haven't done something like this so I'm not sure it's possible without coding):

Setup a condition for Rules with Context Rules, something like 'Node author is "admin"'.
Create a Rules action using Content Access to set 'Per node access control' if that Context condition is triggered.


Take a look at the module Nice Menus or Superfish menus.  Both offer a lot of flexiblity and control for managing menus.  In both cases you will configure the module to provide some menu blocks and configure the blocks to attach them to your main menu.  You will then put the Nice Menu (or Superfish) block where you want it and hide the main menu block.  (I like superfish)


Render array in controller response without surrounding theme

There are two ways.

One is, you render it yourself into a string, then build a Response object with it and return it. Drupal won't alter/touch a Response object and return its content as-is.

Second, since you mention ajax, Drupal actually has a built-in mechanism for its own ajax command system. If you pass ?_wrapper_format=drupal_ajax to the request, it will automatically transform it into ajax commands that will take care of not only the html content but also contained assets like css/js and drupal settings that are required to correctly display that HTML.

I don't really know in detail how the JS part works, but it basically all happens in ajax.js, for example in Drupal.Ajax.success, which then triggers the commands defined in Drupal.AjaxCommands (which can be extended), so you could write a more or less generic implementation of dealing with that response.


You can indeed edit the exported config and then re-import it to make the title field mandatory.

Always be careful when editing config directly.

The config files generally follow the naming convention core.base_field_override.<entity_type>.<bundle>.title.yml.

There should be a required key which is set to false. Simply change false to true, save and then re-import your config.


Yes, the Menu Attributes module works well.  I used it on nearly all projects.


In your delete route add _entity_access: yourentity.delete to the route requirements.

As Ivan pointed out in the comment, this is a matter of the route not automatically requiring entity access when it points at an entity form. The entity access requirement must be added to the route explicitly.


How can I create multiple chatrooms using the Drupalchat module?

This question is pretty similar to the (still active) issue about Multiple public chat rooms - role controlled, here is a partial quote from that issue:

  Any chance you can allow the administrator to create more global chat rooms? I would like to create a chat room for Children so Adults cannot gain access and adult rooms where teens and children cannot access.

Comment nr 4 (from the module owner of the DrupalChat module) states the following: this option only exists in "iFlyChat Servers" polling method.

Here are some more details about iFlyChat (= quote from https://iflychat.com/):

  With iFlyChat, websites need not worry about setting chat server of their own. iFlyChat server will take care of the hosting part and will provide a hassle free setup of chat system. We use latest onCloud technology which gives a faster chatting experience to all users of your website.


Question about Managing JavaScript in Drupal 7

Those examples are not complete working code examples.

They are just to illustrate that in Drupal 6 you did this:

Drupal.behaviors.exampleModule = function (context) {
  // Your code goes here.
}

And in Drupal 7 you would generally do this:

Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    // Your code goes here.
  }
};

The rest of the code in those examples is not relevant.

However:

Yes, it means that if you click an element with the class "example" it will run the code in your click handler. Your example code is buggy though, it should be like this: <p class="example"><?php echo 'click here'; ?> </p>
The "ul" is referring to an unordered list element. So it will get the next ul from the element you clicked and toggle it.

[EDIT]

To answer your additional question about the example code:

  or can I mention the class or id of div in $(this).next('div').toggle('show'); , so that the data in that part will hide or show?

Yes you can specify any selector you want, for example:

$('.comment').toggle('show');


How to trigger function on vocabulary terms update?

Oh, I probably should use term_update for this:

hook_taxonomy_term_update($term){
if ($term->vid == $vid){
// Action
  }
}

Or Rules module


Depending on how often it appears, you can call t(SPAMBOT_DEFAULT_BLOCKED_MESSAGE) every time you invoke the constant in your code. For instance:

<?php

define('SPAMBOT_DEFAULT_BLOCKED_MESSAGE', 'Your email address or username or IP address is blacklisted.');

/**
 * implement hook_page_alter()
 * JUST AN EXAMPLE. REPLACE WITH YOUR OWN HOOK OR FUNCTION
 */
function mymodule_page_alter(&$page) {
  drupal_set_message(t(SPAMBOT_DEFAULT_BLOCKED_MESSAGE));
}

In order to be able to see the string in the "Translate interface" page (admin/config/regional/translate/translate), you need to display it at least once in a language different from the default language of your site.


Unfortunately point 1 doesn't work for anonymous traffic.

You have to uninstall the Internal Page Cache module.

Or trigger

\Drupal::service('page_cache_kill_switch')->trigger();

in a view hook.

When the View is placed on most or all pages then uninstall the Internal Page Cache, because the page cache kill switch also disables the dynamic page cache and you don't want to disable both caches, unless this is only for a few pages which don't have too much traffic.

Additionally you need point 2 (disabled cache in views advanced settings) in any case.

Update:

  By the way in response header there is a header called
  x-drupal-cache:HIT. (It's MISS for the first time and then HIT after
  first load) Why?

This header is generated by the Internal Page Cache, a HIT means it is served from this cache.


Add js depend jQuery in a specific content type

Checkout https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module especially section Attaching a library in a twig template

See also lib/Drupal/Core/Render/theme.api.php where the library is like $build['#attached']['library'][] = 'core/jquery';

{{ attach_library('core/jquery') }}


Does drupal create new file in image styles?

When you create an image style, a folder is created in /sites/default/files/styles/ that holds processed versions of your image.  When you select to use that style in views or anywhere else, only the processed image is loaded.  It wouldn't load the full size image if you have it set to the 90x70 style.


Sounds like a permission issue, each flag you create has it's own permission settings. Have a look under admin/people/permissions


How to implement search on multiple fields limited to one content type in drupal 7

I'm not a D7 expert but I you can try with an EntityFieldQuery like this:

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                ->entityCondition('bundle', 'YOUR_CONTENT_TYPE_NAME')
                ->propertyCondition('status', 1)
                ->fieldCondition('YOUR_FIELD_NAME', 'value', $searchterm)
                // other conditions...
                ->propertyOrderBy('title')
                ->execute();
$nodes = entity_load('node', array_keys($entities['node']));


Force `` to scale to text field in the views-ticker module

Views Slideshows has an option for forcing equal heights, failing that I would suggest using a jQuery plugin like equal heights

Views Slideshows:

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


How to hide a block for specific users using Views?

Under the block settings in views, there is an option called "access," which you can use to allow access based off of role (anonymous user, registered user, etc). If your users have specific user roles that you can filter off of, you can use this to do what your looking for.


How do you embed addtional RSS feeds into the  section of your theme

You can use drupal_add_feed() or if you don't want to have an icon appear
on the page itself

 drupal_add_html_head_link(array(
    'rel' => 'alternate',
    'type' => 'application/rss+xml',
    'title' => $title,
    'href' => $url
  ));


Hiding a filter in a view with same filter in contextual filters

The following code will help you to solve your issue.

/**
 * Implement hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'views_exposed_form') {
    if($form['#id'] == 'views-exposed-form-myview-page') {
       // argument 1 represent city1
      if(arg(1)) {
        // hide city field
        unset($form['#info']['filter-jobs_in_city']);
        hide($form['jobs_in_city']);
      }
    }
  }
}

Notes:

Replace form id views-exposed-form-myview-page with your own form id
Replace argument 1 with the right City1 argument index
Replace jobs_in_city field name with your own city field


Custom Views Relationship with Custom Entity

I fixed it by copying some of the code from the entityreference.
I have to use a different views handler for this relationship  and add other attributes to that relationship

function clinical_trial_views_data_alter(&$data) {

  $data['clinical_trial_research']['clinical_trial_research_sites'] = array(
    'title' => t('Clinical Trial Research Sites'),
    'help' => t('Field Reference Appear in Clinical Trial Research Sites.'),
    'relationship' => array(
      'handler' => 'views_handler_relationship',
      'label' => t('Clinical Trial Research Sites'),
      'base' => 'clinical_trial_research_sites',
      'base field' => 'study_num',
      'relationship field' => 'study_num',
    ),
  );
  // The reference field in the node entity is not entity reference , its just a basic text field
  $data['clinical_trial_research_sites']['site_comp_code']['relationship'] = array(
    'handler' => 'views_handler_relationship_entity_reverse',
    'field_name' => 'field_site_comp_code',
    'field table' => 'field_data_field_site_comp_code',
    'field field' => "field_site_comp_code_value",
    'base' => 'node',
    'base field' => 'nid',
    'title' => t('Referencing entity'),
    'help' => t('Field Reference Appear in Location Content type.'),
    'title' => t('Location'),
  );
}