How to add template suggestions for form elements of a certain form ID?

This is kind of tricky as you'd have to write a lot of custom code to pass the form id to a form element as you stated above.  Fortunately, there is a contrib module called "Themable forms" which does exactly that, both for form elements and form element labels.
So for example, if I am on the user login page, for the form elements, I see these default theme hooks for all individual form fields.
<!-- THEME HOOK: 'form_element' -->
<!-- BEGIN OUTPUT from 'themes/custom/mytheme/templates/form/form-element.html.twig' -->

<!-- THEME HOOK: 'form_element_label' -->
<!-- BEGIN OUTPUT from 'themes/custom/mytheme/templates/form/form-element-label.html.twig' -->

Note, there is no granularity at all for the above.
Now, after I enable Themable forms, I start to see very granular theme hook suggestions being output in the form of
  form-element--[form-id]--[element-type].html.twig
  form-element--form-id--[form-id].html.twig
  form-element--type--[element-type].html.twig
  form-element.html.twig

So for example, with the username field, I now see
<!-- THEME HOOK: 'form_element' -->
<!-- FILE NAME SUGGESTIONS:
   * form-element--user-login-form--textfield.html.twig
   * form-element--form-id--user-login-form.html.twig
   * form-element--type--textfield.html.twig
   x form-element.html.twig
-->

<!-- THEME HOOK: 'form_element_label' -->
<!-- FILE NAME SUGGESTIONS:
   * form-element-label--user-login-form--textfield.html.twig
   * form-element-label--form-id--user-login-form.html.twig
   * form-element-label--type--textfield.html.twig
   x form-element-label.html.twig
-->

You'll now note a few things, the form id in the form element suggestion as well as the name of the form element itself.
This should get you where you want to be according to your question above.
You can install the module with:
composer require drupal/themable_forms


I used a module called Localization Client which provides a user GUI for translations, enable it and go to the page with the translation you should be able to find it in the list then and alter it.


Add static text on flag confirmation form?

It can be done in the hook_form_alter. You can just add markup element to this form with flagging guidelines


How can we get Block Bundle Type for block in code?

This is how I would do it:

use \Drupal\block_content\BlockContentInterface;

/**
 * Implements HOOK_preprocess_block().
 *
 * @param $variables
 */
function mymodule_preprocess_block(&$variables) {
  $content = $variables['elements']['content'];
  if (isset($content['#block_content']) && $content['#block_content'] instanceof BlockContentInterface) {

    if ($content['#block_content']->bundle() == 'xxx') {
      // ...
    }

  }
}


If I understand your request well, I think this is the solution supplied by @monymirza. But in the latest stable version of quicktabs you have the possibility to select quicktabs to be show under a tab.

Checkout this image to see : (ab is a quicktab instance that has been created earlier, and c is the parent tab that will contain ab)


How do I use another field inside view as the base table?

Give this module a shot - Views Expose Tables

  Exposes Drupal DB tables to Views

  This is a simple module which does one thing: provides an admin page
  for site-builders to choose which tables in a site's Drupal DB to
  expose to Views.

  The module then loads all the fields for each chosen table and detects
  the data type of the field and sets appropriate views field, sort,
  filter, and argument filters (for example numeric, string, date, or
  "default").

  It also looks for a primary key of the table and if one is found it
  sets it as the base field for a views base table and makes the table
  accessible to views.


Batch update XML Sitemap for content type using VBO - D7

Looks like there isn't really a rules integration yet.  The best outcome here would be to write that integration and contribute it to the project.

Failing that, a custom action using PHP would do the trick.  Obviously you should take a backup before executing anything like that.


You can add new templates to already existing using hook_theme_suggestions_HOOK_alter

Example of adding a content type:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page_title__' . $content_type;
  }
}

Then use page-title--content-type.html.twig

You could use $node->id(); if content type is too broad.


You might want to check out the Print Module.  I've used it successfully for print media in the past.


You can read URL with out base path using $_GET['q'] ..

<?php if ( $_GET['q'] == "search" ) : print ('active'); endif; ?>

OR

You can use current_path API function which does the same...


There is no setting for that.

You can either do it with a preprocess function as explained in Remove the 'read more' and 'Add new comment' links on the home page or you can implement hook_node_view_alter(). Both is possible in a module or in a theme.

The read more link in is added in node_build_content(), and you should be able to remove just that link like this:

function yourmodule_node_view_alter(&$build) {
  if ($build['#node']->type == 'page') {
    unset($build['links']['node']['node-readmore']);
  }
}


How to use current user object in Drupal 8?

Yes you need to use a name space, you can include the name space directly like this

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$name = $user->get('name')->value;


How to find drupal 6 ubercart Persian translation?

You can find the direct link here:

http://ftp.drupal.org/files/translations/6.x/ubercart/ubercart-6.x-2.9.fa.po

In case you're interested (and for future reference) that comes from the Ubercart translation downloads page on Drupal.org.

You're pretty lucky, it was only generated 2 days ago!


Anonymise Webform submission in database

I would intercept on the redirect/thank you page after form submission assuming the mail is send directly (is it).

See modules/webform/src/EventSubscriber/WebformSubscriber.php where $webform_submission = WebformSubmission::load($route_parameters['webform_submission']);
.

You probably need to override the service webform.event_subscriber defined in webform.services.yml


How do I use node_load() with an array as first parameter?

The equivalent of $values = array('title' => $vcenter_name, 'type' => 'vcenter'); $nodes = node_load($values); for Drupal 8 is entity_load_multiple_by_properties(), whose first parameter is the entity type, differently from node_load().

Since entity_load_multiple_by_properties($entity_type, array $values) is deprecated, you should use the following code.

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties($values);


How can I create a Drupal "Page" (not a block) without any theme?

Try the ThemeKey module.

This module has a number of really useful options; relevant to your question, you can have it use a different theme or a stripped down version of your existing theme on certain paths or conditions.


I think you need to have your annotation outside of the class

/**
 * Source plugin for MRCTV video nodes.
 *
 * @MigrateSource(
 *   id = "mrctvVideoSource"
 * )
 */
class mrctvVideoSource extends SqlBase {


How to Create a single page within a module and set page variables?

The link in my comment may not get you all the way there so I am adding a working example. Assuming everything else in your code is working changing this line

