How do I need to configure my site on AWS with Elastic Load Balancing to force HTTPS everywhere?

Got it myself.

Configuration is absolutly correct, but i set the wrong reverse_proxy_adresses to be allowed. I thought, that i can use the beanstalk-url, but it worked perfectly fine with one of the internal IP Configs for AWS: 172.16.0.0/12


Load id of paragraph in hook_preprocess_layout using load($id) method

Thanks to Beau for the help.
The method is simply

$ID = $variables['content']['#paragraph']->id();


There are 2 components to the Install New Module UI access callback:

It requires the Administer software updates permission for the user to be enabled. It can be enabled for any user role underneath the People > Roles administration section for the relevant user role.
It requires update_manager_access variable to be set to TRUE. By default, this should be TRUE, but it can be overridden in settings.php or manually set (e.g. drush vset update_manager_access 0). In which case, it needs to be adjusted in settings.php or by updating the variable in the database (drush vset update_manager_access 1).


How to properly use two contextual filter for taxonomy

This happens because the views checks the first parameter and the first parameter overrides the second parameter. In your case, if you rearrange parameters so that parameter 2 comes before parameter 1, you will see this time views working with parameter 2 and not with parameter 1.

You can fix this behavior by creating two separate pages in views and each page will override the behavior of the other by selecting For:"This page(override)" option.

In the first page add the two contextual filters(parameter 1 and parameter 2). While adding the contextual filters you have to select For:"This page(override)".

In the second page of the views, add the two contextual parameters, this time add parameter 2 before parameter 1. In this case also, while adding the parameters you have to select For:"This page(override)".

Good luck!


How can I conditionally display something in Views header area depending on the argument in URL?

I don't know if it's standard practice to answer such an old post, but another solution may be helpful to those who don't want to do any coding.  You can conditionally attach a header by using Views Attachments. This may not be the best practice for a production site, but that's another discussion. This answer is just to let you know of the possibilities.
Add an Attachment display for each Vocabulary you want a separate header for, and set their properties according to the images below. Notice that all attachment properties are overridden, in order to not affect your main Page or Master (default) display.
Edit: The images displayed below are for Views 3.x. Hopefully, they are helpful for Views 2.x, as well.

Add Attachment:

Add an attachment for each header you want displayed conditionally (as shown above).

Attachment Filter:

The above filter will ensure no records are displayed by the attachment, only the header.

Contextual Filter (1/2):

Set the contextual filter for each attachment (as shown above and below).

Contextual Filter (2/2):

Set the term to be used for this attachment (my example is "Glossary"). Be sure Action to take if filter value does not validate is set to 'hide', so that only the desired header is displayed.

Attach To Page:

Be sure to attach your attachment to something (here, attached to the "Page" display). Click on Global: Text Area to set your header.

Set Global: Text Area (in Attachment Header):

Click Global: Text Area (prev image) and set your desired header. Notice: still overridden. Also be sure to check Display even if view has no result since the filter for the attachment excludes all records.

Page/default Contextual Filter:

Last, but not least, set the Contextual Filter for the main page itself (not an attachment) according to your needs.


Creating an exposed filter on a view as a list with taxonomy terms

Better Exposed Filters would be helpful for that.  It allows you to replace the select/autocomplete with normal anchors that can be styled however you prefer.

After installing and enabling BEF, add your exposed filter and save it (you only have the standard options at this point).  Then, go to the views advanced settings and change "Exposed form style" to Better Exposed Filters.  Then you will have a BEF Settings option, this is where you will see the options below.

Advanced settings:

This is the setting you're looking for:


Blank screen with no error messages on new server

In case anyone else is struggling with the same problem, here is how I could partially solve it and open the site without the white screen.

In the settings.php file I commented out this line:

// $conf['memcache_servers'] = array('localhost:11211' => 'default');

So if you are using Memcache and are moving to a new environment, try the above if you encounter a white screen problem.


Remove "pubdate" attribute from Submitted Time tag in Drupal 7

