Creating view filter that lists most recent, except the x most recent

I would create a view and have two different displays. One display holds your slideshow thing and the other display holds the rest of the items.

The second display would be set to have the style item list and the pager settings should be set to have an offset of three. The offset will skip the first X items that are present in your first display.


Like so:

if (variable_get('darksite_status', 0)) {
  // Yes.
}
else {
  // No.
}


Globally providing title attribute to links

A lot of links end up going through theme_link() at some point (even those that go through the l() function by default); so providing a preprocess function for that theme, that adds a title to any link that doesn't already have one, would be a very good start:

function MYTHEME_preprocess_link(&$vars) {
  // If there is already a title set, and it's not empty, we don't need to continue.
  if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
    return;
  }

  // Otherwise we use the link text as the title.
  $vars['options']['attributes']['title'] = strip_tags($vars['text']);
}

This won't catch links that are outputted directly in HTML, or don't go through l()/theme_link(), but I think you'll struggle to intercept those anyway (it would require some DOM parsing or ugly regex).


Anyone know how to build a menu like this?

Welcome to stackexchange. When asking a question please try to be as specific in your question as possible. Try describing what you want to know – also using screenshots or wireframes is ok – but please avoid forcing others to ckick on a link to understand your question. Questions like "How can I do <link>this</link>?" are usually not very likely to get a lot of attention from the community.

That said – I did click the link – and I suppose whether there is a module providing this effect/functionality or not is probably not that important since you could achieve a fairly similar effect with either a drupal menu or a drupal view and some javascript / jquery / ajax (for loading the second level dynamically) and some additional css3 for the sliding effect.

You could probably even skip the scripting part, display a standard list of links, hide the non-active second level items and use css3 to slide the second level in once it's needed. Asking ofer at stackexchange might be the more suitable forum to ask about this (here is for example everything about 'slidetoggle').

I'm sorry this is probably not the answer you were looking for – but maybe if you provide more information on what you want to achieve someone else can point you to an appropriate module.


How to clear image (or file) field data for specific node programmatically?

I assume that your field accepts only one file at a time. This is the code you need to use:
// Replace this with the ID of the node you want to update.
$node_id = 123;

/** @var \Drupal\node\NodeInterface $node */
$node = \Drupal\node\Entity\Node::load($node_id);

// Step 1: remove the file. This will actually delete the file from the
// filesystem, so in case you want to keep it just remove the next two
// lines.
/** @var \Drupal\file\FileInterface $file */
$file = $node->get('field_NAME_OF_YOUR_FIELD')->entity;
$file->delete();

// Step 2: remove the field data.
// The 0 in this case is the index of the item you want to remove. It simply
// means the first value in that field needs to be removed.
$node->get('field_NAME_OF_YOUR_FIELD')->removeItem(0);
// We have to save the changes to the node.
$node->save();


How to filter admin/structure/block per role

Checking the code, this popped up:

  // Remove the block completely if it's not allowed to be viewed
  if (!block_access_can_view($module, $delta)) {
    unset($form['blocks'][$key]);

in block_access_check_perms (.module file)

Otherwise it only removes the operations that user doesn't have access to. Now, this function gets called in the form_alter for the block overview page. So, you have two options as far as I can see.

First, restrict the view permission to be the same as edit (these permissions have no effect on the front-end visibility, as per the project page). This is your best bet I believe.

The other option is to alter the form again after this module has already altered it, run your own checks and then unset the blocks with no operations left.


Drupal 7 Error 324 (net::ERR_EMPTY_RESPONSE)

I found something else as well. It turns out that I was using a beta version of a module that was spitting out so many error messages that it was crashing apache.

Best advice I can give is to stick to trusted and tested modules.


You can try Quiz Drag Drop module

  This module allow you to add drag drop type of question in quiz
  module.

  By using this module admin can upload images with their titles and
  later all the titles will become placeholder. User need to drag and
  drop images on the correct placeholder to get points.

  This module is an attempt to enhance Quiz module features by
  introducing another type of question.


Authenticated users can't edit their own content even with permissions set accordingly

You don't need to restore your database, you only need to enable your nodeaccess module in your modules page and it should restore on its own and you will have access to all stored data. Then go to nodeaccess config, undo all the restrictions, save, then go back to modules page and uninstall nodeaccess. And rebuild permissions. Hopefully that'd do the trick!


Message "Restricted HTML" on node/add page

Please try again after raising xdebug.max_nesting_level to 500 or so.

Steps:

Know where is the php.ini:

In your drupal site go to admin/reports/status/php

Then edit your php.ini in this case, is on /etc/php5/fpm/php.ini

Search the xdebug section:

Change the variable xdebug.max_nesting_level to 500 or add it.

Restart the web server.


Output the width & height of an image using a particular image style

image_get_info() is the function that will get you the details. But it accepts uri as the param (Not sure about url). You can try passing the argument.
If you manage to get the path of the images then this function return the following ,

"width": Width, in pixels.
"height": Height, in pixels.
"extension": Commonly used file extension for the image.
"mime_type": MIME type ('image/jpeg', 'image/gif', 'image/png').
"file_size": File size in bytes.


Determine if an entity is a certain content type

You should be able to check the entity type and content type like this:
use Drupal\Core\Entity\EntityInterface;

function hook_entity_presave(EntityInterface $entity) {
  if($entity->getEntityTypeId() == 'my_entity_type' && $entity->bundle() == 'my_content_type') {
    // Do your stuff here
  }
}

Where my_entity_type is the entity type and my_content_type is the content type.
Adding Clive's answer, since the entity type you want to work with is already known to be a node, you can use hook_node_presave() instead of hook_entity_presave:
use Drupal\Core\Entity\EntityInterface;

function hook_entity_presave(EntityInterface $node) {
  if($node->bundle() == 'my_content_type') {
    // Do your stuff here
  }
}


How i can use entity_metadata_wrapper for new database entry and update data in Drupal 7

Its simple

// $nid - nid of node you want to udate
$node = node_load($nid);
$entity_wrapper = entity_metadata_wrapper('node',$node);
...
$entity_wrapper->field_eventbrite->set($row->eid);
$entity_wrapper->field_venue->set($row->name);
$entity_wrapper->save();


Have you tried the following?

Navigate to the facet setting page (/admin/config/search/facets/facet_name/edit)
under widget set it to List of Checkboxes or List of Links (not sure what you are using)
Within List of Checkboxes setting or List of Links Setting, there should be an option Show Reset Link.
Enabled it and it will show a Reset Text input box where you can add Reset Facet or whatever you need.
Apply other settings and click save.


CKeditor: Allow choosing CSS classes from a select menu in dialogs

You can specify a custom "ckeditor.styles.js" editing the profile > CSS > Predefined styles and also the Predefined Styles Path fields.

Additionally, you can override any other CKEditor configuration in Advanced Options > Custom JavaScript configuration


I get image field upload errors with a custom node_add() form

I believe the problem is, roughly, that while you've ensured the include happens before initial form build, that include doesn't happen when the AJAX file upload processing attempts to rebuild the form... So node_form() function is undefined and things fall apart.

The solution that worked for me was to use form_load_include() in place of module_load_include(). According to its documentation, this alternate function exists for this express purpose - "ensures that the include file is loaded whenever the form is processed."


How to change Drupal's default login error text

I'm pretty sure you shouldn't have a semi-colon after your if condition.

 if ($form_id == 'user_login'); {}

Does removing that have any effect?


By default, Drush runs ssh with the option -o PasswordAuthentication=no, which prohibits username/password access and requires that you use a public/private key pair to access your server.  This is exactly what you want, and in fact, by default, ssh will use the private key that it finds at $HOME/.ssh/id_rsa to authenticate you with remote servers.

If you need to use some other private key, though, you can put this line in your drushrc.php file:

$options['ssh-options'] = '-o PasswordAuthentication=no -i /home/YOURUSERNAME/.ssh/other_id_rsa';

Note that Drush will not automatically evaluate bash shortcuts such as $HOME or ~.  If you do not want to hardcode the path to your home folder, you may look it up with $HOME = drush_server_home();.


View displays nodes that should be excluded by filter

Your filter says, "if the stock level is greater than 0 (1,2,3,4...) OR stock is not active, don't show the product". You want it to say, "if the stock is equal to 0 ( or <=0 ) OR stock is not active, don't show the product“. In other words: Stock: Level (=0) OR Stock: Active (No)

On second thought, if you're not filtering out, you would want Stock: Level (>0) OR Stock: Active (Yes) to show all bikes that are active, and have more than 0 in stock.


Drupal 7 - Internationalization module - some blocks not visibile (i18n)

Translatable means you have to actually translate it to show on the second language. On the block configuration it should give an option to translate it or perhaps check the block's visibility language settings.

Another option if you want the same exact image on both languages you make the block untranslatable.

You need to also enable i18n_select if you have not done so
and go to "detection and selection" admin/config/regional/language/configure
and enable at least URL selection for interface/content

This will allow that when you visit yoursite.com/page assumes English
and when you visit yoursite.com/LAN2/page assumes LAN2

More info on setting up internationalization


How to display contents which matches the path alias of a content from URL using views contextual filters?

Views URL alias

  The 'Views URL alias' module allows Views to be filtered by path
  aliases.

  This module is useful if your website uses heirachical paths. It
  allows you to filter and sort a view by URL aliases.


Multiple billings for one user in one day for Monthly Recurring (Drupal commerce)

There is a fixed issue with Commerce Authorize.Net, discussed on https://www.drupal.org/project/commerce_authnet/issues/2161989.

If your setup already incorporates that fix, then most probably it is hitting the issue Duplicate queue items should not be created. Apply the patch in #6 and you should be fine.


Why am I getting redirect to node?destination=node when trying to login?

This link might able to help you.
How to see the error messages when I get the white screen of death?

It might be .htacces problem. Maybe you should ask your hosting provider to help you solve this problem. My hosting provider always help me solve when this problem appear.


How to use CiviCRM contact data latitude and longitude in drupal gmap formatted view

There is a good recipe for using leafhttps://civicrm.stackexchange.com/questions/12862/how-to-put-your-civicrm-contacts-on-a-leafleft-map-in-5min if you are happy to slightly switch track. For D7

Also you will get more Civi eyeballs if you post on that channel, and while I appreciate this is a 'drupal' question, more civi folk use drupal than drupal folk use civi ;-). Good luck