 return array('variables' => array("var1" => "Hello World Attempt #2") , '#markup' => '
This is some markup content displayed correctly in the page
');

to

$output = array("var1" => "Hello World Attempt #2" , '#markup' => '
This is some markup content displayed correctly in the page
');
return theme('page', $output);

Added the entire $output array to the hook_preprocess_page`.

NOTE: You may have to add a theme callback to your menu item. Example here.


How to use preprocess function for custom templates defined in hook_theme?

Drupal will automatically call hook_preprocess_[template] for each template defined in hook_theme.

e.g:

MODULE_preprocess_custom_slider(&$variables){}

Should be called by default. If not, then clear your cache to be sure the preprocess function is registered.

Fun fact is preprocess functions are called for theme functions as well, e.g theme_item_list calls hook_preprocess_item_list prior to rendering.


Updating from 7.34 to 7.35 after successfull update, drush status shows version 7.34?

This is a file permissions issue.  See:

Can't update drupal core to 7.27

Drush should give an error message here, instead of pretending to work.


Is is possible to call a function inside a .inc file of a module via drush eval?

You could add module_load_include() to your eval code like you would anywhere else.

Like this:

drush eval "module_load_include('inc', 'my_module', 'INCLUDE_FILE_NAME_WITHOUT_EXTENSION'); my_module_my_function();"


how to provide a content type variable to region--header.tpl.php

Try this...
https://www.drupal.org/node/115419

<?php
  // Only show if $match is true
  $match = false;
  // Which node types
  $types = array('book', 'news', 'anothernodetype' );
  // Match current node type with array of types
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load(array('nid' => $nid));
    $type = $node->type;
    $match |= in_array($type, $types);
  }
  return $match;
?>


How do I know when a render array will be processed properly?

See Render Arrays in Drupal 7

  Note: While render arrays and arrays used by the Form API share
  elements, properties and structure, many properties on form elements
  only have meaning for the Form API, not for the Render API. Form API
  arrays are transformed into Render arrays by drupal_get_form.

Because form arrays are converted to render arrays before they are rendered if you add a render array to the form array it will be also rendered when the whole form-array-converted-to-render-array is processed.

As the quoted text says you have to keep in mind that form arrays are not directly renderable, they have to be converted first to a render array. During this conversion, render array attached to the form array are bypassed because they are already a render array.


How can I restrict users to some parents node with node hierarchy?

I suggest you attach a taxonomy vocabulary to your content type and use the Taxonomy Access module.

So, create your vocabulary:

Arts & Science
Economy
News

Create roles based on taxonomy:

arts_role
economy_role
news_role

Assign permissions to roles:

Edit terms in Arts & Science to arts_role
Delete terms from Arts & Science to arts_role
Edit terms in Economy to economy_role
Delete terms from Economy to economy_role
Edit terms in News to news_role
Delete terms from News to news_role

Assign your users to your roles:

Stephanie gets arts_role
John gets economy_role


I have encountered the same error while installing the drush on MAC, I have tried the following and that worked for me:

composer self-update
ln -s /path/to/drush/drush /usr/bin/drush

I have downloaded the Drush from this git repository: https://github.com/drush-ops/drush

And followed the method described here for installing the Drush on MAC: https://www.drupal.org/node/1674222

For Installing Drush on Mac using Homebrew, check https://www.drupal.org/node/954766


Is there a fast way to see a site without the drupal admin elements?

I put together a simple javascriptlet that I can click on to show/hide most admin elements.  It is kind of a static solution (I'll need to update it periodically as new admin elements appear that need to be hidden), but it's simple.  Works with the Admin-Menu module too.

Just make a new bookmark and paste this into the 'url' field:

javascript:(function($){ if( $('html').data('drupal_clutter_hidden') ){ $('html').data('drupal_clutter_hidden', false); $('#block-search-form').css('z-index', ''); if( $('html').data('drupal_has_adv_toolbar') ){$('body').addClass( $('html').data('drupal_has_adv_toolbar') );$('#admin-menu').show();$('html').removeData('drupal_has_adv_toolbar');} else {$('body').css('padding-top', '64px'); $('#toolbar').show(); }$('.alpha-grid-toggle, .alpha-block-toggle,em.placeholder, #messages, .krumo-root, ul.tabs.primary, .region-inner > .tabs, .contextual-links-wrapper').show(); } else { $('html').data('drupal_clutter_hidden', true); $('#block-search-form').css('z-index', '100'); if( $('body').hasClass('admin-menu') ){var classes = $('body').hasClass('admin-menu-with-shortcuts') ? 'admin-menu admin-menu-with-shortcuts' : 'admin-menu';$('html').data('drupal_has_adv_toolbar', classes); $('body').removeClass( $('html').data('drupal_has_adv_toolbar') );$('#admin-menu').hide();} else {$('body').css('padding-top', '0'); $('#toolbar').hide(); }$('.alpha-grid-toggle, .alpha-block-toggle,em.placeholder, #messages, .krumo-root, ul.tabs.primary, .region-inner > .tabs, .contextual-links-wrapper').hide(); } }(jQuery));

Before:

After:


Try to uncheck the "require this relationship" checkbox in the relationships of your view


Drush > ignore files and folders (ie : IDE conf) when pm-update

Nope.  Drush always does a full directory replacement when upgrading a module with pm-update.  This insures that any files removed from the release do not remain on the disk after the update.  Contributions to improve drush in this area would be appreciated.

As a workaround, if you have your .idea folder checked into git, then you could always use git checkout -- .idea after pm-update to get it back.


Changing drupal project folder breaks links

You need to rebuild theme registry. Download Registry rebuild module.
and apply the following command drush @site rr


How to export feed agregator list and setting as feature?

I have achieved this using aggregator_save_feed() function in hook_install() or hook_update_N() of my custom module. It's not a feature but there is not much difference.

Example:

/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  $feed = array(
    'title' => 'Business',
    'url' => 'http://feeds.bbci.co.uk/news/business/rss.xml',
    'refresh' => 3600, // Update interval in seconds
    'block' => 5, // News items in block
  );
  aggregator_save_feed($feed);
}


or (even better) the term name into the title override?

1) Add Taxonomy term: Name as a field

Check Exclude from display
Uncheck Link this field to its taxonomy term page

2) Click on Title: and put {{ name }}


A couple of things...firstly

$query->condition('data.fk_users_uid', !$uid);

!$uid returns false when used on a positive non-zero integer in PHP (and true for zero, the anonymous user).

You probably meant:

$query->condition('data.fk_users_uid', $uid, '<>');

Secondly, you're using the same alias for both tables. That'll never work. Change the one in the join to data2 or something:

$query->join('foolzz_user_has_user', 'data2', 'data2.fk_user1=:uid OR data2.fk_user2=:uid', array(':uid' => $uid));


How to programmatically copy Webform handler config?

Ended up using the ConfigFactory service, which I believe is fine to do:
$config = \Drupal::configFactory()->getEditable('webform.webform.' . $webform->id());
$config_key = 'handlers.' . $webform_handler_id;
$config->set($config_key, $new_handler_config)->save();


$page not targetting views block but $is_front is. Need help with trying to solve this in any way

See template_preprocess_node() for details on how the $page variable is created.

It is this:

$variables ['page'] = $variables ['view_mode'] == 'full' && node_is_page($node);

So it is only for the full view mode and only if you are viewing the node page of the node that is currently being themed.

So something like this will not work because $page will not be true if $view_mode == 'teaser':

<?php if ($page): ?>
  <?php if ($view_mode == 'teaser'): ?>
    // Views list
  <?php endif; ?>
<?php endif; ?>

There is also currently a bug in the views module where if you have a view on a node page and one of the results of that view is the same node as the one whose page you are on then views will break the $page variable in the node template, causing it to always be FALSE.

To see if that is part of your problem try the patch at https://www.drupal.org/node/1574806

I would not theme a view mode differently in different places. For example the teaser would always look the same regardless of what page it was on. Then you just use:

If you are using teaser already for something else then use a different view mode (you could use the entity view mode module for this if you don't want to code it).


How to display a list of users tagged with taxonomy term, but taxonomy term already used in another display

I you just want a view you can use any path you desire, as long as you have the correct contextual filters. Clone the existing view and adapt the path and whatever else you need.


Put your extensions in ~/.drush.

If add-squeeky-table is a drush command, put it in ~/.drush/squeekytable.drush.inc.  See drushify.

If you want to define add-squeeky-table as a shell alias, put it in ~/.drush/drushrc.php.  See the example Drush configuration file.


Why did ~20k Drupal 7 websites just drop off the map?

If you look back through the statistics they fluctuate quite often really.

Looking at stats for May 26th 2013 (642,589 Drupal 7 sites) or June 9th 2013 (666,573 Drupal 7 sites) I'm not actually certain it can be taken to represent sites disappearing so much as people evaluating Drupal or indeed installing and uninstalling new development snapshot instances.

It's also well worth bearing in mind that the accuracy of the statistics is not 100% and sites which don't use the update manager module don't report in at all. (It is, in some circles, common practice to disable this component once a site goes live if it's being updated in a separate development environment).


How to create custom placeholders on hook_menu, like "%node"?

In order to use a placeholder like %student, you need to define a student_load() function in your module, or an enabled module should define such function. Drupal automatically uses that function when the placeholder is used; that is the reason why you should avoid any conflict between the used placeholders and the existing functions.

In your case, you should use code similar to the following one.

function student_menu() {
  $items['path/%student'] = array(
    'page callback' => 'student_page',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('see student page'),
  );

  return $items;
}

function student_load($id) {
  // Load information from the database; return FALSE in case of error, or when the equivalent database row is not found.
}

function student_page($student) {
  // $student is the value returned from student_load().
  // …
}

Reference

Dynamic argument replacement (wildcard)
Wildcard usage and core's wildcards


Clearing the cache breaks the installation

You need to check the PhP error logs on your server for the reason for the 500 error.

A quick guess would be that your backup excluded the actual cache table structure and not just it's contents.  So when the code needs to access one or more of the tables, it is not there.  The log should show you the specific problem.

An alternative would be to use something like MySQL Workbench and working / non-working databases and start comparing tables between the two.  Missing tables should be fairly obvious.


How do I convert the result fro views_get_view_result() to an array?

This is the entity you are looking for:

$node = $row->_entity;

And the field values:

$values = $node->toArray();

These are all of the values from the node, however if you want the results from the fields configured in the Views UI, see Get result view with formatter programmattically


Upload Data From Excel Sheet to taxonomy

Try Taxonomy CSV import/export

  This module allows you to import or export taxonomy from or to a CSV
  (comma-separated values) file or with a copy-and-paste text.


Need more info! The Devel module has an option for interrupting page redirection and displaying the page you're about to be forwarded to - very handy for debugging redirection. Common redirection issues stem from Rules, Context, Delta, and even just the URL Alias system within Drupal itself.

The transition from Apache to IIS is an interesting hint though - any chance we can take a look at your .htaccess and web.config files to check for differences? Something else to watch for could be trailing slashes and the difference in server handling, as well as the user that PHP is running as under a possibly different CGI.


How to add role selection field to the registration form?

If any module doesn't fit yoour requirement then you can use the  below code
 You can create any custom module or put this code in template.php of your theme.
 function testing_custom_form_alter(&$form, $form_state, $form_id){

if($form_id=="user_register_form"){
    $result = db_select('role', 'r')
                ->fields('r',array('rid','name'))
                ->condition('name',array('administrator','anonymous user'),'NOT IN')
                ->execute()
                ->fetchAll();
    $role   =   array();
    foreach($result as $userRole){

        $role[$userRole->rid] = $userRole->name;
    }

$form['role']['#type'] = "select";
$form['role']['#options'] =$role;
$form['role']['#required'] = 1;
$form['role']['#size']='auto';
    $form['#submit'][] = 'custom_assign_role';

}

}

function custom_assign_role(&$form, $form_state){
   $uid=  $form_state['values']['uid'];

    user_multiple_role_edit(array($uid), 'add_role', $form_state['values']['role']);

}

Hope it will help!


Wrong value when using PHP with the Views module

print_r($row); should give you the structure of the row and tell you the names of the various fields and values etc.


If your intent is showing node content by clicking on node title or similar, you can use the Views Reference Filter filter instead of the Exposed filter. It basically filters one View display with another display. You create one display with a list of node titles, another view display showing node content and add the special filter to the second display. This makes for a very nice user interface for instant filtering.

You can use this answer to a similar case to compare and follow steps: Filter a view by clicking on a link on another view


To alter the region where blocks defined by other modules are placed, you can implement hook_block_info_alter(), which receives the following arguments:

$blocks (passed by reference): the array containing the block definitions, keyed by module, and delta
$theme: the theme for which the blocks are being defined
$code_blocks: the blocks as defined from the hook_block_info() implementations, before their values are overridden by the values obtained from the database


Incorrect branch when adding modules with composer

Make sure you are using the correct repository endpoint for Composer. For Drupal 8, it is https://packages.drupal.org/8.

Your composer.json file should contain a repository key like so:

{
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    }
}


How to use Font Awesome with Bootstrap LESS theme?

Figured it out. Add:

@import "../font-awesome/less/font-awesome.less";

to sites\all\themes\MYBOOTSTRAPTHEME\font-awesome\less\font-awesome.less.


Why I can't I drop field_data and field_revision table in phpmyadmin?

@hampercm explained why directly deleting records and tables from database is not recommended. It is so true that everyone is encouraged to use admin UI or Drupal API to remove the fields and field instances.

But, I guess you know what the best practise is and wanna do that by SQL query with some reason (e.g. company policy. YES, I faced this stupid requirement before)

You are on the right track. Drupal save field and field instances config in field_config and field_config_instance. BUT, Drupal also cache these data in cache table.

So, you need to truncate the cache table.


STEPS:
1. Start creating a new view by clicking "Add new view" link under Admin > Structure > Views.

2.
a) Type "Other Contents by Author" in "View name" text box.
b) [Optional step.] You can check "Description" checkbox and write a description for view. If you wish, check and write "A list which contains other content by author."

Select "Content" from the "Show" select list.
Uncheck "Create a page".
Check "Create a block". You can enter any block title you wish. To limit the items shown in block, type a number in the "Items per page" text box. (You can change it later.)
Click "Continue & edit". At this stage, it is a good idea to click the "Save" button after each alteration/change to save the View.

7.
a) Click the "Advanced" link in right side of the page (if the pane is not open).
b) Click the "add" link in CONTEXTUAL FILTERS row.
c) Check the "Content: Author uid" checkbox from the "Add contextual filters" popup.
d) Click "Apply..." button.
e) Check "Provide default value" option in the WHEN THE FILTER VALUE IS NOT AVAILABLE section.
f) Select "User ID from URL" from the "Type" select list.
g) Check "Also look for a node and use the node author" checkbox.
h) Click "Apply..." button.

8.
a) Click "add" link again in the CONTEXTUAL FILTERS row.
b) Check "Content: Nid" checkbox from the "Add contextual filters" popup.
c) Click the "Apply..." button.
d) Check "Provide default value" option in the WHEN THE FILTER VALUE IS NOT AVAILABLE section.
e) Select "Content ID from URL" from the "Type" select list.
f) Scroll down to the MORE section and check the "Exclude" checkbox.
g) Click the "Apply..." button.

Click the "Save" button and save the view.

You can add different fields and filters and make changes to create solutions for different needs.


The problem with your code is that it needs a submission handler to handle the uploaded file. Using #file as form element type is fine, since that is also done from Drupal core in system_theme_settings().

$form['logo']['settings']['logo_path'] = array(
  '#type' => 'textfield',
  '#title' => t('Path to custom logo'),
  '#description' => t('The path to the file you would like to use as your logo file instead of the default logo.'),
  '#default_value' => theme_get_setting('logo_path', $key),
);
$form['logo']['settings']['logo_upload'] = array(
  '#type' => 'file',
  '#title' => t('Upload logo image'),
  '#maxlength' => 40,
  '#description' => t("If you don't have direct file access to the server, use this field to upload your logo.")
);

The form submission handler (system_theme_settings_submit()) then handles the uploaded file with the following code.

  // Exclude unnecessary elements before saving.
  form_state_values_clean($form_state);

  $values = $form_state['values'];

  // Extract the name of the theme from the submitted form values, then remove
  // it from the array so that it is not saved as part of the variable.
  $key = $values['var'];
  unset($values['var']);

  // If the user uploaded a new logo or favicon, save it to a permanent location
  // and use it in place of the default theme-provided file.
  if (!empty($values['logo_upload'])) {
    $file = $values['logo_upload'];
    unset($values['logo_upload']);
    $filename = file_unmanaged_copy($file->uri);
    $values['default_logo'] = 0;
    $values['logo_path'] = $filename;
    $values['toggle_logo'] = 1;
  }

You could use similar code in a form submission handler, but as described in When theme-settings.php has a managed_file field and a submit callback, " Call to undefined function" error is thrown. such form aubmission handler would not be found because Drupal doesn't load the theme-settings.php file automatically.
If you get around that, and you are able to make Drupal automatically load the file containing the submission handler, you could use the following code in your submission handler.

  if (!empty($form_state['values']['banner_image'])) {
    $file = $form_state['values']['banner_image'];
    unset($form_state['values']['banner_image']);
    $filename = file_unmanaged_copy($file->uri);
    $form_state['values']['banner_image_path'] = $filename;
  }

With theme_get_setting('banner_image_path') you will then get the path of the last uploaded file.
I would do as Drupal does, and add a textfield for the path of the last uploaded file.


In short, to answer your question "How can I specify required fields when programmatically loading a node creation form?" ... use hook_form_alter() and keep your sanity! :)

Here is what I ended up doing after toying with a bunch of proposed solutions I ran across wile learning hook_form_alter() and Drupal's Form API.

I'm sure this solution could be massively improved, but this worked for me and it seems to be fairly simple to manage/maintain.

Managing a Single Content Type With a Complex Workflow Using Node Edit Forms

First after hours of debugging, I decided not to use a custom callback.  Instead I edited the built in node add/edit form using nothing more than hook_form_alter(). (I like hook_form_FORM_ID_alter() instead of hook_form_alter() as it helps me keep my code organized. A personal preference for sure.)

  Note: Drupal 7 use the Administration theme by default for creating
  new nodes/content. You can get around this by unchecking the 'Use
  the administration theme when editing or creating content'
  field at the bottom of 'admin/appearance' page in the admin panel.

Using the Rules Module To Keep Track Of Workflow Stages

I added a new field called "workflow" to my node type (Added through UI at: http://example.com/admin/structure/types/manage/%content_type%/fields) so I could keep track of what stage the user was currently at.

My workflow field ($form['field_workflow']) was a select list with predefined options (stages).

 'new' => 'New', //Default Value For New Nodes
 'foo' => 'Foo',
 'bar' => 'Bar'

I used the Rules module to move the workflow along.  Rules allowed me to move a bunch of the 'submit function' code into rules configuration.  This made updates simpler as I don't need to make as many module edits.

Rules makes it very simple to do things like 'if the node is new, set the workflow to foo after saving' or 'if the workflow is set to foo, set the new workflow state to bar after saving.'

Organization: Ugh...  Setting Up The Actual Flow

First I tried to keep each stage of the workflow as clean as possible by packing alterations in their own functions with a custom naming convention.

function MODULE_stage_new(&$form) {
    //Insert all alterations here for use when node has not yet been saved. It's new!
    $form['field_favorite_color'][LANGUAGE_NONE][0]['value']['#access'] = FALSE;
    $form['field_favorite_food'][LANGUAGE_NONE][0]['value']['#access'] = FALSE;
}

function MODULE_stage_foo(&$form) {
    //Insert all 'foo' stage alterations here.
    $form['field_favorite_color'][LANGUAGE_NONE][0]['value']['#required'] = TRUE;
}

function MODULE_stage_bar(&$form) {
    //Insert all 'bar' stage alterations here.
    $form['field_favorite_food'][LANGUAGE_NONE][0]['value']['#required'] = TRUE;
}

/**
* Implements hook_form_FORM_ID_alter().
*/
function MODULE_form_FORM_ID_alter(&$form, $form_state) {
    /**
    * Place any alterations here that apply to all stages here before the
    * 'if' statements below.
    *
    * I generally place my validation callbacks and CSS additions here.
    **/

    if (empty($form['nid']['#value'])) {
        MODULE_stage_new($form);
    } else if ($arg == 'foo') {
        MODULE_stage_foo($form);
    } else if ($arg == 'bar') {
        MODULE_stage_bar($form);
    }
}

Now that hook_form_alater() is being used exclusively without a custom callback, you shouldn't have any issues with the ['#required'] elements.

Occasionally I would have to add an '#after_build' function (yea, yet another function to keep track of...) but did so with a common naming convetion.  For example, if I needed to add a new stylesheet at the 'foo' stage I would use the following functions.

function MODULE_stage_foo(&$form) {
    //Insert all 'foo' stage alterations here.
    $form['field_favorite_color'][LANGUAGE_NONE][0]['value']['#required'] = TRUE;
    $form['#after_build'][] = 'MODULE_stage_foo_after_build';
}

function MODULE_stage_foo_after_build($form, &$form_state) {
    drupal_add_css(path_to_theme() . "/css/foo.css");
    return $form;
}

I hope this wasn't too overkill or off topic.  I honestly found that sticking to hook_form_alter() for node add/edit form modifications saved me a ton of headaches over how I was trying to do it before.  The custom callback method using module_load_include('inc', 'node', 'node.pages'); never worked for me the way it seemed to for people writing the examples I found.  Then again, I'm still pretty new to Drupal. :)


How do I add the author's image in a view?

You can try using a relationship in your view.

Under advanced in your view -> Relationships -> add and choose Content: Author.
You should then have the option to add the user picture in your Fields section.


Can adding a cache tag create another cache row in database

First of all you should add tags of all nodes/terms you use to build the breadcrumb. You can't set too many tags, because a tag doesn't influence how many cache entries are stored.

This is only a problem you have by adding cache contexts. By default this is url.path.parent. But if you use for example the title of the current node, then you need url.path. When you have 300.000 nodes this can indeed make caching quite useless and you could consider setting a cache max-age of 0 to disable caching. Perhaps by doing this you also benefit from lazy loading of the breadcrumb block by Big Pipe, if this is for logged-in users, I've never tried this. And for anonymous users pages are cached for each path anyway.


How to include jQuery UI on a page without PHP?

How about creating a 'scripts.js' file in your theme folder and then simply either add it in using the drupal_add_js method in template.php (the same method you are using above) or if it's something that's more global, include it in your theme's .info file. You will need to tweak the JQuery call according to 7 standards. I use both of these methods all the time and it works great.

So in your 'scripts.js' file you will have something like this:

(function ($) {
Drupal.behaviors.myTheme = {
attach: function(context, settings) {

// your custom JQuery here

}
};
})(jQuery);

... and then call that however you wish as I have described above. You can also have a look at this post: Managing JavaScript in Drupal 7


Resize & Crop Image Style Lowers Resolution

The jpeg quality is defined at 75%, this can be changed at /admin/config/media/image-toolkit


related news and articles block on content page based on tags

most probably you have more tags on the related content, so it is shown several times. try selecting "distinct values" in Query settings


Date picker libraries are missing in specific page

Do you have a custom theme? If so, the easiest way to ensure jquery.ui.datepicker loads on every page is to list it as a dependency in your theme libraries file. E.g.

# @file /themes/custom/my_theme/my_theme.libraries.yml

# My theme global library.
global:
  js:
    js/my_theme.js: {}
  css:
    theme:
      css/my_theme.css: {}
  dependencies:
    - core/jquery
    - ...
    - core/jquery.ui.datepicker

Alternatively, you can add it via a theme or custom module.

/**
 * Implements hook_preprocess_page().
 */
function my_theme_or_module_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'core/drupal.date';
}


Is it possible to add a CiviCRM API to the Webform CiviCRM integration module and how would I do that?

I found this old link for plans to add arbitrary api calls to the module, but it doesn't appear to have ever been implemented:
http://forum.civicrm.org/index.php?topic=22304.0

But it appears that I could use hook _webform_submission_presave to execute the api call when the webform is submitted.


Try this:

$entity->set('field_geofield_name', [sprintf("'POINT (%s %s)'", $longitude, $latitude)]);

Cheers!


How does one override default icons used to dislpay uploaded files from within a module instead of a theme?

I think you would want to do something along these lines:

function YOURMODULE_theme_registry_alter(&$theme_registry) {

  if (!empty($theme_registry['file_icon']['function'])) {
    $theme_registry['file_icon']['function'] = 'YOURMODULE_file_icon';
  }

}

and then create YOURMODULE_file_icon() based upon the core theme_file_icon():

/**
 * Returns HTML for an image with an appropriate icon for the given file.
 *
 * @param $variables
 *   An associative array containing:
 *   - file: A file object for which to make an icon.
 *   - icon_directory: (optional) A path to a directory of icons to be used for
 *     files. Defaults to the value of the "file_icon_directory" variable.
 *
 * @ingroup themeable
 */
function YOURMODULE_file_icon($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);
  $icon_url = file_icon_url($file, $icon_directory);

  return '<img class="file-icon" alt="" title="' . $mime . '" src="' . $icon_url . '" />';
}

and change up either $icon_directory to point within your module and include all of the various file type icons there, or do a switch or if on the $mime type and grab them from wherever you want, eg, if it's the special mime type you want, grab them from your module's directory, otherwise, grab them from the core/default directory.


A time field instead of end date in drupal 7 date field

The Date single day module for Drupal 6 worked great for this use case. There isn't a 7.x version yet, but there is an issue to port it.


check_markup() will:

  Run all the enabled filters on a piece of text.

Since one of those filters will probably be the HTML corrector, you'll get the

 tags wrapping your text string.


It's not being controlled, it controls.

The widget allows you to edit the comment status of a given node/entity. That is stored in the comment field, and the comment formatter, that displays the comments/comment form is then using it to decide what to show.


The Views module is typically how this kind of thing is done. There are options for outputting tables or unstyled divs that you can theme yourself.


I've got it sorted out.
The images in the LIs were too bug and covering over the effect. Once I resized the images everything was fine.


How to retrieve the link and description in a custom file field twig template

File link: {{ file_url(item.content['#file'].getFileUri()) }}

File description: {{ item.content['#description'] }}


:source you can understand as parent of that node when you get in touch with drupal translation you can easily understand what hierarchy this :source is referring to.

as per above link:

Translations are managed in sets of posts, which represent the same information in different languages. Only content types for which the administrator has explicitly enabled translations could have translations associated. Translations are managed in sets with exactly one source post per set. The source post is used to translate to different languages, so if the source post is significantly updated, the editor can decide to mark all translations outdated.

so :source here is referring to the parent node from which it gets translated (if there are translation enabled if not then you need not to worry about :source)


You need to enable the taxonomy field to be used as attributes so it is exposed to the cart form.

Here you've got the step by step guide here: https://drupalcommerce.org/commerce-kickstart-2/adding-taxonomy-field-product-attributes


Get all fields for a content type using REST

The /entity/entity_form_display/{entity_form_display} should works.

Example:

/entity/entity_form_display/node.article.default?_format=json

It will return json like this:

{
"uuid": "058dd73d-366d-466d-9393-ad0d5d44e928",
"langcode": "en",
"status": true,
"dependencies": {
    "config": [
        "field.field.node.article.body",
        "field.field.node.article.comment",
        "field.field.node.article.field_image",
        "field.field.node.article.field_location",
        "field.field.node.article.field_tags",
        "image.style.thumbnail",
        "node.type.article"
    ],
    "module": [
        "comment",
        "image",
        "path",
        "text"
    ]
},
"id": "node.article.default",
"targetEntityType": "node",
"bundle": "article",
"mode": "default",
"content": {
    "body": {
        "type": "text_textarea_with_summary",
        "weight": 1,
        "region": "content",
        "settings": {
            "rows": 9,
            "summary_rows": 3,
            "placeholder": ""
        },
        "third_party_settings": []
    },
    "comment": {
        "type": "comment_default",
        "weight": 20,
        "region": "content",
        "settings": [],
        "third_party_settings": []
    },
    "created": {
        "type": "datetime_timestamp",
        "weight": 10,
        "region": "content",
        "settings": [],
        "third_party_settings": []
    },
    "field_image": {
        "type": "image_image",
        "weight": 4,
        "region": "content",
        "settings": {
            "progress_indicator": "throbber",
            "preview_image_style": "thumbnail"
        },
        "third_party_settings": []
    },
    "field_location": {
        "weight": 121,
        "settings": [],
        "third_party_settings": [],
        "type": "options_select",
        "region": "content"
    },
    "field_tags": {
        "type": "entity_reference_autocomplete_tags",
        "weight": 3,
        "region": "content",
        "settings": {
            "match_operator": "CONTAINS",
            "size": 60,
            "placeholder": ""
        },
        "third_party_settings": []
    },
    "path": {
        "type": "path",
        "weight": 30,
        "region": "content",
        "settings": [],
        "third_party_settings": []
    },
    "promote": {
        "type": "boolean_checkbox",
        "settings": {
            "display_label": true
        },
        "weight": 15,
        "region": "content",
        "third_party_settings": []
    },
    "status": {
        "type": "boolean_checkbox",
        "settings": {
            "display_label": true
        },
        "weight": 120,
        "region": "content",
        "third_party_settings": []
    },
    "sticky": {
        "type": "boolean_checkbox",
        "settings": {
            "display_label": true
        },
        "weight": 16,
        "region": "content",
        "third_party_settings": []
    },
    "title": {
        "type": "string_textfield",
        "weight": 0,
        "region": "content",
        "settings": {
            "size": 60,
            "placeholder": ""
        },
        "third_party_settings": []
    },
    "uid": {
        "type": "entity_reference_autocomplete",
        "weight": 5,
        "region": "content",
        "settings": {
            "match_operator": "CONTAINS",
            "size": 60,
            "placeholder": ""
        },
        "third_party_settings": []
    }
},
"hidden": []
}


How to add HTML to page following user/register to track Google AdWords conversions?

In case of GA or some of the social plugins, you can just add the code in a custom block with FULL HTML format, so you can try creating custom block (maybe in footer) with your code and set the pages where it will appear to user/register


Google rich snippets, custom content type

This can be accomplished by printing the values you're self instead of letting fivestar do the default rendering.

Here's an example:

$results = fivestar_get_votes('node', $node->nid, 'tag');
//$results now has everything you need to do microformats

The results will have the average and counts. You can print those variables where ever you like. Also note you probably should disabling the text display on the fivestar widget.

There is also an issue over at http://drupal.org/node/901260.


As Oswald mentioned, you have to implement some hooks in your custom module to redirect your form submission. Here is a quick example (assume your form_id is 'webform_client_form_1'):

// hook_form_alter()
function customform_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'webform_client_form_1') {
    // Add form_submit() handler
    $form['#submit'][] = 'customform_webform_submit';
}

}

// form_submit()
function customform_webform_submit($form, &$form_state) {

// Submited values are in $form_state['values']['submitted_tree']
$field_values = customform_webform_values( $form_state['values']['submitted_tree']    );

// Build URL Query
$query = '';

foreach ($field_values as $value) {
    $query .= $value . '&';
}

$redirect = array (
                'myphpapplication',
                array (
                    'query' => array (
                        'query' => rtrim( $query, "&" )  // Get 'query' values with $_GET['query']
                    )
                )
            );

$form_state['redirect'] = $redirect;

}

// Recurse through webfrom submited values
function customform_webform_values($component) {

static $webform;

foreach($component as $key => $value) {
    if (is_array($value)) {
        customform_webform_values($value);
    }
    else {
        $webform[$key] = $value;
    }
}

return $webform;
}


You could add an entity_reference field to the profile and reference the node in that field.


Adding links to EntityForms on submission confirmation page

One rules action you could use would be the System > Show a message on the site where you could use replacement patterns to build your recommended links to other forms. This way users would always see the message regardless of the initial entityform redirection page. (This is actually a very handy concept and I will file it away for future use :)

Note: in order to get the replacement patterns you need, you may need to add conditions to your rule in order to make the right data available to the rule.


List all tags associated from specific content type only?

Thomas - the answer is going to assume you are using Drupal 7, since you didn't specify.

Likely, the issue here is that you are using Taxonomy terms as the base of your view and therefore not able to select Content: Type as a filter.

To get that filter to show up, you need to add a Relationship (under the Advanced section of the view options) for Taxonomy term: Content with term.

After you do that, then Content: Type will show up in your filter list.


How to modify the class names of socialmedia module

As you can see here https://jsfiddle.net/81kbx4f4/, if you do an inspect element, you will see them here too.

Those are added by facebook and it's not something that you can control.


How to add discount for final subtotal in ubercart?

Try Ubercart Simple Discount

This module works with rules, so you can add a condition in rules.
You may not get an 'easy plug and play' module for doing this, but the result you want may be possible with some Rules


How to get only field value in View template

You must specify which one of Views template files you are working on, If it is views-view-fields.tpl.php then $fields variable is availabe but if it is not views-view-fields.tpl.php then $view object is available. use kpr($variable) to get the $variable available properties.

You can also use hook_preprocess_views_view_fields(&$var) to set the values of fields in $var array then retrieve them in fields template file

UPDATE:

First define the following function in your template.php file

    function THEME_preprocess_views_view_fields(&$variables)
    {
        $view = $variables['view'];
        if($view->name == "THE_VIEW_NAME")
        {
              $variables['my_field'] =strip_tags( $variables['fields']['field_myfield']->content);
              $variables['title'] =strip_tags( $variables['fields']['title']->content);
              $variables['theme_hook_suggestions'][]='views_view_fields__SOMETHING';
         }
     }

By this function the $my_field and $title variables are available in the views-view-fields--SOMETHING.tpl.php file. You have to create views-view-fields--SOMETHING.tpl.php file in your theme directory and use above variables in it. views-view-fields--SOMETHING.tpl.php file is created to theme every output (record or row of columns) of your View. Make sure you are using - instead of _ when creating views-view-fields--SOMETHING.tpl.php file.

$view variable is a variable that contains every detail of the current View. you can use kpr($view) to see its results.


Button that changes form field value based on other field values (D8)

I found the solution myself. In case someone else stumbles upon this: In the ajax callback you need to change #value instead of #default_value.

So this callback works:

function sumValues_ajax_callback(array &$form, FormStateInterface $form_state)  {
   $n1 = $form_state->getValue('number1');
   $n2 = $form_state->getValue('number2');
   $sum = $n1 + $n2;
   $form['sum']['#placeholder'] = $sum;
   $form['sum']['#value'] = $sum;
   return $form;
}


Manual Ubercart Views Taxonomy Order (D6)

Ended up using taxonomy manager: http://drupal.org/project/taxonomy_manager

Allows you to setup weights for Taxonomy Terms easily and quickly.

I then had to adjust the view to sort terms by Taxonomy weights in order to order the terms accordingly in my views.


How to set a contextual filter based on an entity reference field

On the View you started (Podcast Views) the Contextual filter you need to add is the Entity reference field, not the Nid.

Here are the settings for it:
When the filter value is NOT available:
Provide default value
Content Id from URL
When the filter value IS available or a default is provided (optional)
Specify validation criteria
Validator Content
Emission

Place the block on Emission nodes. The block will take the NID of the Emission node it's on, pass it to the Entity reference contextual filter to match Emission in question, and Views results will be limited to only Podcasts which reference that Emission through the field.

You don't need the Relationship unless you plan on displaying Emission information in this block, which you probably don't.

Another approach would be through the opposite side, through Emission Views, where you list Emission content type, but you don't have to display any Fields concerning Emission. Instead you'll display only the Title field of the Podcast that is referencing that Emission.

You do that by adding the Contextual filter ID (it's not the same field as above, but the settings are are the same).

And you have to add the Relationship for the Entity reference field, but the reverse one (Relate each Content with a field_emission set to the content.)!

Then you add the Title Field, but make it uses the above Relationship. This will make the Title Field show Podcast title, and not Emission title. Set its label to something like "Podcasts referencing this Emission".

Make sure to tick "Hide if empty" under "No results behavior" so nothing is output on Emission pages that have no Podcasts referencing them.

And in the end display that block on Emission pages.


Where are valid password reset tokens stored?

I do not think Drupal stores password tokens. I have used drush uli many times and it generates a one time login link, similar to link generated by user_pass_reset_url(). You should see the functions coding


How to realize ajax on a form element with autocomplete

I managed to find the solution.
My code works with an event "autocompleteselect".

Here's an example of code

$form['autocomplete_field'] = [
            '#type' => 'textfield',
            '#title' => t('Autocomplete search'),
            '#autocomplete_route_name' => 'autocomplete_route',
            '#ajax' => [
                'callback' => '::ajaxFunctionAfterAutocomplete',
                'event' => 'autocompleteselect',
            ]
        ];


What is the preferred way to delete la arge amount of data from a Drupal site?

I'm not seeing any simple way to truncate (or truncate from X) a table like this.   The tables that would contain field data would be all mixed up and not nicely sorted.

In this case I would;

Start with a view that generated a list of node IDs based on your
select criteria (content type, status, older than date published,
etc)
Write a custom module with a drush command
Load the node IDs
Either node_delete($nid) OR...
Examine what node_delete() does and delete * from {table} where nid= $nid

The tables node_delete() may touch will largely be dependant on your content types.  node_delete() will do the job, doing it my hand will take more time to prepare but may be faster to run. With the volume of records you're talking about a few milliseconds per delete may save a decent chunk of time.


Best CSS and JS aggregation/minification strategy for D7

For D7, there's Core Library which has a learning mode that aggregates based on real-world statistics about your site.

If you want to brute-force everything into one giant aggregate, I've written an article with some sample code:

/**
 * Implements hook_js_alter().
 */
function mymodule_js_alter(&$javascript) {
  uasort($javascript, 'drupal_sort_css_js');
  $i = 0;
  foreach ($javascript as $name => $script) {
    $javascript[$name]['weight'] = $i++;
    $javascript[$name]['group'] = JS_DEFAULT;
    $javascript[$name]['every_page'] = FALSE;
  }
}

/**
 * Implements hook_css_alter().
 */
function mymodule_css_alter(&$css) {
  uasort($css, 'drupal_sort_css_js');
  $i = 0;
  foreach ($css as $name => $style) {
    $css[$name]['weight'] = $i++;
    $css[$name]['group'] = CSS_DEFAULT;
    $css[$name]['every_page'] = FALSE;
  }
}

Drupal.org issue #1034208 also proposes relaxing the strict ordering requirements slightly.


Webform token for select field value (not key)

It turns out the issue was with the form alter hook. I had updated the #options which made the form work just fine, however I needed to update the webform component with a line delimited list of key|value pairs.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {

    // get all tours
    $query = db_select('node', 'n');
    $query->fields('n', array('nid', 'title'));
    $query->condition('n.type', 'tour');
    $query->join('field_data_field_tour_type', 't', 't.entity_id = n.nid');
    $query->fields('t', array('field_tour_type_value'));
    $result = $query->execute();

    // group by tour type
    $options = array();
    $flat_options = array();
    while ($row = $result->fetchObject()) {

      // tour type 1
      if ($row->field_tour_type_value == 1) {
        $options['Type 1'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
        $flat_options .= $row->nid . '|' . date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title . "\n";
      }

      // tour type 2
      else if ($row->field_tour_type_value == 2) {
        $options['Type 2'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
        $flat_options .= $row->nid . '|' . date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title . "\n";
      }
    }

    ksort($options);

    // set the tour options correctly
    $form['submitted']['tour']['#options'] = $options;
    $form['#node']->webform['components'][7]['extra']['items'] = $flat_options;
  }
}

I've added the $flat_options variables to handle this and assigned it to the proper field in my form array. Keep in mind referencing the component by number [7] is not the cleanest and most maintainable way to do this but it works in a pinch.


How do I let users with a certain role add nodes but use the front end theme (not the admin theme)

Role Theme Switcher seems to be what you need:

Useful Drupal module to assign separate themes for different roles (including anonymous) in your system.
Often you want to separate Drupal administrative interface from frontend. You can do this assigning appropriate theme for you as user. What to do if you want to show different theme for non-authorized user?


To solve the problem set '#validated' => 'TRUE' in your form element definition.

Example:
 form['my_dynamic_select'] = array(
 …
 '#type' => 'select',
 '#validated' => TRUE
 …
 )

Reason:

If we are using a dynamically populated SELECT (dropdown) via AJAX this error will pop up. When a value is not present in options array, Drupal will consider it as illegal. So the user couldn't inject an illegal value into the database.

But in our case it's totally ok, so we need to use the attribute 'validated' => TRUE to skip the validation.

Source: An illegal choice has been detected. Please contact the site administrator.


How do I set "Add to Cart form" css globally using Commerce Kickstart as basis?

My solution is not elegant, but it got the job done:

Using inspect element, identified css that dictating styling of the "Add to Cart" form elements that I wanted to keep. This css was buried in the subtheme_style.css file associated with "Product" only: .node-product-type.
Copied css to start of subtheme_style.css file
Removed the references to .node-product-type. This set all the select widget fields and all the "Add to cart" buttons to the desired style/look.

This seems like an odd way to go, but also means that I don't have to differentiate among all product display types, as I build out panel displays that are unique to each one. What would you have done differently?

This is the css that I repurposed and generalized by deleting the reference to .node-product-type:

.field-name-field-product form.commerce-add-to-cart label {
  float: left;
  margin-right: 5px;
  width: 45%;}

.field-type-commerce-product-reference form.commerce-add-to-cart .form-submit {
      background-color: #9E4934; /*CG Add to Cart button*/
      background-image: url("../images/bg_add_to_cart.png");
      background-position: 90% 50%;
      /* LTR */
      background-repeat: no-repeat;
      border: 0;
      -moz-border-radius: 8px;
      -webkit-border-radius: 8px;
      -khtml-border-radius: 8px;
      border-radius: 8px;
      color: #ffffff;
      font-family: "Open Sans", sans-serif;
      font-size: 17px;
      font-weight: 400;
      float: right;
      margin-top: 40px;
      margin-left: 5px;
      /* LTR */
      padding: 5px 50px 5px 10px;
      /* LTR */ }

.field-type-commerce-product-reference form.commerce-add-to-cart .form-submit:hover {
        cursor: pointer; }


You dont have to use tokens there. You can use hook_form_alter to add the correct node titles to the form at that stage. You write a custom query, and populate the empty list.


What are Hooks, Actions and Triggers in basic terms

Hooks are one concept, and actions-and-triggers are a separate concept.
See What is the basic concept behind hooks? for the canonical explanation of hooks (there are some excellent answers to that question, there would be no point in trying to reproduce them here).
Actions and Triggers are best explained in Using the new Actions and Triggers functions in Drupal 6 (the concept is the same for Drupal 7).
From that page:

What is a trigger?
Triggers are Drupal events such as saving or updating a post, a user logging in or someone viewing a piece of content. Think of it like a trigger for an argument – when the trigger happens (ie. A disagreement), an Action happens (the argument). This allows you to heavily customize Drupal and paves the way to amazing new implementations of the software.
What is an action?
Actions are something that happens after the trigger. For example, you could redirect the user to a page, send an email notice to administrators or display a special message. This can allow you to integrate Drupal into other systems.

You might also be interested in the Rules module which is

a replacement with more features for the trigger module in core

It's far more powerful than the trigger module and has a lot of extra features.


How do you theme the taxonomy description field?

The term description isn't a field, it's actually a property of the taxonomy term entity and doesn't have a theme/template associated with it.

It's built up in taxonomy_term_view() as a standard render array:

$build['description'] = array(
  '#markup' => check_markup($term->description, $term->format, '', TRUE),
  '#weight' => 0,
  '#prefix' => '
',
  '#suffix' => '
',
);

So to theme it you could write a preprocess function for the taxonomy term template, maybe something like:

function MYTHEME_preprocess_taxonomy_term(&$vars) {
  if (!empty($vars['content']['description'])) {
    $vars['content']['description']['#prefix'] = '
';
    $vars['content']['description']['#suffix'] = '
';
  }
}


Adaptivethemes and panels - how to create custom layout?

Panels - how to create custom layout?

In Panels, (or Adaptive), find the directory layouts directory.

In it, each layout has it's own directory with a couple of files in it.

Copy any of these directories, rename all the files to the new name of the directory, and you have a new plugin.

Also see the comment for the function at_get_plugins which provides Ctools specific integration so you can subtheme AT and have new layouts in your subtheme.


How to embed webform to update existing submission

Existing webform submissions are entities and you can use the entity form builder service to build the form:

// load the webform submission entity
$webformSubmission = WebformSubmission::load($submissionId);
// build a form for the entity
$webform = \Drupal::service('entity.form_builder')->getForm($webformSubmission, 'edit');


I get "You are not authorized to access this page" when I try to load a view with Ajax

Try with page arguments in hook_menu:

function custom_api_menu() {
  $items['ajaxgettip/nojs/%'] = array(
      'page callback' => 'custom_api_test_ajax',
      'page arguments' => array(2),
      'type' => MENU_CALLBACK,
      'access callback' => TRUE,
  );
  $items['ajaxgettip/ajax/%'] = array(
      'delivery callback' => 'ajax_deliver',
      'page arguments' => array(2),
      'access callback' => TRUE,
  );
  return $items;
}


Add extra html to ubercart cart and checkout pages

You can achieve this in following ways,
1) define a template file:- in your template.php, define a template file for checkout page

/**
* Implements hook_theme().
*/
function themename_theme($existing, $type, $theme, $path) {
  $items = array();

  $items['uc_cart_checkout_form'] = array(
  'render element' => 'form',
'template' => 'uc-cart-checkout-form',
  'path' => $path . '/templates/',//where the tpl files are located
   );

   return $items;
 }

Then in your templates folder create a file uc-cart-checkout-form.tpl.php, here you can render your form with additional htmls

2) Override the theme

Check this instruction on Ubercart How to Theme the Checkout pane in Ubercart 3, by following this you can include your custom html.

Similarly the above methods are applicable to cart page also


AJAX pagination with back button Drupal view

There is a module views_ajax_history which uses https://github.com/browserstate/history.js to maintain the current state of page and push them into browse history with HTML5 history api. This library support fallback if history api is not supported by older browser.


Security Review - Untrusted users are allowed to input dangerous HTML tags

Plain text is just that, no html tags, so this shouldn't be a security issue.

Perhaps the img tag is considered dangerous because it is possible to use a specially crafted png or jpg to launch an attack against a users browser.


From what you're describing it sounds like you need Faceted search. I'm not sure if Views filters can give you the functionality you're looking for.

Have a look at the Search Api module, it provides faceted search widgets which behave the way you described.

https://drupal.org/project/search_api


How to show thumbnails gallery images in the footer first section?

To do that you can use a views block to list all the pictures you want. After that you can use an image style to crop them like you want.

For the theming, feel free to use Views Theme Suggestion and Views Preprocess(ex : here) to add features et style images and content wrappers.

I hope it helped you.


Looks like my issue was here:

function _my_module_form($form_state) {

Should have been:

function _my_module_form($form, &$form_state) {


I managed to get it working. The missing link was the sites/sites.php file.
Although I did provide that, it started working after I put the following in it:

$sites = array(
   'localhost.owtest' => 'owtest',
   'localhost' => 'default',
);

I can now browse to localhost/owtest and have a completely different content collection that is used by the localhost site itself.
Now I am facing a style problem, I keep tring...

Ruud


How to stop twig debug from breaking HTML when inside tags?

You can apply |render|striptags|trim twig filters:

{{ fields.title.content }}

  If you want to save (not delete) for example div or img tags you can also write:

  {{ fields.field_image.content|render|striptags('
, ')|trim }}

Seen here https://www.drupal.org/node/2672656#comment-11821896


cache : "drush cr" versus admin toolbar "flush all caches"

Drush's cache-rebuild command does the following:

Clears the APC cache
Bootstraps Drupal
Calls drupal_rebuild()
Clears the Drush cache (to maintain consistency with Drupal 7's drush cache-clear command)

Source: https://drupalize.me/tutorial/clear-drupals-cache?p=2512.

In drupal 8 it is recommended to use cache-rebuild instead of cache-clear.
Your dev settings shouldn't matter for this.

in drupal 8 the drush cc all is deprecated and yo should always use drush cr.


Translations have to be entered manually... always.  There is no "automatic machine translation" function provided by Drupal core or the Internationalization suite of modules.

Putting a string inside t() simply makes it available to Drupal's translation subsystem for translation; the string will still be displayed "as is" until it is translated manually.

To translate strings manually from the UI, if you have the Locale module enabled, you can go to the Translate interface page.  (On Drupal 7: /admin/config/regional/translate/translate)


How can I export the "Enable for OG Menus" content type option status in a feature?

I was missing a Strongarm variable.

Strongarm lists:

og_menu_assignment
og_menu_block_links
og_menu_context_limit
og_menu_create_by_default
og_menu_enable_page
og_menu_enable_section
og_menu_hide_create_option
og_menu_hide_help
og_menu_max_menus_per_group
og_menu_show_blocks
og_menu_show_nodetype

The variables I needed were:

og_menu_enable_page
og_menu_enable_section

og_menu appears to create a variable per content type you want to use it on. In my case I had two content types, page and section. Once I added those variables to my feature, it successfully exported the setting.


Trying to integrate Rate-Widget (Rate-Module) into Status-Block (Statuses/Facebook Style Status)

A couple problems here.

I assume you are using Drupal 7, and therefor this module:
https://drupal.org/project/statuses

Which is the successor of facebook_status module for D6.

Your hook is for the D6 module, and does nothing for the D7 module.

I couldn't find the replacement hook in the new D7 version:
http://drupalcode.org/project/statuses.git/blob/bc7e520:/api.php

The other problem, is that 'statuses' are their own 'entity' - for lack of a better word.  They are not actually even 'entities' in the Drupal terminology.  Just some entries in it's own DB table.

The reason this is a problem, is your code is looking to load a node from path when on a path like (/statuses/5), but a 'status' is not a node.

As far as a solution, you'll have to decide a new road to go down, but at least this helps you understand the situation.


Add Custom Bulk operations to an existing Views

hook_views_default_views_alter() is the sauce you're after


Back button form in node linking back to view

You can not do this with the views module alone. A views link will simply link you to a node page and when you are on the node page, it does not know how you got there.

you could do this, which is basically the same as pressing the browser back button:

<input type="button" value="Go Back" onclick="window.history.back()" />

or this:

<?php
  $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
  echo 'go back';
?>


You have five options.

Use the https://drupal.org/project/special_menu_items module
Do something like node/16#gohere (I'm not sure if you have a static page this is for)
Create a module to either edit a menu item or add one
Backport the https://drupal.org/project/void_menu module
Make your own module to do this :)

Sadly there is no way to do this by default.


Profile Completeness reminder to the user

You could take a look at Profile Complete Percent (for core Profile module) Content Complete (if using Content Profile).

If you are using Content Profile, here is an article to assist setting up with Rules: Measure node completion in Drupal, part 3.  I'm sure you could probably get a Rules workflow going with core Profile module as well.


Both of these are forms, so you can do something with a hook_form_alter.  The easiest thing to do is do a View Source, find the form, and look at the ID on the <form> element.

The permissions form is user_admin_permissions.  My suggestion would be to alter the form to add a new submit handler, eg

function mymodule_form_user_admin_permissions_alter(&$form, &$form_state, $form_id) {
  $form["#submit][] = 'mymodule_log_permission_change';
}

The settings changes are going to be tricky, as they are spread across many, many forms.  The idea is the same, you just need to figure out whether you are on a setting for or not.  You could alter all of the important setting forms, or you could try using the base hook_form_alter() and check the $form_id.  You could also try checking the URL from withing the submit handler, as many of the settings live under /admin.


How do I hide the display of a field if another field is set?

Use the #states property. Here is a tutorial.

Alternatively just use the Conditional Fields module which provides a nice easy to use UI making it easy to set up multiple rules.


How to show a image preview of the files in IMCE file browser?

I have seen it work sometimes, but I can not tell does not always work. I will recommend you opening an issue on the IMCE module page in Drupal.org. See it working on the image below:


Views url paths not using proper url on localhost

You need to alter your .htaccess file:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal


Save tags in parent and children of vocabulary with shs module

on taxonomy/term/% view, enter contextual filter

  "Has taxonomy term ID (with depth)"

and change the depth settings to -1 and children view will take parent tag nodes too.


How to add a class for forgot password link?

Why don't you create a custom block in "admin/structure/block/add," and then add that link with that class into the block? Place the block where you want to place it. It should still fulfill the same requirements.


How to reset/save $_SESSION variables in forms for each user?

By default Drupal's sessions are kept for about 23 days. You can modify this in settings.php. Look for gc_maxlifetime and cookie_lifetime to reduce it to 0 so sessions are destroyed when the browser is closed.

This will effect logged in users too so when they close the browser they will also be logged out.

On a side note if you were unaware drupal already have flood control and will block IPs for multiple failed login attempts


The page title of the user profile page (like example.com/user/1) is generated by format_username(). If you want to control the username everywhere it occurs in the site, you can implement hook_username_alter in a custom module.

If you just want to change title on the user profile page, you could add THEMENAME_preprocess_page to your template.php to override $variables['title']. An example (untested code):

<?php
/**
 * Preprocess function for page.tpl.php.
 * Replace 'THEMENAME' with the name of your theme.
 */
function THEMENAME_preprocess_page(&$variables) {
  // Only act when the first part of the url equals 'user', the second
  // part is a number and the third part is empty.
  $arg = arg();
  if ($arg[0] == 'user' && is_numeric($arg[1]) && empty($arg[2])) {
    // Do stuff to create the desired username and set the $title variable for the template.
    $variables['title'] = $variables['firstname'] . ' ' . $variables['lastname'];
  }
}
?>


Contextual links only appear the first time

I figured out that someone else has hit this error, and has contributed a patch for it:

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

The patch stops the Contextual Links module from adding a contextual link placeholder to the array if it's already in there.  I'm still not quite sure why there's a cookie for the contextual link (as I said in the comment above) if it's going through them and adding them anyway.  If anyone else knows more about this issue, feel free to answer.


A menu block won't show up for second language

In the specific menu edit mode: structure/menu/manage/your-menu/edit alter the Translation Mode.


in your settings.php, uncomment

# if (file_exists(__DIR__ . '/settings.local.php')) {
#   include __DIR__ . '/settings.local.php';
# }

so it looks like this:

if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

then in the same directory edit the settings.local.php to have your local settings.

Then add settings.local.php to your .gitignore file

That way, you can keep local settings that differ from the settings on dev.

So your dev server would have it's own unique settings.local.php file that differs from your local settings.local.php file.

If you need to check your database settings, you can add this at the bottom of settings.php

dump($databases); die();

You should see your correct settings (you can do this on both your local and your dev site to verify, then remove the dump command once you have verified.


Why is this Drupal services RESTful API not working?

Later of try and try, when read from other tutorial, i make a resource with rest, soap for me is imposible in drupal, i try but without success, you can copy and page this code and modify only the custom module name and hooks.

/**
 * Implements hook_ctools_plugin_api().
 */
function core_custom_webservice_ctools_plugin_api($owner, $api) {
  if ($owner == 'services' && $api == 'services') {
    return array(
      'version' => 3,
      'file' => 'core_custom_webservice.services.inc'
    );
  }
}

function core_custom_webservice_services_resources() {
  $resources = array(
    'webservice_resources' => array(
      'operations' => array(
        'retrieve' => array(
          'help' => t('Response of webservice'),
          'file' => array('type' => 'inc', 'module' => 'core_custom_webservice', 'name' => 'core_custom_webservice.resource',),
          'callback' => '_core_custom_webservice_get_response',
          'access callback' => '_core_custom_webservice_access',
          'access arguments' => array('view'),
          'access arguments append' => TRUE,
          'args' => array(
            array(
              'name' => 'parameters',
              'type' => 'string',
              'description' => 'The parameters that define requested data',
              'source' => array('path' => '0'), // first argument in the url
              'optional' => FALSE,
            ),
          ),
        ),
      ),
    ),
  );
  return $resources;
}

/* * *************************************************************************************************
 * Access callback
 * For now only view/retrieve is implemented and if the user is logged in, he gets access
 */

function _core_custom_webservice_access($op) {
  global $user;
  $access = TRUE;

  switch ($op) {
    case 'view':
      if ($user->uid) {
        $access = TRUE;
      }
      break;
  }

  return $access;
}

function _core_custom_webservice_get_response($arg) {
  $response = 'something';
  return 'print '.$response;
}

try again in your service path and success with
http://path.come/?q=webservice_server_rest/webservice_resources/string.json


What's the best file permission to drupal's files and directories?

Drupal has already a well documented page with all informations you are looking for.


/**
 * Implements hook_node_info().
 */
function non_recruiter_node_info() {
  // We define the node type as an associative array.
  return array(
      'job_template_2' => array(
          'name' => t('Job Template 2'),
          'base' => 'job_template_2',
          'description' => t('A content type for posting your jobs.'),
          'title_label' => t('Job Template 2'),
          'locked' => TRUE,
      ),
  );
}

/**
 * Implements hook_node_type_insert().
 */
function non_recruiter_node_type_insert($content_type) {
  if ($content_type->type == 'job_template_2') {
      $body_instance = node_add_body_field($content_type, t('Job Description'));
        $body_instance['display']['non_recruiter_list'] = array(
        'label' => 'hidden',
        'type' => 'text_summary_or_trimmed',
    );

// Save our changes to the body field instance.
field_update_instance($body_instance);

// Create all the fields we are adding to our content type.
foreach (_non_recruiter_installed_fields() as $field) {
  field_create_field($field);
}

// Create all the instances for our fields.
foreach (_non_recruiter_installed_instances() as $instance) {
  $instance['entity_type'] = 'node';
  $instance['bundle'] = 'job_template_2';
  field_create_instance($instance);
}
  }
}

/**
 * Implements hook_form().
 */
function job_template_2_form($node, $form_state) {
  return node_content_form($node, $form_state);
}

function _non_recruiter_installed_fields() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'node_example_quantity',
          'cardinality' => 1,
          'type'        => 'text',
      ),
  );
}

function _non_recruiter_installed_instances() {
  return array(
      'non_recruiter_quantity' => array(
          'field_name'  => 'node_example_quantity',
          'label' => t('Quantity required'),
          'type'        => 'text',
          'widget'      => array(
              'type'    => 'text_textfield',
          ),
          'display' => array(
              'non_recruiter_list' => array(
                  'label' => 'hidden',
                  'type' => 'hidden',
              ),
          ),
      ),
  );
}


How do I wrap the label text of a checkbox with a span tag?

You would either need to override theme_form_element in your theme, or, do a hook_form_alter, target specific checkbox form elements, and change their #theme_wrappers callback to your own theme implementation.

I personally would do the latter, since overriding theme_form_element will change the default rendering for any form element in your theme, and that may not be desirable in every scenario.


If you have all of these different themes enabled (and you aren't using something like Panels), then you can simple edit this from the Block administration page (admin/structure/block).

If you want this to be completely removed from configurability, then I would recommend either doing a preprocess function for the content region (or hard-coding, ick, your custom HTML into the region itself).


Why should we avoid theming forms with template files?

I can see no good reason for not using a template file to theme a form. As I stated in that question, the simple #prefix and #suffix tricks might not be enough, say if you wanted the entire form to be a table rather than div based. I've used drupal_render with a form element parameter in a template to draw the individual fields in the form, but make sure you call drupal_render without an argument at the end of the template to populate the rest of the form, such as the form hash etc. as it won't validate.


How to detect Adblock on my Drupal website?

As of right now, there are no ad blocking modules on drupal.org, save for the dSero module, which is more of a proxy for the dSero service, thus, not really a solution for detecting adblock usage.

AdBlock detection is simple in practice; include markup regions (e.g. a div & image sized to a standard 728x90 leaderboard ad size) and/or execute JavaScript (e.g. running JS called ad.js) that triggers the AdBlocker to hide it, then having some other isolated code check if region was hidden or the JS code was executed.

With that known, any Drupal based solutions are going to involve either finding an existing front-end library (e.g. FuckAdBlock) or creating your own. Given that any popular solution is ultimately self-defeating (e.g. the AdBlock updating its code to check for common Anti-AdBlocking tactics/libraries), you're probably better off creating your own custom front-end solution that catches ad blocking.


i find....

variable_set('node_submitted_'.$my_content_type, false);


How I get notified every time their is an *new* update and not every day for the sames updates?

I can use hook_mail_alter to cancel the sending of the mail. I can simply store a md5 of the mail's body every time the mail is send and compare it with the "new" email, if it's the same I don't send it.


User password Reset without sending an email

I found a module called Password Reset. This is what I was looking for. I've tested this module and working great!.

  The password_reset module allows for passwords to be reset without involving e-mail addresses through the use of security questions. This module would typically be used on sites that do not require users to enter their e-mail addresses or prefer not having to deal with spam folder issues etc.


How do I remove the text "webform content" at the top of a block?

It looks like you are including the field label in the display. If you created the block using a custom block type do the following:

Go to Admin->Structure->Block Layout->Types
Then select your WebForm block type
There will be a tab labeled "Manage Display"
On this page, mark the field label as hidden.

Not sure what to do if you are using the built in Webform blocks


How to use a drupal footer and header on an external page

This may be fairly simple (with a couple of caveats, explained below). Treat it as though you were just going to use static files--i.e. so your site can simply include the contents of those files in the relevant *.tpl.php files in the theme.

The meat of the problem is that you'll need to convince Drupal to make those files for you. You can do this by creating two nodes in Drupal on the portal--call them something like 'header-include' and 'footer-include'. Take note of their node ids.

Then, assuming for the sake of demonstration that the two new nodes have node ids 1 and 2, copy the portal theme's page.tpl.php file twice, so that you have two files, page-node-1.tpl.php and page-node-2.tpl.php (see Drupal 6 Template Suggestions for more details). Modify any paths in these files that refer to the portal site.

That done, remove everything from one file except for the code and markup required to generate the header, and everything from the other file except for the code and markup required to generate the footer. Depending exactly how you need to do this, you may need to include the opening html tag and all the scripts etc. for the header, and similarly for the footer.

Clear the caches on the portal site, and you should now have two pages, header-include and footer-include that contain only the basic html code required for the header and footer respectively.

These can be included into the theme on the new site using PHP's file_get_contents() function.

Caveats

There are two points where this can go wrong:

1. Some paths may still be wrong

If there are paths in the header and footer includes that you generate (i.e. paths not hardcoded into the original page.tpl.php file), they will either include the domain of the portal site, or no domain at all. If there are any such, you will need to change how they're output at the portal (difficult), or add the relevant domain to the include at runtime (potentially expensive, though if the resulting pages will be cached, maybe not a huge concern...)

2. Include files may be accessible

This way of doing things makes the include files accessible to anyone on the portal site with the access content permission. How much of a problem this is is up to you and the client, but I don't know of a simple way to exclude them from search results in Drupal 6.


How to sort the content types/bundles on /node/create page

You can do this in preprocess by overriding this code from node.module:

function template_preprocess_node_add_list(&$variables) {
  $variables['types'] = array();
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $type) {
      $variables['types'][$type->id()] = array(
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label(), new Url('node.add', array('node_type' => $type->id()))),
        'description' => array(
          '#markup' => $type->getDescription(),
        ),
      );
    }
  }
}

Or you can replace the foreach loop in the twig template

node-add-list.html.twig

    {% for type in types %}

{{ type.add_link }}

{{ type.description }}

    {% endfor %}

with a hard-coded list:

{{ types.article.add_link }}

{{ types.article.description }}

{{ types.page.add_link }}

{{ types.page.description }}


Place custom Block, return Internal Server Error

When developing and encounter 500 errors, you should see if Drupal has logged the error or your webserver has logged the error. Depending on your configuration you might be able to see a full stacktrace explaining the error.

In this case you are missing a ; after your namespace declaration. So

namespace Drupal\pagebuilder\Plugin\Block

Should be

namespace Drupal\pagebuilder\Plugin\Block;

This should fix your error.


Storing objects of custom type in $_SESSION - legal way?

actually, I have found a workaround to do so without patching the core.

it is simple.

Drupal 7 core includes all module files which have hook_boot() registred, prior to open session, but hook_boot() is called only then session is started.

What you need to do - is to manually include class declaration outside of a hook_boot() (in a root context of a file containing hook_boot() of your module).

Such code is immediately executed as file being included by Drupal Core (prior to session_start() call), which gives us the desired behavior - we now can store objects of a CustomClass in $_SESSION variable and they wont become corrupted on next page load.

but be carefull if your CustomClass is extending from AnotherCustomClass located in different module and loaded by same mechanics (as described above) - you cannot be sure in order file loads.
This can lead to fatal runtime error: Undefined class


What's wrong with the fetch rss feed code?

if (empty($link)!== 0) {
  $link = $default_link;
}

That condition makes no sense. empty() never returns 0, it return TRUE or FALSE. Just use if (empty($link)) {.

Also, you probably want to use the Aggregator, or Feeds module.


Commerce kickstart 2 creating custom front page

I suppose you could create a custom block at admin/structure/block/add.
It comes with body field and after creating the block you can assign it to "content" region and set it to show up only on .

You have the possibility to create new regions in theme.info file and render them only in page--front.tpl.php.

I think these are the clean ways to do it, and don't require much coding.


Only one organic group id / name is shown in content listing

Found a solution: Include 'Content: group audience'


Doing a post to create a node using Drupal services endpoint with Postman app

In that  petition you are calling the path user.login, but in services is user/login, with a slash.

Also, maybe you are not preceding the path with the base name of your api (normally is /api). So the url should be /api/user/login. You can see the path in 'Edit' tab, in 'Path to endpoint' field.

I recommend you the module services tools which gives you a page  where you can see the urls of the endpoints. This module contains a submodule called services_definitions, enable it to have this page available.


How to change a file field value with entity_metadata_wrapper

You have to set the uploaded file object rather then the initial file object. Please check the return value of file_save() function.

The error explained that there is duplicate key uri, which means the code is trying to save the initial file object again.

$ewrapper->field_video->set() only accept (array) $file but not $items.

$file = file_save($file);
$file = (array) $file;
$ewrapper = entity_metadata_wrapper('node', $node);
$ewrapper->field_video->set($file);
$ewrapper->save(true);


How can I bulk delete Menu Itemes in Drupal 8

Bulk delete

there is module https://github.com/robdecker/menu_delete which you can use that provides checkboxes for easier delete of menu items.

its at the time of this writing missing a SELECT ALL feature which would make it even more helpful

its proposed to be included in core but there is no sign that it will https://www.drupal.org/node/2772961

so you can install it and take advantage of it using following commands

cd modules
git clone https://github.com/robdecker/menu_delete.git
drush en menu_delete -y

and then go into your menu and you should have available checkboxes and delete selected button

Bulk delete alternative process

1. create a custom menu
2. edit items that you want to delete and try to put them under 1 parent (or few parent items)
3. edit those parent menu items and reassign them to the custom menu
4. delete the custom menu

Bulk edit

For bulk edit the https://www.drupal.org/project/menu_editor module is not yet ported to drupal 8 but it will be a good candidate if it gets ported


For Drupal 8.3.x you need to update Display Suite as well to 8.3.x (as is stated on the module page: https://www.drupal.org/project/ds).

  IMPORTANT NOTICE

  Due to changes in core a new version is created.

  Drupal 8.2 or lower: Use Display Suite 8.2
  Drupal 8.3 or higher: Use Display Suite 8.3

Maybe that's what causing all your problems; possibly, updating the module will solve your issues.


Mobile switch more than is mobile is not mobile

People on tablets prefer to browse the Desktop version.

From this page: https://developers.google.com/webmasters/smartphone-sites/tablets:

  If your website has different pages to serve desktop and smartphone
  users and does not have tablet-specific pages, in our experience
  tablet users usually expect to see your desktop site rather than the
  site's smartphone pages.

Mobile switch does not work with caching on.

So I'm using the php code from this site:  http://detectmobilebrowsers.com/

Also see : https://stackoverflow.com/questions/11381673/javascript-solution-to-detect-mobile-browser.

So if you want more control, you need to write your own module giving the flexibility you need.


Using Context, can I (programiatically) move the page's menu to a different region?

You could place all blocks in template_preprocess_page with

$variables['page'][$region_key] = array();
$variables['page'][$region_key][]['#markup'] = $region_content;

Seeing your edit, you can check for the plugins blocks like this

$context_content_bottom = array();
  $blocks_content_bottom = array();

  // Blocks that are assigned to the region using Context
  if ($plugin = context_get_plugin('reaction', 'block')) {
    $context_content_bottom = $plugin->block_get_blocks_by_region('content_bottom');
  }

  // Blocks that are assigned to the region using the blocks interface
  if ($blocks = block_get_blocks_by_region('content_bottom')) {
    $blocks_content_bottom = $blocks;
  }

  // Merge them together
  $vars['region']['content_bottom'] = array_merge($context_content_bottom, $blocks_content_bottom);

Taken from here

but why not do it in the UI ??
just place the block several times under opposed conditions


How to get field value of form before submit?

If I'm not wrong, you want to update the other fields based on group_name entered by user. To achieve this you can use AJAX API provided by Drupal 8 Core.

If you don't know how to use/work with AJAX API, you can have a look at Examples for Developers module which provides working examples for many of the functionality. To see AJAX API Example, you can install "Form API Example" Sub-Module from Examples Module. Feel free to go through Examples Module code for any help you need.


Filter :

A views module will do the same with few tweaks on exposed filters

like:
 Name filter operator (starts with) and show all (a-z) characters with link each character accordingly.

Pagignation :

You can have pagination on top and bottom by overwriting that views template.
just print print $pager; where ever you required.

Its better to not load another modules help for something that can be achieved with small changes. :)


This post on StackOverflow says that the Drupal Form API does not support adding classes to labels, but it does contain a decent workaround:

  Instead, you could target it using the wrapper class for the field and label:

.form-item-field-foo label {
  /* CSS here */
}

The API documentation for theme_form_element_label() shows why labels aren't possible (at least not out-of-the-box): the attributes array is initialized in the theme function and populated with just two optional classes ('option' and 'element-invisible').

So, is it completely impossible? In fact, I think it can be done, but I must add that I haven't tried this myself. You could try to:

Add a new #label_attributes property to some (or all) form elements using hook_element_info_alter() in a custom module;
Override theme_form_element_label() and make it merge the $attributes array with the value of $element['#label_attributes'].

If you're going to give this a try, please let us know if it worked.


Active views are stored in the config table of the db. For example the view that produces the "recently added" block is stored in config table as name=views.view.content_recent.

The view's config itself is in the data (blob) column of that config-row.

Views that get installed by contrib modules at install time are located in the config/install/views.view.* file of the module's folder.

Try

mysql> select * from config where name='views.view.content_recent';


How can I hide the username on a custom user-profile.tpl.php page?

You can do it by disable field display property using form_alter

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {
  $form['account']['your_field_name']['#access'] = FALSE;
    }
  }


Getting front page blocks to show on redirected front page

My problem appeared to be with the Top Node module. Apparently, the views display it introduces redirects in a way that causes the <front> tag not to work as it should. The answer is actually quite simple, and honestly makes the Top Node module seem a bit redundant. Although it's not intuitive to me, under "Row Style" on views, you can specify full node content, which, as the name implies, renders node results as they would appear if you typed in the URL directly. I simply made a view that returned one result, Row Style set to full node, and then created a page display at the URL "latest". Problem solved.


Sorry, I made a huge mistake. When I tried to achieve the same thing for the block title, I copied the code from the page header but didn't remove it from the page header. In other words, I used the PHP commands - exactly as described in the question - in the headers of two subviews of the same view simultaneously. To be more precise, the variable $view was used in two places, which caused an error.

When I replace $view = views_get_current_view();
$view->build_info['title'] = 'My Block Title'; with $view_block = views_get_current_view();
$view_block->build_info['title'] = 'My Block Title'; things work as desired!


in this case, the first letter is "a" because the access argument is "administer create". If I remove administer the first letter will be "c" from &create". And all fields from user entity get this letter as content :

name : "a"
tel : "a"
mail : "a",
etc.

Actually I just want to know how to say "if you are admin you can add content, if not, you can't". The best way is to use "Session authentication" or "Basic authentication" or "oAuth" ?? Don't know...


You're going to have to attach view filter "actions" to your menu items.  That way your view results will load with ajax.

this is probably the fastest way to do this, though I've never done it I think it's possible (theoretically).

Of course you could also just create Ajax functions that queried your view with the arguments when you click a menu item.


Can we add a new column to field collection in edit form?

It sounds like hook_form_alter is the way to go.

See this for more information

See both answers because i think that waht you want to do is just add another tab at the end of the node edit form for just a link to another page.

You can always check the form api for more information


Have you cleared the drush cache (drush cc drush)?


How can I print the value of the node body using PHP with the text format applied?

I believe you're looking for the check_markup() function:

Runs all the enabled filters on a piece of text.
Note: Because filters can inject JavaScript or execute PHP code, security is vital here. When a user supplies a text format, you should validate it using filter_access() before accepting/using it. This is normally done in the validation stage of the Form API. You should for example never make a preview of content in a disallowed format.

E.g.
$markup = check_markup($body[0]['value'], $body[0]['format']);


Why Drupal does not see permission from custom module?

The hook is called hook_permission() in Drupal 7, it changed names from hook_perm() (Drupal 6)

  This hook can supply permissions that the module defines, so that they can be selected on the user permissions page and used to grant or restrict access to actions the module performs.

Make sure you clear Drupal's caches once you've made the change so it gets picked up.