While migrating D6 to D7, should sites folder be replaced?

The upgrade documentation is quite precise about this step:

  Update to the latest available version of Drupal 6.x

  [...]

  Remove all old core files and directories, except for the 'sites' directory
  and any custom files you added elsewhere.  [...]
  If you uninstalled any modules, remove them from the sites/all/modules and
  other sites/*/modules directories. Leave other modules in place, even though
  they are incompatible with Drupal 7.x.
  Download the latest Drupal 7.x release from http://drupal.org to a
  directory outside of your web root. Extract the archive and copy the files
  into your Drupal directory.

 cp -R drupal-x.y/* drupal-x.y/.htaccess /path/to/your/installation

Executing the above shell command, will copy all the content of the drupal-x.y directory recursively to your installation directory. This will silently overwrite all files in your installation that are also in the drupal-x.y directory and create directories that are not already there. If there is a directory in both, say sites/default/files, only those files will be overwritten that are also in the source, and no files will be deleted from a directory, that is why you had to remove the core files in step 9. This is the default behaviour of cp. If you want to know more about how this works you could read man cp.

If you are not on unix or you don't have shell access to your server, you have to emulate this behavior (at the moment I cannot think about a copy function either on Windows or Mac that behaves differently, e.g. replacing a folder with files inside with an empty folder), because it is the recommended one, using the admin interface you have.


How to render text including video embed field

check_markup() is not able to handle attached metadata which some text filters need to work properly.
You have to use the render element processed_text:
$renderArray = [
  'content' => [
    '#type' => 'processed_text',
    '#text' => $node->field_html_containing_video_content->value,
    '#format' => $node->field_html_containing_video_content->format,
  ],
];

More info How to safely render node body on a custom variable?


Drupal 7 Forum - Allow Users to 'hide' their online status

You can use hook_block_view_alter to alter the content that is returned by who's online block. Ideally use the same logic that was implemented in user.module user_block_view function, delta who's online block but with extra validations.

Add a field called Show online status to User Profile. Let's say yes or no.

Read the above field value in the alter function for all users online and filter them before displaying.

Hope it solves !


Safe and elegant way to access nested entities via fields

Suggestion, create a domain object that has the logic.

Normally these entities represent something that fits your business-domain.

E.g in your instance, the node might be an event.

So you might model a domain object called EventWrapper.

<?php

namespace Drupal\my_domain;
use Drupal\node\NodeInterface;
use Drupal\media\MediaInterface;
use Drupal\file\FileInterface;

class EventWrapper {
  protected $node;
  public static function fromNode(NodeInterface $node): EventWrapper {
    $instance = new static();
    $instance->node = $node;
    return $instance;
  }
  public function getMedia() : ?MediaInterface {
    if ($this->node->hasField('field_media') && !$this->node->get('field_media')->isEmpty()) {
      return $this->node->field_media->entity;
    }
    return NULL;
  }
  public function getMediaImage() : ?FileInterface {
    if (($media = this->getMedia()) && $media->hasField('field_file') && !$media->get('field_file')->isEmpty()) {
      return $media->field_file->entity;
    }
    return NULL;
  }
  public function getImageCaption(): ?string {
    if (($file = this->getMediaImage()) && $file->hasField('field_text') && !$file->get('field_text')->isEmpty()) {
      return $file->field_text->value;
    }
    return NULL;
  }
}

Then in your code:

<?php

$image_caption = EventWrapper::fromNode($node)->getImageCaption();


How to render two views in the same twig template

The reason you get the same content is due to the #cache property of the render array you get when you call the render() method.

Most specifically, by calling setOffset() earlier in your code, you are implicitly setting a cache key on the render array, (see here):

$this->element['#cache']['keys'][] = 'offset:' . $offset;

This cache key setting, in combination with the #theme property of the render array (views_view), which is the same for both views, will result in getting a cached version of the first one when including the second one, since the [#theme] + [#cache][keys] combination is identical for both views.

To work around that you could:

Remove caching completely for these views, or
Avoid using setOffset(), or
Add more specific keys to the cache so that you have a different cache for each view. E.g.

$variables['viewCalls']['#cache']['keys'] =
  array_merge(
    $variables['viewCalls']['#cache']['keys'],
    array('viewCalls')
  );
...
$variables['viewAppointments']['#cache']['keys'] =
  array_merge(
    $variables['viewAppointments']['#cache']['keys'],
    array('viewAppointments')
  );

I tested your case using the 3. option and it worked as expected, I think before resolving to using another module, you could try sticking to your original code and appropriately modifying the #cache property of both render arrays.

Good luck!


Getting "The form has become outdated" error

Your post just saved me from serious misery. Don't quite know how that connection was made but your post lead me to a small change in my module code. Easy to understand why the "The form has become outdated" error was occurring now though. So see if this might jog your thoughts and help for your case.

My page admin/mymod had a menu item set up that included the following.

'page callback' => 'drupal_get_form',
'page arguments' => 'mymod_main',

In mymod_main($op = '') I am conditionally building one of 2 forms but each build is of course a new form, e.g. $build['mymod_admin'] = drupal_get_form('mymod_admin') or $build['mymod_delete'] = drupal_get_form('mymod_delete').

No problem when the page admin/mymod first loaded and mymod_admin is called. But when the submit button created in mymod_admin is clicked then mymod_delete is called and creates it's form. There comes the "The form has become outdated" error that ruined the form processing. The fix is simply to use mymod_main() as page callback.

Now there is no crossing up of forms when the admin/mymod page reloads for each of the forms as there is not a starting form from the manu callback and then the second form defined in $build.


Defining a Complex Sort (by stripping out a pre-defined set of words) with Views

Have you tried Views Natural Sort -module?

  Provides a views filter that sorts node titles by a more natural manner by ignoring articles like "The" and "A."

Not sure if it matches your needs because of "sorts node titles" and in your question you talk about particular field. But maybe you should try it?

At least you can get base for custom module if you need to build one.


Is it possible to attach discussion board to a node?

Use the core comment module.

(If you want to order the newest comments at the top then see Comment goodness)


Here's the solution I got on the main stackoverflow site (https://stackoverflow.com/questions/31306242/facebook-graph-api-unsupported-get-request):

If page restrictions apply, the page's feed can only be retrieved with an user access token as far as I know (because FB needs to evaluate the visibility criteria, and setting your app to the same restrictions doesn't help here):

See

https://developers.facebook.com/docs/graph-api/reference/v2.4/page/feed#readperms

The alternative is to use page access tokens, but you need admin access to the site page to generate those. This means you will receive all posts, regardless of restrictions.


How do I use block_view_alter for the template file?

I think from the *.theme file you should use hook_preprocess_HOOK


Clear all your caches and try again.

You db seems to become corrupted or misconfigured. Your ctools module is using a different collation to store values in the db. So most of your site is utf8_general_ci and the ctools is using utf8_unicode_ci.

I gathered all of that from this line:

  (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '=': SELECT s.uid, c.updated FROM {ctools_object_cache}

If the clearing of caches fails then...

If you have phpmyadmin installed, go to the site's db and check what the Collate value is. Try changing it to utf_8 or something.

NOTE: I would create a backup of the db before you play with any collate value stuff.


How do I clean up image uploading by removing the additional upload fields?

You can do this. Although it may not be what you exactly want. I'm not going to write all the code for you, but can push you in the right direction:

Make the field accept unlimited values. That will add your "Add another" button, and will only show 1 image upload field initially.
Make a small module which implements hook_form_alter and modify the node_form of the content type which has the image. You need to add an extra validation function.
Write the validation function to check the number of values supplied in the image field. And set form error if more than 6 images uploaded.


I tried to define a custom field formatter but it didn't find the hook.

In the end it was much easier to use the Entity Reference Views Formatter module, then theme the view field to add the desired behavior to the relevant link. I used the rules_link module to define the untag link, then added the untag link into the field's theme. Next time I should probably use a tpl.php file as well.

File: views-view-field--with--block--field-with.tpl.php

<?php
  global $user;
  $my_uid = $user->uid;
  $node = node_load ($row->nid);
  $results = db_query(      // Load the field without loading the entire node.
    "SELECT field_with_target_id
       FROM field_data_field_with
      WHERE entity_id = :entity_id",
    array(':entity_id' =>$row->nid));

  $lines = "";
  foreach($results as $result) {
    $uid = $result->field_with_target_id;
    $account = user_load((int)$uid);
    $rendered = l(mymodule_get_realname($account), "user/$uid");
    $untag = "";
    if ($uid == $my_uid) {
      $rules_link = rules_link_load('un_tag_me');
      $untag = render(rules_link_render_link($rules_link,$row->nid));
      $untag = str_replace (
        array("<div ", 'title="x"'),
        array("


Is it possible to make only one field in a content type language neutral?

I don't believe that it's possible to configure the language type of fields and translate per field. Not in Drupal 6 anyways.

This shouldn't be a problem anyways. When you translate a node, drupal makes a copy of the original node, which means the e-mail address will be pre filled with the correct value.

The does require some extra work when editing, but if you really wanted to, you could create some custom code, or maybe setup a rule, to keep that field in sync with the other translated nodes.


In the views ui, click on 'advanced' and go to 'theme information'. This gives you a number of suggestions for the template file and what code should be in it.


I now used a workaround, instead of the 'menu minipanels' module, i am using 'Menu Attach block' which simply allows to insert minipanels too since they are available as blocks.


$base_url and $THEME_ARRAY using together

This should do it:

$hosts = array('sitea.com', 'www.sitea.com');
if (in_array($_SERVER['HTTP_HOST'], $hosts) && $_SERVER['REQUEST_URI'] == '/optoelectronics') {
  $conf['theme_default'] = 'optotemp';
}


As per image style (imagecache) images are not being created, changing the theme and reverting back fixed the problem. Very strange - it would be nice to know what the cause was!


Use the Date Views module that comes shipped with Date. Add a filter to your view using the Date: Date option.

Now you can use the "In Between" option to either select between two specific dates, or relative dates (within the past 30 days of right now). Make sure to check "Expose this filter to views".


Create a block for your theme with formblock and in visibility settings of your block put it where ever you want.


Drupal 7 not able to run cron after views/panels update

For troubleshooting cron.php problems found this:

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

Cron stopped running; logs say: "Attempting to re-run cron while it is already running."

I have been able to trigger cron using the ultimate cron module, which is in beta.

Still don't understand what was going and didn't find the faulty module but the "attempting to re-run cron while it's already running" error msg has gone away from the logs.


Sounds like you need to use entity reference module and have it render the teaser view mode.

This field can have unlimited values so you can keep "adding more". This will allow you to specify nodes to embed in another node.

Alternately you can use field collection if you do not require these embedded nodes to be a node on their own.

Furthermore you could even add a view which shows teasers as a block to bottom of the node, however the filters / contextual filters will be more dynamic in nature rather than manually selecting specific nodes. You could argue that node queue would allow you to do this but I would say thats a lengthy way of resolving you question.


When creating a Chaos Tools content type plugin, what is a subtype and how are they used?

It's a good question, and some further information can be found in the ctools help file context-content.html

  The CTools pluggable content system provides various pieces of content
  as discrete bits of data that can be added to other applications, such
  as Panels or Dashboard via the UI. Whatever the content is added to
  stores the configuration for that individual piece of content, and
  provides this to the content.

  Each content type plugin will be contained in a .inc file, with
  subsidiary files, if necessary, in or near the same directory. Each
  content type consists of some information and one or more subtypes,
  which all use the same renderer. Subtypes are considered to be
  instances of the type. For example, the 'views' content type would
  have each view in the system as a subtype. Many content types will
  have exactly one subtype.

Also, in ctools_content_get_subtypes

  Get all of the individual subtypes provided by a given content type.
  This would be all of the blocks for the block type, or all of the
  views for the view type.

So in a sense, the subtypes are individual instances of that type, such as individual Views or Blocks, or custom content instances, that use the same rendering functions as the parent content type.

For example, you can see in ctools_content_process

// If a subtype plugin exists, try to use it. Otherwise assume single.
if (function_exists($function_base . 'content_types')) {
  $plugin['content types'] = $function_base . 'content_types';
}

In the example of the block content type, this function returns the content types, or sub types for that plugin.

/**
 * Return all block content types available.
 *
 * Modules wanting to make special adjustments the way that CTools handles their blocks
 * can implement an extension to the hook_block() family, where the function name is
 * of the form "$module . '_ctools_block_info'".
 */