How can I insert fields from custom content to custom form?

An entity can have multiple form modes, so you can exclude some fields in different form modes and leave fields that you want to display.
So, you can create form mode "custom_form_mode", go to manage fields, choose "custom_form_mode" and arrange fields.
In the custom code, you can use the code that you mention in #1, but with an extra argument in the getForm method, which is $operation, and that one is the form mode that you want to use to display form.
$node = \Drupal\node\Entity\Node::create(['type' => 'my_students']);
$form = \Drupal::service('entity.form_builder')->getForm($node, 'custom_form_mode');
return $form


Retrieve translated taxonomy term in current language programatically

Use the following code:

$curr_langcode = \Drupal::languageManager()->getCurrentLanguage(\Drupal\Core\Language\LanguageInterface::TYPE_CONTENT)->getId();

// retrieve term
$taxonomy_term = \Drupal\taxonomy\Entity\Term::load($tid);

// retrieve the translated taxonomy term in specified language ($curr_langcode) with fallback to default language if translation not exists
$taxonomy_term_trans = \Drupal::service('entity.repository')->getTranslationFromContext($taxonomy_term, $curr_langcode);

// get the value of the field "myfield"
$myfield_translated = $taxonomy_term_trans->myfield->value;


The problem is probably that you don't save the order item after updating the title.

Add $item->save(); at the end of your code and it should work.


There is a patch for same feature https://www.drupal.org/node/1207348


How to add css depending on a field value?

Basically you need to drupal_add_css in your template_preprocess_node in your template.php after checking the condition that image exists in a manner similar to

$field = field_get_items('node', $node, 'field_image');
if ($field) {
   //Do something with the field
}
else{
   //There are no results
}


I've asked the question multiple times. It appears that we need to wait for Rules. For the time-being, I'm using the built-in drupal contact form + contact_storage module for form. It's not the best, but it works.


theme() parameters sent to output.tpl.php

As described in Override template files based on template filename as well as hook name, if you theme function is my_file, your template file needs to be my-file.tpl.php; you cannot use output.tpl.php because Drupal would not recognize it as template file, at least until Drupal code is not changed as per the issue I linked.
The variables that you pass to the template file needs to be defined in your implementation of hook_theme().

Your code should be similar to the following one.

function mymodule_theme() {
  return array(
    'mymodule_output' => array('template' => 'mymodule-output', variables => array('my_vars' => NULL))
  );
};

function mymodule_myfunction() {
  // Add here the code that initializes $my_vars.
  // …

  $build['variables'] = array(
    '#theme' => 'mymodule_output',
    '#my_vars' => $my_vars
  );
  return $build;
}

// mymodule-output.tpl.php
<?php echo $my_vars[0]; ?>

I used mymodule_output as name of the theme function and mymodule-output.tpl.php as name of the template because the coding standards used from Drupal suggests to use the module name as prefix; it would not change if you used output where I used mymodule-output or mymodule_output.

If all you are doing is printing a variable, then you don't need a theme. Theme functions (and template files) are used when you plan to allow themes or other modules to alter the output of your module. That is why Drupal uses node as theme function: to allow themes to alter how a node is rendered. The Node module defines its own node.tpl.php file, and the Bartik theme uses its own node.tpl.php.


Use drush config-edit, as stated in the docs.

Or implement an upgrade path for you module, see hook_update_N.


So in this particular problem, what was actually happening was a double-posting of the Ajax submit handler. The first call was being interrupted and it was coming back empty. Removing the extra submit handler fixed the problem. This was directly related to the use of Zurb's custom form fields and a couple of browser issues that caused me to believe that the submit handler was not firing, but indeed it was.


Thanks, i've did this and this work perfectly :

/*
 * ==================================
 * CONFIGURATION MODULE
 * ==================================
 */
/**
 * Implementation of hook_admin()
 */
function food_truck_form_admin() {
  $form = array();
  $form['vocabulary'] = array(
      '#title' => 'Vocabulaires',
      '#type' => 'select',
      '#options' => food_truck_form_vocabularies(),
      '#ajax' => array(
          'callback' => 'terms_callback',
          'wrapper' => 'terms-wrapper',
          'event' => 'change'
      )
  );
  $form['terms'] = array(
      '#title' => 'Types de marqueurs',
      '#type' => 'select',
      '#prefix' => '
',
      '#suffix' => '
',
      '#multiple' => TRUE,
      '#options' => food_truck_form_terms('marqueurs')
  );
  return system_settings_form($form);
}

/**
 * Implementation of hook_menu()
 */
function food_truck_form_menu() {
  $items = array();
  $items['admin/settings/food_truck_form'] = array(
      'title' => 'Food-Truck Configuration',
      'description' => 'Global configurations',
      'page callback' => 'drupal_get_form',
      'page arguments' => array(
          'food_truck_form_admin'
      ),
      'access arguments' => array(
          'administer food_truck_form settings'
      ),
      'type' => MENU_NORMAL_ITEM
  );

  return $items;
}

/**
 * CALLBACKS
 */
function terms_callback($form, &$form_state) {
  $machine_name = $form['vocabulary']['#options'][$form_state['values']['vocabulary']];
  $form['terms']['#options'] = food_truck_form_terms($machine_name);
  return $form['terms'];
}
/*
 * ==================================
 * OTHER FUNCTIONS
 * ==================================
 */

/*
 * Return a term list of a vocabulary by it's machine name or null
 */
function food_truck_form_terms($machine_name) {
  if (! empty($machine_name)) {
    $vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;
    $terms = taxonomy_get_tffree($vid);
    foreach ($terms as $data) {
      $output[$data->tid] = $data->name;
    }
    return $output;
  }
  return NULL;
}
/*
 * Retur a vocabulary list or null
 */
function food_truck_form_vocabularies() {
  $vocabulary = taxonomy_get_vocabularies();
  if (count((array) $vocabulary) != 0) {
    foreach ($vocabulary as $data) {
      $output[$data->vid] = $data->machine_name;
    }
    return $output;
  }

  return NULL;
}


D8: Why updated paragraph content does not lead to an updated translation?

To expand on the comment from @4k4, for most use cases, you want to make the paragraph field untranslatable because it just stores the references to the paragraphs, which are then being translated.

Then you always have the same paragraphs in the same order for all translations.

Translatable paragraph fields are not yet properly supported (this is being worked on in the issue queue) and it should only be done if the paragraph structure must be different for different languages.


Drupal 7 Add user delete tab in user profile

You need to use hook_menu() instead of hook_menu_alter() because you are adding a new menu item rather than altering an existing one.

function YOUR_MODULE_menu() {
  $items['user/%user/cancel'] = array(
    'title' => 'Cancel profile',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_cancel_confirm_form', 1),
    'access callback' => 'user_cancel_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'file' => 'user.pages.inc',
    'file path' => drupal_get_path('module', 'user'),
  );

  return $items;
}

Don't forget to return $items at the end of the function, since it is not passed by reference.

Though I'm not sure if the page callback and arguments are right, I didn't check that, I've just copied from your code.


I use Boost for my company website, and have been pleased with the results.

Did you disable "Cache pages for anonymous users" in the performance settings? Did you add the extra settings required by boost in your .htaccess file? Are you only viewing the site as an anonymous user? Have you made sure the /[drupal-base]/cache is readable by Apache, and /[drupal-base]/cache/normal is readable and writable by Apache?

If yes to all the above, you likely have other issues slowing down your site, such as too little overall RAM (or too much RAM allocated in the allowed_memory setting).


Get path/url/uri of Entity reference field to content in a Twig template?

The url is not an entity field, so you can't access it directly. Also the entity methods to generate url/links are not accessible in Twig because of the sandbox policies. You can build a path though, if you have the id of the referenced node:

{% if not node.field_ref.isempty %}
  {{ path('entity.node.canonical', {'node':  node.field_ref.entity.id}) }}
{% endif %}

Reference: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates


“Neutral” basically means “I don’t care” in this context.

Returning it means you’re saying that your code has no opinion on whether access should be granted or not, and that other methods/modules should make the decision.


Trying to get property of non-object in i18n_langcode() (line 229 of i18n.module) and a bunch of other property of non-object notices

Finally solved this mystery.

I was able to narrow it down to a bean block in the site's footer. Upon inspecting all of the bean's block display fields

Disabling this field fixed the issue. Where is it coming from? IDK yet. I will update once I know. Seems like custom module.

Update

Yep, turns out Featurette image link is coming from a custom module. Notice the big error in line 24 and line 30.

More errors here, what a mess!


How do I grant permissions for translating block content?

Block level permissions for administration is not provided in core. There is a module Block Access which provides block level permissions for admin interface.

  This module adds a set of global permissions for creating, viewing, moving, enabling, disabling and configuring blocks as well as permissions at the individual block level. These permissions only affect the admin interface, front-end view access is handled in core.

UPDATE:

Blocks are not content, so the permission to translate content won't help here. To be able to translate blocks you need to download Internationalization and Variable modules and enable the module Block languages [i18n_block] which ships with Internationalization module.


How can I add a pager to the top of a forum?

Pager is known within the "views-view.html.twig" file: /core/modules/views/templates/views-view.html.twig

If you are using a contributed or custom theme you can override that file and move the pager output where you'd like. So your new file would live here:
/themes/custom/MY_THEME/templates/views-view.html.twig"
 for example.