So `$variables['submitted'] is the one you want to override in your theme's preprocess_node function. Try this as a starting point:

function ThemeName_preprocess_node(&$variables) {
  $variables['submitted'] = t('Submitted by !username', array('!username' => $variables['name']));
}

Which will replace the $submitted variable with "Submitted by username" (where the username will be linked to the user's profile page).


Can you provide a little more information about what you are trying to do?

Regardless, you would need to create a subclass that extends views_handler_field (more info on that here https://api.drupal.org/api/views/handlers%21views_handler_field.inc/class/views_handler_field/7.x-3.x)

If you're trying to modify the output of an existing field, you would need to use a hook_views_data_alter (https://api.drupal.org/api/views/views.api.php/function/hook_views_data_alter/7.x-3.x) and change the handler specified in the $data array. Like so:

$data['table_name']['field_name']['field']['handler'] = 'hook_my_custom_handler_class_name';

This function hook should live in your module's hook.views.inc file within the 'views' folder in your module's root directory.

Your new handler class should be in a new file named the same as the class with .inc as the file type. That file should be added to your .info file using files[] = path_to_.inc_file

In your .module file, you would need to specify the views API:

function hook_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'hook') . '/views',
  );
}

If you're still struggling, I found this video tutorial very useful https://www.youtube.com/watch?v=biKxw5iEzsY

I got caught out with spelling mistakes when doing this so check all your code!


Is it possible to add permissions to a Ctools content type plugin?

It should be possible using a ctools access plugin.  From the linked site:

  Firstly, just like during work with Сtools content type, for the web developer it is necessary to call hook_ctools_plugin_directory() to indicate that we have ctools plugins of specific type in our module:

/*
 * Implements hook_ctools_plugin_directory().
 */
function access_example_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'ctools' && !empty($plugin_type)) {
   return "plugins/{$plugin_type}";
  }
}

  Then in module folder we need to create "plugins" folder and "access" folder inside of “plugins” folder. Create plugin file with the name "access_example_plugin.inc" inside of "access" folder. Write the access rule by array in this file:

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  // Plugin user-friendly name.
  'title' => t('Eldership rule'),
  // Plugin description.
  'description' => t('Controls access depends on eldership'),
  // Without required context plugin will now be shown in Panels UI.
  'required context' => array(new ctools_context_required(t('User'), 'user')),
  // Function which will allow or restrict access.
  'callback' => 'access_example_who_elder_access',
  // Plugin settings form.
  'settings form' => 'access_example_who_elder_access_settings_form',
  // Provides a summary descriptions depends on settings selected.
  'summary' => 'access_example_who_elder_access_summary',
);

It goes on to explain how to create the various callbacks but that's beyond the scope of this question I think.


Standard debugging functions like dpm() and dvm() use the drupal_set_message() function, which is tied to a user's session. When you try using the node form, you see the message because it is saved to your session. However, when you use the service via your iphone app, the messages get saved to a session that is probably not the one you're logged in under.

Fortunately, for situations like this, you can use the dd() function, which will print the debugging information out to a file in the /tmp directory, typically called drupal_debug.txt.

[edit] I notice you're using the debug() function, which triggers error handling, note that this also uses drupal_set_message(), so the above is still relevant. (The dpm() and dvm() functions are from the Devel module.)


How to unset node form select list element_validate?

The solution is here:
https://chromatichq.com/blog/dynamic-default-and-allowed-values-list-fields-drupal-8

the discussion is here:
https://tutel.me/c/drupal/questions/242006/how+do+i+programmatically+update+the+allowed+values+of+a+list+field


Try using the Statistics modules. It come with Drupal core.

Documents from d.o:
http://drupal.org/documentation/modules/statistics

UPDATE BELOW: (SCREENSHOT)


If you are using a custom form which is invoked by a menu callback, you could try this.

Assuming that you have a postal address field type (provided by the addressfield module) which as 5 sub-fields - country, address 1, address 2, city and postal code in your content type.

/**
 * This will be invokded by a menu callback
*/
function yourmodule_custom_form($form, &$form_state){

    /* your form elements definition here */

    $form['#validate'][] = 'yourmodule_custom_form_validate';
    $form['#submit'][] = 'yourmodule_custom_form_submit';

    return $form;
}
/**
 * Validation attached to the form
*/
function yourmodule_custom_form_validate($form, &$form_state){
    // do validation here
}
/**
 * Submit handler attached to the form
*/
function yourmodule_custom_form_submit($form, &$form_state){
    global $user;
    $values = $form_state['values'];

    # Create a node object, and add node properties.
    $node = new stdClass();
    $node->type = 'your_content_type';
    $node->uid = $user->uid;
    $node->created = strtotime("now");
    $node->changed = strtotime("now");
    $node->status = 1;
    $node->comment = 0;
    $node->promote = 0;
    $node->moderate = 0;
    $node->sticky = 0;
    $node->language = LANGUAGE_NONE;

    $field_address = $values['field_address'][LANGUAGE_NONE][0];

    $node->field_address_country = $field_address['country'];
    $node->field_address_thoroughfare = $field_address['thoroughfare'];
    $node->field_address_premise = $field_address['premise'];
    $node->field_address_locality = $field_address['locality'];
    $node->field_address_postal_code = $field_address['postal_code'];

    node_object_prepare($node);
    # Save the node.
    # The node will also get published, if $node->status was set to 1.
    node_save($node);
    $nid = $node->nid;
    # if you want to redirect to a page after submission, use this
    $form_state['redirect'] = 'path/to/redirect';
    drupal_redirect_form($form_state);
}

I did not test the code. It is just for example. You may need to amend it by yourself.
You can inspect your address field name by printing out $form.

dpm($form); // if you have devel module enabled
echo '<pre>'; print_r($form); echo '</pre>'; // if you don't have devel moduel

Also note that when you create a new field, Drupal creates two new tables starting with field_data_field and field_revision_field. If you name the field "address", you will see two new tables field_data_field_address and field_revision_field_address, you could look up into those tables.


How can I add a constraint to a custom field I created?

In case of a field type, you can simply put it in the annotation.

Have a look at FileItem for example:

/**
 * Plugin implementation of the 'file' field type.
 *
 * @FieldType(
 *   id = "file",
 *   label = @Translation("File"),
 *   description = @Translation("This field stores the ID of a file as an integer value."),
 *   category = @Translation("Reference"),
 *   default_widget = "file_generic",
 *   default_formatter = "file_default",
 *   list_class = "\Drupal\file\Plugin\Field\FieldType\FileFieldItemList",
 *   constraints = {"ReferenceAccess" = {}, "FileValidation" = {}}
 * )
 */
class FileItem extends EntityReferenceItem {

Actually a bit surprised that the date classes don't have any constraints, that sounds like a bug.


Most of the blocks are under the "Miscellaneous" category.

I'm not sure exactly what the distinction is, but a few of them, such as user login, end up under "Widgets" instead.


difficult to understand drupal hook menu function

For me the best way to get a solid understanding on Drupal quickly, was to purchase some video tuition. By watching just a couple of these paid downloads, I had a good understanding on the basics.

Most tutorials step you through building your first custom module, explaining what everything is, why it is required and how it works into the overall structure.

A number of companies offer this type of product, and this one is a freebie from one site to introduce the Drupal menu system, including hook_menu()


Insert is must for easy insertion of image links in the text of node. You case insert using Colorbox or lightbox2. It can also insert using image styles you may have defined.

Make sure you do the screencast mentioned in the Insert module page.


From the comments, I think you're confusing things a bit. There are two types of block:

Custom

the ones you create through the UI. The content for these is stored in the block_custom table.

Programatically defined

the ones that Drupal auto-discovers for modules that implement hook_block_info(). The content for these is defined in hook_block_view(), and is built on-the-fly, so to speak. The content can be cached, but when that cache is invalidated the implementation of hook_block_view() will be responsible for re-building it. Drupal doesn't store this content anywhere on your behalf.

You can use either type for your needs. If you want to use custom blocks there's a good approach here.

If you want to use the hooks, the approach should be like this (this assumes you have a data table called my_table that you've populated with the necessary content for the block):

function MYMODULE_block_info() {
  // Get identifiers for all your custom blocks.
  $deltas = db_query('SELECT delta FROM {my_table}')->fetchCol();
  $blocks = array();

  foreach ($deltas as $delta) {
    $blocks[$delta] = array( /* Block definition */ );
  }

  return $blocks;
}

function MYMODULE_block_view($delta = '') {
  $block = array();

  if (!empty($delta)) {
    // Get your custom data for this delta
    $data = db_query('SELECT * FROM {my_table} WHERE delta = :delta', array(':delta' => $delta))->fetchObject();

    // And populate the block with it.
    $block['subject'] = $data->title;
    $block['content'] = $data->content;
  }

  return $block;
}

Obviously that's a trivial example and you'll want to add error checking and the like, but it should get you started. Note that you won't be able to have a temporary table as such with this method, your data will need to persist so it can be re-queried when the time comes.


Webform updates CCK field, doesn't update in node edit

I figured this out: The CCK field was being rewritten by a cached value instead of a value directly from the database. I told the form to query the database directly, and then it began working correctly.


Insert Revision log message programmatically after form submission

I found the solution. I should have used hook_form_BASE_FORM_ID_alter() instead of hook_form_FORM_ID_alter

Also the call back function should be  home_hub1_my_entity_builder


Cannot get value of form field of type 'file' in drupal form

Submitted values are flattened unless the form element contains the #tree property.

So either use:

$form_state['values']['file_path'];

Or change the wrapper:

$form['fileTransfer_settings'] = array(
  '#tree' => TRUE,
  ...
);

And use your current submission code.


How to set role on the registration form programmatically

You need to do this in a form alter hook, not after the form has already been built.
function module_form_user_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($condition) {
    $form['account']['roles']['#default_value'][] = 'mycustomrole';
  }
}


How can I create a D7 View that groups and aggregates a "Rendered Node" field by date, grouping multiple instances for each grouped date?

You don't need the aggregation settings to get the result you want. Instead, I think you want the "Grouping field" option under the settings of "format".

Here is the export of a full View that I think yields the results you want:

$view = new view();
$view->name = 'date_group_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'date_group_test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'field_date',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: date */
$handler->display->display_options['fields']['field_date']['id'] = 'field_date';
$handler->display->display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler->display->display_options['fields']['field_date']['field'] = 'field_date';
$handler->display->display_options['fields']['field_date']['settings'] = array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
  'show_remaining_days' => 0,
);
$handler->display->display_options['fields']['field_date']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_date']['delta_offset'] = '0';
/* Sort criterion: Content: date (field_date) */
$handler->display->display_options['sorts']['field_date_value']['id'] = 'field_date_value';
$handler->display->display_options['sorts']['field_date_value']['table'] = 'field_data_field_date';
$handler->display->display_options['sorts']['field_date_value']['field'] = 'field_date_value';
/* 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']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

And a screenshot of the rendered View:


grouping nodes with collapsible fieldset

OK I found it.

In the HOOK_node_view I can do:

if ($node->type=='CONTENT_TYPE') {

  // clone from a fieldset nearby
  $node->content['#fieldgroups']['group_FOO']=clone $node->content['#fieldgroups']['group_ORIG'];

  // modify fieldset
  $node->content['#fieldgroups']['group_FOO']->label="xxxxxxxxxxxxxxxxxxxxxxxx";
  $node->content['#fieldgroups']['group_FOO']->weight=-1;
  $node->content['#fieldgroups']['group_FOO']->identifier=...
  $node->content['#fieldgroups']['group_FOO']->group_name=...

  // clone from a field nearby
  $node->content['field_FOO'] = $node->content['field_ORIG'];

  // modify field
  unset($node->content['field_FOO']['#items'][0]);
  unset($node->content['field_FOO']['#items'][1]);
  unset($node->content['field_FOO']['#items'][2]);

  // position fieldset and field
  $node->content['#group_children']['group_FOO'] = 'group_ORIG';
  $node->content['#group_children']['field_FOO'] = 'group_FOO';

}


Look at Conditional Fields:

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API. You can, for example, define
  a custom “Article teaser" field that is shown only if a "Has teaser"
  checkbox is checked.

EDIT

To learn how to use the Field UI and create these form items for Users please see:

https://www.drupal.org/documentation/modules/field-ui
https://www.drupal.org/documentation/modules/options


Editing contents of custom block referenced in paragraph type, doesn't reflect changes in node where displayed

So the way that I ended up fixing this, was to use Twig Tweak to output the content block directly, like so:

{{ drupal_entity('block_content', content_block_id) }}

This ends up bypassing Drupal cache. Barring a better fix, this is the one I'm going with.


Why does Apache show such drastic differences in memory usage when using mod_php?

The main difference is that different requests to a Drupal site will do different things.

Serving up a static image, CSS, or JS file has very little overhead and the PHP handler doesn't do anything.

Serving up a cached page invokes the PHP handler and Drupal bootstraps, but the overhead is small, compared to other requests.

Serving up a non-cached page will cause a full Drupal bootstrap, and all of the PHP necessary to render the URL will run.

Serving up an image derivative will invoke PHP, and there will be additional memory overhead.

Serving up a page with an empty Drupal cache will result in all of the overhead of rebuilding the memus, registry, etc, and can cause a pretty big memory swell.

So, I suspect you are seeing the result of processes serving up different types of requests.


how to send a exposed filter when use Service views

I try to find out the views setting that store in database with following code:

$db = db_select('views_display', 'v')
    ->condition('v.vid', '30')
    ->fields('v', array('display_options'));

  $res = $db->execute()->fetchAssoc();
  $a = unserialize($res['display_options']);

the $a contain a filter array. The field_nick_name actually is field_nick_name_value, and uid is uid_raw


How to change block visibility/pages in hook_block in my module?

You can achieve this by writing a hook_update in your module's .install file. You will need to update the 'block' table directly in that hook to change the block settings as needed. After moving your updates to production, run update.php, which will apply the changes in hook_update.


You have an .htaccess rewrite rule / PHP redirect moving all traffic to https://www.example.com when the domain/protocol doesn't match.

If it's in .htaccess look for these lines and comment them out:

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

If there's an http -> https redirect that will have been set up manually (the above is included in the core .htaccess), so you'll need to locate and remove that separately.

If it's in PHP, it typically happens in settings.php. You should be able to see what's doing it fairly easily and comment out/remove for your local environment.

Failing that, you'll probably need to trawl the code to find out what's responsible for the redirect.


Separate domain for specific content type

I had the exact same choice to make 1 year ago and Domain Access was the best way to go.

To answer your questions:

You can always configure what content is available on each domain (basically you will set the new subdomain and set your specific content type to be available only there)
You can worry about advanced settings later; keep in mind now that almost all setting throughout the whole site can be differently set for each subdomain
A good recommendation would be a multi site install like Karel suggested
Another approach would be to just put some rewrite rules in your server, and have multiple themes set on each path which can contain a view that serves your content (this is pretty limited depending on what you want)


How can I let users create new drafts for *existing* content?

We use the Workflow module and have found it to be pretty stable, and we use it exactly as you have described, to allow a content person to edit content, then for an admin to approve it.

Configuring the workflow module is a bit complicated, but it is worth doing as it will provide you the functionality you need. Generally it has the following steps:

Install the workflow module.
Configure the workflows:

Create a new workflow.
Make some states.
Assign the workflow to a content type (the tutorial below calls it a node).

Set the permissions for each type of user to use each state of the workflow.

Creating a Workflow for Drupal Users contains a good tutorial.


How to get an import of a very large Drupal database working?

I'm not sure how much overhead drush puts on top of large SQL imports, I've only used it for smaller imports and queries. You can try the mysql client as an alternative that would remove the drush overhead.

If you can install pipe viewer on your VM you can view the progress of the command consuming the import.

pv mydb.sql | drush sql-cli

Or without the drush overhead

pv mydb.sql | mysql -u <DB_USER> -p<DB_PASS> <YOUR_DB>


How to change the email recipient for contact form

What we do in a few places is to have a hidden reference field to the team node in your contact message entity.

Then you pre-fill that when displaying the contact form and later on in hook_mail_alter(), use that information to change the recipient.

Requires a bit of custom code but then you don't have to create a lot of contact forms.


Change #default_value of a textarea on admin pages

The teaxtarea form field doesn't have any property for the maximum length of the accepted text. The module showing the textarea can implement a form validation handler to limit the length of the entered value, and (generally speaking) that limit is not saved in a module settings; it is generally hard-coded.

In the case the value contained in the textarea field is saved in a database table created from the module showing the form, there is another issue: The value contained in the textarea field must be contained in the database field. If it is longer than what the database field can store, you would get SQL errors.


How to insert 2 answers using Quiz submodule Short Answer?

I guess no solution, so I just hack the module.

/public_html/testserver/the-exaple.com/sites/all/modules/contrib/quiz/question_types/short_answer

public function evaluateAnswer($user_answer) {
  ...
  switch ($this->node->correct_answer_evaluation) {
  case self::ANSWER_MATCH:
    if ($user_answer == $this->node->correct_answer) {
      $score = $this->node->max_score;
    }
    break;
  case self::ANSWER_INSENSITIVE_MATCH:

   ////////////////edit your code here

    break;
  case self::ANSWER_REGEX:
    if (preg_match($this->node->correct_answer, $user_answer) > 0) {
      $score = $this->node->max_score;
    }
    break;
}
...
}

Since I chose my answer is insensitive, I will edit second case.


Alter comment links in blog teaser in drupal 7

If I were you I'd hide the span content in CSS and add a tag for my background image like this:

Template:

    <?php print ($comment_count); ?>

    <?php print render($content['links']['comment']); ?>

CSS:

.submitted ul li span.comment-count {
  width: 16px; // or whatever
  height: 16px;
  background: url("../images/blue-bubble.png") 0px 2px no-repeat;
  background-size: 100% 96%;
  padding: 0px 5px 5px 5px;
}

.submitted ul li span.comment-hidden {
  display: none;
}


default value imagefield -> get from field collection item

I would look in to something like

hook_node_presave

As a rough example I would have it work like this

function MY_MODULE_node_presave($node) {
     if(!isset($node->field_thumbnail)) {
          // load field collection and save that image to this image field
     }
}

I haven't tested this code but i think this would be the direction you would want to go in.


for Views module add filter: Node translation: Language ->  Current user's language.


You can do that through a custom module - create a path and instead of returning the output, just print it.

Here's an example:

/**
 * Implements hook_menu().
 */
function YOURMODULE_menu() {
  $items = array();
  $items['custom-url'] = array(
    'page callback' => 'YOURMODULE_blank_page_callback',
    'page arguments' => array(),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Display the content for your blank page.
 */
function YOURMODULE_blank_page_callback() {
  print 'Your string.';
}


How should I implement a callback to a single Drupal class (in my case it's Transliteration). I don't need a full Drupal load/bootstrap just one independent class.

Taken literally, within the confines of Drupal, I don't believe you can. We rely on PSR-0 for class loading, so at the very least you must bootstrap Drupal to get the class loader running. (Though not necessarily a full bootstrap).

To truly just load a single class, you'd need a to call a different file than index.php where you'd hard code the class loading.

I haven't looked at how Ajax requests specifically have changed from D7 => D8, but thanks to D8's DI, only classes that are used in a single request will be instantiated, so the need to try to speed optimize things out, as you seem to want to do, should be lessened.


What file contains the queries of customized views?

Views settings can be exported through the Features module as custom module code. So, if the site is using Features, and the view has been previously exported, then you will find the code inside one of the module files.

In that case, you can use a command line tool like Grep to find the file which contains the view. I would search recursively for the machine name of the view inside your www folder.

If the Features module is not in use, then you can see the view code if you go to the view edit page, then click "export view" in the upper right hand drop down.


Import Users from D6 to D7 without directly accessing database

Views data export module is perfectly capable of exporting your users to CSV file. You would use Views to define what you want to have exported, so you can export anything. You can also use Views GUI to define mappings, if you want. It is a powerful toolset, and VDO uses all that power.

When you will have your users in CSV, you can use User Import to import them. Pretty obvious, isn't it? For mapping, User Import can

  Match CSV columns to account and profile fields

So if you didn't manage to do it on the Views level, you can always edit CSV when you'll have it locally, or try to do it on import... So many options, I'm sure at least one will work.

Last but not least, make sure your users will get mails with "new password required" explanation, as D6 and D7 stores passwords in incompatible ways.


How do I tell hook_block() about placement

You should use hook_block_info_alter() instead of hook_block(). For example:

function YOURMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  $blocks['MODULE']['BLOCK']['visibility'] = BLOCK_VISIBILITY_LISTED;
  $blocks['MODULE']['BLOCK']['pages'] = 'user/* \n stream';
}

Where YOURMODULE is the name of your module, MODULE is the module generating the block, and BLOCK is the name of the block. You should list all paths where the block should be visible separated by \n, \r or \n\r.


How to hide comment section present in render array?

The result that you get there is only prepared, the actual rendered content is not set there, you can't remove it there.

The comments are a field, you can hide/show them in the manage view display UI like any other files.

Define a view mode/display for your use case if the default ones don't work for you and then configure it there.

Doing it in code is only possibly in indirect ways. You'd need to set a flag in $content and then implement hook_node_view() alter and remove it there.


select nodes title start with charachter

There is no database agnostic support for regex in EntityFieldQuery. The documentation in EntityFieldQuery::propertyConditon lists the available operators. As mentioned by Clive, this list is not complete. Apparently you can use any operator that is supported by your database backend.

As an alternative that should be supported across different database backends, you could build multiple queries using the STARTS_WITH operator and then merge the results.

Or you write a custom query using db_query. Or use db_select with or-linked conditions.


How to place images in footer region through page.tpl.php

If your not going to use blocks how about going a level deeper into the actual footer region template...

region--footer.tpl.php


I think I was confused about what drupal_process_states() does. It does not have to be declared like a hook or even invoked in my custom module. It is simply the machinery behind #states in the FormAPI. Simply using a hook_form_alter() and adding a #states array to the relevant fields is enough.


How to tell what is being loaded on a Rules Content is viewed event

I struggled with a similar question ... The "clue" about what "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?

Be aware: this applies to D7 ... and D6 is another story.


How to use prepareKey() for the Migrate module

You can set the $item_ID_xpath to something that does exist in the XML, for example 'name'

Then inside your migration class, you can use the prepareKey method to generate an ID

public function prepareKey($source_key, $row) {
  $row->glid = crc32($row->xml->name);
  $key['glid'] = $row->glid;
  return $key;
}

I am using crc32() to generate an ID from a string, but I have no clue whether that is smart or not, so use at own risk.

Now that you have an ID ('glid' in the example) you use in the mapping:

$this->map = new MigrateSQLMap($this->machineName, array(
  'glid' => array(
    'type' => 'varchar',
    'length' => '255',
    'not null' => TRUE,
    'description' => 'id generated from a string'
  ),
), MigrateDestinationNode::getKeySchema()
);

Dont forget to deregister the migration if you change this schema.


Adding additional option under node publish options

I think you can do it without adding the 5th option, if you familiar to Views module, and Taxonomy module, you can simply add vocabulary(in Taxonomy configuration) and add Term - for example Active, next you can add field to your Content Type(Article or whatever) and now if you want to post an article you can chose - Active term.
Next step, create new view, add whatever you want(body, title, etc) and in Views/Contextual filters add new filter -> has Taxonomy term ID input the Active id, and now you are done.


Should I use Drupal or a Mediawiki to create a site like Wikihow?

You have the source code for Drupal, as well as for Mediawiki (that's the nature of scripting languages such as PHP). This means, both platforms allow endless customization and you can implement your requirements using any of those systems. A decision between Drupal and Mediawiki is therefore not a technical decision, but a business decision: which platform will get the job done with lower costs?

If your are working on your own, you have to weigh "getting it done using something you know" against "risk using a new system but allowing you to become proficient in it". There are also other factors that come into play, like time constraints and the pricing scheme.

A correct answer to your question cannot favor one or the other platform. It can only give you suggestions on what factors to take into account so that you can decide for yourself. My list is not exhaustive.


How can I ensure that a user account on my local dev server has the same uid as an account on my production server?

It's not currently possible to export Users into a Feature.

There's an open issue for adding support to uuid_features.module.


How to print "Time" field in twig template

By default, it considers the entered time as UTC. So when we render the value of the time field, it prints the value according to the user's timezone.

I used below code to print the same value as entered in the backend

node.field_time.value|date('h:i A', 'UTC')

or we can also use false instead of UTC to get the same output without setting any time zone.


How to search views with exposed filters

Views filter populate should help you with your issue.  What you need to do is don't expose the Title, Body, and Location in the Filter Criteria of your view.  Then add Populate filters and expose it and select Title, Body, and Location as your filters.


Drupal 7 views exposed filter: Removing -Any- and sorting items

You should implement hook_form_alter on your exposed filters form (if you have devel enabled then use dpm to find the form's name).
Using the form alter sort (or just revert)  the date's array and remove the '-any-'.
By the way to remove the '-any-' you may also use CSS which will allow you to quickly bring it back in the future if you'll want to.

I edited a similar code I used in the past according to your need, so you will need something like this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {
    case 'views_exposed_form':
      if( !empty($form['#id']) && $form['#id'] == 'views-exposed-form-myview') {
        // This is the myview view

      // Remove the start date label
      if( !empty($form['field_sw_date_value']['min']['#date_label_position']) )
        $form['field_date_value']['min']['#date_label_position'] = 'none';

      // Remove the end date label
      if( !empty($form['field_sw_date_value']['max']['#date_label_position']) )
        $form['field_date_value']['max']['#date_label_position'] = 'none';
      break;
    }
}


You'll find the node id from each row in _entity:

{{ row._entity.id }}


Create a list of figures, equations and other items

This is a typical use case for views.

If I understand your requirements correctly, you need to do the following:

create a block in views (see http://www.inmotionhosting.com/support/edu/drupal-7/views-module-tutorial/create-block-display)
assign that block to the region you want it to appear in your default theme (Structure -> Blocks), see https://drupal.org/documentation/modules/block

You can also restrict the pages on which the block should appear.


What is the best way to redirect node to node

Try the redirect when logged out of your admin account as I believe when logged in as an admin any redirects from a page that exists won't get triggered. This is to allow you to be able to still access that page as an administrator


Rewrite results (like trimming titles) won't work at all

Clear your Drupal cache by visiting /admin/config/development/performance or if you use the Drush module, simply run drush cc all

Also make sure you're editing and viewing the correct view.  If you're modify the master display but viewing an overwritten display, your master view settings will have no effect.


Field type that is an integer, but accept some strings that means no value is provided?

If you have only one possible non-integer value, leave it as integer, just make it optional (not required). As far as I understand Feeds JSONPath Parser, non-integer value will simply get omitted, giving you no value for this field - exactly consistent as in fact you don't have that price.

Then in your template files check if it's set. If it isn't, show "on demand" string, with a link to make a demand or, well, anything you need.


How do I create a contant managed list of linked images and display it as a block?

I would go down the views route as it will be the simplest. Just set the filters to only return products that have images and limit the view to output 2 items max. You could add an extra field onto the product content type that you then check for in views to allow the admin to control which products get sent to this block.


Commerce product entity not being saved by EMW from another entity form submit

It's seems that by using the product entity directly from $form_state['complete form']['#product']; the entity_metadata_wrapper() works as expected and it saves the values.

if (!empty($form_state['values']['plugins']['plugin_settings'])){
    $selected_sources = array_values(array_filter($form_state['values']['plugins']['plugin_settings']));
}
    //get directly the product, without entity_load_single()
    $product_entity = $form_state['complete form']['#product'];
    $wrapper_product = entity_metadata_wrapper('commerce_product', $product_entity);
    if (!empty($selected_sources)) {
        $wrapper_product->field_product_location_store = $selected_sources;
        $wrapper_product->save();
    }

Although the object loaded by entity_load_single() is identical with the object obtained by $product_entity = $form_state['complete form']['#product']; the entity_metadata_wrapper() works only for the second case, which seems more logical and is faster.


Using Profile 2 with Entity Reference--How to display the user name and not the "Profile Name"

You can use Entity View Modes to create a User view mode, and then set the fields for display on that view mode. Then select the view mode in the field formatter for the Entity Reference field.


Drupal 8 - Drush composerRequireDrupal8 error

Please do not install Drush using composer global require.

Quoted from http://docs.drush.org/en/8.x/install-alternative/.

If you have Drupal 8 installed conventionally best practice would be to install Drush 8 globally by downloading the latest drush.phar, see http://docs.drush.org/en/8.x/install/.

If your Drupal 8 site is composer based then Drush 9 is probably already included. If not see http://docs.drush.org/en/master/install/.


WYSIWYG CKEditor config.js not being used?

This took some research, but I found this article which describes how to do it.

The meat of the article is the following hook, which defines a custom config file:

<?php
/**
 * Implements hook_wysiwyg_editor_settings_alter()
 */
function MODULENAME_wysiwyg_editor_settings_alter(&$settings, $context)
{
    // The $context variable contains information about the wysiwyg profile we're using
    // In this case we just need to check that the editor being used is ckeditor
    if ($context['profile']->editor == 'ckeditor')
    {

        // The $settings variable contains all the config options ckeditor uses.
        // The array keys correspond directly with any setting that can be applied
        // to CKEditor - as outlined in the CKEditor docs:
        // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
        // Another way to override configuration is to use your own configuration javascript
        // file. In this case, we're going to add our own configuration file that will
        // Hold our stylesSet customizations...
        $settings['customConfig'] = base_path() . drupal_get_path('module', 'MODULENAME') . '/ckeditor_custom_config.js';
    }
}


Managed_file form does not show #default_value

The value of a managed file field is a file ID, rather than its URI.

Assuming $file in your code is a file object, change the element array to:

$form['logo_fid'] = array(
  '#type' => 'managed_file',
  '#title' => t('Logo'),
  '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
  '#upload_location' => 'public://logos/',
  '#progress_indicator' => 'none',
  '#default_value' => $file->fid,
);


Why doesn't All Products show all my products in Drupal Commerce?

I know this is old, but I recently encountered the same issue. Bojan Zivanovic's suggestion ave me an idea though. The search index indicated all products were indexed, but clearing the search index and rebuilding it resolved the issue.


How to allow a role to block other users?

Sounds like you must do it by custom module.

For blocking user, use db api and just change status column (users table) value to 0.

Similar things is for unpublish selected user content. All you need is in node table.

So you need two UPDATE statement for this job. That's all.

BTW. Do you try mollom for anti-spam? You can specify any form to work with mollom.
Maybe you can configure this module to work with logged in users.

Mollom has nice permission, e.g.: Bypass Mollom protection on forms, so you can choose which role may bypass spam checking or not. Then just try to find any hook declared by Mollom module that allow you to block user when spam is detected.


How can I repeat a group of fields in a content type?

You should look into the new media entity suite of modules for Drupal 8. You can create media bundles and add fields to them (like title, caption, link, copyright). You can then create a simple Paragraph that holds a media reference field, and set it to unlimited - the theming is up to you to get the display to grid out like a gallery. I'm not sure why you need the image dimensions though. But with media entity, media renders out like normal entities meaning they gain access to display modes and various twig template possibilities.

https://www.drupal.org/project/media_entity
https://www.drupal.org/project/media_entity_image

Here is a walkthrough that covers in depth the technique I'm describing and how to set up a media based workflow:

https://www.annertech.com/blog/reusable-media-drupal-8-tutorial

Using Paragraphs is basically the only way to get 'bundled fields' without resorting to using Entity Construction Kit and entity reference fields - but by the time you engineer all that, you'll have spent three times as long and your field data won't live on the media object itself ( which is another drawback to Field Collection), and for that you will definitely want the Media Entity approach. Please don't make them multiple content types either. Media is media.


Cloned Seven/Bartik themes don't show up

I renamed all the files named bartik to xbartik

When you say all the files, I hope you also did bartik.schema in the /config/schema folder.

  I did a find a replace in the info and theme files to the
  corresponding name change of xbartik and xseven.

You need to do this for all files, including files like bartik.schema, bartik.libraries.yml bartik.breakpoints.yml.


How to create Select list on Entity forms with changeable list of key values?

As for workaround, it is possible to use Taxonomy Term Reference field type as Select list, which would provide me a dynamic list of options (list of terms) which can be changed in the future.

However this is not ideal solution for multiple forms from UX perspective, as I have to create a separate taxonomy vocabulary for each widget (or creating a very long one).


Some Drush master-branch commands report DB problem in Drupal 8

Drush is giving a very accurate error message

  wget nor curl executables found.

You can either install Curl separately as benos suggests above or install more Unix tools. Since you might need Git anyway, why not install Git for Windows? Then you get a proper Bash prompt. If you prefer to use Command or Powershell you can select to update the PATH variable when installing so Git (and the Unix tools) are available there too.


Place a link at top AND bottom of each node

You are placing your link in the links object of the $content array which will generally, unless a template file overrides it, render all it's content in one place.

If the one link you have added visually covers your needs, the other one should be placed within the $content array, with a 'light' #weight property (0 for instance) along with the rest of the array's items (body, fields, etc).

the code could look something like this:

$node->content['top_link'] = array(
  '#markup' => ''.t('Apply').'',
  '#weight' => 0,
   );


A way/module to display a list of Blocks assigned to specific path?

I not sure have I understand your question.

At the picture below you can set it two path. Exmaple:

Page_1

Admin_Block_Page

Another one will be:

Page_2

Admin_Block_Page

When you go to Admin_Block_Page, it will display block in Page one and Block in Page two.

Another Method: views
Module:https://www.drupal.org/project/views
You tube: https://www.youtube.com/watch?v=3L9JLZOb_LQ


Add float or align selector for CCK image fields

Look into the Display Suite Module: http://drupal.org/project/ds

It is designed to give you more control of the display of your content from the Admin UI. There are links to detailed screencasts on the project page. You'll see versions for both D6 and D7.

I don't know if you get those options on the 'add new content' page, but it wouldn't surprise me if you did.


Start form as modal, from the controller

I did an example of this a while ago. Basically I defined a route, and that controller returned an AjaxResponse:

mymodule.growl:
  path: '/mymodule/growl'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::growl'
  requirements:
    _permission: 'access content'

Basic controller:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\igrowl\Ajax\GrowlCommand;

class MyModuleController extends ControllerBase {
  public function growl() {
    $options = GrowlCommand::defaultOptions();
    $options['message'] = 'This is a message.';
    $options['title'] = 'Hello';
    $options['icon'] = 'feather-check';
    $options['type'] = 'success';

    $response = new AjaxResponse();
    $response->addCommand(new GrowlCommand($options));
    return $response;
  }
}

Any link hitting that route fired that Command. So, anytime someone clicks a link going to your defined route, it should create a modal.

You basically want to return a form (use the form builder service provided by ControllerBase instead of the static container) and at a basic level, use OpenModalDialogCommand (or supply your own modal js with custom Command). AjaxResponse will take care of the rest.


grasmash/composerize-drupal is used to convert a Drupal site that wasn't created with Composer into a Drupal site managed with Composer.
Once the plugin converted the site, it can be removed. After the plugin is removed, modules and themes must be added with composer require, not downloading the archive containing the module/theme files.
If that is the only plugin that isn't compatible with Composer 2.x, you can remove it, as it's not necessary to keep it installed.
Drupal 8.9 is compatible with Composer 2.x; it should not create issues with that Composer version.


Commerce License not de-activating when expired

For some reason the basic Drupal cron didn't call the license sync. Using Ultimate Cron I was able to make this work.


Prevent a date from happening in the past

Drupal's Form API allows you to add your own validation functions to a form. There is an example for a date field validation function in this forum topic. Documentation is here.


Add a custom validator to form using hook_form_alter in your custom module.

function custom_mod_form_alter(&$form, &$form_state, $form_id){
  switch($form_id){
    case 'comment_form':
      $form['#validate'] = array_merge( $form['#validate'], array('custom_validator'));
    break;
  }
}

Define the logic to restrict the length of comment length

function custom_validator($form, $form_state){
    if(strlen($form_state['values']['comment']) < 50)
       form_set_error('comment', t('No No....'));
}


Can't pass variable to views style plugin template

In below code you preprocess the variables for views-view.html.twig file

function alpha_preprocess_views_view(&$variables) {
  $variables["beta"] = "1";
}

and, function alpha_preprocess_page(&$variables) will preprocess the variables for page.html.twig

So, if you create a file views-view.html.twig then you will get your variable {{ beta }}


No, it's not OK to use it directly. Always use base_path() function instead. There are two benefits:

You will not risk accidental change in the original variable, so you will not cause other modules to fail if you'll make a mistake.
If, for whatever reason, Drupal will change way it stores base path, your module will continue to work properly.


Relating content types to be used in Views filters

Nikit's response about using Relationships in the view is correct, but it's not clear you've have already set up the correct 'node references' between Games and Developers.

So, rather than maintain your own lists of Developers for a Game, you need to use the References module to add a field that allows 'connections' between these content types. You might also want the Corresponding node references module to auto-update the reference field on a Developer when you edit a Game, and vice versa.

From here you can properly relate Games and Developers, so Views can use these relationships and allow you access the associated Games from your Developers view.


It depends on what fields you are dealing with.

hook_field_extra_fields() allows you to define extra fields for any entity, then the field itself is added in a hook that runs when the entity's content is being generated.

That is the place where you need to add the js.

In that hook you can modify the fields you care about and add your js using drupal_add_js() or #attached.

#attached is generally more resilient to caching as it lives with the field render array.

Use #attached like this:

$form['YOURELEMENT']['#attached']['js'][] = drupal_get_path('module', 'MODULENAME') . '/javascript.js';

For example, if the field you want is being added to nodes, you would implement hook_node_view() or hook_node_view_alter() something like this:

function MODULENAME_node_view($node, $view_mode, $langcode) {
  if (isset($node->content['EXTRAFIELD'])) {
    $node->content['EXTRAFIELD']['#attached']['js'] = drupal_get_path('module', 'MODULENAME') . '/javascript.js';
  }
}

or in hook_node_view_alter() it would be like this:

function MODULENAME_node_view_alter(&$build) {
  if (isset($build['EXTRAFIELD'])) {
    // Change its weight.
    $build['EXTRAFIELD']['#attached']['js'] = drupal_get_path('module', 'MODULENAME') . '/javascript.js';
  }
}

The same principle can be applied to other entity types, like users, which would use hook_user_view() or hook_user_view_alter().

If your field is on multiple entity types you might have to use multiple of these implementations, or even better, you could use hook_entity_view() or hook_entity_view_alter(), which allow you to target all entity types in the one place.

If you need to make sure your hook runs after all other modules' implementations of that same hook then you can either set the weight of your module higher than others or use hook_module_implements_alter() to make sure your module runs last.


I really wish this was better documented.  In addition to the above you need to add a field mapping to the type:

$this->destination = new MigrateDestinationFile('custom_file_type');
$this->addFieldMapping('type')->defaultValue('custom_file_type');

That's it!


Difference between .info files hook_menu() file key?

I'm sorry you do not understand my question, however, I believe the question was pretty straightforward. After discovering some interesting articles I think worked out my confusion.

The files[] entry in the module .info file is not used for "including" php files. It is meant only to auto load your classes and interfaces for your application (if you're writing your module using object oriented methodologies). It could be thought of as the "import" statement in Java.

The following articles go more into detail about PSR-0 standard and auto loading in php.
previousnext.com.au/blog/drupal-8-now-psr-0-code-drupal-7/
riceball.com/d/book/export/html/1200

That being said, the purpose of the file key inside the hook_menu() $item[] is to specify where the file containing the page_callback function exists. If your page_callback function is defined inside a class (statically), then you do not have to provide the file and filepath keys. The callback would look something like this,
    'page_callback' => array('MyClass::myfunction');

For more information on OO Page callbacks in Drupal 7, read the following article.
previousnext.com.au/blog/object-oriented-page-callbacks-drupal-7

If your page_callback is not inside a class, but just inside a file then you'll need to provide the file and filepath keys so that Drupal can include this file when your page is created.


Create an EventSubscriber for a specific module

Each event in the $events array should itself be an array; try:

$events['gathercontent.post_import'][] = ['onGatherContentPostImport'];


How to create charts in Views using Google Analytics data?

You could pull in the data to your Drupal DB via the Google Analytics API (https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtDataImport)

Then create views to display the reports/charts you want. Then install and build data visualizations packages like Views Dataviz with Google Charts API.


What are my options to visualise a views table with many fields grouped in columns?

The DataTables module might help for answering this question. Here is a quote from its project page:

The DataTables module integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:

Variable length pagination
On-the-fly filtering
Sorting with data type detection
Smart handling of column widths
Themeable by CSS
And more ...

Another feature that it offers is that you can "hide" specific columns from the default table display. But still the user has the option to do things like:

expand the hidden columns.
use the DataTables search feature to search for rows containing one or more strings contained in ... even those hidden columns.

So in this question here, I'd use an approach to only show, by default, a subset of all those columns, and leave it to the user to yes/no also display these (initially hidden) columns.
A few more links you may want to look at:

Show / hide columns dynamically (use the links following Toggle column to see it at work).
Tutorial about Using DataTables In Drupal 7.
How to hide (and show) a table column (using the jQuery DataTables plugin).
jQuery DataTables hide column without removing it from DOM.

Refer to the (short) video about Create Powerful Tables with the DataTables jQuery Plugin and Views for an intro about it, and how to use it as a views style plugin. Using the "settings" link for this views style, you can specify all sorts of dataTables options/features. In the above video starting from around 3:00 you see many of them.
The last link in these settings relates to hidden and collapsed columns (you can see the link in the video, though it is not expanded). So there is where you can then specify which of your (many?) columns you want to be processed as collapsed columns (not sure if you want any of them to be "hidden "in you case. Experiment a bit with those options in your environment to check if it is an acceptable compromise (or alternative) for "grouping" your fields (table columns), i.e.:

fields you always want to be shown.
fields you want initially to be excluded from the display, but for which you let the user decide to optionally also shown one or more of them.
fields you never want to be shown.

Example
Below is a screenprint of such display using DataTables. It's a display I created using Views (of course) with a table with:

8 fields in (defined in my view).
5 table columns for the 5 fields I have decided to always show.
3 table columns which I defined as "hidden and expandable" (within the DataTables settings after you select DataTables as the Views style).

Here is how the DataTables display looks like:

For each row there is a link 'Show Details' (in its 1st column). If you click on one (or more) of them, the hidden fields of such row are shown below that row (with grey background here) and the link you clicked changes to 'Hide Details'. Obviously, I've not done any styling for such expanded row (hence the grey background, etc). But you can see the 3 fields that were initially hidden.
Bonus: assume none of the rows are shown expanded, and you type "Basic" in the DataTables search box. It will then dynamically (in the browser, no server calls) reduce the table display to only those rows with Basic Page as value for "Type". But wait, there is even more: if you'd type a string like part of "21:15" instead (hidden in some of the rows), it will also dynamically reduce the table display to only those rows, like the expanded row shown in the screenprint. But wait, there is even (quite) a bit more: a search string like  "basic 21:15" will filter the rows to a combination of both search strings. For only this one feature I often recommend the amazing DataTables module, one of Drupal's hidden gems I think. And then there are the other features like pager, sortable columns, etc.
Remarks

Make sure to use the 1.9.x version of the DataTables library (not 1.10.x or above), as mentioned also on the project page, which states:

While there is work in the 7.x-2.x branch to upgrade to the latest DataTables version (1.10.x), the 7.x-1.x branch only works with DataTables <= 1.9.x. Since it's not listed in the projects download page, you will have to download it directly.

When creating a view, disable the pager of your view, since DataTables provides its own paging features (the video talks about that starting from 2:05).


Displaying static text on a view that disappears after hitting 'Search'?


How to require revision logging for certain users

there is a Enforce Revision Log that will do this https://www.drupal.org/project/enforce_revlog module


How to display node's taxonomy child items in node using views for multiple parents

The goal was to display child items for multiple taxonomy terms of the node in a node's field using views.

Solution:

Create content type with:

Taxonomy term field (multiple values) - it's for parent items
Views field - it's for displaying child items for ALL parents

Make standard taxonomy tree view with ajacency model (search google)

Add a contextual filter with parent term ID

Provide default value
Taxonomy term ID from the URL
filter to items that share any term
When the filter value IS available or a default is provided

Specify validation criteria - taxonomy term ID
Filter value type - Ternm IDs separated by , or +

Edit view field of previously created content type

Select the view created as a default value for this field
From placeholder list select [node:field_bla_bla] (that's taxonomy parent field in the node) as an argument passed to default value


How to replace node_form() with my custom form callback?

Variant 1. You can use hook_menu_alter and you can set your callback

/**
 * Implements hook_menu_alter.
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/add/superpage']['page callback'] = 'MYMODULE_superpage_form';
}

Variant 2. You can use hook_form_FORM_ID_alter  and override/edit the form

/**
 * Implements hook_form_FORM_ID_alter()
 */
function MYMODULE_form_superpage_node_form_alter(&$form, &$form_state, $form_id){
  // your code
}


How to disable copy and paste in webform textarea?

I've not tested this code, but a quick Google search suggests the following (obviously change #Password to the ID of your textarea field).

$(document).ready(function() {
    $('#Password').bind('cut copy paste', function(event) {
        event.preventDefault();
    });
});


DateTime field value is automatically adjusted for the timezone set in Drupal

I am not sure if you can disable it completely, but by changing the site's default timezone to the same timezone as your server, and preventing users from setting their own timezone you should be good.

Both can be configured on /admin/config/regional/settings


How to create an RSS or Atom Feed in Drupal (source)?

Just use Views to create feed with content and fields you desire. A bit more up to date tutorial: https://yalesites.yale.edu/book/creating-rss-feed-views


Default Redirect after login based on destination

You mite need to add 'destination' query parameter for shared link.

For example: https://www.drupal.org/user/login?destination=search/site/destinations


You should be able to use template_preprocess_field() and shuffle() to do this. This is an example randomizing the entries in field_photo for a theme called dummy:

  function dummy_preprocess_field(&$variables) {
    if ($variables['element']['#field_name'] == 'field_photo') {
      shuffle($variables['items']);
    }
  }

You could also try to replacing you call to usort() in your original code with shuffle($variables["items"]).

The above isn't tested, but I think it should work.


How can I return a JSON response from an internal function ? (not the main callback)

You can do it by checking is $this->someCalculation() is instance of JsonResponse. It is is we return the response, otherwise we set $result to the calculation result.

private function someCalculation() {
  try {
    // Something.
  } catch ($e) {
    return new JsonResponse([
      'data' => NULL,
      'error' => $e->getMessage(),
    ]);
  }
}

public function getTemplate(Request $request) {
  // Alternatively you can return an array with a status code and check on that instead.
  if ($this->someCalculation() instanceof JsonResponse) {
    return $this->someCalculation();
  }
  // If it didn't fail set set $result to the calculation result.
  $result = $this->someCalculation();

  return new JsonResponse([
    'data' => $result,
  ]);
}


Taxonomy Term Reference Fields Don't Get Created on Nodes During Migration

The problem wasn't in migrate_plus.migration.upgrade_d6_field_instance.yml but instead the problems were in  migrate_plus.migration.upgrade_d6_field.ym and migrate_plus.migration.upgrade_d6_field_instance_widget_settings.yml.  Also in the term yml files I had to update the field name to include field_ in the file name.

I documented how I was debugging and what I was changing here.


This is related to the Q Remove default “Home” link?. You can not alter that menu item. The only way to fix this is to disable the existing "Home" link, and create a new one instead according to your specifications.

To do this, follow these steps:

Go to admin/structure/menu/manage/main and disable the Home menu item
Add a new menu item at admin/structure/menu/manage/main/add and fill in the options like this:

Click Save and you're done


How to add custom CSS per media query in Omega 3 theme?

Part of the magic of Omega3 is that it does that for you!

Omega will always load the global.css file. If you are in a mobile layout (too narrow for a grid), that is the only file that loads. When you increase the browsers width to narrow, then omega 3 dynamically loads:

global.css
SUBTHEME-alpha-default.css (loads for all non-mobile-layouts)
SUBTHEME-alpha-default-narrow.css

If you keep increasing your browsers width to the normal layout, then these css files are loaded:

global.css
SUBTHEME-alpha-default.css
SUBTHEME-alpha-default-narrow.css
SUBTHEME-alpha-default-normal.css

Note that any CSS definitions you have in SUBTHEME-alpha-default-normal.css will override definitions in global.css, SUBTHEME-alpha-default.css, and SUBTHEME-alpha-default-narrow.css

To answer your question then, custom CSS for the narrow layout should go in SUBTHEME-alpha-default-narrow.css, custom CSS for the normal layout goes in SUBTHEME-alpha-default-normal.css, and custom CSS for the wide layout goes in SUBTHEME-alpha-default-wide.css. Just put it in and let Omega3 do the rest!

See https://groups.drupal.org/node/156719 for more info


If you are configuring the view with the fields. You can try setting the formatter of the image to 'URL to image' and then create the HTML yourself like
<img src="{{ view.field.field_slide_media }}" />

Or you can try file_url


hide the author information from the non-member

If you copy the node.tpl.php file from the templates directory and create a node--mycontenttype.tpl.php file you should see the following around line 91:

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php print $submitted; ?>

<?php endif; ?>

Simply change it to this:

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php if ($logged_in == TRUE): ?>
      <?php print $submitted; ?>
    <?php endif; ?>

<?php endif; ?>

The $logged_in variable is a node template variable that has the value of TRUE if a user is logged in.

In this snippet you're just saying if the user is logged in, then display the submitted information.

Don't forget to clear your caches!

EDIT

Apologies, I've read the question properly now.  The following should do what you want.

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php if ($logged_in == TRUE): ?>
      <?php print $submitted; ?>
    <?php else: ?>
      <?php print $date; ?>
    <?php endif; ?>

<?php endif; ?>

This will display the entire submitted by text for authenticated users, and just the date for anonymous users.


Missing Schema on custom field only during PHPUnit Test

You only get that error during testing because the core testing base classes add a config schema checker during testing.

You have 2 options, the first is the easiest, but is not recommended, and that is to disable the strict config checking in your test by setting this variable to false in your test class:

  /**
   * Set to TRUE to strict check all configuration saved.
   *
   * @see \Drupal\Core\Config\Development\ConfigSchemaChecker
   *
   * @var bool
   */
  protected $strictConfigSchema = FALSE;

This approach is not preferred because you then have invalid config schema data in your module. It would be far better to fix the schema.

Instead of city_state: in your schema file, something more specific like:

field.field_settings.city_state:

or since this appears to be display related, it might be

field.formatter.settings.city_state:


... how to notify the node author when new comments are posted on their content??

To my knowledge, the current answer to this question is: not possible yet.
More info

Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here are some (scary) quotes from it:

... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.

... Even if we got more funding today, fago the current principal maintainer of the Rules module wouldn’t have enough capacity to do the work himself.

Start here if you wonder how to contribute.

One never realizes what has been done, only what remains to be done ...

Plan B
You might want to look at the Message module (and the related modules that belong to the Message Stack), which has a pretty stable release already, and which you could use to create similar functionality.


How do I enable the browser spell checker in WYSIWYG editor?

The Check Spelling plugin is only included with CKEditor Standard and Full by default.

For the CKEditor module spell checking is enabled via the profiles.

Go to Configuration > Content authoring > CKEditor and edit each profile you to to it display on. Then under Editor Appearance drag the appropriate buttons to the "Current toolbar"

If you are using the WYSIWYG module it is also enabled through the profiles.

Go to Configuration > Content authoring > Wysiwyg profiles and edit each profile you want it to display on and check the "Check Spelling" option.

With CKEditor 4 you must enable "Spell check as you type" since the buttons have been merged into one with WYSIWYG.


Try using get_defined_vars() to get the list of all the variables on a page.

  get_defined_vars — Returns an array of all defined variables

Source - http://php.net/manual/en/function.get-defined-vars.php


How to remove "Submitted By" data from google search engines in drupal7?

If you don't want the content to show up in Google search, you have a couple options.

Hide the "Submitted by" in Drupal itself.  You can do this by going to the content type edit page and unchecking the box for "Display author information."
Use a theme template for the content types and move the "Submitted by" information to the bottom of the content. If it is shown at the bottom instead of the top, Google is unlikely to use that information in its search results, since it gives information toward the top higher priority.

What you shouldn't try to do is show information to users but somehow hide it from Google.  This is likely to make Google mad and if they detect it, your site will be penalized.


Drupal How to use regex or specific keywords as menu arguements

There isn't such an option; you just define two route items.

$items['campaign-management/test/%/add'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

$items['campaign-management/test/%/edit'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

Alternatively, you define your route as follows.

$items['campaign-management/test/%/%'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

Your page callback then will do something when the last argument it get is 'add' or 'edit'; eventually, it can return a 404 error when the argument doesn't have one of the desired values.

Keep in mind that in Drupal 7, a user visiting (for example) node/1/sgsdrgdfgdfe45t63635wsg will normally see the node page (node/1, in this case). To keep that behavior, you should define the campaign-management/test/%/add and campaign-management/test/%/edit routes.


How to set value to an unlimited field collection using Rules?

I see 2 errors in your rule, which is about processing a list of field collection items. Each of these errors is further explained below (though I'm not sure if they are the only errors).

Error 1: Rules Condition 'Entity has field' is missing

You should add a Rules Condition "Entity has field" (prior to being able to use it anywhere later on in your rule), which refers to your field collection field. Since your rule doesn't have such condition yet, it may also explain why you got those blank values so far.

For way more details about this, refer to "How to iterate over all field collection items in an eMail body using Rules?" (which also includes a rule in export format you may want to experiment with, if you only adapt some machine names of the used fields).

Error 2: 'Set a data value' needs to be replaced by 'Add an item to a list'

The Rules Action Set a data value that your Rule uses, can only set 1 value, while you're trying to update something that is a list.

So try to replace that action (ie the first data_set within the loop) with an action "Add an item to a list". When doing so, you probably also want to set "ENFORCE UNIQUENESS" to true, so that you "only add the item to the list if it is not yet contained". Even though for your case it may not make a difference, IMO that is a kind of safety-belt when using this action.

For way more details about this, refer to "How to set multiple values to an unlimited Term Refence field with Rules". While reviewing this, also pay attention to the "Fetch entity by ID" (within the Rules loop): I'm about sure (99%), you'll also need to add a similar "Fetch entity by ID" (but from the variable names you used in your rule it's hard to tell).


Product catalog site (+ Store) - what strategy?

Drupal commerce is not your only bet for a shopping site for Drupal 7, but it is the best one.

At this time of writing commerce is on beta-4 but it wont be long before rc-1 will be released. It's very stable considering that it's a beta release, so I wouldn't worry too much about that.

Talking about personal experience I have launched one site on commerce, which was launched when commerce was still in alpha, most likely the first production on commerce. So I have a good firsthand experience with running commerce in a production environment. Other than the pain of having to do my own upgradings from alpha to beta, commerce has been running very stable without any major problems so far.

Taking into account the above. I would personally go with option a):

Install commerce
Create products
Create nodes with products reference to display the data
Don't display add to cart form anywhere.

You might need to use a bit of time to setup commerce and products types, but it would allow you to quickly and easily convert the catalog to an actual shop and that save you a lot of headaches later on.


Drupal 8.2.5 no internal pages on fresh install

Try to clear caches using drush from the terminal.

drush cr

Also uncheck the following under Bandwidth optimization

External resources can be optimized automatically, which can reduce both the size and number of requests made to your website.

Aggregate CSS files

Aggregate JavaScript files

from
http://drupal.local/admin/config/development/performance


Composer Not Getting Latest Version of Module

Composer does not default to the "latest" it defaults to the "Most stable" when there isnt a stable release. In this case 1.0-beta1 is "more stable" than 2.0-alpha1.


How can I list the current user's orders with Drupal Commerce?

There already is one provided with commerce_order_ui called commerce_user_orders. By default it's available at user/[uid]/orders. It needs the permission View own orders of any type.


Uninstalled fb module, but page still pings fb connect for every pageload

It was added by the facebook share button added by sexybookmarks, Disabling that removed the files as well.


That's 4 questions in one ;-)
For #2 checkout my previous question that has just been answered. Services Views would be another solution to do it without code.


Why do we use "target_id" as the name of the index in php instead of "entity_id"?

target_id is generally used in entity references.  So if you have an entity reference to another entity the target_id is the id of that entity.  This depends if it is a node or an entity though.  But I will mention that generally you want to avoid $entity->field_fieldname['und'][0]['entity_id'] but instead using the entity_metadata_wrapper to target values instead:

$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

$mytitle = $node_wrapper->title // Title
$myfield = $node_wrapper->field_my_field->value(); // Value of the field, cleaner

You can also use the set method
$node_wrapper->field_my_field->set("My value"); // If single value

$node_wrapper->save(); // Save my entity


drupal_render in hook_form_alter prevents javascript from being included in the header

Setting the #id to $wrapper['#id'] = drupal_html_id('edit-' . str_replace('_', '-', $wrapper_field_name));  resolved the issue.  theme_textarea was unable to get a value for $element['#id'].

edit

I still had trouble getting the #ajax elements to be processed even after adding a call to ajax_pre_render_element.

I restructured my alter hook so that it prints the textarea inside the form element that I'm trying to append to. that way it prints both fields one after the other.  This way, I'm not touching drupal_render and everything works.


Why can't I delete certain content types?

Delete them by going to the url /admin/structure/types/manage/content-machine-name/delete

content-machine-name being the machine name of the content type you want to delete. Also, make sure you use dashes in the machine name rather then underscores.


Display a (view) block for everyone except one role

In the Blocks Admin page, you can use PHP to display/not display the block, so you could put something like this in there:

<?php

global $user;

if (in_array('ROLETHATSHOULDNOTSEETHISBLOCK',array_values($user->roles))) {
  return FALSE;
} else {
  return TRUE;
}

?>

OR just check all the roles BUT the ROLETHATSHOULDNOTSEETHISBLOCK in the other part of the form :)

ADDITION:

With respect to PHP and security, I presume JoeS is referring to these paragraphs within The Definitive Guide to Drupal 7...

Avoid Using the PHP Filter Module

Although it’s handy to be able to write PHP code directly into your Drupal web interface without having to create a module, it’s also very dangerous! All PHP code should live in the form of modules or themes. Writing PHP in Drupal’s web interface is a bad idea for the following reasons:

• It’s unfriendly to edit and debug (no syntax highlighting and no proper error reporting).

• It makes code reviews difficult and versioning impossible.

• A trusted user might inadvertently damage your site with malformed PHP code.
• If your site was to be compromised, a hacker could penetrate and damage your server using well-crafted PHP code. Keeping the PHP Filter module turned off (or even better, removing it entirely from the filesystem) could help contain such intrusion to the Drupal level only.

• In terms of performance, storing PHP code in the database will prevent any opcode caching mechanism from working on this piece of code

Note that some contributed modules might offer a functionality similar to that of the PHP Filter module; they will suffer from the same flaws noted previously.

                                   **and**

■ Tip If the PHP Filter module is enabled, try to disable it. PHP Filter module should not be used to provide functionality on node (content) pages. Avoiding that is a good idea from both code quality and deployment perspectives. For placing functionality, rather than content, on a page or part of a page, use Drupal’s hook_menu(), hook_block(), or hook_page_build().

...which refer to the PHP Filter Module, not the admin interface.  This module allows users to enter PHP code into a node directly and I wholeheartedly agree that this opens far too many doors.

However, in this case, I am talking about using an option given to the administrator of a site by the drupal admin interface, one that hopefully is used by someone with far more PHP experience than casual users of the system.

Furthermore, using this option is most probably a one shot deal and would be properly tested, unlike the Filter option, which would allow a user to change the code at will, opening further doors to mayhem.

In any case, this discussion does highlight the fact that running a drupal site has many facets, security being a large part, and knowledge is key, but all I can hope is that there isn't a security hole that has gone unnoticed for several releases in the admin interface that would allow any code injection into the 6 lines of code suggested here.


Hide/show pages depending on landing page click

You can use Domain Access module with Subfolders Domain to create two instances Gym and personal training. This will allow you to administer content for both sections.


What is the programmatic equivalent of block save?

The solution is to call drupal_form_submit.  For example:

module_load_include('inc', 'block', 'block.admin');
$form_state = array();
$form_state['values']['module'] = 'block';
$form_state['values']['op'] = 'Save block';
drupal_form_submit('block_admin_configure', $form_state, 'block', $delta);

You can apply this solution to other forms: from the browser, inspect the submit button, and get the 'op' value and the form's machine name.  In source, find the admin.inc that implements the form, and include that, and get the submit functions parameter signature; in this case, the 4th parameter is the form's delta value.


Drupal 7 Migrate: How do I migrate a mult-field key into a single taxonomy term

In your migration class, you can override the Migration::prepareRow() method to add a new name field to your rows:

  public function prepareRow($row) {
    $row->name = "{$row->element_id}-{$row->scale_id}-{$row->category}";
    return parent::prepareRow($row);
  }

And then simply map that field:

    $this->addFieldMapping('name', 'name');

But for simple concatenation, you can also use SelectQuery::addExpression() to add the CONCAT(...) to your SQL query:

    $name_alias = $query->addExpression(
      "CONCAT(element_id,'-',scale_id,'-',category)",
      'name'
    );

And then simply map the expression to the name field:

    $this->addFieldMapping('name', $name_alias);


l() Link function adding Icon before Link Text

you can use something like this:

l(t('Back'), 'node/' . implode(" ",$link[options][attributes]["class"]) . '/edit/', array('attributes' => array('class' => array('btn btn-default btn-back'))))


You can add a new menu link to act as the parent of all the items, a menu link that the users will have access to, then move the Content sub items underneath it. Or you could just move them out from underneath the Content menu item, but that'll probably make a messy toolbar. The toolbar just shows part of the Administration menu, all items under the Administration menu link.


Views Slideshow: keeps showing all images below slider

Figured this out. I guess all I needed to do was make a post about it. On the toolbar go to Structure > Views > Your_Slider (whatever it's called) Under Format click on settings beside slideshow Scroll to the bottom. Go to Widgets and make sure there are no pagers selected here. Save and you're done.


Send a CSV file to the user on FAPI form submit

I guess the code in this blog post http://sirkitree.net/node/23 will help. Essentially you need to use exit() or die() at the end of your submit handler to prevent redirect.

  $file = $header ."\n";
  foreach ($accounts as $row) {
    $file .= $row ."\n";
  }
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="users.csv"');
  die(print $file);


View to show 2 different fields that have multiple values next to each other

As commented there might be better data models. But in case you can't change the data model it's probably the easiest solution to switch the View to display content in a view mode and display the field deltas in a node template:

node--content-type--view-mode.html.twig

{% for key, item in content.field_image if key|first != '#' %}

  {{ item }}

  {{ content.field_description[key] }}

{% endfor %}


loadMultiple() should be fine for this:

$types = \Drupal::entityTypeManager()
  ->getStorage('node_type')
  ->loadMultiple();


new created zen subtheme - content offpositioned

Ahhh.  I had this same problem yesterday and it turned out that I was using the wrong version of compass.  I installed version 0.12.6 and the content returned to where it was supposed to be.
You can either unistall compass and then reinstall
https://stackoverflow.com/questions/3088454/how-do-i-downgrade-to-an-old-version-of-compass-using-gem-instal

or just add the old version and explicitly invoke the older version like so:
compass 0.12.6 watch


i just found this module that is supposed to do that
https://www.drupal.org/project/conditional_fields
I believe a form alter function on a module should do the trick however i haven't implemented anything like it.
Good luck.


With a quick glance at the shurly code, I'd think this should work:

function yourmodule_shurly_redirect_before(&$redirect) {
  $redirect->destination = 'path/to/advert?somevar='. $redirect->destination;
}

And then you need to set up your advertisement page as path/to/advert and have it redirect to $_GET['somevar'] after the timeout.


How to create different Panels for Add and Edit node?

On the node/edit panel, create two variants, "add" and "edit."

Make sure the add variant is first.  Then add a selection rule for the add variant:

String: URL path  node/add/*

All paths not meeting this condition will be sent to the edit variant, which should
give you the effect you want.


7 - How to Add Custom Error Class to Radio Button and Checklist Fields

Out of the box webforms created with Drupal core and the Webform module do not have in line error messaging and indicators for each form field.

You can either:

add custom hooks and javascript to get inline validation, or
install client-side validation module and associated javascript library to get validation/messaging for all standard form elements.  See https://www.drupal.org/project/clientside_validation


Programatically upload/link images and attatch to Ubercart's product node?

Ubercart already has the option of a predefined cck imagedfield, where do you plan on getting the correct image programatically? I remember using a default imagefield image before in the field settings.

Have a search for creating ubercart products programatically, its a fairly common thing as people import products from other dbs and excel files etc.

Here is a start, it all depends on where your data is coming from;

<?php
function MYMODULE_createnode() {

global $user;
if (isset(

$_POST['values_from_form']))
  {
    $values['nid'] = intval(check_plain($_POST['nid']));
    $values['title'] = check_plain($_POST['title']);
    $values['type'] = 'product'; //uc node content type
    $values['body'] = $_POST['body'];
    $values['name'] = $user->name;
    $values['uid'] = $user->uid;
    $values['field_cck_field'][0]['value'] = $_POST['cck_field']; // Custom CCK field example for whatever it was you were wanting to do
    $values['status'] = 1;

    $node = node_submit($values);

    node_save($node);

    }
}
?>


I need to reference a custom field I created in User Profile

Use the $user object to access the logged in user.

 global $user;
 $account = user_load($user->uid);

Now you can use $account->field_iweight['und'][0]['value'] (just an example) to access the weight or any other field from the user profile.

Updated code:

<?php
global $user;
$account = user_load($user->uid);
$entity_field[0]['value'] = $account->field_iweight['und'][0]['value'] - $entity->field_current_weight['und'][0]['value'];
?>


Use the geofield module 2.x. It contains proximity capabilities


I believe ultimately both will do the same thing. But when you use 'type' you are referring to what drupal element to use (see https://api.drupal.org/api/drupal/elements) and when you use '#theme' you're directly telling it what twig template to use.


I am not sure whether to making 'jQuery' version down to some level is good or not. But, I tried to downgrade the jquery version to 1.5 and it works well with my website.

I refereed this post:
Media 7.x-1 Library tab empty

Now, I can see all my images by selecting 'jQuery' version - 1.5.

To do so:
Go to
Home » Administration » Configuration » Development

Thanks!

Vidushi


How to specify translation for strings in twig template & php files

I think you could do that with the User interface translation, "/admin/config/regional/translate" (which is part of the multilingual core package).
By the way you can also use:

{% trans %} Your english text {% endtrans %}


First install the devel module and then check the theme registry to see if the forum form is in the theme registry or not. for more information about registering a form visit this page. as an example to register the comment form you must use this code:

function YOUR-THEME-NAME_theme($existing, $type, $theme, $path) {
    return array(
           'comment_form' => array(
               'render element' => 'form',
            ),
       );
};

When checking the existence the form theme in theme registry make sure that you use the YOUR-THEME-NAME as administrator theme.

Now use the hook_form_id_alter to customize the form.to see the form elements write:

kpr($form);

now you can hide or change the order of form elements.

Here is the video tutorial


hook_file_dowload() randomly thinks user is anonymous

Solution is insuring all site urls use the same subdomain, either including the www before the domain or not including the www before the site domain. Plus within .htaccess forcing all user urls to reference the site via that same subdomain qualifier.

The problem was inconsistent use of www and nothing as the site's subdomain.


Unable to sort by term weight within multiple term reference

On further looking at this issue, I decided to approach it from a different angle. Without any modifications to my view, which has no sort order defined, I installed and enabled the Taxonomy Term Reference module (https://www.drupal.org/project/term_reference_sortable).

Using the above module and setting my Menu Categories term reference to use this widget, I found the order I selected is reflected in my view.


How to install with composer external library that drupal module depends on

You should be able to include this package via composer by adding some repository info.

Add a package definition to your repositories section in your composer.json. The resulting repositories section may look like this:

"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
        "type": "package",
        "package": {
            "name": "usrz/bootstrap-languages",
            "type": "drupal-library",
            "version": "dev-master",
            "dist": {
                "url": "https://github.com/usrz/bootstrap-languages/archive/master.zip",
                "type": "zip"
            }
        }
    }
]

Then you can just use composer require like:

composer require usrz/bootstrap-languages

This will add a new line to your require section in composer.json like

"usrz/bootstrap-languages": "dev-master"

Normally I would try to use this approach with a release tag of a package, rather than the master branch, but no tag exists for this repository.


Select only one radio button in a webform

The problem with the radios approach is that they're separate form fields, so the browser is correctly allowing only one selection per field.

Instead, you should use radio - https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#radio and specify the attribute of name to only allow one value to be selected.

I'm assuming this is going to be built programmatically in a loop instead of procedurally, but I'll demonstrate as if this was hard-coded. Also, in a perfect world you'd add markup in the theme, not in the form definition.

$form['submitted']['800_title'] = array(
  '#markup' => '8 a.m.',
  '#prefix' => '
',
);

$form['submitted']['830'] = array(
  '#type' => 'radio',
  '#value' => 'default',
  '#return_value' => '0830',
  '#title' => t('8:30am'),
  '#attributes' => array('name' => array('time')),
  '#prefix' => '',
  '#suffix' => '',
);

$form['submitted']['845'] = array(
  '#type' => 'radio',
  '#value' => 'default',
  '#return_value' => '0845',
  '#title' => t('8:45am'),
  '#attributes' => array('name' => array('time')),
  '#prefix' => '',
  '#suffix' => '
',
);

$form['submitted']['900_title'] = array(
  '#prefix' => '
',
  '#markup' => '9 a.m.',
);

$form['submitted']['900'] = array(
  '#type' => 'radio',
  '#value' => 'default',
  '#return_value' => '0900',
  '#title' => t('9:00am'),
  '#attributes' => array('name' => array('time')),
  '#prefix' => '',
  '#suffix' => '',
);

$form['submitted']['915'] = array(
  '#type' => 'radio',
  '#value' => 'default',
  '#return_value' => '0915',
  '#title' => t('9:15am'),
  '#attributes' => array('name' => array('time')),
  '#prefix' => '',
  '#suffix' => '
',
);


EntityFieldQuery with "NOT IN" FieldCondition and "=" FieldCondition on the same multi-value field is only processing one FieldCondition

This happens because EntityFieldQuery::addFieldCondition() is written like so:

protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  // The '!=' operator is deprecated in favour of the '<>' operator since the
  // latter is ANSI SQL compatible.
  if ($operator == '!=') {
    $operator = '<>';
  }
  if (is_scalar($field)) {
    $field_definition = field_info_field($field);
    if (empty($field_definition)) {
      throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
    }
    $field = $field_definition;
  }
  // Ensure the same index is used for field conditions as for fields.
  $index = count($this->fields);
  $this->fields[$index] = $field;
  if (isset($column)) {
    $conditions[$index] = array(
      'field' => $field,
      'column' => $column,
      'value' => $value,
      'operator' => $operator,
      'delta_group' => $delta_group,
      'language_group' => $language_group,
    );
  }
  return $this;
}

Note that a field condition is stored as an array in the $conditions variable, indexed by a a value that represents the field. When you add a new fieldCondition on the same field, it just overwrites the array.

I don't know if this was intentionally designed this way, or if it's a bug... but the behaviour you are seeing is exactly what the code says it should do!