function ctools_block_content_type_content_types() {
  $types = array();
  foreach (module_implements('block_info') as $module) {
    $module_blocks = module_invoke($module, 'block_info');
    if ($module_blocks) {
      foreach ($module_blocks as $delta => $block) {
        $info = _ctools_block_content_type_content_type($module, $delta, $block);
        // this check means modules can remove their blocks; particularly useful
        // if they offer the block some other way (like we do for views)
        if ($info) {
          $types["$module-$delta"] = $info;
        }
      }
    }
  }
  return $types;
}

Lastly one more example for good measure from the views_content content type plugin

/**
 * Return all content types available.
 */
function views_content_views_content_type_content_types($plugin) {
  $types = array();
  // It can be fairly intensive to calculate this, so let's cache this in the
  // cache_views table. The nice thing there is that if views ever change, that
  // table will always be cleared. Except for the occasional default view, so
  // we must use the Views caching functions in order to respect Views caching
  // settings.
  views_include('cache');
  $data = views_cache_get('views_content_all', TRUE);
  if (!empty($data->data)) {
    $types = $data->data;
  }

  if (empty($types)) {
    $views = views_get_all_views();

    foreach ($views as $view) {
      if (empty($view->disabled)) {
        $types[$view->name] = _views_content_views_content_type($view);
      }
    }

    views_cache_set('views_content_all', $types, TRUE);
  }

  return $types;
}

In this case _views_content_views_content_type returns

function _views_content_views_content_type($view) {
  $title = $view->get_human_name();

  $icon = 'icon_views_page_legacy.png';

  return array(
    'view' => $view->name,
    'title' => $title,
    'icon' => $icon,
    'description' => filter_xss_admin($view->description),
    'category' => t('Views'),
  );

}


How do I delete a vote (e.g.rate module)?

The voting api defines some drush commands:

drush generate-votes <entity_type> <vote_type>
drush votingapi-recalculate <entity_type>
drush votingapi-flush <entity_type>

if you don't use drush, you can run the code from the function that the module uses on devel php or similar

<?php
$entity_type = "name_of_the_entity";
$cache = db_delete('votingapi_cache');
$votes = db_delete('votingapi_vote');

if (!empty($entity_type)) {
  $cache->condition('entity_type', $entity_type);
  $votes->condition('entity_type', $entity_type);
}
if (!empty($entity_id)) {
  $cache->condition('entity_id', $entity_id);
  $votes->condition('entity_id', $entity_id);
}

$cache->execute();
$votes->execute();


X-Frame-Options and Strict-Transport-Security are prohbiting me from uploading any images via ajax error due to self signed cert (on a dev box)

File under just being a bad morning.

It turned out to be the ADMIN THEME was using jQuery 1.4 instead of an updated version. Using jQuery Update, the admin theme now has a 1.8 and content creators are happy.


How to get the field values with EntityQuery?

No, it is not possible.

There is no API to get values of specific fields. Views also doesn't do that anymore, it always loads entities as well.


Not able to assign value to hidden form field using form_alter hook

I managed to do it by validate handler of the form. Using validate handler I assigned my value to the form variable before submit.

In form alter hook call validate handler like below

$form['#validate'][] = 'my_module_name_form_validate';

And following is the validate handler function code

function my_module_name_form_validate(&$form, &$form_state) {
$form['field_my_field']['#parents'] = array('field_my_field');
form_set_value($form['field_my_field'],array('und' => array(0 => array('value' => $new_value))),$form_state);

}

For reference please go through link


Is using Views overkill to display a single image above the footer of all pages on my site?

If you need a static image, just use a block.  If you want a slideshow or something, Views is better.

Unless your site is going to get a huge amount of traffic, I wouldn't worry about the performance differences between these two options.  The main concern is how much harder is it going to be for you to set up a view versus setting up a block.

I don't know why you would created a content type and field specific for the image.  If you just want to stick a piece of content in the same place on every page, that is one of the things that the blocks system was designed to do.


export search_api settings with features

I was having this problem today too.  Features would not display my search_api index for export.  It also wasn't displaying my Page Manager pages, Page Manager handlers, or Views.

I realized the problem was that I had moved all of those configurations into a custom module.  Features wouldn't try to export anything that is module-provided, even if those items had been created through that site's UI in the first place.

I disabled the module (without un-installing) and Features was happy to let me export my index configuration after that.


Possible to save form "field by field" as soon as a user changes a field instead of pushing a save button at the end of the form?

There is the Autosave module for node edit forms for exactly this use case.


A plain db_query() might be easier for this particular query, but if you want to use db_select() you can make use of the SelectQuery::where() method:

$string = 'Americana Abstract Art Art Antique Jewelry Antique Jewelry Jewelry';

$query = db_select('cms_tags', 'ct')
  ->fields('ct')
  ->where('INSTR(:string, ct.name)', array(':string' => $string));


When I upload an image in drupal 8 the imagestyles are not shown for the first time

We had similar issue in our project might be same please check this link.

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


How to load file, when I know it's filename, but not fid?

I'd definitely go with EntityFieldQuery, not a really complicated solution:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'file')
      ->propertyCondition('filename', '<filename>%', 'LIKE');
$result = $query->execute();
if (!empty($result['file'])) {
  $files = entity_load('file', array_keys($result['file']));
}

Use of conditions is not really recommended on any load multiple function anymore, the method above would be more standard and "future proof" as EntityQuery is the way to go in Drupal 8.

Installing file entity module would add much more value on what you can do regarding managed files.


The correct approach for this would be to implement a service, in which you put the contents of the fb.php and there all the Drupal functions will be recognized.
Here is an example of a service implementation: https://docs.acquia.com/articles/drupal-8-services-dependency-injection-and-service-containers


How can I change the year range displayed by a FAPI date field?

If you don't want to change every date field—which might have side effects else where on the site—you can easily do it on specific form elements.

function example_form(&$form, &$form_state)  {
  $form['birthday'] = array(
    '#type' => 'date',
    '#title' => t('Birthday'),
    '#required' => TRUE,
    // Add a second process function so we can change the years:
    '#process' => array('form_process_date', 'example_fix_year_range'),
  );

  return $form;
}