As near as I can tell there's no setting for this in core currently, although it's been requested.

See also: https://api.drupal.org/api/drupal/core%21modules%21views%21templates%21views-view.html.twig/8.7.x

https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/function/template_preprocess_views_view/8.7.x


Exposed Filter Fulltext Search having the Searched fields as options along with the text box

I found a work around for this. We can create a radio button list in hook_form_alter() having the searched fields. Using hook_search_api_views_query_alter(), we can alter the fields that are passed in the $query object, so that the result set is returned only for the field that is been searched.

function MYMODULE_search_api_views_query_alter(&$view, &$query) {
    if(isset($_GET['your_field_name'])) {
        switch($_GET['your_field_name']) {
            case 'field1':
                $fields = $query->getFields();
                $fields = array( 0 => 'field1_value');
                $query->fields($fields);
            break;
            .....
            .....
          }
        }
      }


Sanitizing strings before adding as taxonomy term

Running the text through check_plain() will sanitize anything dangerous, giving you the same result you'd get if you were to input the same title as part of the normal 'create term' process via Drupal's UI. I'd also run it through trim() to get rid of preceding/trailing whitespace. Beyond that, yes, you might need to do some custom regex to clean up things in your data, but that's impossible to say without seeing your data.


CCK fields are always stored as an array of fields, even if the actual field is limited to only a single value.

So you it should be something like:

'field_ip_address' => array(array('value' => '1.2.3.4'))

Note that in Drupal 7, field values are additionally grouped by the language, which is 'und' (LANGUAGE_NONE) if the field is language-agnostic. So it would be something like this:

'field_ip_address' => array('und' => array(array('value' => '1.2.3.4')))

Copied from my comment, so that the question can be marked as fixed :)


How can I use Drush to determine if a module is being used or not in a multisite architecture?

This works in Drush 6.x and later:

$ cd /path/to/drupalroot
$ drush @sites pm-info MODULENAME --fields=status
You are about to execute 'pm-info devel' non-interactively (--yes forced) on all of the following targets:
  /path/to/drupalroot#default
  /path/to/drupalroot#other
Continue?  (y/n): y
.path.to.drupalroot#other   >>  Status   :  enabled
.path.to.drupalroot#default >>  Status   :  enabled


what is the use of form[#special] in a drupal form?

You can embed anything in your form. Just add # at the beginning of the array index to indicate it's not a child element, and Form API will accept that even if it does not define or use it. Form API reference does not mention #special, so it is not an standard parameter. Instead, it's a parameter created by module's author for his own need.

For example, I usually add #machine_name to anything that can trigger AJAX, for easier handling of $form_state['triggering_element']. There are many uses.


How do I add comments to a YAML webform?

Context

Drupal 8.x
Webform module
YAML comments

Use-case

developer KoenC wishes to add comments to a YAML file and have those comments retained upon save

Problem

Per the YAML specification, comments are specified as "throwaway" artifacts.
This means that YAML commments are not required to be preserved by parsers that implement the YAML specification

Workaround

Metadata and comments can be added as separate YAML nodes (see e.g., https://stackoverflow.com/a/8565238/42223)


Create Drupal 7 page specific tpl files without using node ID's

Happened upon this old question that didn't have a completely legit answer.

In short, you can set up templates based on path by using the formulae...

page--[front|internal/path].tpl.php

Put simply, if you want a specific page template for a custom page with a url of support, you would create a template named

page--support.tpl.php

or support/contact would be

page--support--contact.tpl.php

Of course you can and probably should use the node--[type|nodeid].tpl.php pattern if you are dealing with node pages.  But creating a template based on path is definitely possible.


Getting Views Rows Data in Custom Module

as this site is not about php programming I will not go very deep into this. but what you are probably looking for is http://api.drupal.org/api/views/views.module/function/views_get_view_result/7

to render the view use $view->render();

further reference: http://drupal.org/node/342132


Copying out the relevant portion of the template:

  <?php foreach ((array) $rows as $row): ?>

      <?php foreach ($row as $cell): ?>
        <td id="<?php print $cell['id']; ?>" class="<?php print $cell['class']; ?>">
          <?php print $cell['data']; ?>

      <?php endforeach; ?>

  <?php endforeach; ?>

If you want the  wrapping your cell to have an additional class based upon what is inside that cell, you will need to do something like this:

  <?php foreach ((array) $rows as $row): ?>

      <?php foreach ($row as $cell): ?>
        <?php
          $new_class= // grab information out of $cell['data']
        ?>
        <td id="<?php print $cell['id']; ?>" class="<?php print $cell['class'] . ' ' .  $new_class; ?>">
          <?php print $cell['data']; ?>

      <?php endforeach; ?>

  <?php endforeach; ?>

If it's not easy to do, $cell['data'] is probably HTML since it is just being printed, you do have the entire $view object to work with, and there, you can grab stuff out of $view->result and correlate that to these cells.


As written in that answer, that is blocking a whole apache thread and therefore not a good idea.

I suggest you have a look at http://drupal.org/project/nodejs. node.js is an event-based webserver written in JavaScript and that is the module that integrates it with Drupal. Then, your clients keep a connection option with the node.js server and you can contact them through that server.

The project is still in development, I don't know how well it is working already.


In Drupal 7, you just need to use Image style as answered by Jack-PL


Locating the source of Forbidden message

I started disabling modules one by one and rest_auth was actually causing it though it was  not being used. Simply disabling solved it. And yes it does not contain any word "forbidden".


common.inc error in newly downloaded Drupal 7.69

I think it is PHP related.  According to the Drupal 7 php requirements PHP 7.4 is not fully supported.  If you are running on 7.4 perhaps try downgrading it to 7.3 and see if it makes a difference.

This is probably the relevant issue that you encountered.  Alternatively see if you can use the latest patch in there and post your findings so you can help move the issue forward.


CCK field related to non-drupal table columns

Well, one of the possible ways to do that is to create a cck field of type integer and use "select list" as a widget. And then in your implementation of hook_form_alter you need to extract data from Customers table and populate the select with this data.

You might find the following piece of code useful:

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_CONTENT_TYPE_NAME_node_form') {
    $sql = 'SELECT id, name FROM Customers';
    $result = db_query($sql);
    $options = '';
    while($row = db_fetch_array($result)) {
      $options .= $row['id'] . "|" . $row['name'] . "\n";
    }
    $form['#field_info']['field_YOUR_FIELD_NAME']['allowed_values'] = $options;
  }
}


define my own entity.tpl for my custom entity?

Unfortunately, is not as simple as creating a custom template named ENTITYNAME.tpl.php.

You may want to reconsider theming an entity.  Entity-level code should only deal with low-level data manipulation.  Rendering for the browser should handled separately by the Drupal theme layer, not the entity itself.

However, if you want to override the theme layer for your entity, you can do it by overriding the page template for your entity (i.e. page–-ENTITYNAME.tpl.php (where "ENTITYNAME" is the machine name of your entity).

But this is probably not what you're asking about.  If you insist on theming your entity, there is a solution is written up here: Theming Custom Entities @ Drupal.org.

To summarize: You do it by means of three functions that you place in the module defining the entity:

MODULENAME_menu() hook.
Page Callback
MODULENAME_theme() hook.

The MODULENAME_theme() hook is used create this module's Theme Registry entries.


How can I prepopulate a field when creating a new node with the values from a field collection?

You can try and look at this module. It allows to have corresponding node references and hence if you select something from one node, you can prepopulate the other node as well. http://drupal.org/project/cnr


Shortcut menu not showing after admin menu installed

Toolbar is the core drupal module which  displays the shortcuts near the top of the page, along with an Edit shortcuts link. After installing admin-menu we do not need core toolbar module otherwise it causes redundancy for admin menu,uninstalling the toolbar module causes vanish of shortcut bar with it.

Shortcut bar comes from shortcut module, which simply allows us to place the shortcut block by going to (Administer > Structure > Blocks) and look for Shotcut block which by default goes under disabled block.


Collapsible fieldsets in form using button

you may use jquery for this. give some id to your button and on button click trigger the default fieldset collase or use toggle to hide show fieldset. Hope this help!


Trying to leverage drupal_add_html_head to add an ie10 class

Hope this will help you,

Use Browser class module.

  This small module helps theme-developers to deal with cross-browser compatibility. It makes easier to handle different types of non-widespread browsers just as much as it helps with using different versions of Internet Explorer.
  The module extends the $body_classes variable in page.tpl.php based on the enduser's browser, and platform.

  The module also makes a $browser_classes variable available in page.tpl.php, which stores the data in an array, this way the developer can make use of it as needed, if he does not wish to use the $body_classes variable.


How to form_later the user profile form to only allow 1 role to be assigned/removed

Roles are removed because when the form is submitted those roles are missing (and thus unchecked). You can hide those options instead:

$form['account']['roles']['3'] = array(
  '#disabled' => TRUE,
  '#attributes' => array('class' => array('hidden'))
);

And some CSS .hidden { display: none; } or something.

  In D7+, form_process_checkboxes() and form_process_radios() already support you in doing so by allowing for partial sub-element pre-definitions read more


Slideshow showing 3 slides (prev - active - next)

Edit2:

I found the solution by studying the flexslider module. You can manipulate sliders by #ID with the following commands:

(function ($) {
$(document).ready(function(){
$(".page-about-livio #flexslider-2 .flex-next").click(function() {
    $('#flexslider-1').flexslider("next");  //Go to next slide
    $('#flexslider-3').flexslider("next");
});
$(".page-about-livio #flexslider-2 .flex-prev").click(function() {
    $('#flexslider-1').flexslider("prev");  //Go to next slide
    $('#flexslider-3').flexslider("prev");
});
});
})(jQuery);


How to create a page showing only articles in a certain language?

Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.

Also, to make view results correspond to the language switcher, add a filter for Content Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

Note: The Internationalizations Views module only has an alfa version for D7, but right now there are over 41K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because +41K users can't be wrong, right?

PS: I'm assuming this question is about D7.


Creating a views reference list to be used in a node reference

You can use entity reference module  (https://drupal.org/project/entityreference). It provides the forward and backward reference of views.


Are there alternative ways to creating themes in Drupal 7?

The short answer is "no." At least not at the level you are looking for.

A .info file is always required for a Drupal theme, this is how Drupal recognizes that the theme exists. Adding CSS and JS within this file is important because of CSS/JS caching which is important for site performance and other reasons. You should read the Drupal Theming Guide for more information, if you haven't.

There is, however, no requirement for template.php in a theme. If you do not want to utilize RDF on your site, you can disable the core RDF module.

There are other Theme Engines for Drupal, but they have all been abandoned in favor of PHPTemplate in Drupal 7. There are also a number of contributed base themes for Drupal, which are helpful for getting started with theming more quickly.

Unfortunately, the theming approach of Drupal is often a shock for users coming from other CMSes, especially Wordpress. The inherit flexibility and functional power in (and legacy of) Drupal core necessitates an extremely complex theming layer. You are not going to find a Wordpress-like experience in Drupal 7.


Remove Parent Theme Settings From Child Theme

This definitely isn't the nicest solution, but it does work. If you find a better one, do post it here.

function THEMENAME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
  unset($form['global']);
  unset($form['bootstrap']);
  unset($form['general']);
  unset($form['theme_settings']);
  unset($form['logo']);
  unset($form['favicon']);
  unset($form['components']);
  unset($form['update']);
  unset($form['javascript']);
  unset($form['advanced']);
}


add first/last classes when using theme_menu_link

Use Menu attributes module and give special ID or classes to your menu items. The module currently allows you to set the following attributes for each menu item:

Id
Name
Target
Rel
Class
Style
Accesskey


Simplenews unsubscribe link shows a 404 Page

There are many issue thread on simplenews about this issue.

Simplenews 404 issues

Currently the only supported version of simplenews is version 6.x-1.3 (May 21st 2010).   Most of the issues have patches that are commit to 6.x-2.x-dev and 6.x-2.0-alpha2.  You might want to upgrade.  If you don't, then you will need to apply one or multiple patches to fix your problem.


What is the replacement pattern in rewrite ouput for current user id?

The twig variables in {{ }} are replacement patterns for fields. Globally available tokens are accessed by their usual square brackets syntax:

[current-user:uid]

Custom text field

This token works in a global text area, but not a custom text field, because this plugin Drupal\views\Plugin\views\field\Custom doesn't have global token replacement. You need to extend it and override renderAltered():

/src/Plugin/views/field/CustomToken.php

<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\views\Plugin\views\field\Custom;

/**
 * A handler to provide a field extending custom by global token replacement.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("custom")
 */
class CustomToken extends Custom {

  /**
   * {@inheritdoc}
   */
protected function renderAltered($alter, $tokens) {
    return $this->viewsTokenReplace($this->globalTokenReplace($alter['text']), $tokens);
  }
}

and tell the plugin manager about the new class:

mymodule.module:

function mymodule_views_plugins_field_alter(array &$plugins) {
  $plugins['custom']['class'] = 'Drupal\mymodule\Plugin\views\field\CustomToken';
}

This applies the function globalTokenReplace() before the twig patterns are replaced.

Then you can use

{% if anotherfield_id == '[current-user:uid]' %} YES {% else %} NO {% endif %}

You have to enclose the token in single quotes so that you get a valid twig syntax after the global tokens are replaced.

Global text area

A global text area in header/footer is exactly the opposite, it supports global tokens but not Twig.

You could do the same as before and add Twig support in a custom plugin. But there is an easier solution. Install the module Twig input filter and go to "Text formats and editors" in Configuration and enable the Twig filter for the text format you use in the text area.


Views: upcoming events list with first upcoming event at the top

I have managed to do this by creating a module (easier than you might think) and adding a post execute function like this (text in caps has to be replaced by your module and view names):

function MODULENAME_views_post_execute(&$view) {
  if($view->name == "MYVIEWNAME") {
    $view->result = array_reverse($view->result);
  }
}


How to get BundleKey in EntityManager after getting storage of entity?

You can get bundleKey of your entity type by this way:

$type = 'commerce_product';
$bundle_key = \Drupal::entityTypeManager()->getDefinition($type)->getKey('bundle');


looking for equivalent webform select view module on Drupal 8

I believe what used to be webform_views_select module is part of Webform core for Drupal 8.

You can search for entity and choose any of the following elements

configure an entity reference view to be use as options

NOTE1:  Due to perhaps this issue entity reference is not recognized by webform the way outlined above, but it should work if core patch in #7 is applied (as confirmed by reports in this issue)

NOTE2:  Perhaps a work around would be to use content or taxonomy term instead of a view (since view reference is not working) if you don't have great need for views filtering capabilities.


As your requirement is to create a block that will show Black Setter on the White Setter page and vica versa, there is another simple way to achieve this.  The function taxonomy_get_related() will do this.

Create a block with input format as php and use above function to print related terms by passing current page term id. Then assign the block to particular region. The following snippet will works,

for eg:

 <?php
    $termid = arg(2);
    $terms = taxonomy_get_related($termid, $key = 'tid');
    //print_r($terms);
    foreach($terms as $term){

       $link = url('taxonomy/term/'.$term->tid);
       echo ''.$term->name.'';
     }
  ?>


I tested it on a local server. Now I can say that:
1/ Image is processed at upload ONLY if it is larger than maximum authorized width/height (if it fits in this max size, it is not processed).
In this process, the JPEG quality ratio set up in configuration (admin/config/media/image-toolkit) will be applied.
This first step generates the "drupal original image" with will be used to generate image styles.
2/ In this new process of generating the image styles, the JPEG quality ratio will be applied AGAIN when resizing the thumbnails.

This means that it seems better to keep the JPEG quality ration roughly around 60-80% to have lights pages, but in order to avoid it to be applied twice on the images styles thumbnails displayed in the pages, upload "original" images that are 100% quality JPEG and fit to the max allowed size (so that are not processed at upload).


Worked this one out after a bit of fiddling, so for others trying to figure it out too...

First find the template file you need to override - if it's part of a module, it might be in the module templates folder. Otherwise install Theme Developer - it will help you track down the template that's being used for that content https://www.drupal.org/project/devel_themer
Chances are you'll need to override that template with one from your theme - identify the template theme that you want to use (easiest done using Theme Developer on the page that is coming up how you want), then copy that template file from your theme templates folder ([theme].tpl.php) to your sub-theme templates folder
Rename the template file in your sub-theme templates folder the same as the one you want to override (as identified in step 1), and voila.
(optional) you might find a CSS file somewhere is still screwing up the way your content looks (in my case it was in the module css folder) - you can either tweak it with other tools like CSS Injector, or copy the offending CSS file into your sub-theme css folder and tweak it there.
If you are overriding CSS, you'll need to identify the CSS file in the sub-theme .info file (found in your sub-theme folder) - add the following line: stylesheets[all][] = css/filename.css  (where filename.css is the name of the tweaked CSS file) under the line stylesheets[all][] = css/custom.css


With the few things I know about your field field_surl and about the way you tried to solve it, I might purpose this simple answer, sorry if it sounds obvious :

You wrote :

$output .= '
title.'" />
';

Where did you initialize your $field_surl variable ? At least, assuming $field_surl is loaded within the same node, try :

$output .= '
field_surl.'">title.'" />
';

Or even better, as suggested in @Brandon comment, use url() function :

$options = array('absolute'=>TRUE); //i.e, or set whatever options you need for your url
$my_url = url($nd->field_surl, $options);
$output .= '
title.'" />
';


In your .module file add the following to the very top of the module (just after the opening <?php tag):

module_load_include('inc', 'common', 'common.query');
module_load_include('inc', 'common', 'common.taxonomy');

For your reference:

module_load_include();

EDIT

Seeing as how you're not going to be needing these on cached pages, then putting them in hook_init() is much better practice.

Like the following:

function common_init() {
  module_load_include('inc', 'common', 'common.query');
  module_load_include('inc', 'common', 'common.taxonomy');
}


title of view posted link is not showing

It looks to me that the problem is with the node display itself and not the view.

When you click the title you're led to the node page.

Check your content type display settings in Structure->Content Type->(your content)->Manage Display


That should be in the base of your site's file directory. Navigate to /admin/config/media/file-system to see where it is configured.


Disqus not showing on panel page only (panel set as homepage)

A workaround I found in this comment #5 out of the Disqus issuequeue adding disqus on the frontend.

    function HOOK_preprocess_page(&$vars) {
  if (module_exists('disqus')) {
    $identifier = $_GET['q'];
    if (strstr($identifier, 'path/to/add/comments/to')) {
      $domain = variable_get('disqus_domain', ''); // A.K.A. short name
      $url = url($_GET['q'], array('absolute' => true));
      $title = drupal_get_title();
      drupal_add_js(drupal_get_path('module', 'disqus') . '/disqus.js');
      drupal_add_js(array('disqus' => array('domain' => $domain, 'url' => $url, 'title' => $title, 'identifier' => $identifier)), 'setting'); // Add to the Drupal.settings for the script above to be able to pick it up.
      // Add the div to the page for the Disqus embed script to be able to drop in the comments code dynamically.
      $vars['page']['content']['system_main']['main']['#markup'] .= '

';
    }
  }
}

Still curious about what it is in the backend that made the comment box disappear below the Panel though. I also disabled all the modules apart from the Disqus, panel en core, but still nothing.


You should create a custom module (use core >= 8.3). Use this code as a base to start:

custom_breadcrumb.info.yml

name: 'Custom breadcrumbs'
description: 'Custom breadcrumbs implementation'
package: 'Custom'
# core: 8.x
type: module

version: '8.x-1.0'
core: '8.x'
project: 'custom_breadcrumb'
datestamp: 1443649740

custom_breadcrumb.services.yml

services:
  custom_breadcrumb.breadcrumb_views:
    class: Drupal\custom_breadcrumb\Breadcrumb\ViewsBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 1 }