/**
 * Follow form_process_date() and re-do the years.
 */
function example_fix_year_range($element) {
  $year = format_date(REQUEST_TIME, 'custom', 'Y');
  $element['year']['#options'] = drupal_map_assoc(range($year - 120, $year));
  return $element;
}


Change the google marker icon on Geofield module

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
Note: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.


Why D7 creates two tables when i add one custom fields in user registration?

You can find the answer on your question on Duplicate data in field_data* and field_revision* tables. In particular, see this comment:

  The field_revision tables store the revision id, which never changes in these tables. The field_data tables store the node's current revision id and does not store old revision data. Basically the field_data tables only ever contain 1 entry per node. The field_revisions table will contain the number of revisions you've created, preserving the revision data. So if you never use revisions, then yes, the tables will contain identical data.

  Since revisions are a core part of Drupal I don't think there's anything you can do about this. You can probably delete the contents of the field_revision tables (please test first, don't take my word for it!), but as soon as you start creating/editing nodes the field_revision tables will repopulate.


How do I theme the core modal with twig?

Modals in Drupal are built with jQuery UI. If you want to add just some class to the modal window, you can make use of the dialogClass option.

Click me

or

\Drupal\Core\Link::createFromRoute(t('Click me'), 'entity.node.canonical', [
  'node' => 11,
], [
  'attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => ['modal'],
    'data-dialog-options' => \Drupal\Component\Serialization\Json::encode([
      'dialogClass' => 'foobar',
    ]),
  ],
]);

but that won't make you a Bootstrap modal. For that you could either dynamically load the node and build the markup completely following the Bootstrap sample with a button targeting a
 with a certain ID (nah, probably not the best idea, performance-wise).

OR you could make use of view modes and the concept of the View Mode Page module.

  Create separate pages for different view modes for a given content type.

That is, you create a new view mode for your node type for example mymodal, where you display only the fields you need and where you have full control over the markup using a view-mode-specific template like for example node--article--mymodal.html.twig. Now you can build the markup exactly like Bootstrap needs it. And finally link to this node in that view mode: /node/11/mymodal

or

\Drupal\Core\Link::createFromRoute(t('Click me'), 'view_mode_page.display_entity', [
  'view_mode' => 'mymodal',
  'entity_type' => 'node',
  'entity_id' => 11,
], [
  'attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => ['modal'],
  ],
]);

The only thing that would be missing now is to hide the jQuery UI modal title bar, 'title': FALSE didn't do it. But just CSS would do.


How to set roles of drupal "and" with each other?

You could use hook_block_view_alter() in your theme's template.php

function MYTHEME_block_view_alter(&$data, $block) {
  global $user;

  $roles = array('accountant', 'employee');
  $required_roles = array_diff($roles, $user->roles);

  if ($block->delta == 'YOUR-BLOCK-DELTA' && !empty($required_roles)) {
    $data['content'] = $data['subject'] = NULL;
  }
}

The array_diff() here will check that the roles the user needs to have appear in the user's roles array. If either accountant or employee do not appear in $user->roles it will set the block's content/subject to NULL and Drupal will not display it.


There's no way for the module out-of-the-box to block cookies created by 3rd party components. That's a simple fact of life. For example, if you by some means inject the code to embed a YouTube video on your site, it'll serve YouTube cookies to visitors to that page and EU Cookie Compliance won't be able to block them. When a YouTube video is served there is a direct communication between YouTube and the browser which other components cannot interfere with.
(In the case of YouTube you can use their cookie-free domain but let's ignore that for the sake of this illustration.)
In order to allow EU Cookie Compliance to prevent YouTube videos appearing to users who haven't accepted cookies, you'll need to implement some Javascript that calls the function Drupal.eu_cookie_compliance.hasAgreed() provided by the module for this purpose and blocks YouTube by some means when they have not. Typically you'll have to alter the embedding code to include your own JavaScript checks and display a suitable placeholder message when a video is blocked.
An example of how to do this for Google Analytics can be found at https://www.drupal.org/node/1648286#comment-6145800
For YouTube, the EU has their own component that does a similar job, that can be seen at https://ec.europa.eu/trustfund-syria-region/content/home_en
You'll need to perform a full audit of all cookies if you want to properly comply with the regulations. That's a larger topic than I can cover here but there are plenty of online guides and tools to get you started.


HDI display the human readable node type at the end of the breadcrumb

I'm not used to doing stuff in the theme layer, so my solution would be to use a module. Have you seen this one: http://drupal.org/project/custom_breadcrumbs ? I think it would allow you to do what you want.


Hide or show fields based on whether the node is published

You might be able to piece something together using Conditional Fields, but a custom module (using hook_form_alter()) would definitely be the recommended path here, because it sounds relatively custom.

Conditional fields are simply hidden using JS, while it sounds like you might need to make it so people can't access the fields (so, #access property = FALSE) on the edit form in certain situations.

Rules doesn't have much integration with content editing forms; but you could probably set some field to a different value if the status of a node is changed from draft to published, or something like that, which could trigger something with Conditional Fields... but I think doing it in a custom module would be better in this case, and would definitely be more robust.


How do I append a country to a views exposed filter field geofield proximity?

As with any form, a custom module can modify the #submit array to put a submission handler in front of the views exposed filter form to preprocess the data.

Here we're just modifying the submitted origin value so that " Canada" is appended if any text is entered by the user:

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#submit'], 'MYMODULE_form_views_exposed_form_submit');
}

/**
 * Modify submission value if given origin has been supplied.
 */
function MYMODULE_form_views_exposed_form_submit($form, &$form_state) {
  if (isset($form_state['values']['field_geofield_distance']['origin']) &&
      strlen($form_state['values']['field_geofield_distance']['origin']) > 0) {
    $form_state['values']['field_geofield_distance']['origin'] .= ' Canada';
  }
}


How to conditionally load a javascript or css?

What your looking to do is remove extra JS or CSS files, correct? AdvAgg can do this for you.
hook_advagg_js_pre_alter()
hook_advagg_css_pre_alter()
are the hooks you want to implement. Then inside of the hook you can use the arg() function to figure out what page your on.

$args = arg();
if (   isset($args[0]) && $args[0] == 'node'
    && isset($args[1]) && is_numeric($args[1])
    && !isset($args[2])
      ) {
  $node = node_load($args[1]);
  if (!empty($node) && $node->type == 'page') {
    // Do awesome stuff to the JS/CSS array.
  }
}

See advagg_js_cdn_advagg_js_pre_alter() for an example on how the hook is used. Also be aware of drupal_is_front_page(); it might be useful.


How to use external JSON API to create/update node's fields?

If there's no complicated authentication/request method for the service (e.g. a simple HTTP GET for http://service.example.com/api/siteinfo/1), then a combination of Feeds, Feeds extensible parsers, & Libraries with the JMESPath library installed works great here.

The Feeds module has an HTTP fetcher that can be used in conjunction with the JSON JMESPath parser that allows you to enter JMESPath queries for each field you want parse and insert/update into a node (e.g. in the parser settings you'd could put "@" (root) as the Context & "whois_record. domain_name" if you wanted to map that object's property to a node field).

In this solution, Feeds is handling the import/update bookkeeping while you're tasked with figuring out the correct queries to parse the data. If you go this path, it's very helpful to study JMESPath syntax while using the Feeds Import Preview module to test your imports before execution.

If you need your URL to vary for each import, you can wrap a programmatic invocation of a Feeds import into a function and call it for each imported URL in a drush eval or some other arbitrary location in your environment. For example:

//$url = Is your imported feed.
//$my_feed = Your imported feed machine name
//(i.e. the MY_FEED_MACHINE_NAME in http://example.com/import/MY_FEED_MACHINE_NAME)
function MYMODULE_import_feed($url, $my_feed) {
  $feeds_source = feeds_source($my_feed);
  $feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);
  $feeds_config['source'] = $url;
  $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
  $feeds_source->save();
  $feeds_source->startImport();
}

//Example execution
function MYMODULE_cron() {
  $import_titles = array('title_1', 'title_2');
  foreach ($import_titles as $title) {
    MYMODULE_import_feed("http://service.example.com/api/siteinfo/$title",'MY_FEED_MACHINE_NAME');
  }
}


Why can't I change textfield #default_value based on checkboxes' values after an AJAX response?

While I'm not sure why it doesn't work, the fix I've found in the past is to set the default value as #value in the AJAX callback. While this generally goes against the principle of #AJAX in Drupal (ie - changes should be made in the form definition), it works.


This documents manually copying the default starterkit subtheme in Omega 4.4. The instructions are similar for both "dusty" and "default" starter kits. Note that the "default" theme has libsass, and has less files then "dusty."

  Dusty: the original omega front-end set up, which is becoming increasingly outdated.
  Default: a more contemporary subtheme, front-end development wise. This is the better option.

Note: since I use a simple, one-word theme name in this example I can replace THEME-placeholders with one value. If you wish to have a more complex subtheme name, consider this array from the drush omega subtheme function:

'/{{ THEME }}/' => $machine_name,
'/{{ THEME NAME }}/' => $name,
'/{{ THEME SANITIZED }}/' => str_replace('_', '-', $machine_name),
'/{{ THEME CAMELCASE }}/' => $camel,
'/{{ THEME CAMELCASE LOWER }}/' => lcfirst($camel),

Prerequisite: Your theme's name. I'm using "mytheme" Substitute mytheme with your theme name.

Copy themes/omega/omega/starterkits/default (or dusty) to themes/mytheme
Copy default.starterkit.inc to mytheme/mytheme.info
Changes to mytheme.info

Change the name value to 'mytheme'
Insert base theme = omega to line 3
Change the theme file names from {{  THEME SANITIZED }} to mytheme
For example - from:
stylesheets[all][] = css/{{ THEME SANITIZED }}.reset.css
To:
stylesheets[all][] = css/mytheme.reset.css
Change the scripts name to css/mytheme.behaviors.js
Add regions info:
; ========================================
; Regions
; ========================================
regions[branding] = Branding
regions[header] = Header
regions[navigation] = Navigation
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[sidebar_first] = First Sidebar
regions[sidebar_second] = Second Sidebar
regions[footer] = Footer

Update theme name in files:

package.json: {{ THEME }} to mytheme
template.php: {{ theme name }} to mytheme
theme-settings.php: {{ THEME }} and {{ theme name }} to mytheme
preprocess/page.preprocess.inc: {{ THEME }} to mytheme
process/page.process.inc: {{ THEME }} to mytheme
sass/README.md {{ THEME SANITIZED }} to mytheme
The following renames are in dusty only:

.ruby-gemset
bower.json
libraries.make

Rename files as necessary:

Rename css files to css/mytheme.reset.css (default subtheme only) and css/mytheme.styles.css
Rename scss files to sass/mytheme.reset.scss (default subtheme only) and sass/mytheme.styles.scss
The following file-renames are in dusty only:

Rename css files to css/mytheme.hacks.css, css/mytheme.no-query.css and css/mytheme.normalize.css
Rename scss files to sass/mytheme.hacks.css, sass/mytheme.no-query.scss and sass/mytheme.normalize.scss

And there it is:

I've created a github of that shows the comparitive starterkit to wizard-created subthemes. Using this link, you can see all the necessary modifications you'll need to make, for dusty here or for default, here

I've updated this document out of pure curiosity. If I were in your situation, however, I would simply run the omega-wizard on my local dev environment, and push the theme to my server.


How to display the abstract with javascript

One way you can do it is with the field group module.

You can go to the display settings of your content type and add a group, set it as a div or fieldset, depending on what you want it to look like, and set it as collapsed.

That is probably the easiest way.


Field API, Field Attach API, Field Instance API, Field CRUD API OR Schema API?

Personally I wouldn't bother doing it yourself, Drupal has it all set up for you and it's just a matter of working out the format it wants data in and you can use all the goodness of the entity/field system.

The following function is one I use all the time. Given an existing entity type, field name and bundle it will produce the code you need to run to create said field instance:

function __export_field($entity_type, $field_name, $bundle_name) {
  $info_config = field_info_field($field_name);
  $info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
  unset($info_config['id']);
  unset($info_instance['id'], $info_instance['field_id']);
  include_once DRUPAL_ROOT . '/includes/utility.inc';
  $output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
  $output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
  drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');
}

For example, if you have a field called field_image attached to the standard article content type, you would export both the field creation code, and field instance creation code with this:

__export_field('node', 'field_image', 'article');

The code prints out to the standard drupal message area and can just be copied and pasted to wherever you need it.

For your specific needs, the value list for a select widget is added in the settings part of the field array, under allowed_values:

$field = array(
  'translatable' => '0',
  'entity_types' => array(),
  'settings' => array(
    'allowed_values' => array(
      1 => 'First Choice',
      2 => 'Second Choice'
    )
  ),
  // etc...
);

If you haven't seen it already check out the Examples module, there's loads of example code in there to help with entity/field manipulation.


Ckeditor and IMCE not working with Plupload

Use Insert module instead of IMCE

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.


Use custom variable in html.tpl.php for critical css

Instructions for the Critical CSS module:

Navigate to: admin/config/development/performance/advagg/critical-css

Under Add Critical CSS
- Select the theme that is your front page; usually the default is correct.
- User type should be set to 'anonymous' under most circumstances.
- Type of lookup, select URL
- Value to lookup, type in
- Critical CSS, paste in the generated CSS from running your homepage url
through https://www.sitelocity.com/critical-path-css-generator which is inside
of the 'Critical Path CSS' textarea on the sitelocity page.
- Click Save Configuration.


Do I need all drupal core history in my own repository

Drupal.org suggests a similar approach.  But, I'm not sure I understand the need to keep core's history under your own repo either. Or any code you yourself didn't create or amend.

Why not just have your repo at /sites/?  And have your ignore file leave out anything you haven't touched, including unmodified modules from drupal.org (and all the stuff in /sites/default/files/). Then you're workflow could be to use drush to update core, modules and themes and use git for all your own code.  Use drush rsync for files when working between local, dev, stage and production.

Side note: I'm glad to see this question here because this is something I've been wondering myself and though I don't use the approach I've just suggested, I'm thinking about it.


Display summary of paragraph text field in twig

you can get the summary with summary attribute in field level.
{{ content.YOUR_FIELD_NAME['#items'][0].summary }}

in your case answer will be :
{{ content.field_description['#items'][0].summary }}


The requirement you have asked can be easily achieved without making custom queries or use of webform module

Consider this:
If the students enrolled are supposed to login into your site, then with no doubt use user entity and wherever you want to list the students in tabular form or simple list use views module as suggested before.

If the students are not supposed to login to the system they go well with node entities,for that simply create a content type as students with field on it as you require like roll number etc.. again to list them simply use views module it will do the query for your plus will allow you to show the results in tabular way.


If you have the Click Heatmap module enabled, either disable the module or add clickheat to the libraries folder.

Though, looking at the path that is output in the error, it seems that clickheat is probably being included in a template file somewhere, find the code and remove it. Do a search through your files to try to find 'click.php'.

Just disabling database logging will remove it, but will also not log anything else, so this is probably not your best option. Better to fix the problem rather than just hide it.


Here are a few pointers which might help:

If you are talking about the name of your site, then please use the Admin > Configuration > System > Site information page to configure it - once in English and once in German.
If you are talking about a page node you created, then:

Make sure that you enable translations for the title property from content translation settings.
Make sure you use the Translate tab on the node to input the German title for your page.

Having done everything above, if you still do not see the German title on the German version of your page, try clearing cache from the Configuration > Development > Performance page.

References:

https://www.drupal.org/docs/8/multilingual/translating-content


How can I allow users to create private pages?

What you're talking about is Drupal node access control, which is a huge subject.

The core's built-in support for node access control is rather course, and to control per-user access to view a page, you must use some sort of node access control module.  There is a page at Drupal.org listing all node access modules, with a capsule review of each.  I suggest you take a look at that page to see if you can find a suitable module.

One I suggest you take a closer look at, is Flexi Access.  It let you control access to a single node (page) for an individual user.  This, I believe, fits well with your requirements.  Many other content access modules have content types and/or roles or groups as their smallest unit of resolution.

Disclosure: I am the maintainer of Flexi Access.


Different cusztomizable user profile types

You can try creating different content types and referencing those contents with different users


How to mark a Message as 'viewed' when a user sees it in a View?

I will go about this differently. Create a non-global flag on the message (ie for each user) and only give flag action (not unflag). Do not auto display this flag.

Then in your view you add the flag action as a field on the row and test whether it works by clicking on it (to test you could give temporary unflag permission). When it works to you satisfaction hide the flag link via css, and add some javascript to click the flag if the row is hovered (or whatever) over. And set the Javascript up so that it can only activate the link once as one can sometimes fire off multiple events when on the border of an element.

And then just add you rule to fire when the message is actually viewed to cover that angle as well as the user may go to that path from somewhere else but your view.

EDIT: jQuery example code:

This code is for a flag called 'test', and a view called 'all', jQuery version 1.7+

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
        attach: function(context, settings) {
            $('.view-all .views-row').once().on('mouseover', function(){
               // unbind this event handler so it only fires once
                $(this).off('mouseover');
                // get the flag and click it.
                $(this).find('.flag-test a.flag').trigger('click');
            });

            window.alert = function(text) {
            // Prevent unwanted ajax errors when navigation away
            return true;
        };
        }
    };

})(jQuery, Drupal, this, this.document);

One other little issue is that views does not seem to respect the flag unflag permissions per role. I circumvented that by adding a field 'Flags: Flagged (A boolean field to show whether the flag is set or not.) and setting its output to 0/1. I then hid this new field as well as the flag link, and added a Global PHP field with this Output Code, and it worked like a charm:

<?php
if (!$row->flagged) print $row->ops;
?>

There is a possible patch for this behaviour at Flags: Flag link views field should respect permissions, but I have not tested it.


How to get the publishing and menu fields from the node edit form in the "Manage fields" tab?

Issue solved mainly thank to the Renderable elements module.

It adds the core node edit form's vertical tabs and their content to the usual Manage fields tab, allowing any kind of customization (adding, removing, reordering tabs and fields, the tabs properties can even be turned into horizontal tabs if one needs this, etc.).

There is a very good short video introducing this module's main features.

The only limitation is that the way this module alter the forms may cause incompatibilities with other modules. On my side I just noticed minor issues with no impact to the end-user:

The standard checkbox "Provide a menu link" does not hide automatically the other menu related options depending on its state, this is a non-issue for me since I precisely wanted to customize this behavior,
Modules like Conditional Fields do not detect yet the supplementary fields added by the Renderable Elements module. The few States API effects directly involving these fields might need to be coded specifically (Conditional Fields offers an option to manually define the jQuery selector to be used, I didn't tried yet if this could be a reliable workaround for this issue),
Other modules which were already programmatically altering the default vertical tabs may be confused and become unable to alter the tabs anymore. For instance, Fast Permissions Administration does not add anymore its "Manage Permissions" link in the Publishing options vertical tab.

The good news is that this module is fully compatible with Display Suite and Field Group. The vertical tabs and its components can be moved to any Display Suite's region, but more importantly the vertical tabs content can be organized in any kind of group you like (<DIV> markers, (collapsible) fieldsets, other tabs, etc.).


How can I filter/sort a Drupal view in this way?

The easiest way I can think of you doing it since you have just three areas, is creating One block display with two attachments.

The block contains one area with the most recent pdf, and the two attachment, would contain one area each with the most recent attachment, and link the attachments to the block display.

See Image of how to add an attachment

UPDATE

When you are using more than one diaplay and are adding a display you want to make sure at the top of the popup dialog you choose for this display, rather than all display. See image below


You can't add extra joins to an EntityFieldQuery directly (it's not supported), but you could add a tag to the query, implement hook_query_TAG_alter(), and add the join manually when the query is converted down to a standard db query.

This isn't tested but will probably get you most of the way there:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'node_access')
  // etc
  ->addTag('MYTAG');

// get the query results as normal

And then the query alter function:

function MYDMOULE_query_MYTAG_alter(QueryAlterableInterface $query) {
  $query->join('node_access', 'node_access', 'node_access.nid = node.nid');
}

The other way to do it would be to subclass EntityFieldQuery itself and add the join, but I think the above method is simpler in this case.


How do i dynamically import changing feed links within a feed

It sounds like you need a custom implementation that will dynamically add feed importers based on a particular "Master feed import".

Personally I would do this with the migrate API instead of feeds as it gives you much higher flexibility for data manipulation and queue control for large datasets.


When theming a view there are two approaches, in a template file or rewriting field output, what are the advantages and disadvantages of each?

You would want to use a template suggestion as they are called for small modifications to the design or DOM output adjustments.  You will use this %90 of the time.

rewriting field output should be handled by hooks EXAMPLE: if you are taking a value and turning it into an image for rating display....

Use pre-processing hooks when you are applying logic to output values.
Use theme suggestions when making adjustments to layout structure.


How to populate a node reference field based on the selected taxonomy term?

I would accomplish this by arranging your vocabulary like so:

Category 1

Task 1

Task 2

Category 2

Etc.

I would probably just name it Service Tasks, but that's my preference. Then use the hierarchical select module.

Enable the module and it's Taxonomy Select sub-module, then add a term reference to Services using the hierarchical select widget. Now you can choose tasks related to their parent categories without having to make all sorts of references.


How to create a simple Drupal module that updates a custom node field

Hooks, in a module, only work inside the .module file.

You don't need a controller nor a routing file here, these are used for creating pages.

/modules/updateprices/updateprices.module

<?php

use Drupal\Core\Entity\EntityInterface;

function update_prices_node_presave(EntityInterface $entity) {

  $entity_type = 'node';
  $bundles = ['product'];

  $fld_price = 'field_price';
  if ($entity->getEntityTypeId() != $entity_type || !in_array($entity->bundle(), $bundles)) {
    return;
  }
  $entity->{$fld_price}->setValue(10.75);

}


You should not put your Drupal modules on packagist.org. Drupal modules are available on packages.drupal.org, where the module will be automatically exposed if you add it on Drupal.org.

it is explained here:
Using packages.drupal.org.


Moving site to another domain, install appears

When install appears on a site that you expect to be fully installed, the problem is usually with the file settings.php (in the sites/default/ directory).

It may be missing in action, not visible to the web server user, or unable to establish the credentials to connect to the site's database.


How to use Php code in Views page contextual filter with dynamic URL i.e using %?

I'd highly recommend not using PHP code to do this; tying PHP code to configuration can be error-prone and it won't exist in Drupal 8's Views.

Rather, you can use the solution in Drupal 7 views contextual filters taxonomy name where you can use the Validator, Taxonomy Term, instead of PHP Code, with the Term name converted to Term ID filter.


Override webform confirmation and email message if token data is missing

The Settings handler allows you conditionally override the confirmation message and any other webform setting.

The Email handler support conditional logic and now also supports custom Twig template which allows you to use if/then (conditional) logic in the email message.


Nest a Field Widget's primary field in a Fieldset array

I ended-up just adding a submit and validation callback that re-aligned the index.

In the hook_field_widget_form

function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
//  widget form logic....

//  Add a custom submit handler to realign the values
    $form['#submit'][] = 'mymodule_option_selector_submit_validate';
    $form['#validate'][] = 'mymodule_option_selector_submit_validate';

//  Tell the form what field uses the option selector so it knows which fields to relign
    if(!isset($form['#option_selector_fields']))
        $form['#option_selector_fields'] = array();
    $form['#option_selector_fields'][] = array(
        'field_name'=>$instance['field_name'],
        'langcode'=>$langcode,
        'delta'=>$delta,
        'columns'=>$element['#columns'],
    );

    return $element;

}

function mymodule_option_selector_submit_validate($form, &$form_state){
    if(isset($form['#option_selector_fields'])){
        foreach($form['#option_selector_fields'] as $field_data){
            foreach($field_data['columns'] as $column)
                $form_state['values'][$field_data['field_name']][$field_data['langcode']][$field_data['delta']][$column] =
                        $form_state['values'][$field_data['field_name']][$field_data['langcode']][$field_data['delta']]['filter']['client_selector'][$column];
        }
    }
}

Still would be nice to know if there is some kind of toggle in the widget form system to accommodate this.


Are changes to the user status stored somewhere?

Core doesn't store revisions/changes for the User entity type (the functionality simply isn't available out of the box).

So unless you have something like the User Revision module installed, or some custom functionality storing that data, you're unfortunately out of luck.

If you take regular backups, you might be able to fudge something together using those, but it would be a very manual process.


Is there a way to clone a feature in Drupal/Open Atrium?

Try http://drupal.org/project/features_clone.  From the project page:

  Features Clone is a Drush command that allows quick cloning of a Feature. It can be used to rename or fork (e.g. to start a new feature off of an existing one) a Feature installed on a Drupal site.


Allow users to edit the list of CCK allowed values for "select list"

A simple solution would be to use taxonomy.

Taxonomy has it's own permission system.
Drupal adds a lot of nice features for taxonomies.
Categories such as cities is a perfect match for a taxonomy.


update variable from 7.1 to 7.2 : got error message "The form has become outdated"

So to answer the question :

for people who don't manage to update simultaneously variable and i18n to get variable 2.1 & i18n 1.7 :

even if unusual, you have to update first from your current version (i.e i18n 1.4  and variable 1.1 ) to i18n 1.5 and variable 1.2, only after that you'll be able to update to variable 2.1 and i18n 1.7 versions.

Always following same steps :

clear cache
replace modules folders with the new version
run update.php


Can i get rid of the 'default' site in multisite?

You can leave the default directory in place. Just make sure there is no settings.php file in the default directory, and only the sites/www.yoursite.com directories will be accessed.

When you upgrade core, the default directory will always be replaced and will receive a new copy of default.settings.php, so it makes no sense to delete it.


How can I update the field of the entity?