src/Breadcrumb/ViewsBreadcrumbBuilder.php

<?php

namespace Drupal\custom_breadcrumb\Breadcrumb;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\LinkGeneratorTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Link;

class ViewsBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  use LinkGeneratorTrait;
  use StringTranslationTrait;

  /**
   * @inheritdoc
   */
  public function applies(RouteMatchInterface $route_match) {
    // This breadcrumb apply only for some views.
    $parameters = $route_match->getParameters()->all();

    if (isset($parameters['view_id'])) {

       $views_id = array(
         'VIEW_MACHINE_NAME_1',
         'VIEW_MACHINE_NAME_2',
       );

       if (in_array($parameters['view_id'], $views_id)) {
         return TRUE;
       }
       return FALSE;
    }
  }

  /**
   * @inheritdoc
   */
  public function build(RouteMatchInterface $route_match) {
    // Breadcrumbs set up (cache settings are so important!).
    $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
    $breadcrumb->addCacheContexts(["url"]);
    $breadcrumb->addCacheTags(["view_id:{$parameters['view_id']}"]);

    $parameters = $route_match->getParameters()->all();
    if (isset($parameters['view_id'])) {
      if ($parameters['view_id'] == 'VIEW_MACHINE_NAME_1') {
         $breadcrumb->addLink(Link::createFromRoute(t('VIEWS NAME 1'), '<none>'));
      }
      else if ($parameters['view_id'] == 'VIEW_MACHINE_NAME_2') {
        $breadcrumb->addLink(Link::createFromRoute(t('VIEWS NAME 2'), '<none>'));
      }
    }

    // Reverse order for this to work!!!.
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
    return $breadcrumb;
  }
}

Remember to replace VIEW_MACHINE_NAME_1 and VIEW_MACHINE_NAME_2 with the machine name of your views. Also replace VIEWS NAME 1 and VIEWS NAME 2 with the breadcrumb title you want for each view.


Logins with port numbers not including ports on redirect/login

Check if anything in this list of typical things might help:

Check if you get the same problem using another browser. If with another browser it works, then it might be a cookie problem. To solve that, delete the cookie in the browser where you have the problem.
Make sure "clean urls" is enabled. Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.
Make sure the value of "base_url" is set correctly in your settings.php (for D7) and settings.php (for D6).


How should I perform a redirect in hook_form_alter()?

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function [MODULENAME]_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Alter login form and add own custom submit handler.
  $form['#submit'][] = '_[MODULENAME]_user_login_form_submit';

  // Not all forms pay attention to $form['#submit'][]. For these
  // try adding your submit hook to the #submit for the specific
  // button.  e.g.,
  $form['actions']['submit']['#submit'][] = '_[MODULENAME]_user_login_form_submit';
}

/**
 * Custom submit handler for login form.
 */
function _[MODULENAME]_user_login_form_submit($form, FormStateInterface $form_state) {
  // Set redirect to login form.
  $form_state->setRedirect('custom.redirect_callback');
}


Creating 'index' content views for L1-LX within a taxonomy

There are features in Views concerning taxonomy hierarchy, displaying terms with depth, you should look into it. There is also Group by field option under Format in Views where you can, for example, group by Parent field (Parent of the Taxonomy term). You may need to add a Relationship for the Taxonomy field first before you can see those extra Fields/Filters. Contextual filter with depth might also be useful.
You should look into displaying Menus with depth, since each Taxonomy Vocabulary already has a Menu block. You can learn more about it here: Primary and Secondary Navigation in Drupal 8

Generally speaking, you want to get to a point where you have correctly nested HTML list items. Then you can use CSS to adjust the numbering to go into levels 1.1, 1.2 etc.

Or if that numbering is so important you could add a field for it on your Vocabulary, so each item has that textual bit of data associated with it (not numbers because the sorting won't be correct, you want 1.10 > 1.1). Sorting in Views can still be done with the term weight (the sorting you saved in Taxonomy).


The Media module might be a good solution to this, depending on your needs. It is still under development and still has a few issues, but it's probably stable enough to us (we are using it on several production sites without any problems). I think this module has the best approach to the problem of embedding images within node content.


How to delay sending emails using Rules to avoid being considered as a spammer?

Below is a summary of how you can get this to work:

Introduce an additional flag to allow "flagging" these (new) nodes by all users "who subscribed on another user to get messages" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).
Adapt the rule you already have, like so:

Remove the Rules Action "send eMail".
Flag the newly saved content, using the new flag (from step 1) for each of the users you already have in your existing list in your existing Rules Action.

Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged nodes (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first X users only (pick a value for X that fits your needs).
Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

eMail each of the users in that VBO list (you can probably reuse the Rules Action "send eMail" that you already had, but removed in step 2).
unflag (using flag from step 1) the node (for the user for which you just produced an eMail). This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the exectuion of the same rule within Y minutes or hours  (pick a value for Y that fits your needs).
Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every Y minutes (or hours), Rules will notify X users "as requested".


It's pretty straight forward, setup your content type with the required fields, then you want to use code similar to this:

$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = $mime;
$file->filesize = filesize($filepath);

$file->uid = $uid;
$file->status = FILE_STATUS_PERMANENT;
$file->timestamp = time();
drupal_write_record('files', $file);

$node = new StdClass();
$node->type = 'type';
$node->body = 'body';
$node->title = 'title';
$node->field_file = array(
  array(
    'fid' => $file->fid,
    'title' => basename($file->filename),
    'filename' => $file->filename,
    'filepath' => $file->filepath,
    'filesize' => $file->filesize,
    'mimetype' => $mime,
    'data' => array(
      'description' => basename($file->filename),
    ),
    'list' => 1,
  ),
);
$node->uid = 1;
$node->status = 1;
$node->active = 1;
$node->promote = 1;
node_save($node);


How to strip html from Elasticsearch and search API index?

i had the same problem.
The solution for me came from unchecking the 'Elasticsearch direct link' checkbox in the edit form of the autocomplete tab in the search api index.


Layout problems (backgrounds and blocks region)

You would have to learn CSS and how to work with themes to do this yourself.

An alternative option, for no code solution, you could use Glazed Builder. However, it's not free, but might be worth the price of admission if you no time to learn how to code.

Important: There is Glazed builder for Drupal 7 & Drupal 8, remember to get the version of the Drupal version that you are using, as the 7 version will not work for Drupal 8 and vice versa.


No, the /includes does not (if you haven't hacked core) contain anything personalized. That folder contains code that doesn't belong to a (core) module.

The correct place for libraries is sites/all/libraries, see http://drupal.org/project/libraries.


How can I remove the remains of the Mass Contact module not properly uninstalled?

This is an issue already resolved for the 8.x-1.x branch, as reported in Uninstall should remove mass_contact_opt_out field.

The code that has been added to the uninstall hook is the following one.

Drupal::configFactory()->getEditable('field.field.user.user.mass_contact_opt_out')->delete();
Drupal::configFactory()->getEditable('field.storage.user.mass_contact_opt_out')->delete();

If you have Drush installed, you can write those two lines in a file (for example, fix-module.php) and run it with drush php-script fix.module.php. You can also put the following code in a file next to the authorize.php file that comes with Drupal core, and access that file from the browser.

use Drupal\Core\DrupalKernel;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

// Change the directory to the Drupal root.
chdir('..');
$autoloader = (require_once 'autoload.php');

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->boot();
  Drupal::configFactory()->getEditable('field.field.user.user.mass_contact_opt_out')->delete();
    Drupal::configFactory()->getEditable('field.storage.user.mass_contact_opt_out')->delete();
} catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}


Programmatically redirect users to the default "access restricted"

You can throw an exception at any point in your code:

403:

throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();

404:

throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();

The exception is then catched by DefaultExceptionHtmlSubscriber and a subrequest for /system/403 or /system/404 is returned, which you can configure in the basic site settings if you don't want to display a generic "access denied" or "not found" page.

Other options depend on where the code is placed:

Return a 403 or 404 response from a controller or a form
Set a response in an event if you are in an event subscriber.

What you should never do is to send a response directly. This doesn't stop the code and produces two responses, one you've sent and one returned by the Drupal kernel. This will result in unpredictable behavior.


How do I get the content type name using code?

To get a property, there is ConfigEntityBase::get(). Since ConfigEntityBase is a base class for NodeType, you can always use $value->get('name') to get the value of the name property.


Copy data from a selected view in a fieldcollection field

Yes, it's possible but you're going to have to do some hoop jumping to make it happen:

Determine when this copy action will happen (e.g. hook_entity_update trigger).
Programmatically retrieve the View's data (e.g. via Views::getView() /  views_get_view() depending on your Drupal version)
Parse the view data an update the update relevant node fields with the view data. (which will also depend on your Drupal version).


How to access raw data in twig template using views table format

You can try to apply getValue() of the field handler on the result row, for example:

{% if view.field.field_name.value(view.result[key]) %}

Edit:

In a views table template row is not of the type ResultRow, so you need to get it directly from the view object using key of the loop {% for key, row in rows %}.

See these questions for different views templates:
How can I get data from ResultRow object in views template and How to preprocess view field?


Homepage accessible to non-members though title of the page says : "Access Denied"

I have no idea what caused that though i solve it by creating a custom menu item with HOOK_menu giving it full permissions, then i added that new menu item in the homepage field in site configuration .


I am not 100% on your desired set up but there are a couple of ways that I can think of to get the functionality that I believe you want. If you have a view with filters and displays that also includes a jumplist (the jumplist is just a part of your desired view) I would suggest adding an attachment to your view. This attachment can share contextual and exposed filters.


how to display the last mailchimp campaign?

I think you use mcc module for create mailchimp for node. when you disable this module its show list of all campaign which you created.

you can also use mailchimp function for getting list of campaign:

$campaigns = mailchimp_campaign_load_multiple();


Duplicate the value of the price of the products to field in node

You need to use Computed Field here.

  Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

Now, substitute plain link with Entity reference - that way you will be able to access referenced product's fields in code and use them, especially price, in node's computed field


Exporting Site Configuration Settings into Features

In order to export Drupal 6 system settings like the CSS and JS aggregation. Or anything else stored in the {variables} table, you can use the strongarm module. https://www.drupal.org/project/strongarm


Add custom forms in checkout process in commerce kickstart

Use hook_form_alter to add field(s) or section on any form in drupal.

For more information go through the documentation of this hook.


It's literally what the description says it is - during a cron run, Drupal will spend a maximum of the seconds you provide in that value processing that particular queue, regardless of the number of jobs in it.

If you're looking for the relevant code it's in drupal_cron_run()

foreach ($queues as $queue_name => $info) {
  if (!empty($info['skip on cron'])) {
    // Do not run if queue wants to skip.
    continue;
  }
  $function = $info['worker callback'];
  $end = time() + (isset($info['time']) ? $info['time'] : 15);
  $queue = DrupalQueue::get($queue_name);
  while (time() < $end && ($item = $queue->claimItem())) {
    $function($item->data);
    $queue->deleteItem($item);
  }
}


I can't speak for Drupal 6 (haven't used it in a while), but in Drupal 7 the standard method used to invoke a hook is something like the following:

$modules = module_implements('some_hook');
foreach ($modules as $module) {
  // Call the hook
}

module_implements() caches the hook implementations, and as such the index is only rebuilt when the caches are cleared (or more specifically, the bootstrap cache).

As for parsing the code in modules, this falls outside of Drupal's jurisdiction; PHP will parse all of the code in any included file. Since hooks must reside in a .module file (or at least a file that's explicitly included from a module file), and all enabled module files are included on each page request, the whole file will be parsed every time.


You can use drush user-login together with curl (or wget) like this:

drush --uri=http://your-site.com/drupal-dir-if-any/ user-login --browser=0 username path/to/heavy/site | xargs curl -L

The drush user-login command prints a one-time login link of the following form:

http://your-site.com/drupal-dir-if-any/user/reset/1/1390809497/hzqAmTzHMdBIXDIrkbDsmLIyPQtcDnjAufz9Fd5OUJk/login?destination=path/to/heavy/site

Then xargs will pick it up from stdin and passes it as last command line argument to curl. Finally the -L flag instructs curl to follow redirects. You might want to also supply -o /dev/null in order to discard the output of curl.


how can i get a menu of a parent taxonomy term?

If your output should be a block or page, you could do it with Views.
If not, meaning you want to show only that part as a menu itself, you might want to consider writing your own query for it, and adding it as a hook in your template.php


Permissions and ownership of /var/www and /var/www/example_drupalsite.com