The QueryInterface::execute() method returns either an integer or an array, not an object. It is a good idea to check api.drupal.org (if you don't use an IDE), or let your IDE do the work for you with intellisense.

It probably would be easier to use loadByProperties, which loads the entities for you. However it is definitely useful to get the query object, but you need to call loadMultiple.

$entities = \Drupal::entityTypeManager()
  ->getStorage('question')
  ->loadByProperties(['key' => $key]);

if (!empty($entities)) {
  $entity = reset($entities);
  $entity->set('key', 'new_value');
  $entity->save();
}


Dynamically change Commerce Customer profile type on checkout

If you can accomplish this through the Forms API, then go for it. There's no specific Commerce way to make this happen.


What's the easiest way of importing content of a custom D6 content type into a D8 site?

The two options here is the inline D6>D8 migration, or to use the Migrate API + Migrate Plus (if needed) directly to write your own migrations. The latter has example migrations you can look at. There is never going to be a case or scenario where you will want to write a manual SQL migration script. You should not need Views or Feeds for this - the Migrate API has source plugins that can connect to databases or other data sources to query and pull data.

Here is a docs page outlining how to migrate from a SQL source:

https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins/migrating-data-from-a-sql-source

You would set the two databases side by side in MySQL, create a connection setting as mentioned and create a source. The class controls certain aspects of querying and the migration YAML(s) map the fields to their new destinations.

For all the nuanced aspects, I would recommend joining the migration channel in the Drupal Slack, people are always willing to help there.


Do you know Node Queue?
It could be useful for you:

  The Nodequeue module allows users to collect nodes in an arbitrarily
  ordered list. The order in the list can be used for a any purpose


Building an advanced multicriteria search

I think facets are a great way to do advanced searching.
Facet API is a great module that is flexible.

You can use it with core drupal search using Faceted Navigation for Search or Search API, which can use the drupal database to search.

However, due to the queries that are run in the calculation of facet data, there are performance implications of using faceted search with drupal SQL based searching.

If you have a lot of content, are using a lot of different facets, or have high traffic, I would definitely recommend using a better search engine.

Apache solr, is great and is pretty easy to get set up these days.

You main options are the Apache Solr Search Integration module and the Search API module, in conjunction with the Search API Solr search module.

Both those integrate with the facet API module.

Solr is not really shared host friendly though. Generally you will have to find a host that will provide apache solr hosting, or use a VPS or dedicated server that allows you to install solr yourself.


Allow users to see restricted nodes via views

I've not used Taxonomy Access Control, but I'd look in Views' Advanced Settings / Query Settings and check Disable SQL rewriting. But, as the warning says, "Disabling SQL rewriting means that node access security is disabled. This may allow users to see data they should not be able to see if your view is misconfigured. Please use this option only if you understand and accept this security risk."


How can I get the labels of values of a field?

This was my solution:

  if (isset($node->field_k_status[LANGUAGE_NONE][0]['value'])) {
    $info = (field_info_field('field_k_status'));
    $status =  $info['settings']['allowed_values'][$node->field_k_status[LANGUAGE_NONE][0]['value']];
  } else {
    $status = "Not Set";
  }

At this point, $status will have the label of whatever field_k_status is set to.
field_info_field() gets the details about the field, and $node->field_k_status[LANGUAGE_NONE][0]['value'] gets the value. I think that there is likely a better way, but I couldn't find it. There is a somewhat similar question asked here, but I didn't find what I was looking for anywhere else.


If you are using the Sub-pathauto module simply:

Disable the subpathauto module.
Add your menu item(s) for user/login.
Re-enable the subpathauto module.


in teaser view, truncated body is displayed instead of summary

In the Manage Display settings for the content type, choose 'Summary or Trimmed' this way if a summary is provided it will display that. Otherwise it will display a trimmed version of the body.

You can download other formatters, i.e one that will strip tags and trim on a word boundary. By default the trimmed function will always split on a paragraph.


Custom template file for taxonomy term in drupal 7

taxonomy-term.tpl.php is used in Drupal 7. You can find it in ROOT_DIRECTORY\modules\taxonomy\taxonomy-term.tpl.php.
To override this template, copy it, place it in your theme template directory, and modify it. Don't forget to clear the cache to see the output from the modified template.

Do not modify any core files (including template files), in any case.

If you want to show only the details of taxonomy term then you can create a view of type 'Term referance' with suitable filter.


How the get all the child menu's Node IDs?

I think you're approach is just from the wrong end, the menu is just a list of links and not meant to control content.
What you want to do is:

Make "Company" as a views > page or a views blocks within etc.
Make a taxonomy reference for the sub pages or make them separate entity or content type,  in order to specify your sub pages in views.
Create view_mode like teaser to format their subpage display.


How to save a new term with multiple fields while adding content?

You can use References dialog module with this patch

  This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.


First problem is to handle the value for the column number. On the first build get it from configuration, on a rebuild get it from the user input and put it in $columnNum.

The second is to decide, what part of the form changes in AJAX and put this in a div container with the id columns-wrapper.

class AJAXexample extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        $columnNum = empty($form_state->getValue('columnNum')) ? $this->configuration['columnNum'] : $form_state->getValue('columnNum');
        $form['columnNum'] = [
            '#title'   => t('Number of Columns'),
            '#type'    => 'select',
            '#options' => [
                1         => '1',
                2         => '2',
                3         => '3',
                4         => '4',
            ],
            '#default_value' => $this->configuration['columnNum'],
            '#empty_option'  => t('-select-'),
            '#ajax'          => [
                'callback'      => [$this, 'columnCallback'],
                'wrapper'       => 'columns-wrapper',
            ],
        ];
        $form['column'] = [
            '#type' => 'container',
            '#attributes' => ['id' => 'columns-wrapper'],
        ];
        for ($i = 0; $i < $columnNum; $i += 1) {
            $form['column'][$i] = [
                $i => [
                    '#type'       => 'details',
                    '#title'      => t('Column '.$numTitle),
                    '#open'       => FALSE,
                    'columnTitle' => [
                        '#type'      => 'textfield',
                        '#title'     => t('Column Title'),
                        '#value'     => $config[0]['columnTitle'],
                    ],
                ],
            ];
        return $form;
    }

In the callback we only need to return the ajax wrapper.

public function columnCallback(array&$form, FormStateInterface $form_state) {
    return $form['column'];
}

Drupal rebuilds the form on every ajax request and puts it in the parameter $form of the callback. It would make no sense to try to rebuild it again.


Where can i try searching the module "File_styles"?

File Styles is a module that is part of the Styles project.


Inserting a form into a block in Drupal doesn't work

Got it.

There was error in my programming. This is how i fixed it.

<?php
/**
 * @file
 *  This is module file which display the links on the welcome page.
 *  This module will create a block of the link which is to be displayed on the welcome page.
 */

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function welcomepage_links_block_info() {
  $blocks['user-filter-ajax'] = array(
        'info' => t('User Filter'),
        'cache' => DRUPAL_CACHE_PER_ROLE, // default
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function welcomepage_links_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'user-filter-ajax':
        $block['subject'] = t('User Filter');
        $block['content'] = drupal_get_form('welcomepage_links_form'); /**Problem was here**/
        break;
   }
  return $block;
}

function welcomepage_links_form() {
    $form = array();
    $form['restripe_command_example_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t("Demonstrates the Ajax 'restripe' command.")
);
    $form['restripe_command_example_fieldset']['restripe_num_rows'] = array(
            '#type' => 'select',
            '#default_value' => !empty($form_state['values']['restripe_num_rows']) ? $form_state['values']['restripe_num_rows'] : 1,
            '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
            '#ajax' => array(
                    'callback' => 'user_filter_ajax_restripe_num_rows',
                    'method' => 'replace',
                    'wrapper' => 'restripe_table',
            ),
    );
    $form['restripe_command_example_fieldset']['restripe_restripe'] = array(
            '#type' => 'submit',
            '#value' => t("Restripe the table"),
            '#ajax' => array(
                    'callback' => 'ajax_example_advanced_commands_restripe_callback',
            ),
            '#suffix' => "

first row

'Restripe' Command Status: Unknown
",
    );
    return $form;
}


Form display: How to move fields into the advanced group?

In a custom module or your theme, create a group and place your field in there:

/*
* Implements hook_form_alter()
* @param     Array $form, Object $form_state, Array $form_id
* @return    Array $form
*/
function MY_MODULE_form_node_form_alter(&$form, FormStateInterface $form_state,  $form_id) {

  // Create a languages group in the right-hand column
  $form['languages'] = [
    '#type' => 'details',
    '#title' => t('Languages'),
    '#group' => 'advanced',
    '#attributes' => [
      'class' => ['node-form-options']
    ],
    '#attached' => [
      'library' => ['node/drupal.node'],
    ],
    '#weight' => 100,
    '#optional' => TRUE,
    '#open' => TRUE,
  ];

  // Move the languages settings to the right-hand column
  $form['field_article_language_filter']['#group'] = 'languages';

  return $form;
}

This is based on this gist, thanks to Dan Braghis.


drush help node-export

You can pass --format to supply the format of the output. Try doing drush node-export-export --type=poll --file=xpoll --format=xml


Specifying text format when creating field on custom node type

Set the 'format' => 'filtered_html' to allow filtered html

<?php
    // ...more fields above
        'release_notes' => array(
          'field_name' => 'release_notes',
          'type' => 'text_long',
          'label'  => $t('Notes'),
          'description'  => $t('Release notes (e.g. liner notes)'),
          'widget' => array('type' => 'text_textarea'),
          'settings' => array('text_processing ' => '1'), // Filtered HTML...?
          'format' => 'filtered_html' // <<--- Set this value to allow filtered HTML
          'weight' => 9,
        ),
    // ...more fields below
    ?>


In Drupal 6, you can theme cck fields by copying content-field.tpl.php from the CCK module's includes directory to your theme directory and then creating a content-field-FIELDNAME.tpl.php to customize the look of that individual field.  Or, if you want to wrap every field with a uniquely id'ed div, you could edit your copy of content-field.tpl.php and add:

<div id="<?php print $field_name_css . '-' . $node->nid; ?>">

-- php code between the check if the field isn't empty --

</div>

to the template, or around whatever portion in it you needed.  Just be careful with multiple field items, their ids would need a -$delta added to them if you put this inside the code of the template instead of wrapping it entirely, or adding the id= to the first div, etc.  If you want to id it with a user supplied field, you can grab that from the $node given, eg

$node->field_my_optional_id[0]['value']

but you have to sanitize it.

Now, I know you said Drupal 7, and I am sure it's subtly different there, but this should put you on the right path.  Hope it helps!

UPDATE/EDIT:  It's field.tpl.php from the system module field's theme directory in D7.


What is best for setting up the vocabulary for ubercart products?

The way your describing it cannot be used as a vocabulary taxonomy as each term is related to one another. What your describing is a type of content. Since each tire has an attribute of:

type
brand
speed rating

Your vocabulary should be those 3 separate ones, with each appropriate term under them. From there you would create a product in ubercart and those would be the 3 ATTRIBUTES and you would then add OPTIONS to those attributes. Ubercart's architecture isn't very appropriate for your type of setup last i tried. Technically you are only creating 1 product in ubercart and have 3 attributes for it with a bunch of options.

My suggestion would be to use Drupal Commerce as it would work perfectly for you as it will represent each product properly. Each unique tire will be represented as a product item. It will be alot of them as you have 3 attributes for each.


How do I load all images and thumbnail for a multivalued image field in node view?

You can use galleryformatter and then a bit css if you want


is there a way to find out which quicktab tab is active?

After much consideration and a ton of tries I decided to go with cookies,I added this to my script file from
http://drupal.org/node/1454486

Drupal.behaviors.quicktabsHistory = {
attach: function(context, settings) {
  // enable accordion memory
  $('.quick-accordion', context).each(function() {
    var id = $(this).attr('id');
    var accordion = $.cookie(id);

    if (accordion != '') {
      $(this).find('h3 a[href="' + accordion + '"]').click();
    }
    $(this).find('h3 a').click(function() {
      $.cookie(id, $(this).attr('href'));
    });
  });

  // enable tab memory
  $('.quicktabs-wrapper', context).each(function() {
    var id = $(this).attr('id');
    var tab = $.cookie(id);

    if (tab != '') {
      $(this).find('ul.quicktabs-tabs a#' + tab).click();
    }
    $(this).find('ul.quicktabs-tabs a').click(function() {
      $.cookie(id, $(this).attr('id'));
    });
  });
}
};

thanks for your time and efforts


How do you get and submit a webform in React?

Whenever I ask for a module it gets closed. You got lucky, I guess?

It seems https://www.drupal.org/project/react_webform_backend together with https://github.com/oikeuttaelaimille/gatsby-drupal-webform provides a solution for React/Gatsby. Note:

  This module only provides basic components (textfield, number, textarea etc.) out of the box. More advanced webform components or composite components should be built as custom components.

And then there's an example.


How to add user upload files to git when the node is pulished?

You can take advantage of the Version control api

  Version Control API is an engine for Drupal integration with a variety
  of version control systems. The focus is primarily on working with
  canonical, server-side repositories. It provides basic tools that
  allow for things like history listings, commit access controls,
  triggered actions when new code comes in, and direct on-disk
  repository management.

  This module is a core engine and does nothing on its own without a
  "backend" module that provides integration with a specific VCS (e.g.
  git, bzr, svn). This module provides a consistent base interface (UI
  and API) for interacting with all the different backends.

You will also need the version control git backend as the module does not work on it's own

  This module provides an implementation of the Version Control API that
  makes it possible to use the Git version control system. It can
  retrieve commit information by parsing commit logs.

  The Git backend depends on the Version Control API module. It also
  requires Git >=1.7.2 to be installed on the server.


Count only published nodes with taxonomy term

You need to add a Filter Criteria on the view, and choose Content: Published as the criteria, and Yes as the value. This also needs to use the (node) relationship.

See /* Filter criterion: Content: Published */ on this code. Or import it and look under "Filter Criteria"

$view = new view;
$view->name = 'Taxtest';
$view->description = 'Displays node count values for terms';
$view->tag = '';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'term_node_count';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '100';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all'] = 0;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'nid' => 'nid',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
  'nid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
);
$handler->display->display_options['style_options']['override'] = 1;
$handler->display->display_options['style_options']['sticky'] = 0;
/* Relationship: Taxonomy term: Content with term */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 0;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = 1;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = 1;
/* Field: COUNT(Content: Nid) */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count';
$handler->display->display_options['fields']['nid']['label'] = 'Count';
$handler->display->display_options['fields']['nid']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['nid']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['nid']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['nid']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['nid']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['nid']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['nid']['alter']['trim'] = 0;
$handler->display->display_options['fields']['nid']['alter']['html'] = 0;
$handler->display->display_options['fields']['nid']['element_label_colon'] = 1;
$handler->display->display_options['fields']['nid']['element_default_classes'] = 1;
$handler->display->display_options['fields']['nid']['hide_empty'] = 0;
$handler->display->display_options['fields']['nid']['empty_zero'] = 0;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['relationship'] = 'nid';
$handler->display->display_options['filters']['status']['value'] = '1';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');