What I do is, on dev machines I make all of my Drupal files owned by my user account (e.g. developer1), and I make the group www-data.  I use chmod g+w to give write access to the web server on the directories that need it (see article quoted above in question comments, http://drupal.org/node/244924).

On production and staging machines, I make all of my Drupal files owned by a special www-admin user, and give sudo access to www-admin to any user account (e.g. developer1) that might need it.  I then can do, for example, sudo -u www-admin git pull if I want to operate on the Drupal files.  (Aside: I usually store my git root at /var/www/drupalsite.com, and point the webserver document root at /var/www/drupalsite.com/htdocs.  This puts the .git directory outside the web root, and also gives me another place to put file and directories that belong with the site, but should not be served by the webserver, e.g. D7 private folder.)  If I am hosting on a small shared hosting site, I sometimes keep only the dev site under git revision control, and use drush rsync @dev @prod to push just the files over.  By making the Drush site alias remote-user www-admin and setting the Drush rsync mode to 'rlptz' (e.g. $command_specific['rsync'] = array('mode' => 'rlptz');), then the filesystem modes will be copied over (so the folders that are g+w on dev will be g+w on prod), but all of the files will still be owned by www-admin on the target site.

I'm supposed to write some docs about this for Drush, but have not yet.  :p  See: http://drupal.org/node/1343892 and referenced issues.

Update: I'm in-progress on working on a Drush command to fix / set permissions.  See http://drupal.org/node/990812. The default values used in that command give some hints on ways to set permissions, although different strategies are possible.


How do I get my custom route to a custom menu link

Have a look at filter.links.menu from core. There you can see how the filter module is placing its link under 'Content Authoring'. You can do is the same way.


How do I place a block in a region, programatically?

You can try this, create an instance of a block plugin on the fly for the block content:

$block_content = \Drupal::entityTypeManager()->getStorage('block_content')->load(12);

$plugin_id = 'block_content:' . $block_content->uuid();
$block_view = \Drupal::service('plugin.manager.block')
  ->createInstance($plugin_id, [])
  ->build();

$variables['page']['content_right']['custom_block'] = $block_view;

But it's better to configure the block plugin in UI and build the configured block instead. For more info see this question Programatically render a block in a twig template


'Illegal choice' error while submitting/validating selectbox shown with AJAX

Setting #default_value for the 'venue_radio' form element solved my problem: http://drupal.org/node/1545316#comment-5914060
I also changed my code to how it is described in the Ajax altering node form example. Everything is working now in the way I wanted it to. Issue solved.


One way to do this is with a views geojson layer. This seems to be the only way that works right now...at least for me.

With static data, you create a views display of type feed (create a view with no page or block and set it to type feed). Then, set the format to geojson. You'll have to set the settings to your geofield, and add your geofield as a field to the view. Then finally, create a layer through the OL UI and set your feed as a source. Hope this helps.


Get just the first item from a multiple valued field using field_view_field()

Have you considered using field_view_value?  It is the recommended way to retrieve a single value from a multi-value field.


View To Show Tagged Comments Via Arguments

Add Relationships Field: newtag (whatever your term referance field is called)

Contextual filters (term from field_newtag) (add relationship from above)


How to have a dialog box displayed automatically when a page is reached without having to click the link?

Your JS needs to be formatted like this:

(function ($, Drupal) {
  Drupal.behaviors.myThemeBehavior = {
    attach: function (context, settings) {
      $('.use-ajax', context).once('auto-open').each(function () {
        $(this).click();
      });
    }
  };
})(jQuery, Drupal);

Your library needs to be defined like this:

example:
  js:
    js/example.js: {}
  dependencies:
    - core/jquery #Just ot be save
    - core/drupal.dialog.ajax #Required for dialogs


Content Field Type For Video, Images and Text

I think that the best solution is to use Conditional Fields module.
You can manage dependencies between fields. So you should have one field type and all type fields separately and display them depend to type field.


How to create absolute url for a page/node?

You should use the l() and url() functions as specified in the answer to the question you link to. Those are core Drupal functions so nothing else is needed.


How do I avoid behaviors are invoked after an AJAX call?

You are using .once in the wrong spot

(function($, Drupal) {

  "use strict";

  function openColorbox(context) {
    $(context).find("div.search-result").once("openColorbox").each(function () {
      if ($('body', context).hasClass('page-search-site')) {
        var nid = url('?node');
        if (nid != undefined) {
          if (nid.trim()) {
            $('div.search-result')
              .find('.node-' + nid)
              .click();
          }
        }
      }
    }
  }

  Drupal.behaviors.openColorbox = {
    attach: function (context) {
      openColorbox(context);
    }
  };

}(jQuery, Drupal));

Note that this is D8 style. If you are using D7, the above will not work as it is done differently, and you didn't tell us which Drupal version you are using.


How to change search_api_server options via CLI

This problem was probably specific to Drupal-VM, but here's how I solved it. Rather than write a post-provision script that tried to run the sql command itself, I made a new file containing the sql command and told the post-provision script to use that file.

So instead of the script running this itself

sudo mysql -u root -proot drupal -e "UPDATE search_api_server SET options = 'a:14:{s:9:"clean_ids";b:1;s:9:"site_hash";b:1;s:6:"scheme";s:4:"http";s:4:"host";s:9:"localhost";s:4:"port";s:4:"8983";s:4:"path";s:17:"/solr/collection1";s:9:"http_user";s:0:"";s:9:"http_pass";s:0:"";s:7:"excerpt";i:0;s:13:"retrieve_data";i:0;s:14:"highlight_data";i:0;s:17:"skip_schema_check";i:0;s:12:"solr_version";s:0:"";s:11:"http_method";s:4:"AUTO";}' WHERE id='1'";

It now does this

sudo mysql -u root -proot drupal < $SEARCH_API_SERVER_SETUP_SQL_COMMAND_FILE

(Replace -u root -proot drupal with your sql username, password, and the site db)


If you are comfortable with Custom coding, you can try following route

On your theme template.php implement template_preprocess_maintenace(), this will help you introducing new variables to maintenance page tpl file, something like below

function yourtheme_name_preprocess_maintenance_page(&$vars) {
  if (function_exists('_your_form_builder_funtion')) {
    $vars['your_custom_form'] = drupal_render(drupal_get_form('_your_form_builder_function'));
  }
}

Now copy the maintenance-page.tpl.php in your custom theme templates folder and on the template file, you can use the variable like any other being already used. So somewhere on your maintenance-page.tpl.php add following

  <div class="contact-form">
    <?php print $your_custom_form; ?>
  </div>


"This theme is missing a 'content' region".?

Looks like you need to indent your region names 2 spaces. See https://www.drupal.org/node/2349827 for more information on defining a theme with an .info.yml file.

Also the link in your description is missing a closing  tag.

You should also be quoting some of your strings.  There is a link on the page above to read the quick introduction to the YAML file format that takes you to http://symfony.com/doc/current/components/yaml/yaml_format.html . That page provides good information on quoting strings.


function name to be called by another module via drupal_alter?

A hook implementation is always prefixed by the short name of the module implementing it; alter hooks need to have _alter appended. So, in your case, since workbench_access_crud_by_state is the machine name of the module, workbench_access_crud_by_state_workbench_access_user_alter($access, $account) is the correct signature for that alter-hook implementation.

As for the parameters, drupal_alter() accepts:

$type is the type of the alter hook, without the _alter part; in your case, that is workbench_access_user
&$data is the reference to the variable which contains the value to alter

There are other three parameters, which are optional and normally used to give context to the operation being performed.

In Drupal 8, the call to drupal_alter() is replaced with a call to \Drupal::moduleHandler()->alter(); in this case, the number of context parameters has been reduced to 2.


How not show in a View certain taxonomy items if there are no associated nodes?

Easiest way is to add a relationship in the view to the node type that contains the taxonomy term reference field and make it mandatory. This will force Views to only return the taxonomy terms that are present on a node.

Edit your view
Expand "advanced" (if its not already expanded)
Click "Add" beside Relationships
Click "Taxonomy term: Representative node"
Click "Require this relationship"
Click "Apply"

Note: I used the representative node vs the content with term option for performance reasons, the former only retrieves a single node for each term vs matching every term to every node


Where do I find the translation overview?

You can find the translation overview on:

admin/config/content/translation-overview-manage


Updating Node Field using drupal_write_record doesn't show changes until cache flush

When you write directly to the table (which drupal_write_record() does), it bypasses any APIs that are called. As such, you should really only use drupal_write_record() for tables you've created yourself, that don't have any APIs to be bypassed.
In this case, you are better off changing the values in the $node, then calling node_save() on it. This will not bypass any APIs.


What does the option "Enable Display field" shown when creating a new file field do/mean?

It will provide you an additional option whether you want to display the attached file or not. As you can see the description provide under that option in following image.

Now enabling it, will add check box option to content editing layer as you can see in following image.

Include file in display

So, if you check it will show the file in final display and if you uncheck it will not show the file.

Hence, it provides one extra quick option to author whether they want to show the attached file or not other-wise previously they had to go back and delete entire file from the content and again if they want to put they have to again upload and insert. Here, it is like On-Off Switch.


You need to alter the login form and add a submit handler which will take care of the redirection. You cannot use $form_state->setRedirectUrl() directly in the form alter, since it will be overwritten by UserForm::submitForm().

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
  $form['#submit'][] = 'mymodule_user_login_submit';
}

/**
 * Form submission handler for user_login_form().
 *
 * Redirects the user to the dashboard after logging in.
 */
function mymodule_user_login_submit(&$form, FormStateInterface $form_state) {
  $url = Url::fromRoute('mymodule.dashboard');

  // Check if a destination was set, probably on an exception controller.
  // @see \Drupal\user\Form\UserLoginForm::submitForm()
  $request = \Drupal::service('request_stack')->getCurrentRequest();
  if (!$request->request->has('destination')) {
    $form_state->setRedirectUrl($url);
  }
  else {
    $request->query->set('destination', $request->request->get('destination'));
  }
}


Maintenance Page -> Show a specific block

You cannot. The maintainance page is used for when you have put the site offline, or when the site is experiencing trouble.

When you put the site offline, you typically will be doing database migrations, updates and the likes.
When Drupal puts the site offline, there is trouble; e.g. the databaseserver cannot be reached/is crached etc.

In case 1. You don't want your average users to reach the database, after all, no-one knows what state that database is in. The whole point of bringing it down, is to avoid people writing and reading from a crippled, stateless and changing database.

Since Drupal stores its blocks or their configuration in the database, Drupal cannot should not read from the block system.

From the relevant code:

// The bootstrap was not complete. So we are operating in a crippled
// environment, we need to bootstrap just enough to allow hook invocations
// to work

That said, you can still modify the maintainance template. Just be very carefull with calling Drupal API's and/or the database in there. The maintainance theme is there for the cases when these are not available. And if they are not, your users are going to see ugly fatal errors (or nothing at all).


How do you move a file/image reference attached to a current node to a different node?

I can't recommend this as finished code, and I certainly can't vouch for it's safety/usability, but I was able to accomplish this with:

<?php
function testymod_node_presave($node){

    if($node->type == 'image_gallery'){
        $nl = $node->language;//to shorten lines

        if(isset($node->field_image,$node->field_image[$nl],$node->field_image[$nl][1])){
            //Leave the first file, but move all the rest to indidivual nodes of their own
            for($i=1;$i<count($node->field_image[$nl]);$i++){
                $tmpNode = new stdClass();//Create a node object

                $tmpNode->uid = $node->uid;

                //Use the current node data
                $tmpNode->type = $node->type;
                $tmpNode->title = $node->title;
                $tmpNode->language = $nl;

                //Set some defaults
                node_object_prepare($tmpNode);

                //Add the file
                $tmpNode->field_image[$nl][0] = (array) unserialize(serialize($node->field_image[$nl][$i]));//Only way I know to do a deep clone

                $tmpNode = node_submit($tmpNode); // prep for saving

                node_save($tmpNode); // Should have an nid now
            }
            //Remove attachments from the original
            $node->field_image[$nl] = array_slice($node->field_image[$nl], 0,1);
        }

    }
}
?>

I may try to develop this into a usable module with a switch in the content type to enable it for a given content type, but I'd need to figure out how to automatically copy any relevant fields over as well.


How to Associate Page Title with Author as Variable or Token or Relationship

In your theme template.php file add preprocess_node as below.
The below code will grab the author of current node for your custom content type.
And $node_author will be available to user on node.tpl.php
With the help of $node_author you can make the link

//
//Override or insert variables into the node template.
//
function MYTHEME_preprocess_node(&$variables) {
  //dpm($variables);
  if($variables['type'] == 'my_custom_content_type') {
    $node_author = $variables['uid'];
    $variables['home_page'] = $node_author;
  }
}

In your views add contextual filter for author uid to grab from url.
This should work for you.


You'll have to add a condition to your Rule.

Make an "Entity has field" condition that checks for your weight field.

You'll now be able to use that data value.


The function block_admin_display_prepare_blocks() is the function used in the block module admin page for this purpose, but it's not part of the documented API, so you cannot absolutely rely on it. You would need code along the following lines:

module_load_include('inc', 'block', 'block.admin');
global $theme_key;
$blocks = block_admin_display_prepare_blocks($theme_key);
...

This will return all blocks, unlike block_list() which only returns those for the current user and for the current page.


Move a site hosted on IIS/MS SQL Server across to LAMP stack

There shouldn't be any issues as such if you properly follow the steps of Migrating a Drupal Site. You can find detailed steps on How to Migrate a Site.

This documentation provides a detailed documentation on Backing up and migrating a site.

Regarding taking a database backup of Site, you can checkout Backup and Migrate Module for quick and easy database backup of site. Here's how you can quickly setup Backup and Migrate module and backup your site databse.


What is a good flexible way to send auto system emails to users?

I think the most easy and user friendly way for you is to use Rules module.

EXAMPLE:
Create new rule

Add action

Follow next steps to set your mail.


Is it necessary to cache external api requests?

Depends. Do you display this on a specific page? Or on multiple pages? Is it a page, a block... ? Do you have many authenticated users?

If it's a single page callback or a block that's always the same, then it's possibly fine to not cache it yourself. That only makes sense when you call your code on many different pages.

If you also have a lot of users, especially with different roles, multiple languages or or cache contexts that might vary but always the same API call, then it might make sense again to cache it yourself.


Populating file fields with an http-request with the Services module and a REST Server (Drupal 7)

Currently services doesn't offer the ability to add a file to a node in ONE method call, but thats easily within the scope of what services can offer, its just not in services core.

Currently you can make a request to create a file and get the returned FID, then you can process to submit a node with the field structure for a file field.

Which is something like

{"nid":1, "field_image":{"und":[{"fid":2}]}}

Forgive me thats very rough, but you can can use devel to look at an already existing node with an image attached and mimic that in your submission and it will work.

The current process is:

POST to /file

get returned FID

PUT to /node make sure to have nid and field_* in the correct structure or it won't stick.


Drupal 7.8, Webform 3.x w/ AJAX - #process callbacks cannot be found for select components

There is the form_load_include() function that is invoked during the initial form build and before form_builder(). You can include this in a hook_form_alter().


Node reference to show only author of node

Use views integration option in Node Reference Field Settings... You can connect the node reference results with the view results.. When you edit node reference field settings you can see the setting to select view with which Reference Field pulls results...

You need to build a view first that will display all games created by logged in user... Then select this view in node reference field settings....


You're probably looking for taxonomy. Create a vocabulary and name it something like "categories". Add terms for each category you want like graphics,3D,ect. Then just add links in your navigation menu. Under your content type, add a term reference field and choose your "categories" vocabulary. That way your users can choose a category when they submit something.


Responsive image gallery with unique URL per image?

Give a try to Flexislider module:

  Flex Slider module integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

Some features of FlexSlider slideshows include:

Touch enabled nagivation
Keyboard navigation
Configurable slide animations
Multiple sliders per page

Demo available here: http://www.woothemes.com/flexslider

  Library available at: https://github.com/woothemes/FlexSlider

And as far as the unique URL per panel thing is concerned I guess that depends upon how you creating the structure for slider, i.e while creating the structure for slider you can define the unique id attribute for each li as following:

  Drupal also have the royalslider library integration which integrates the royal slider library


JavasScript from custom module not detected

Drupal uses a high-level principle: assets (CSS or JS) are still only
  loaded if you tell Drupal it should load them. Drupal does not load
  all assets (CSS/JS) on all pages, because this is bad for front-end
  performance.

You need to inform Drupal to attach your library to the page.

In your case, you can use hook_form_alter and check the $form_id or hook_form_FORM_ID_alter for a single case and add this:

$form['#attached']['library'][] = 'mymodule/nodeEditForm';

Then clear the cache. Search the core folder for $form['#attached'] for more examples. You should then see your js file listed in the source of the page as well as console log output.


Switching out the autocomplete items in a user based entity reference

In case anyone else stumbles on this... Its currently broken in 8.0x+ https://www.drupal.org/node/2174633


How to display the form fields of content type in a table using custom template file?

Add the following snippet in template.php of your active theme;

<?php
function THEMENAME_theme($existing, $type, $theme, $path) {
    return array(
        'article_node_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'node--add--article',
            'render element' => 'form',
            ),
    );
}
?>

Then create a template file called node--add--article.tpl.php (same as the 'template' field in template.php.)

This is node--add--article.tpl.php:

    <?php print drupal_render_children($form['field_1']); ?>
    <?php print drupal_render_children($form['field_2']);  ?>
    <?php print drupal_render_children($form['field_3']);  ?>

<?php print drupal_render_children($form);  ?>

Now Clear Cache and see the result.


Display page created using panel programatically

You should be able to set the path to /user/%user/my-profile within Panels.  For an example of this, look at the "User edit template" override provided with Panels, which, if enabled, overrides /user/%user/edit.

To set the path in Panels, go to /admin/structure/pages, choose the page you wish to edit, click Basic under Settings, and set the Path.

The help text there states the following:

  The URL path to get to this page. You may create named placeholders
  for variable parts of the path by using %name for required elements
  and !name for optional elements. For example: "node/%node/foo",
  "forum/%forum" or "dashboard/!input". These named placeholders can be
  turned into contexts on the arguments form.


The taxonomy display won't do this on its own. You could create a view to do this, then display the view below the term page.

If you call the view from a taxonomy term template you could use a "Contextual filter" to pass the term id (tid).


You can use Full Html to allow tr th and table but If you need to use Filtered HTMl for security reason you can use wysiwyg_filter Module that allow you to add some html tags to filtered html
about select box under ck-editor it's a permission problem that only filtered html appear


Domain Access is great module that allows you to different domains set for instance, per path basis, or view basis, or node id basis.

The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.


Without page refresh views exposed filters have to work (without AJAX)

You might wanted to check

Masonry Views

  This modules defines a masonry grid view style using Masonry API
  module.

Isotope.js

  Isotope.js provides David DeSandro's Isotope jQuery plugin to Drupal
  as a library. Isotope is a display plugin that comes with several
  unique layout modes for content, including the ever-popular "masonry"
  layout. In addition, the plugin also provides several methods for
  responding to user events like window resizing and real-time
  sorting/filtering.

Here is a good tutorial on Building a Dynamic Image Display with Drupal & Isotope


How are Field API fields transfered from config entities to content entities?

This works essentially the same way as in Drupal 7.

Config entities like node types, custom block types, vocabularies and so on are used as storage and are then exposed as bundles of nodes, custom blocks, taxonomy terms, ...

There's not much magic involved, you can see what happens in e.g. node_entity_bundle_info() and taxonomy_entity_bundle_info(), so the modules have to do that part themself, you'll notice small differences there e.g. how they handle the bundle label.

The bundle_of annotation key was added recently that allows to explicitly define that relationship between two entity types, but it's currently only used by field_ui_entity_operation_alter() to automatically add operation links to the listings of node types, vocabularies and so on.

While it looks like you add the fields to config entities, you really add the field to the corresponding content entity for the given bundle. Just like it already was in 7.x, the only thing that really changed is all those different things now use the same API for storage, in 7.x, they were stored in separate tables and didn't have anything in common.


I'm often using the excellent module Custom Formatters for this kind of purpose. Simple and clean.


Auto-increment field based on value of another field

Checkout hook_node_presave() here you can set the values dynamically.
And variable_get() and variable_set() for the increment.

With str_pad() you can add the starting zeros to the increment.

hook_node_presave($node) {
  if ($node->field_A[LANGUAGE_NONE][0]['value'] == 'Location X') {
    $increment = varibable_get('LocationX_increment', 0);
    $increment++;
    $node->field_B[LANGUAGE_NONE][0]['value'] = 'X' . str_pad($increment, 3, '0', STR_PAD_LEFT);
    variable_set('LocationX_increment', $increment);
  }
}

You don't need to save the node in this hook, just change the value of the field.


I'm going to assume there is something running with cron like a search indexer or something handling nodes, and since it is run anonymously, it triggers this.


How to remove link to profile under title, when rendering a profile as block in the module Profile2

This link is part of template file profile2.tpl.php defined as $title and it appear for non page display modes as described by the template code.

<?php if (!$page): ?>
<h2<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

<?php endif; ?>

The short possible solution can be to unset title variable implementing hook_preprocess_profile2. But to remove whole markup you will have to overwrite theme registry implementing hook_theme_registry_alter(&$theme_registry) to replace template against profile2.

$theme_registry['profile2'] = array(
  'render element' => 'elements',
  'template' => 'profile2_custom',
  'path' => path_to_theme(),
);


Views Display for a query that doesn't display view content to user

Alright. So here's what I did. I installed Views Access Callback, then created a callback function that checks for the cron key.

The funny thing is, this disables the page URL access for me as user #1, even though I have "access all views" permission, and "Disable SQL rewriting" under Advanced -> Query Settings is turned on, which I would think bypassess access checks, but views_get_view_result() is getting results from the view even when my access function returns false. That's acceptable for me. I need to disable access via a URL.

Here's my implementation

/**
 * Implements hook_views_access_callbacks()
 */
function mycustommodule_rules_views_access_callbacks() {
  $callbacks['mycustommodule_rules_is_cron_view_access'] = t('Is function run from cron');
  return $callbacks;
}

function mycustommodule_rules_is_cron_view_access() {
  if (isset($_GET['cron_key']) && variable_get('cron_key', 'drupal') == $_GET['cron_key']) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}


"Limit allowed HTML tags" filter is deleting Ckeditor table styles

style="width: 60%;" is an html attribute, not a tag.

  I put this to the allowed tags: <th style>

Therefore, you need to remove the style part and just put table header tag <th> in the allowed tags.


You might be needing this module views_field_view to insert a sub view inside a view as a field.


Views Dependent Filter showing when no controller value selected

This was a bug relating the default views multiple select filter. I used the Better Exposed Filters checkboxes and now the dependent filter works as intended.


How can you price attribute options in drupal commerce properly?

As per your requirement you want to give option to the user to select one from many option from your given list while purchasing the product, but you don't want to create separate SKU for each of them. I think Commerce Option module will work for you in this case...I hope it help...Good Luck :)


I faced the same issue where 'Needs Review' tab appeared empty after the workbench moderation state for conten type is set to 'Needs Review' or 'Draft'by the creator.
I applied a patch from drupal.org and it worked. Please find the below patch and apply it in your Workbench Moderation module.

https://www.drupal.org/files/node_revision-1363990-2.patch

Let me know if you still face an issue.


On View Rewrite Results I don't see additional options like Add Read More button when checked "Trim this field to a maximum length"

My guess it is a Jquery incompatabilty. I had the same problem this morning while setting up a new site. After activating views there where no accordions and a faulty overlay.

So i set the Jquery-version in Jquery-Update Module from 1.8 to 1.5 and everything turned back to normal.

Edit: here's the issue queue on drupal.org: http://drupal.org/node/1869988


Blank pages or wsod on a recently migrated site to a godaddy server only after logging in

Check the official Drupal page for "white screen of death" (WSOD), you will useful guidance to help you to find the problem.

As my suggestion, enable temporaly the error report for php, adding on the index.php the following lines:

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

Another thing that you could do is to go to admin page of your Godaddy shared hosting account and enable the option error.

A last thing, check if you have copied the .htaccess file too on the directory of the web hosting server.


How to programmatically set a Views display to override style options

This is how you can achieve that:

diff --git a/src/Plugin/views/display/ChartsPluginDisplayChart.php b/src/Plugin/views/display/ChartsPluginDisplayChart.php
index 3dbad31..68048ce 100644
--- a/src/Plugin/views/display/ChartsPluginDisplayChart.php
+++ b/src/Plugin/views/display/ChartsPluginDisplayChart.php
@@ -29,6 +29,10 @@ class ChartsPluginDisplayChart extends Attachment {
     $options['style_plugin']['default'] = 'chart';
     $options['inherit_yaxis'] = ['default' => '1'];

+    // Set the default style plugin to 'chart'.
+    $options['style']['contains']['type']['default'] = 'chart';
+    $options['defaults']['default']['style'] = FALSE;
+
     return $options;
   }

API docs:
https://api.drupal.org/api/drupal/core%21modules%21views%21src%21Plugin%21views%21display%21DisplayPluginBase.php/function/DisplayPluginBase%3A%3AdefineOptions/8.2.x


How do I get the order_id and order_number on the checkout completed page?

The following should work:

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = \Drupal::routeMatch()->getParameter('commerce_order');


Rename images while uploading and put in specific folder

File (Field) Paths let you set file name and file path for file field:


How to print block generated by views in the tpl file?

Have you tried views_embed_view()?
http://drupalcontrib.org/api/drupal/contributions!views!views.module/function/views_embed_view/6


Are you looking for field_collection?

Install and enable the module.
Add a field of type "Field Collection" to your entity type.
Go to admin->structure->Field COllection
Add 2 fields
1 field is of file type
2 field is either select box with countries or can be taxonomy reference field

Now while creating the content, you will have option to upload a file and select a language for it.