In your hook_views_data implementation, you need to specify that the table is about an entity.

You need to define the entity first. I assume you have already defined your new entity using hook_entity_info.

<?php
function hook_entity_info() {
  return array(
    'my_table_item' => array(
      'label' => 'My new entity item',
      'base table' => 'my_table',
      'load hook' => 'my_table_item_load',
      'entity keys' => array(
        'id' => 'mtid',
        'label' => 'My new entity item',
      ),
    ),
  );
}
?>

Then, mention this new entity type in the hook_views_data implementation.

<?php
function hook_views_data() {
  $data = array()
  $data['my_table'] = array(
    'table' => array(
      'base' => array(
        'field' => 'mtid', // Primary field
        'title' => 'My new entity item',
        'help' => 'My Table',
      ),
      'entity type' => 'my_table_item', // <-- Important. Set the entity type here.
      'group' => 'My Table',
    ),
  );
}
?>

VBO will start to show actions that are type of entity in the available actions.
To add new actions, implement hook_action_info.

<?php
function hook_action_info() {
  return array(
    'my_table_do_awesome_things' => array(
      'type' => 'my_table_item', // <-- New entity type here
      'label' => t('Do awesome things'),
      'behavior' => array('changes_property'), //<-- Triggers an entity save.
      'configurable' => FALSE,
      'vbo_configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}
?>

I'm the first author (improved by the community later) of VBO for Drupal 7 drupal.org documentation. Have a look at it as well, for a deeper explanation for hook_action_info and making them configurable at VBO level.


How to pass variable of paragraphs type to another preprocess function

This was quite a ride.

First of all: I didn't got this running in the theme. I needed to create a custom module AND move its implementation of the fontawesomeicons hook last.

Next thing was: hook_preprocess_fontawesomeicons doesn't contain a hint of the parent entity the icons are used in. So I used hook_preprocess_field first to pass the paragraph type over to drupal_static() and retrieved it back then in hook_preprocess_fontawesomeicons.

/**
 * Implements hook_module_implements_alter().
 */
function MYMODULE_module_implements_alter(&$implementations, $hook) {

  if ($hook == 'fontawesomeicons') {

    // Run MYMODULE_preprocess_fontawesomeicons() last.
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

/**
 * Implements hook_preprocess_field__FIELD_TYPE().
 */
function MYMODULE_preprocess_field__fontawesome_icon(&$variables) {

  if ($variables['element']['#entity_type'] == 'paragraph') {

    $paragraph = $variables['element']['#object'];

    $ptype = &drupal_static('paragraph_type', TRUE);
    $ptype = $paragraph->getType();
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_fontawesomeicons(&$variables) {

  $ptype = &drupal_static('paragraph_type', FALSE);

  if ($ptype) {
    $variables['paragraph_type'] = $ptype;
  }
}

Inside any variation of fontawesomeicons.html.twig you now can:

{% if paragraph_type == 'my-very-special-paragraphs-type' %}
  {# do your magic here #}
{% endif %}

I never heard of drupal_static() until today. Read more:

How do I pass data between hooks that don't interact?
Share a value between two different hooks


How to delete a large amount of nodes effeciently during cron?

I would not recommend using Cron for this task.Since you have so many nodes it would always time out. Your better off using Drush and the Delete All module.
Or if you're fully purging all your nodes for instance I have written an SQL script before I can invoke with Drush which uses the sql truncate command to remove all data from Fields of a content type and then does a delete all from node and node_revisions for the given content type, and url aliases -- etc. Using SQL makes such a task take very little time for hundreds of thousands of nodes.
EDIT:
The Delete All admin UI has options for a quick delete that uses sql JOINs and not node_delete. See the admin form code: http://cgit.drupalcode.org/delete_all/tree/delete_all.module#n71
I suggest you install and try using the module.


now worked. I also discovered +1 works for one hour before the event.


How can I set an API key, which contains equal sign set at Drush site-install?

It looks like there isn't a way to do this, actually. The site installation code splits the string on the '=' and doesn't do any unescaping nor does it look like it would support this. I haven't tried escape()ing the value and then passing it in (so that = would become %3D) but unless you were expecting an escaped value this would probably still not work.

Depending on what you're setting, your best bet might be to do some sort of drush variable-set and set the values after the site install completes.


How to: Admin flags content, owners of content gets email nofication

Part 1 - Rules Component to send an eMail

Here is a Rules Component (in Rules export format) to send an eMail to a user indicated as a parameter of the Rules Component (adapt the subject and eMail body to your own needs):

{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Your eMail subject goes here ...",
          "message" : "Your message body goes here ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Part 2 - Rule to trigger the Rules Component

Here is the rule (in Rules export format) to execute the Rules Component from Part 1 (adapt the machine name of the flag you're using prior to importing it in your own site):

{ "rules_send_email_to_author_of_a_flagged_node" : {
    "LABEL" : "Send eMail to author of a flagged node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_playlist_confirmation" : [] },
    "DO" : [
      { "component_rules_send_email_notification" : { "user_to_notify" : [ "flagged-node:author" ] } }
    ]
  }
}

This rule gets triggered (Rules Event) when a node is flagged with a flag that has machine name playlist_confirmation. Note the value of the parameter passed to the Rules Component, i.e. flagged-node:author (the author of the node being flagged). Obviously, you want to limit access to this flag to users like your admin only.

That's really it.

PS: you don't really need to use a Rules Component, since you could "integrate" (hardcode) what the Rules Component does in your actual rule also. So that's rather a matter of coding style. If you'd make your eMail subject and message body another parameter for the Rules Component, you can re-use that Rules Component for all sorts of eMails you want to send via Rules. And if some day you'd want to replace sending eMails (by Rules) by using the (amazing) Message module, you'd only have to adapt your Rules Component for it.


I've finally found how to export the Drupal commerce payment method settings using commerce_features and the patch: https://www.drupal.org/node/1973098#comment-10559856


Drupal Add Javascript type=text/javascript

you can use

$js = "(function($) {

    };
})
(jQuery)";
drupal_add_js($js, array('type' => 'inline','scope'=>'footer'));

OR

drupal_add_js("(function($) {
$(document).ready(function(){
    $('.mobile-navigation').click(function(){

     });
    });
})
(jQuery)","inline");

OR

drupal_add_js('sites/all/themes/dawn/js/skrollr.js', array('scope'=>'footer'));
drupal_add_js(drupal_get_path('module', 'module name') . '/js/name.js');


Force initialization of custom field set in CiviCRM

Can you include 'publish my profile' custom field in your membership page?
If option 1 is not possible, the next best bet might be to implement the civicrm postProcess hook on membership form and create the custom field record in the form.

Civi only creates custom field records on a as needed basis

alternatively you might be able to do the above via use of mysql triggers (maybe on creation of a contact record?)


Initialize form object properties based on url params?

Yes, you can use form_state storage.

Object properties should work fine as well as long as you do not use private, use protected. private conflicts with the DependencySerializationTrait.

And yes, everything you store like that is serialized (unless it is a service, then that trait will remove and restore it) because that's the only way to transport this data across different requests.


Content created with drupal UI:

You need to configure proper user permissions for content. e.g. If you don't want to show content from Content type "Article" to anonymous user, Go to the permissions page (Administer > People > Permissions) and remove content view permissions for anonymous user.

Content Created programmatically :

1) Menu page :
While you register your custom menu with hook_menu, you should assign proper value to "access arguments". e.g.

/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items['example'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}

2) Custom block:

For custom blocks, you need to define your access by user role. You can assign role visibility either by drupal UI(block configuration page) or you can do same thing programmatically.
Please refer below reference.

https://drupal.stackexchange.com/a/69897/57643

After configuring user permissions over content, drupal will show access denied page if user don't have permission to view content. Its drupal's default behavior. If you want to override this behavior, you can use contributed module Redirect 403 to User Login. This will redirect user to login page instead of just showing access denied page.


Display Author Pane in view (with Display Suite View Mode)

For anyone who ends up in my same situation, I will post the answer.

Author Pane is only prepared to be displayed on full view nodes, but not in View's lists or Display Suite custom view modes. This is because calling the function "menu_get_object()" will not retrieve anything.

What you need to do is to alter Author Pane's function "author_pane_get_block()" or find a way to implement a hook to do the same thing properly.

I quickly edit the first condition removing the numerical condition of arg(1) and after $node = menu_get_object() line, I check if node is not set, and in that case, I assign $node variable the current view node from somewhere in the context. (in my case, I could get it from Display Suite context, but you can get it from anywhere, including (in the worst case) the stacktrace arguments.

Hope this helps someone!


Get Post data of a view in inside a block

Try

$view = views_get_current_view();
dsm($view->exposed_input);

instead $_POST.


Incorrect File Permissions When Images Are Uploaded in the CKEditor WYSIWYG using ElFinder on Windows

I was able to correct this by enabling inheritance on the c:\windows\temp folder, after verifying that the IIS_IUSRS (machinename) account has read & execute/list folder contents/read permissions.  I was prompted about a potential security risk, but ultimately this fixed it.


How to make 2 different code run acording to different cron schedule?

Adding a GET parameter should work. In your crontab edit the url and add something like &type=facebook.

In the hook_cron implementation you should be able to catch the type via $_GET['type']


How to bulk install modules from local machine?

You can just put them in one zip file, and upload using Drupal UI just as if they were one. Drupal will store them together, in  subdirectories just as you packed them. That's all, never been a problem for me.

Perfect example is, well, Examples project: http://ftp.drupal.org/files/projects/examples-7.x-1.x-dev.zip one zip, many functionally unrelated modules.


What are some design patterns found in prominent contributed modules?

One place to start is with core itself and the patterns exposed to contrib. - a great write-up by Larry Garfield (Crell) can be found in a Drupal Watchdog article.

  Observers, visitors, and peeping toms

  Drupal is actually built on the twin patterns of Observer and Visitor, although it doesn't call them by name. Instead, it calls them hooks. hook_node_load(), hook_user_login(), and so forth are, in essence, observers on nodes and users. hook_form_alter(), hook_node_view(), and so forth are, in essence, visitors. Because Drupal does not differentiate between the two, some hooks could arguably be considered both patterns but the principle is the same.

  Factories and commands

  There are several variations on the Factory pattern, but they all boil down to the same idea: One object, a client, asks another object, a factory, for an appropriate implementation of a piece of logic, but doesn't care which it is. That's up to the factory to decide. Consider the db_insert() function, the important bits of which are show below:

   function db_insert($table, array $options = array()) {
       // ...
       return Database::getConnection($options['target'])->insert($table, $options);
     }

  The Database::getConnection() method is a factory that returns a connection object appropriate for this site.

  Doctor Drupal's Dependency Injection

  In Drupal 6, the menu system was gutted and rewritten to be a multi-step process. We would now implement the same page callback like this:

   function example_menu() {
       $items['node/%node/example'] = array(
         'page callback' => 'example_page',
         'page arguments' => array(1),
         // ...
       );
       return $items;
     }

     function example_page($node) {
       // Do useful stuff here.
     }

  In this new setup the menu router gets more complex. In return, however, the page callback gets the node on which it depends passed to it, that is, injected into it. That gives us a number of benefits.

  Go for Broke(r)

  One common approach is some variation on the idea of a Broker or Mediator. In this design, an object doesn't request information from another object directly. Instead it asks an intermediary object, which may have been injected into it, to make such a request on its behalf. While it still means the first object has to actively request information, it is only tightly coupled to the mediator object and not to the myriad of other objects it may need to request information from. That means if those other systems change we need only update the mediator, not every system that touches it.


Create a route to show a node with a custom display/view mode

In Drupal 8 there are two display modes: view mode and form mode.

You can define the view mode in a route using the _entity_view key.

  _entity_view: The value is entity_type.view_mode. Will find an entity in the path and render it in the given view mode. E.g. _entity_view:
  node.teaser will return the render array of the {node} in teaser mode.


Unless you are one of the maintainers or have been explicitly granted write access to the repository, you will not be able to push your commits to the "official" branches.

The recommended route to contribute is the following:

Checkout the git repository for the correct branch (instructions here)
Create  patch with your changes (instructions in the above link)
Search for a relevent issue or create a new one in the project's issue tracker on Drupal.org
Submit the patch in the issue


You can do that by adding this function ( a customized version of the original views_json_get in the view_datasource module ) in your template or custom module

/**
 * Gets JSON data from a View rendered in the JSON data document style.
 *
 * This is useful for when working with a JSON view in code.
 *
 * @param $name
 *   The name of the view.
 * @param $display_id
 *   The display of the view to use.
 * @param $args
 *   The arguments to pass to the view.
 * @param $raw
 *   If TRUE, the JSON data is returned as a string.  Otherwise, an object
 *   representation is returned.
 * @return
 *   The JSON data in the form of an object or a string or NULL otherwise.
 */
function views_json_noheader_get($name, $display_id = 'default', $args = array(), $raw = FALSE) {
  $view = views_get_view($name);
  if (!is_object($view)) {
    return NULL;
  }

   $view->display[$display_id]->display_options['style_options']['using_views_api_mode'] = 1;

  $preview = $view->preview($display_id, $args);
  $start_pos = strpos($preview, '{');
  $finish_pos = strrpos($preview, '}');
  $length = $finish_pos - $start_pos + 1;
  $json = trim(substr($preview, $start_pos, $length));

  if ($raw) {
    return $json;
  }

  return json_decode($json);
}

and  get the result of your view  by typing in your function:

$json = views_json_noheader_get('yourviewname', 'yourview json display id', null, true);


You can create block configuration page using hook_block_configure().
where you can create form with your required field like textfield, file etc.

function demo_block_configure($delta = '') {
    $form = array();
    if ($delta == 'demo') {
        $form['demo_number'] = array(
            '#type' => 'textfield',
            '#title' => t('Number of nodes you want the block to show'),
            '#default_value' => variable_get('demo_number', 10),
            '#size' => 60,
        );
    }
    return $form;
}

function demo_block_save($delta = '', $edit = array()) {
    if ($delta == 'demo') {
        variable_set('demo_number', $edit['demo_number']);
    }
}

now you can get this variable using variable_get function

$no_of_block = variable_get('demo_number');

you can see this page in configuration of your block