Can a module provide a default block with editable content? (editable through the standard block interface)

Drupal adds custom blocks in a form submit function using database queries directly, it doesn't expose an API for that particular function unfortunately, so you'll have to write/copy the code manually.

You can find all the code you need in block_add_block_form_submit().

You insert the custom block into the database like so:

$delta = db_insert('block_custom')
  ->fields(array(
    'body' => '
Some markup
',
    'info' => 'Block description',
    'format' => 'full_html',
  ))
  ->execute();

Then you need to make this block available to all installed themes:

$query = db_insert('block')->fields(array('visibility', 'pages', 'custom', 'title', 'module', 'theme', 'status', 'weight', 'delta', 'cache'));
foreach (list_themes() as $key => $theme) {
  if ($theme->status) {
    $query->values(array(
      'visibility' => 1, // visible
      'pages' => '', // list of pages
      'custom' => 1, // This is a custom block
      'title' => 'Block title',
      'module' => 'block', // The block module handles custom modules
      'theme' => $theme->name,
      'status' => 0,
      'weight' => 0,
      'delta' => $delta,
      'cache' => DRUPAL_NO_CACHE,
    ));
  }
}
$query->execute();

You'll want to put that code either in hook_install()/hook_enable() if you plan to do this in a custom module, or hook_install() if you're doing it in an install profile.


InvalidArgumentException: The specified translation (fr) cannot be removed

"#3" patch file is working to me!
https://www.drupal.org/files/issues/2019-03-26/3043535-no-failure-deleting-multiple-translations-3.patch

Please refer: https://www.drupal.org/project/drupal/issues/3043535


I usually remove all default formatting from every field, then hide all of my fields from display apart from the last field in views, and also remove all formatting, making the hidden fields plain text where possible.

Then in that last fields settings, rewrite the results, and input all of the fields as tokens from the replacement patterns.

Then instead of div elements, I use span which plays better inside an anchor, and just add unique classes for each span element.

So an example rewrite results might be...

[title]
[body]

This should not suffer the same issue if you go to each hidden field, and under the style fieldset, make sure than no default wrapper or classes are applied, and also that each field is plain text. This will strip all formatting and place it inside the rewritten span elements. Like @BeeBee says, div and p will break the anchor wrapper.


Is there a way to have a views filter value be determined by PHP?

Setup the page to use a contextual filter per field you want to be searchable. Then for the contextual filter set it to look for the value provided by the URL. Then select PHP Code for WHEN THE FILTER VALUE IS NOT IN THE URL.

In that PHP blob supply code that pulls the field argument from $_COOKIE, if any or return NULL.


Theme mobile optimization and upgrade suggestions

Mobile developing for D6 shouldn't be any harder than for D7.
Actually, i remember that when i was building my last responsive website, there were a few useful modules only available for D6.

D8 much probably won't be out before 2014, and after the official release, it's going to take many months before all the themes and modules will get ported... many people may not be able to use D8 until 2015 or so. Probably.

It will be indeed much more mobile friendly, so it might be well worth the effort of porting.

But I don't really see the need to port to D7 at the moment.

Whether to make a separate site on a subdomain or a single responsive site is a very subjective question. Anyway, mobile_tools will probably have everything you need for both scenarios: https://drupal.org/project/mobile_tools


Drupal 8: How to properly add a settings widget to a node add/edit form and save the value?

I'm going to take a stab and show how I solved it, but I'm still curious to know if there's a better way.

In a nutshell, I used hook_form_BASE_FORM_ID_alter(), hook_node_submit(), and hook_ENTITY_TYPE_insert() or hook_ENTITY_TYPE_update() in the .module file.

Then I have a class called HierarchyManager that does all the heavy lifting that the D7 .module and .inc files used to do. It's listed as a service named "nodehierarchy.manager".

Lastly, I have a class called HierarchyOutlineStorage that handles the database inserts and updates. Quite a bit of that code was copied directly from D7.

In my .module file:

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 *
 * Adds the hierarchy form element to the node form.
 */
function nodehierarchy_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Load the node object associated with this form
  $node = $form_state->getFormObject()->getEntity();
  $account = \Drupal::currentUser();

  // Optional but keeps the .module code cleaner IMO
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');

  // Do your permission checks here
  $has_permission = ...;
  if($has_permission) {
    $form = $hierarchy_manager->addHierarchyFormElement($form, $form_state, $node, $account, $collapsed);
  }
}

/**
 * Implements hook_node_submit().
 */
function nodehierarchy_node_submit(NodeInterface $node, $form, FormStateInterface $form_state) {
  // Here the node object gets updated with the form value to be used later
  // If you aren't sure about the $form_state, download/enable devel and add
  // dsm($form_state->getValues()) to show all available values
  if (!$form_state->isValueEmpty('nodehierarchy_parents')) {
    $node->nodehierarchy_parents = $form_state->getValue('nodehierarchy_parents');
  }
}

/**
 * Implements hook_ENTITY_TYPE_insert() for node entities.
 *
 * Save the form settings
 */
function nodehierarchy_node_insert(NodeInterface $node) {
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');
  $has_permission = ...
  if ($has_permisson) {
    $hierarchy_manager->hierarchySaveNode($node);
  }
}

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function nodehierarchy_node_update(EntityInterface $node) {
  $hierarchy_manager = \Drupal::service('nodehierarchy.manager');
  $hierarchy_manager->hierarchySaveNode($node);
}

In the HierarchyManager.php file:

public function addHierarchyFormElement(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
  // Insert $form array here
  $form['hierarchy'] = array(...);
}

public function hierarchySaveNode(&$node) {
  // Do all your processing here, then insert or update dB record
  $isNew = ...
  if ($isNew) {
    return $this->hierarchyOutlineStorage->insert($item);
  }
  else {
    return $this->hierarchyOutlineStorage->update($item->hid, $item);
  }
}


Redirect user/register to external user creation

Roling your own user registration and authentication requires a number of steps. I try to eyplain them.

Calling yourmodule_form_user_register_form_alter(&$form, &$form_state, $form_id) would be a good idea. Actually you have to alter only the submission call back and may be the validation call back. You can have a look at the last lines of user_register_form how this is done in drupal core.

To make sure the users can login. It's possible to include an external authentication service. Have a look at user_login_default_validators for this.

What is most important for you, that at the end of the login procedure you have to have a valid drupal user object. I'd recommend to have parallel external and drupal users. Probably do the authentication on your external service but let drupal load the corresponding drupal user once this was successful.

This gives you basic working system. Next steps would be to handle password change and one time password recovery links in a correct way.


How to specify in a form field's #ajax setting that the entire form should be rebuilt

The workflow in an AJAX callback with a non button element is:

Submit data is received, form is constructed and validated.
If no validation errors are detected form is rebuilt. This means that the form function is called again (the form that returns the form structure).
AJAX callback function is called. The task of this function is only to return the data to the browser. No persistent calculations should be done here.

You have to detect if tou are in an AJAX form request in your form function. If yes, calculate your date. Then, construct your form accordingly. Last, return the right form fragment (or the whole form) in your AJAX callback function.

Form function:

 $form['info'] = array(
    '#type' => 'select',
    '#title' => 'Player',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => info_options($form_state['values']['key1'], $form_state['values']['key2']),

    // ajax to bind this select to the players select
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'my_ajax_callback',
      'wrapper' => 'my_form_id',
    ),

// If all selects have values get data to populate elements in vertical tabs.
if (all_select_have_values()) {
  $form_state['storage']['draft'] = my_mysql_get($form_state['values']['id']);
}

// Then add the rest of form elements.
$r =  !isset($form_state['storage']['draft']) ?  array() : $form_state['storage']['draft'];
...

In callback just return your form:

function my_ajax_callback($form, &$form_state) {
  return $form;
}

You are losing the values in $form_state because you are adding data to the $form_state in the callback function. AJAX calls are procesed by ajax_form_callback(). This function first calls drupal_process_form(), and then the AJAX callback function. $form_state is saved (when condition apply) at the end of drupal_process_form function.


How do I get drush to run remote drush not in a path?

The alias setting %drush-script is used to solve this.

$aliases['alias'] = [
  'path-aliases' => [
    '%drush-script' => '/home/[user]/bin/drush',
  ],
];


Is it possible to force Views to collect a minimum count of nodes per group?

Check out Views Grouping Row Limit module.

From the project page:

  This is a basic Views style plugin that allows for a limit on the number of rows displayed within a grouping field.


Does the sitemap.xml file does from the xmlsitemap module actually get generated?

Yes, that's normal behaviour.

xmlsitemap_menu() includes a route for /sitemap.xml specifically.


Can I post a blog entry in a user's name?

If not, I can copy /paste them; but can I create a new blog post entry in the user's name? And can I change its time-stamp to agree with the original?

In Drupal 6, the users with the permission of administer nodes can set the author of a node they are creating, using the following field set:

It is possible to change the author of a node already existing, and a node that is being created.

The same is true for Drupal 7.


The problem you're facing is that shipping rates are calculated at the order level while your field exists at the product level. You can loop over the line items on an order to inspect this field value and then make calculations to the price based on what you find, but what do you do when the field value is different for different products on an order?

In my opinion, this logic is going to get confusing quickly to try and reproduce in Rules. I would favor writing a custom Rules action that inspects and sorts the product data in code, adjusting the price directly via the API instead of through the Rules UI.


Add a CSS class to field in content type

I wrote a blog post about this a little while ago.  It mostly serves as a reference for understanding the method for targeting the markup for specific fields in specific content types utilizing theme functions in template.php which is stored in your theme's directory.

Definitely check it out.  If you can understand it, then in the future changing any of the HTML for particular fields, including the classes generated, becomes trivial.

To bring the pertinent content from my blog post into this thread, we have the following function in template.php:

function theme_field($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':&nbsp;
';
  }

  // Render the items.
  $output .= '
';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

What you would do would be to replace the word theme in the function name to the name of your theme, and since you're targeting a specific field in a specific content type, you would append to the word field in the function name with __custom_page_main_title__custom_page.  So the function would look something like:

function themename_field__custom_page_main_title__custom_page($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':&nbsp;
';
  }

  // Render the items.
  $output .= '
';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

Now you need to decide where in the structure of the field the class needs to be added, so perhaps add that on as an addition to your original question.


For each row in a view, show a list of entities with entity reference field pointing to that row's content?

To create a list of referencing content for each row in a view, use views_field_view to pull a secondary view into the row.

Add a secondary view with the fields to list and a contextual filter to receive the nid of the content being referenced from each primary view row.

Add a "Global: View" field to the primary view and use [!nid] for the contextual filter in View Settings to pass each row's nid to the secondary view.


How do I hide Bartik Main Menu on front page from unauthenticated users?

In case you are using D7, when you configure your menu block, you have a section called "visibility settings".There select the Roles tab and check the option "authenticated user" under "show block for specific roles". Then click save block.


How to create a hook for a module in a theme?

I think this style of theme hook is deprecated in Drupal 8. From the API docs:

  Theme functions are deprecated in Drupal 8.0.x and will be removed before Drupal 9.0.x. Use Twig templates instead.

So since there doesn't exist a theme function theme_links(), the functions MYTHEME_links and MYTHEME_links__language_block would not be called.

You can still customize this output by adding a links--language-block.html.twig file to your theme.

You can also utilize preprocess functions (MYTHEME_preprocess_links()).


How to list different terms with their nodes in one view?

You can achieve you requirement by below steps:

Create view at /admin/structure/views
Now add fields which you want to display.
Click on Settings under FORMAT section.

Now add your taxonomy field as Grouping Field


Just to eliminate a possible cause of your problem, and assuming your web server is Apache: make sure the mod_rewrite module is enabled. If it is not, then enable it and restart Apache.

To verify this, open the file httpd.conf inside your Apache installation folder and find the line starting with AllowOverride:

If that line looks like AllowOverride None

Then:

edit it to look like so: AllowOverride All
and afterwards restart Apache.

If you're using PHP Storm (as mentioned now in the further edited question), it might help to try what is documented in Disabling clean URLs. Here is a quote about that page:

  It's possible that a Drupal site that was once configured to run with clean URLs later on stops doing so. After that, almost all content is inaccessible, because the paths being generated are not supported by the hosting platform.


How do I add menu-entry to the admin menu with node reference?

You could use the Menu Token module to achieve the same:

Install the module and its dependency, i.e. the Token module.
Create a new menu item with path node/[node:nid]/edit.
Place the menu block which contains the menu item in any region of your choice.
Drupal menu system takes care of showing the menus as per the access; which means that only users which have permission to edit the node should see it.

The image below is an example shown on the project page. You could use it as a guide.


This is the correct approach. Don't do all the work yourself, extend  DefaultExceptionHtmlSubscriber for 403/404 or HttpExceptionSubscriberBase for general exceptions.

As example see this question for access denied: How can we catch the acces denied exception in drupal 8

The most important thing is to use a higher priority than the core event you want to override.


How to print a field in node.tpl.php without labels or markup?

If you just want the value of a given field, it will be in the $node object in your node.tpl.php file (or node--type.tpl.php).

Normally it's under something like:

$node->field_name['und'][0]['value']


Only show title of referenced node in a view if the node contains files in another field?

Your view has all the info you want (and then some); simply override the view template or use hook_view_preview() to unset/hide the result you dont want.

There are many examples of this on the web and in documentation.


How can I stop auto uploading of managed_file elements?

Try overriding the #attached library on the managed file field:

$form['sitemap'] = [
'#type'              => 'managed_file',
'#name'              => 'sitemap',
'#title'             => t('Upload Site Map (xml)'),
'#upload_location'   => 's3://private/sitemap',
'#field_suffix'      => 'XML format supported',
'#upload_validators' => [
  'file_validate_extensions' => ['xml'],
],
'#required'          => TRUE,
'#validated'         => TRUE,
'#attached'          => [
   'library' => [],
 ]

];


Hide node and file paths in view when printing page

Sounds like a CSS issue, so before this question gets flagged, hopefully this will help you out.

The most efficient way, assuming it is a CSS issue, is to add a stylesheet to your theme whose media type is print (see below for example).

Assuming the part you want to hide is an element (div, span, etc) whose class is mycustomclass, inside that stylesheet you could add something like this:

.mycustomclass {
  display: none;
  visibility: hidden;
}

And here's the example mentioned above:

<link type="text/css" rel="stylesheet" href="http://www.example.com/sites/all/themes/mytheme/print.css" media="print" />

HTH...

:)


Yes, you can do it with Contextual filters in Views. You can Duplicate the Taxonomy term Views and work on it, disable the original for future reference.

You need to add one Contextual filter for each of your Vocabularies. You probably have one field for each of those on your Content type, so add the Taxonomy reference fields as your Contextual filters. The alternative is to use "Has taxonomy term" twice and limit Vocabularies.

You'll need to set up a default value taken from the URL. You can find a lot of tutorials online about the details of setting it up: Add a contextual filter to a view, How to use Contextual Filter in Drupal 8.

The above approach will only work with term IDs example.com/16/35.

To have term names displayed instead of TIDs you need to add a Relationship to the Taxonomy field to your Views, then add Taxonomy term: Name in your Contextual filters and it will use that Relationship in the Taxonomy Contextual filter. Repeat for the other Vocabulary. Also see this answer: How to setup view to filter based on second URL parameter?

That is how you can get example.com/applications/automotive.


in_array() returns a boolean (and takes two arguments), whereas Drupal is expecting an array to be passed for the default value.

The default value array needs to be keyed by the same key used for the options array, so in this case uid. The value for each array element should be TRUE or FALSE, to mark the element as checked or unchecked respectively.

$uids[1] = TRUE;
$uids[2] = FALSE;
$uids[3] = TRUE;
// etc.

$form['msg']['accounts'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#default_value' => $uids,
  '#empty' => 'no companies',
);

EDIT

I haven't tested the following, but since your $uids array contains only the array keys you want checked, and a positive number is automatically cast to a boolean TRUE in PHP, you might get away converting your array in one step:

$uids = drupal_map_assoc($uids);


Lightbox gallery is not working in mobile website

At last I found an alternative solution for image gallery:

Photoswipe,it is working for me...(Compatible with lots of mobile devices and all popular JavaScript libraries and development frameworks. )

http://www.photoswipe.com/

sample:

http://www.photoswipe.com/latest/examples/04-jquery-mobile.html


Displaying fields in multiple rows for one node with Views format

Drupal 7 Field API handles this case very well. I rewrote the Office Hours module using the Field API. Each row has day of week and time open and time close. This would be exactly the same for you except instead of day or week it would be port, time open would be time of arrival and time close would be time of departure.

The solution is to build a custom module with Field API in Drupal 7. Are you using Drupal 7?


Where to store JS and CSS that is not associated with a module?

My gut feeling would be to place it in a folder in the root of your website and access it through a subdomain. I'm not sure, without knowing more about the application, if there is an effective way to integrate it with Drupal. It seems like it should stand on its own, in it's own directory structure, as it is a separate entity. I stand to be corrected here, but i don't see a problem with hosting it concurrently with your Drupal installation. It won't be manageable through the CMS, but without building the functionality in Drupal itself, it wouldn't be anyway.


Just add the ID of the pane (fieldset) to the URL as a fragment, e.g.

http://example.com/node/[ID]/edit#edit-metatags

Assuming metatag is installed, that code will open the metatags tab directly on page load.

An example for core might be:

http://example.com/node/[ID]/edit#edit-options

For the "Publishing options" tab.


Which Rules Event can be used with Drupal Commerce when a cart is updated?

Make sure you have the Commerce rules extra module installed. This module will provide, among other things, the extra Rules Event "Quantity of line item has changed" (as described on its project page):

  Line item quantity has changed (occurs when adding or removing a product to cart and when an amount has been modified in the cart form).

That should help to achieve your goal.


Instead of applying the updates to each individual site by using @sites which never worked, I was able to achieve it by running the updates on one specific site. Here is the code that worked for me:

drush -l example.com pm-update

example.com being the name of my symlink.  Side note: I did not have to create a drush alias for this to work.


The DB log should log user logins. It usually appears as "Session created for [user name]".

Alternatively, you can create an admin-only view of users and the time they last login and/or the last time they accessed. iirc, users have access and login fields in the DB which are timestamps that represent last page access while logged in and login time, respectively. I believe they are exposed to Views.

For reports, there is Views Data Export which adds a display to a View, exposing itself as an endpoint from which you can download the data. Exports in various formats, most especially CSV.

However, for the views approach mentioned, it will only display the latest data. This doesn't do historical record-keeping.


Which cache bin to clear after changing services

Drupal Console uses Cache::getBins() for its list of valid cache bins - that method returns all services in the main container tagged with cache.bin. The container cache service is part of the bootstrap container, which is managed internally by DrupalKernel.

I haven't dug deep enough to know for sure, but keeping the management of that bin internal seems to be deliberate, so there's probably no simple (maybe even no desirable) way to hack around it.

Fortunately, a custom plugin for Console is easy to create with drupal generate:command (there's a tutorial here). Just be sure to inject the kernel service, and call $this->kernel->invalidateContainer(); in the command 's action callback.


How to bring facebook connect button in login form?

You have to alter both form using hook_form_alter and add a markup field with value fboauth_action_display('connect')

$form[fb_connect] = array(
   '#markup' => fboauth_action_display('connect'),
);


The db_query function  isn't just for select queries, it will execute anything.

Just use that instead of the loop, the performance will be miles better:

db_query('INSERT INTO superstatistics_counter SELECT * FROM node_counter');


How anonymous users are able to complete survey, even when webform is set only for registered users

Admin menu --> webform --> Choose one of your webform and click component--> form setting

Under SUBMISSION ACCESS untick anonymous user.


To take a different angle:

It's very possible to do this, but you shouldn't. Your web server user should not have the capacity to write to the web root (except for designated folders like the public files folder). You should therefore not be able to delete module folders from code. Doing so presents a security risk to your server.

This is one of the checks the Security Review module performs, and throws up a nice big red error if it find the web server can write to such files:

I understand this might be unavoidable if you're on shared hosting, but I think it's a good piece of information to have either way.


How do I add a variable for a Twig template in my preprocess function?

I finally solved the problem, it turns out the problem was that I tried to add the variables in the wrong preprocessor. Editing the #theme works there, but to add variables I needed to preprocess the theme I set there:

function template_preprocess_imagegallery_format(&$vars) {
  template_preprocess_image_formatter($vars);
  $vars['image']['#theme'] = 'igimage';
}

function template_preprocess_igimage(&$vars) {
    $vars['thumbnail'] = ImageStyle::load('thumbnail')->buildUrl($vars['uri']);
    $vars['fullimage'] = file_create_url($vars['uri']);
}


Thank you for your help. Finally we use a taxomony and Taxomony Access Control and we don't have the problem !
We create a vocabulary : Intranet with two words Private and Public. And we use Taxomony Access Control


Connection timed out and lock_may_be_available() on working site

There could be multiple reasons/thoughts:

Are you sure mysql is running?
Has your site got just too big for the resources allocated to mysql in the configuration?
Did you manually "emptied" all of the cache files via the database?
Low file system space on the database server
If you just moved the site to the other server and mysql is not set up to accept enough connections.
The user you are connecting with has SELECT permissions on mysql but not DELETE or UPDATE etc.
The host settings in sites/default/settings.php doesn't matche the one from the User in the database
MySQL 5.7 does not allow root user to access a database from client app. After switching to a normal user, it solves.
Sometimes tuning xampp like on php.ini (memory_limit=256M) and my.ini (max_allowed_packet = 32M) and disable devel by drush (drush dis -y devel) also works.
...


Why is the database not updated before a next Rule is launched?

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rule 2 in a Rules Component, so that your Rule 1 "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Publish content" for sure completed, and your "number" will have been updated as expected.


How do I combine two content types in one Views block and get them to sort correctly?

In the end, using hook_views_query_alter() turned out to be the simplest solution for my needs. I used code similar to that found in the solution below.

https://drupal.stackexchange.com/a/53128/18497


how to do a list navigation into a node content

For this requirement you should go for twig to your content type:

  node--content-type.html.twig

In hook_preprocess_HOOK render all the fields you would like to show in twig file.

For better understanding of twig file follow this.


Taking as example the Article content type, on admin/structure/types/manage/article/fields, you alter the field's order in the edit form; on admin/structure/types/manage/article/display, you alter the order the same fields are shown when rendering a node.


From Pantheon docs: "Pantheon cannot be used to host files over 256MB, no matter how the file is uploaded"

http://helpdesk.getpantheon.com/customer/portal/articles/745361-known-limitations

It could be that your file is too large and therefore Pantheon will not host it.


Entity Reference: Filter by an entity reference view not working as expected

You can't at the moment.

See \Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection::getReferenceableEntities(), it just uses the view to get the results and then calls $entity->label(). Which means you have no way to override that.

Which means that if you want this, you need to provide your own plugin. You can either subclass from ViewsSelection and still a view, or just extend from the default and override that method.

Might also be worth opening a feature request, I've already had this use case multiple times, and a new checkbox or option somewhere would be a nice, backwards compatible way to introduce this feature in a minor release.


Outputting recent comments in a different part of the node

You can do that using views.

Then you can either add this view as a block or you can use http://api.drupal.org/api/views/views.module/function/views_embed_view/7 in node.tpl.php


Is there a way to get the max size of a varchar textfield?

There's no single function that will extract the value for you, but field_info_field() will get you an array that contains the data:

$info = field_info_field('field_foo');
if (isset($info['columns']['value']['length'])) {
  // Do something with $info['columns']['value']['length']
}

It it's a core text field, value will always be the name of the column you need to check. For other field types it may differ.


It sounds like you are looking for something like the Quicktabs module. I have an implementation here: http://gamebah.com/gsqrd/node/24.

You  will make a block for each tab (Twitter, Facebook, Feedback, etc.) and then using Quicktabs (under Admin > Structure > Quicktabs) you can add the blocks to a new tab set. It is very self explanatory but if you need more help, don't hesitate to ask.


Run second site in the same VM: Is it possible?

Yes, this is possible, but take it from me as a guy who did it for about 12 sites - it gets tedious fast to manage it.

Setting up and tearing down VMs is so fast and cheap, it's simply more practical to me to create one per project. It's less to manage, and it just becomes a 'part' of the project codebase (you can fetch Drupal VM with Composer now for example, or download and keep it in a 'tools' folder outside of docroot).

Also it does not sound like you are setting up Drupal VM properly... I suggest re-reading the docs or posting more information.


A better approach is to edit the content type settings and omit body altogether.

In Drupal 6, you can do this by going to /admin/content/types/ipaper and leave the "Body field label" empty.

In Drupal 7, go to /#overlay=admin/structure/types/manage/ipaper/fields and delete the Body field.

If you really need to keep old content in the node body, then use hook_nodeapi() with $op == 'view to unset $node->body


The easiest way is to go to Configuration > Development > Performance (admin/config/development/performance), and enable:

Cache pages for anonymous users
Cache blocks

And also:

Compress cached pages
Aggregate and compress CSS files
Aggregate JavaScript files

For websites with mostly anonymous (not logged-in) visitors, this is often sufficient. Note that if you enable compression in Drupal, you should not enable page compression on the web server level (Apache) as well.


jQM Theme does not work properly on front page

Are you including the CSS/JS via your themes .info file? If so, the CSS/JS should be included in the order specified there. The only other thing you should check is that if you have a page override for the homepage (page-front.tpl.php) and verify you have the correct JS/CSS in place in there as well.
Good luck


Show table records in view via hook_form

I manage to get things working like I wanted !! So I will include a screenshot and the code for people on the same boat.

function rss_list_form($form, $form_state) {

$header = array(
'article' => t('Article'),
);

$rows = array();
$sql = "SELECT * FROM {rss_table}";
$result = db_query($sql);
    foreach ($result as $dbrow) {
    $rows[$dbrow->GUID] = array(
        'article' =>
        '
'.$dbrow->title .'
'.'
'
        .'
'.$dbrow->description.'
'.'
'
        .$dbrow->date .'
'.''.$dbrow->link.''.'
',
    );
    }
$form['rss_select'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('No articles found.'),
);
$form['import'] = array(
    '#type' => 'button',
    '#value' => t('Import'),
    '#weight' => 0,
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);
$form['delete'] = array(
    '#type' => 'button',
    '#value' => t('Delete'),
);
return $form;

}


How to add a link in a menu with query parameters in paths

There are multiple ways to solve this problem.

Use the absolute URL of the page, instead of the Drupal path.
Write a module that provides a menu item via hook_menu(), e.g. for the path resources/field_resources_type_tid_i18n/130. The page callback for the menu item would either redirect to resources?field_resources_type_tid_i18n[0]=130 or serve the desired page directly.
Add a rewrite rule to the webserver configuration, the translates resources/field_resources_type_tid_i18n/130 into index.php?q=resources&field_resources_type_tid_i18n[0]=130 and add resources/field_resources_type_tid_i18n/130 to the menu.

Solution 1 is the most simple, but not very flexible. You need to touch the menu links database table if the absolute URL of the site changes. Adapting the link to the currently used scheme (http:// or https://) is not possible.

I prefer Solution 2, but it requires knowledge about Drupal module development.

I do not like to rely on URL rewriting to provide essential functionality, so I do not recommend Solution 3.


drupal_html_id() alternative for non-Ajax content?

Here's a simpler version I came up with by altering drupal_html_id() that doesn't pay attention to the $ajax_html_ids. Also note that it produces dashes instead of hyphens:

function foo_html_id($id) {
  $id = strtr(drupal_strtolower($id), array(' ' => '_', '_' => '_', '[' => '_', ']' => ''));
  $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
  $id = preg_replace('/\-+/', '_', $id);

  $seen_ids = &drupal_static(__FUNCTION__);

  if (isset($seen_ids[$id])) {
    $id = $id . '_' . ++$seen_ids[$id];
  }
  else {
    $seen_ids[$id] = 1;
  }

  return $id;
}


How Can I restrict a date picker in a date field, to disable a list of specific days from the calendar widget?

Using this answer: https://stackoverflow.com/a/15400806/1475662 and a bit of custom coding to add the js and the list of available (or not available) dates to the page.


How to uninstall module if admin/modules path is not accessible due to memory error

Use drush:

drush dis MODULE-NAME

You can also disable modules manually in the database:

UPDATE system SET status='0' WHERE name='module_name';

Then you need to clear cached system list (Drupal 7 only):

DELETE FROM cache_bootstrap WHERE cid='system_list'


Feed import save empty value in multilingual site

Feeds: Entity Translation

  This module adds support for importing data through Feeds into
  translatable fields handled by Entity Translation.

  The module exposes fields that are translatable into all enabled
  languages, enabling the creation of translations of entities when
  importing.

Another fantastic Solution

Import from two xml files (on for each language), my empiric solution :

I created two feed imports.
I forced the language field for each one.
Two separated nodes were created for each content (one in each
language) but it didn't links the translations.
So I used a SQL query to finish the job, it's based on the feeds uuid


Get the user uid (uid) from comment id (cid)

You need to load the comment object:

$comment = comment_load($cid);
$uid = $comment->uid;


Given the error  'TypeError: $.browser is undefined' I would surmise that there is a discrepancy in the version of jquery running. If you have the module jQuery update installed and running on one or both, check to see if both sites are running the same version of jquery.


How do I have views exposed filter results in separate block?

This has worked for me:

Make a View Page with the fields, filters and exposed filters you want. Make the view work with exposed fields in the Views Admin UI. In the view settings assign a page url.
When done with the above step, click the Exposed Form block in the advanced view settings (make a block of the exposed filters).
Then goto the Admin Blocks UI for your drupal site and place the block on whatever URL and theme Region you want. I placed my exposed form block on a Panel page.

When the filter form is used, it POSTS to the Views page URL within your view. You can't just make views block(s) for the display and exposed filter form(s). A block does not know from within Views where the <form action="SOME_URL_HERE" method="POST" /> url of the form should post to.

For example, the exposed form on some page

The result of submitting the form


How to add a value to an entity reference field set to unlimited values using entity metadata wrapper

$wrapper->field_foobar[] = $additional_value;

Just change field_foobar to the machine name of your entity reference field.

The empty brackets insure a new value is added rather than overwriting existing value(s).

Good luck!


How to redirect all URLs to a new domain

The problem with trying to do it with PHP or a module is that PHP doesn't handle every request; for example, if someone deep linked to a file, no PHP solution would help.

So the easiest (and most complete) way to do this is actually with Apache (or whatever web server you happen to be using):

RewriteEngine on
RewriteCond %{HTTP_HOST} ^old\.example\.com$
RewriteRule ^(.*)$ http://new.example.com/ [R=301,L]

You can do this in the host configuration file or the .htaccess file: assuming the old site is a Drupal site, you'll want to place everything except the first line immediately after RewriteEngine On (around line 58 in Drupal 7.x).


$result = $query->execute()->fetchAll();

should do the trick.

There's a lot more info and several more examples in http://api.drupal.org/api/examples/dbtng_example!dbtng_example.module/7


How can I create a link to permission group and configuration page on module install page?

For settings page, in your_module.info.yml

configure: 'your_module.route_to_settings.form'

Permissions link is automatically shown whenever you have permissions defined in your module.


Trying to pass id to the ajax callback function, keeps overwriting, how to solve this?

I'm sure you can pass some arguments to your callback by doing this:

$form['image-entry'][$some->id]['submit3' . $some->id] = array(
  '#type' => 'submit',
  '#value' => 'Delete',
  '#ajax' => array(
    'callback' => 'image_gallery_delete_photo_callback',
    'parameters'=> array('param1'=>$some->id)
   ),
);

Try to catch those parameters at your function image_gallery_delete_photo_callback($form, $form_state, $args)

The variable $args should contain 'param1'as your ID

Hope it helps !


Using the same form more than once per page with AJAX callbacks

Define a class property for a sub id and append it to the form id:

class MyForm extends FormBase {

  public $sub_id = '0';

  public function getFormId() {
    return 'my_form_' . $this->sub_id;
  }

  ...
}

You can append this sub id to the wrapper as well, if you want to have different wrappers for each form:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $wrapper = 'ajax-wrapper-' . $this->sub_id;
    // use $wrapper for #ajax and div container in buildForm()
    ...
  }

Then set a different sub id for each instance of the form.

For example in a block the first instance:

$form = \Drupal::classResolver()->getInstanceFromDefinition('Drupal\mymodule\Form\MyForm');
$form->sub_id = '1';
$build['form'] = \Drupal::formBuilder()->getForm($form);

and the second in preprocess:

$form = \Drupal::classResolver()->getInstanceFromDefinition('Drupal\mymodule\Form\MyForm');
$form->sub_id = '2';
$variables['form'] = \Drupal::formBuilder()->getForm($form);


This has a solution on Stackexchange here already, but:

This would be your full javascript file:

(function ($, Drupal) {
  Drupal.behaviors.myModuleName = {
    attach: function (context, settings) {
      // I am doing a find() but you can do a once() or whatever you like :-)
      $('#element', context).find('.sub-element').each(function () {
        // Do your thing here
      });
    }
  };
})(jQuery, Drupal);

Note on the question's js: I would say when calling a function like your addStyleClasses() it would be more reliable to explicitly pass your target element in the function call than using $(this) in there.


How to download the files data attached to webform

You can do it by using these modules:

Webform Protected Downloads

  This module provides a handy solution for the following situation:

  you want to offer some files for download to either anonymous or    registered users
  you don't want those files to be publicly accessible
  you want to collect some data before granting access to the files
  you want to be sure that the user gives a valid email address

Webform2PDF

  The Webform2PDF Drupal module is an extension of the Webform module.
  It can be used to generate PDF document from the results of a form.
  The generated PDF document can be attached to the form summary e-mail
  sent by Webform module, or it can be downloaded from the /Results/
  page. Different PDF templates can be set for each form.


How to use php filter for "contact page" in drupal 6?

If your want to enable php code filter for user end, it could be dangrous for your site.
Any one can perform some dangerous activity by adding php code.
or if you want to alter the "contact form" then you have to use  "hook_form_alter".


Linking an action to the button in the view

You can do this with the help of the Rules module. You'll probably want to create a Component (they don't have Events that trigger them, as opposed to full Rules) and connect them to your Views custom field.

Views Bulk Operations (VBO) is a better option though. It's also well integrated with Rules so you can use that instead of a Custom text Field. With VBO you get checkboxes for each Views row and a button for each action you want to perform on a Views row, so you can select more than one row at the same time.


Removing dozens of Routes from a collection

I think the way you're doing it is fine, although you could probably add a patch to the original module that adds the option of which entities to affect, so that instead of them being added and removed, it would only add them for the entity types you select.

Ah, I see you've already thought of this!


How to display a field collection as a responsive table?

Unfortunately there isn't a good solution for displaying tabular data in a responsive way. Even big organizations like Wikipedia, Google, and GitHub display tables as horizontally scrollable entities.

If you can think of a way to display tabular data legibly with variable width, be sure to publish it. :)


Password Toggle is already doing something of this sort. Code is simple and straight

Its basically a JS to be added at the right time.

function password_toggle_add_js_and_css() {
  $path = drupal_get_path('module', 'password_toggle');
  drupal_add_js($path . '/password_toggle.js');
  drupal_add_css($path . '/password_toggle.css');
}

You can borrow the module's js code for your module.


Creating an iframe playlist that loops through urls (from a node field)

I'd probably do this in two steps (all within the formatter hook).

Separate the js processing into an external include, added via drupal_add_js();
Put the urls into Drupal.settings.mymodule.playlist and call these from your ChangeSrc() function.
If you're wanting to do it semantically, skip point 2 and just ouptput <a href="src" data-something="60"> in your formatter markup. Then pull those hrefs with your js and inject them into the iframe.

Standard code for including custom js settings:

$settings = array();
$settings['mymodule']['playlist'][] = array('url1','metadata1');
drupal_add_js($settings, 'setting');


There is also the Better Exposed Filters module.

If you use the latest dev version there is support for jQuery UI slider, which was recently committed from a patch at http://drupal.org/node/1627524

It allows the use of a jQuery UI slider for any numeric filter (except date filters, which are technically an extension of the numeric filter).


"You are not authorized to access this page." immediately after logging in with any user

Backup the database and rebuilt the permission of the user under "/admin/reports/status/rebuild"..


You should try the features module

  The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it declares its components (e.g. views, contexts,
  CCK fields, etc.) in its .info file so that it can be checked,
  updated, or reverted programmatically.

  Examples of features might be:

  A blog
  A pressroom
  An image gallery
  An e-commerce t-shirt store


Remove site name from template using twig function

You can remove the block in the block layout.

If you don't want to do it in the ui, you have to look for the block name. This is probably sitebranding.

For example to remove the block with the name sitebranding from the region header in the page template:

{{ page.header|without('sitebranding') }}

If you are looking for the site name in the kint print out, it is not always possible to find the actual content early in the templates. Often it is processed at a later stage.


Which modules should I add to Advanced Forum to provide increased functionality?

While I do think this question is off-topic for this site, I know what you're going through. I recently built a forum with drupal, and I was surprised at how difficult it was to choose a good module to fulfill certain requirements, or even how to find the right ones for the job.

So to help you out, here's some modules I used to add functionality to the forum:

Flag + Flag Abuse
Privatemsg
Subscriptions
ACL + Forum Access
Author Pane
AutoAssignRole
CAPTCHA + reCAPTCHA
Comment Permissions
Comment Upload
Custom Search
Flatcomments
Override Node Options
Private Upload
Quote
User stats


How to put a Token in a path in a view Path setting?

In the contextual filter settings:
When the filter value is NOT available -> provide default value ->User ID from url

and edit link of the view just without the argument/token


No, unfortunately, this is not possible. The used memory of a module is scattered among many functions, caches, etc.

There are tools which allow you to display the memory usage per function, how much time a function used, and so on; for example, there are XHProf and Xdebug, but both are PHP extensions and you will not be able to install them on a shared host.

You could, however, create a local installation (if you haven't already) and then check these tools out. Devel integrates nicely with XHProf, so you only need to install the extension, and enable the corresponding checkbox in the configuration settings of Devel.


How get subscribe to user flag on a node

You could create a block with a php filter or create a custom template for that node. You can also alter that node from from template.php

http://www.webomelette.com/altering-node-content-it%E2%80%99s-rendered-page-drupal-7


Is there an official/recommended way to organize CSS files for a responsive theme?

This is possibly hard to answer. But all the way are acceptable.

Mostly people don't like reading through a single HUGE CSS file, and maintaining it is very difficult. On the other hand, splitting it out causes extra http requests which could potentially slow things down.

My opinion would be one of two things:

If you know that your CSS will NEVER change once you've built it, I'd build multiple CSS files in the development stage (for readability), and then manually combine them before going live (to reduce http requests).
If you know that you're going to change your CSS once in a while, and need to keep it readable, I would build separate files and use code (providing you're using some sort of programming language) to combine them at build time (runtime minification/combination is a resource pig).

With either option I would highly recommend caching on the client side in order to further reduce http requests.

I also found another question related to this https://stackoverflow.com/questions/16657159/when-using-media-queries-does-a-phone-load-non-relevent-queries-and-images . This will further clear your concept about this.


How to debug or explore an unknown object or array too big for Drupal's debug()?

Devel

Devel module provides dd() command which is very useful for dumping very large object. Just run dd($vars) in the middle of code, it'll dump any object to the temporary file in your Drupal temp folder (temporary://drupal_debug.txt).

XDebug

Use XDebug PHP extension, so var_dump() will be replaced by xdebug_var_dump() so your big dump won't consist circular dependencies and would be limited only by specific depth.

Alternatively use TVarDumper, array_slice, serialize or json_encode, so check below for further details:

Using print_r and var_dump with circular reference at SO


Computed field won't update itself or save to the database

If you would print the rest of the MySQL error message I assume your error is a malformed query such as:

SELECT AVG(field_review_payment_value) FROM {field_data_field_review_payment} WHERE entity_id IN ()

Eg, you cant have an empty IN primary key list.

Since you want to show an average value you could do something simple like:

if (isset($nids)) {
  $entity_field[0]['value'] = db_query('
    SELECT AVG(field_review_payment_value) FROM
    {field_data_field_review_payment}
    WHERE entity_id IN (:nids)',
    array(':nids' => $nids)
  )->fetchField();
} else {
  $entity_field[0]['value'] = 0; // no values to average == 0.
}


Do custom theme suggestions execute on every page load and does that impact performance?

To answer your questions:

Yes, it executes on every page load.
It won't impact your server load any noticeable amount.

The amount of processing power for that one function is extremely low. You could probably run it 1000 times without causing a noticeable performance it.


How to allow anonymous comments on one content type, but not all

Check out the Allow anonymous comments per node type


Avoid the user is asked to download the files

By listening to it , it sounds that your browser does not have PDF plugin installed , that is why it downloads file instead of opening.

The same thing can happen to lot of your user, solution to that is Mozilla Project pdf.js

Drupal also have a module for this PDF Module, check that out and see if that helps.


I think that is the rate module, like many such modules it uses the voting api.

You should use votingapi_select_results() to get the results. The $criteria array that you pass to it will be

$criteria = array(
    'content_type' => $content_type,
    'content_id' => $content_id,
    'tag' => $widget->tag,
  );

I have only skimmed the code but I belive that $content_type and $content_id are node type and node id. The $widget->tag will be specific to your widget.


This snippet will return you user points :

<?php
print userpoints_get_current_points($user->uid);
?>

But to Place this PHP snippet in menu link, you may need Menu views and PHP Menu Modules


There's the Prepopulate module

  The Prepopulate module allows fields in most forms to be pre-populated from the $_REQUEST variable.

  For example, the following URL,

  http://www.example.com/node/add/blog?edit[title]=this is the title

  will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well.

It's only in dev for Drupal 7 but I've used it in a couple of projects and I haven't had any major problems. If it doesn't quite match your use case you could always take a look at the code, it shouldn't be that tricky to adapt for other purposes.


Services Views module no longer maintaines. What are my options?

The Views Datasource's sub module called Views JSON is what I would recommend: https://www.drupal.org/project/views_datasource

It's very similar to Services Views, except you just create a "JSON Data Document" Page Display for your View, and specify a Path at which the View can be accessed.


How to run PHP code only once on node creation?

If you want to run code just once when a node is created, the Rules module may be a better choice.

Using Rules, you can do the following:

Create a new rule that acts on the event "After saving new content."
As the action, "Set a data value" and target the field you want to modify (this would be a standard field rather than a computed field in this case).
As the "Value", input your PHP code in php tags.

This way the code will be evaluated only once.


Is theme_pager() vulnerable to HTTP Parameter Pollution?

Simple answer: no, theme_pager() isn't vulnerable to this kind of attack.

The pager functions only use the page parameter and don't make use of any other. As far as Drupal core goes, that argument is used only in the context of a PDO-prepared database query, and so any effort at malicious manipulation of that page parameter will simply fail.

As with anything, careless use of theme_pager() outside of the proper API - e.g. using the associated preparatory functions manually without properly prepared database queries - can result in unwanted side-effects. But the function and its associates aren't inherently insecure, and from a core perspective are used safely.


How to use a token in "Behavior without results" of a view?

You have to check the checkbox and then use the token you want BUT you have to be careful because you are in the case you do not have any results and the {{ id }} will use the first result of your view as said on the description.

So you have to use your contextual filter : {{ arguments.id }} and it will work as you want.


The core migrations from D6/D7 to D8 do preserve IDs by default. But, it is fragile, you have to be careful not to create any content on the D8 side before you've completed all migration. Unless you depend on public-facing addresses (e.g., /node/[nid]), it's simpler to just allow IDs to be assigned on migration. See https://www.drupal.org/node/2748609#comment-11293627 for more.


How to set default value for textfield programmatically in drupal 7?

Try

 $form['field_add_on_nids']['und']['#default_value'] = $default;

Thanks


How to share Redis cache across Drupal servers?

If you use the Redis module for Drupal, you can set the database and prefix used by your sites. The default Redis database is 0 (so multiple sites use the same database) but the default prefix is the HTTP_HOST variable (so multiple sites use different prefix). You can however, set a shared prefix on both site in their settings.php:

$conf['cache_prefix']['default'] = 'mysite_';

You can also set prefix per cache bin, to only share a subset of the cache between them. See Redis module's README.txt for more details.

Of course, this should only be done if your are sure the cache can actually be shared. In your case, I guess the sites share the database and are used to balance the load.


how to obtain fivestar field value in rules?

I'm not sure about forms, since you didn't mention how you set those up on your website, but I can help you with the case where the Rule is called after saving a new comment with a Fivestar field, say it's called Stars. Follow the guidelines underneath for your Rule:

Events: After saving a new comment.

Conditions:

Check whether the comment has a field Stars with Entity has field.
Check whether the field Stars is not empty with NOT Data value is empty.
Run this custom code: return $comment->field_stars['und'][0]['rating']<=60;.

Adapt these steps to your needs. Be sure to compare the rating with a score out of 100, since Fivestar works internally with percentages.


Why does cloning a private git repository via Drush make file fail using SSH authentication?

Using modules and not theme_name may resolve this.

projects[modules][type] = modules
projects[modules][download][type] = git
projects[modules][download][url] = git@bitbucket.org:company/repo.git
projects[modules][download][branch] = master

Here are a couple of useful links:

https://groups.drupal.org/node/194303#comment-918073
http://www.systemseed.com/blog/drush-make-private-git-repository-github


You should assign your menu link to one of the specific groups on /admin/config by setting the correct path. You can find most of them in system.links.menu.yml and it usually matches the path, e.g. parent: system.admin_config_media.


How can I view the IP addresses of visitors who view the home page of my site?

If you are using Apache, all page requests are recorded in the log directory. On a Ubuntu machine the location of this directory will be /var/log/apache2.

To block spam traffic, I recommend the mod_spamhaus module. This link contains information on how to setup mod_spamhaus on a Ubuntu machine. The module checks for blacklisted IPs listed on the Spamhaus project and subsequently refuses the connection if a positive match is found.


Remove novalidate attribute from webform for client side validation

The Clientside Validation module is automatically adding the novalidate attribute to the form.


Create views from combination of various vocabularies' terms

You can have nice block displaying all terms coming from your mentioned vocab by help of Cumulus.

Though its in DEV mode but it works fine. This requires module Tagadelic to be enabled first.

You can create a cumulus block by visiting admin/structure/block/add-cumulus-block, where you can mention name of the block & setting for it such as Vocabulary IDs to be included, Number of tags to display, Width, Height etc..


Views exposed filter error "An illegal choice has been detected. Please contact the site administrator."

I was having the same issue. In my case the 'illegal choice' message was displayed when changing the country from 'United States' (the default value) to 'United Kingdom' and selecting 'North Yorkshire' as state/province and saving.

I did the following to fix it:

Go to the Configure page of the Location field (by editing the node type and going to 'Manage fields').
In the 'Events settings' section (not the 'Locative information' section), there is a drop down group called 'Default value'. I set 'Country' to United Kingdom.
Save field settings.
Done.

Using:

Drupal 6.28
MySQL 5.1.72
PHP 5.3.3.7+squeeze17
Location: 6.x-3.3-rc3+6-dev (2013-Oct-25)
GMap Location: 6.x-2.0-beta5+1-dev (2013-Sep-30)

Hope it helps.


After add node redirect to previous page

You can achieve this by

Make sure the ?destination parameter in your url is filled out. This will redirect you to the page defined in the destination parameter.
Use the node save redirect module. This module allows you to configure the redirect path per node type after saving a node.

Node Save redirect module.

This module provides a method of specifying a location to take the user after saving a piece of content.

A set of radios buttons are added to the submission vertical tab on the content type edit form.

The available options are.

  Default - Default behaviour Return to Edit page after saving
  Return to content overview page (assuming the user has access
  permissions Re-redirect to another location. (any valid drupal
  path)


How to change value of a field in hook_node_view

Take a look at the API documentation for hook_node_view, specifically the comments at the end of the page -> Has anyone been able to successfully modify a node object?. There's talk of using hook_node_load as a solution as well as many of the hooks that are field specific. Note the comments at the bottom of the hook_node_load API page that explains why $nodes is not called by reference but is still changed when changes are made to the variable within the hook re: OOP -> http://php.net/manual/en/language.oop5.references.php.


How do I append a view to the node body in custom module?

So it turns out that the hook_node_view was all that was needed, but I don't know why it didn't work the first time:

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode){
  // Get the arguments to send to the view.
  $arguments = ...;
  if ($view = Views::getView('my_view')) {
    $display = ...
    $build['some_name'] = $view->buildRenderable($display,$arguments);
    $body = $node->get('body')->value;
    $node->set('body')->value = $body.render($build['some_name']);
  }
}


Edit panel not showing up (Gear -> Edit Panel -> NOTHING??)

You or one of the modules you installed is loading latest version of jQuery.  In the latest version of jQuery code like

if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {}

does not work.

This code is in one of the Drupal core files. You can find it in modules/overlay/overlay-parent.js file on line 932, 975 and 985.

I do not recommend editing this file, but you can test this change on your localhost to make sure it is the latest version of jQuery which is causing this issue.


how to get the count of total comments posted for specific content type including deleted comments too?

You can always dig around the database with a db query with something like:

$content_type = 'mycontenttype';
$query = db_select('comment', 'c');

$query->join('node', 'n', 'n.nid = c.nid'); //JOIN node with comment
$query->fields('c', array('cid')); //SELECT the fields from comment
$query->condition('n.type', $content_type, '=');
$query->orderBy('c.cid', 'DESC'); //ORDER BY comment id

$num_comments = $query->countQuery()->execute()->fetchField();
$latest_comment_cid = $query->execute()->fetchField();

EDIT
In this example I assume you mean unpublished comments and not deleted. See Anil's answer if you want to track count of deleted comments as well.


Have in mind that a post is a node, so it doesn't behave such as comments and so, it doesn't fall into the same logic.
If you want moderation for posts, you should do something else, maybe playing with rules (and or views) to establish a moderation panel/system.


Rule to complete checkout for all orders

There is no default Commerce rules action that selects all orders. You're going to have to build your own action, or find a contrib module that provides it for you, that selects such a list of commerce orders to act upon.


Check if referenced field exists in commerce product display

If I understood your question correctly, you should check if that element exists; here's how:

if (isset($content[$my_field])) {
  //
}

This way if the field is not set, you won't get the undefined index error.


How do I drush vset a number with decimals?

Turns out that calling Drush as follows does the trick.

<-- language: lang-bsh -->

drush php-eval "variable_set('latest_version', '6.34');"

It also turns out that this is a bug, and that awesome greg_1_anderson fixed it within hours of me asking the question.


Wherever that "Illegal access" Ajax error comes from, I recommend to rebuild node access from the command line instead. With Drush the following command should do it.

$ drush php-eval 'node_access_rebuild();'

With that many (600k) records in your database it may also be better to have that done by some more advanced process like the one provided by the Node Access Rebuild Progressive module. It also provides its own Drush command.

$ drush node-access-rebuild-progressive

  Approach

  The module works by processing nodes in chunks, from highest node.nid
  to lowest, until all nodes have been recomputed, storing the last
  processed nid in a variable (d7) / as state (d8). This ensure no nodes
  can be skipped, while avoiding having to populate a Queue or other
  equivalent mechanism, which can be heavy in itself.


All modules will need to be have some tradeoff between a simple solution, and a powerful tool. Field slideshow is a relatively simple solution, while Views slideshow is a vastly more powerful tool.
Utilizing the power of Views, you have far better control of your slideshow, one example being, that you can easily create blocks.


A module to limit number of posts a user can make during a set period of time?

Maybe Node limit module can help? I haven't used it but it seems that this may be what you need.


views exposed filter on field collection item

Field collection items can perfectly participate as Views filters. The key is to use Views relationships. You can create a relationship for the portfolio field, and then in the filter specify to use that relationship. That will cause the filter to analyze the field collection's contents, as opposed to the host entity's.

For example, here I established a relationship to an image gallery collection, created a file id filter, and associated the filter with the collection. The fid filter is also exposed:


How to upload file in Webform content type

Yes you can upload files to webform. Create field for resume by choosing type as file. Check following screenshot


For logging you could use Watchdog. The first parameter $type can be used as a filter on the report page which is often handy.


It appears you may be having the same issue as this person - http://drupal.org/node/1136822

May I suggest you apply the tweaks mentioned in the issue, and if it improves your performance, perhaps consider writing a patch to place back in the issue queue.

I have cross linked the drupal.org issue with this, so that everything is visible


Panels, panel node print header and footer

I should use min-panel. Panel page and panel node both have page structure.


Views gives 200 instead of 404 if incorrect argument and a pager is present

I found a solution: I had to set "Show page not found" in the Global Null argument "When the filter value is not in the URL."


How to provide a translation for a string used within t()?

First, make sure you install the Localization update module.  It is the key to handling anything that has to do with translation.  Enable automatic translation updates.

If the module is an "official" module with a stable release. the Localization update module will pull down translations from localize.drupal.org - provided they exist.  If they don't exist, you should provide them (read about how you can contribute on localize.drupal.org) - and the Localization update module will install them for you within 24 hours (if you've enabled automatic updates).

If the module does not have a stable release, there will not be anything on localize.drupal.org.  In that case, you must add local translations using the built-in translation interface.


Create custom template for a specific node without node ID?

Sure, you can use hook_preprocess_node() or hook_preprocess_page() to suggest any template you want for a node or a page.  I am suggesting both because of the name you gave in your question page--node--11.tpl.php is really a page template not a node template.

Regardless, you could do this:

function YOURTHEME_OR_MODULE_preprocess_node(&$variables) {

  if ( /* whatever logic */ ) {

    $variables['theme_hook_suggestions'][] = 'node_whatever_you_want_to_call_it';

  }

}

or

function YOURTHEME_OR_MODULE_preprocess_page(&$variables) {

  if ( /* whatever logic */ ) {

    $variables['theme_hook_suggestions'][] = 'page_whatever_you_want_to_call_it';

  }

}

and now when that node is rendered, it will use node-whatever-you-want-to-call-it.tpl.php or if the page, page-whatever-you-want-to-call-it.tpl.php.


If you want to user tabs and have blocks inside them coming from then, then one very beautiful module which you can use is Drupal Quick tabs: http://drupal.org/project/quicktabs

This module works amazingly. It also takes arguments and allow you to do a lot of advanced modifications like Ajax call to the tabs or directly load them etc. You can check the Techtree website for an example of quick tabs that we have used in the side bar.


Webform is currently not enabled on any content types

Just make sure you have enabled WEBFORM in the Drupal menu modules


How to add multiple js files in hook_field_widget_form()?

Seems you missed step 3. from the README.

  Download the fancyBox plugin and extract the entire directory into    sites/all/libraries. (You may need to create this directory). The path
  to    fancyBox should be
  sites/all/libraries/fancybox/source/jquery.fancybox.js.    (the module
  uses the minified version, so actually jquery.fancybox.pack.js).

The second JS then doesn't fire anymore as the first JS virtually raised an exception already (due to the non-existent 3rd party library).


Menu Block - stopping displaying children after a specific level

You could use 'display:none' in the css as a solution.  I think using Nth-child would help achieve what you need http://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/


This is a known bug: https://www.drupal.org/node/2563515

As a workaround, remove the entity type definition (e.g. by removing the @ so it doesn't parse it as an annotation), clear cache, then uninstall.


You need to enable webform UI, then set in your sites/default/settings.php file the privates files directory path:
$settings['file_private_path'] = 'sites/default/files/private'; where 'sites/default/files/private' is your privates files directory path. You can choose another directory. And give to this directory the write permission. Then clear all caches. Now you can add files fied in your webform while adding new element. In the popup that appears, typing file, you will see all files type like image, audio, etc.


Solution:

We need a different path:

 * @RestResource(
 *   id = "custom_rest_resource_user_check",
 *   label = @Translation("Custom User Check"),
 *   uri_paths = {
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/custom/user_check"
 *   }
 * )

Source:
https://www.drupal.org/node/2799383#comment-11619919


Using a View as a filter criteria to another view

You can try the Views filter view sandbox module, which does exactly what you are asking for.

  This module will allow to filter results by another view.
  This other view is either not active on the current site at all, then the view is executed and the result is taken.

  If the view on the site was runned already, the result is reused


How to implement jQuery Accordion for a Menu?

You have to include the accordion library by adding this line to your theme's template.php:

drupal_add_library('system', 'ui.accordion');

Then you trigger the accordion by adding this to yout template.php or an external js-file:

$( "#menu-container" ).accordion( {
  header: "li",
  collapsible: true
} );


How do I redirect a user role on login (Drupal 6)?

I'm not 100% sure since I don't have a D6 to test, but you should be able to do this with rules.

If there's a missing link in rules it's straight forward to code your own condition or action:

add your own action
add your own condition


Load node entity from external script with image URI

you can try:

$image_uri  = $node->field_image_field->entity->getFileUri();

echo $image_uri;

$image_url= file_create_url($image_uri);

echo $image_url;

in the variable "$ image_uri" contains the uri of the image.

in the variable "$ image_url" contains the complete url of the image.

Note: please, change field_image_field for your machine name field


Facets hierarchical taxonomy terms not working

I fixed it by re-added the field from admin/config/search/search-api/index/default_index/fields and take the ID from the index instead of name. Then in the Facet settings use Transform entity ID to label. Then the hierarchical structure from the taxonomy terms works!


Notice: Object of class stdClass could not be converted to int in drupal_write_record()

The error is caused from the fact $account->picture is an object, and drupal_write_record() is trying to convert it to an integer, since the my_avatar_selection_usage defines fid as an integer value. See the following code used from user_save(), which the function invoking hook_user_insert().

  // Process picture uploads.
  if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
    $picture = $account->picture;

    // Omissis

  }

As you see from that code, the correct code you should be using is the following one.

/**
 * Implements hook_user_insert().
 */
function my_avatar_selection_user_insert(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture->fid;
    drupal_write_record('my_avatar_selection_usage', $usage);
  }
}

/**
 * Implements hook_user_update().
 */
function my_avatar_selection_user_update(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture->fid;
    $has_rows = (bool) db_query_range('SELECT 1 FROM {my_avatar_selection_usage} WHERE uid = :uid', 0, 1, array(':uid' => $account->uid))->fetchField();
    if ($has_rows) {
      drupal_write_record('my_avatar_selection_usage', $usage, 'uid');
    }
    else {
      drupal_write_record('my_avatar_selection_usage', $usage);
    }
  }
}


Form fields still treated as required even after setting #required to false

Have you tried unset() on the #required element, rather than making it false?


Fix for "'csrf_token' URL query argument is invalid" error during logout

You can use POST method on /user/logout without params and token, the cookie will be deleted so the user will be logged out, but in the server-side Drupal will not destroy the session, so you'll end up by having a lot of unused sessions...

I wonder why do you want to remove the _format=json from the URL ?


How to display an add content form inside another content view page?

With Advanced Form Block you can use a "Node add" form has a block, you could show it at the end of your node content using regions or node tpl file


`drush cc all` command takes too long time, what can I do?

The clearing cache it-self doesn't take a long time, since it's just truncating cache tables. What takes time the most is rebuilding the cache registry after that. Usually it's theme registry which scanning for all new hooks and all your Drupal folders for new template files, system which scanning files for the new modules and class files, and similar.

You can always clear specific cache by specifying drush cc theme-registry or any other.

It's highly recommended that you use PHP caching mechanism (e.g. OPCache, XCache, etc.) to speed up the processing. And memory-base cache to replace heavy usage on SQL tables (e.g. memcached or redis), so clearing cache would take no time, just by flushing the cache (e.g. echo flush_all > /dev/tcp/127.0.0.1/11211 in Bash).

Alternatively you can always clear cache manually, e.g. by:

echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v

Debugging

To check what's taking the most time specifically, you need to debug/profile it (e.g. XDebug, XHProf, phpdbg, dtrace).

On OS X/Unix, this can be achieved by dtrace (after running drush):

sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'

On Linux, use strace, e.g.

strace -e trace=sendto,recvfrom -s1000 -p $(pgrep php)

To look for some specific things, try adding e.g.: strace ... 2>&1 | grep -C5 UPDATE.


Using a Paragraph field value as a View filter

Have you seen these Modules, i have not used them but they look like they do the job.

https://www.drupal.org/project/viewsreference
https://www.drupal.org/project/viewfield

Otherwise you could preprocess your paragraph and render the view

function renderView($viewId, $displayId, $arguments)
{
    $result = false;
    $view = Views::getView($viewId);

    if (is_object($view)) {
        $view->setDisplay($displayId);
        $view->setArguments($arguments);
        $view->execute();

        $result = \Drupal::service('renderer')->render($view->render());
    }

    return $result;
}


Why has this "details" accordion appeared in this view?

I ran into this issue with a View as well. Fortunately, this issue was reported to Drupal Core, fixed and released in Drupal 8.9.2 and Drupal 9.0.2 all in under a month which is quite commendable.
I just tested this issue by upgrading a test to Drupal 8.9.2 which resolved this issue.


Is there an opposite / reverse of entity_uri()?

I'm afraid there's nothing (existing at least) that will do that, the URI function is provided by the module implementing the entity (in hook_entity_info()) and the method within that function is completely transparent to Drupal...the core entity module doesn't give modules the chance to implement a function that reverses the process, nor does it store how the conversion was made.

Because of this I don't think a fully generic function is possible, however you could do it on a type-by-type basis:

$uri = entity_uri('node', $entity);
if (preg_match('/node\/([0-9+])/', $uri, $matches)) {
  $entity2 = entity_load('node', array($matches[1]));
}

You could then extract that logic to build a slightly more generic function based on the known attributes of your Drupal installation...it's not a pretty way to do it though, I'd love to hear a different solution to this.


How to use uploaded images from an image gallery in an article?

The module Entity reference can do the job.

  Entity reference provides a field type that can reference arbitrary
  entities

...ie your gallery files!

With this module you can add an "Entity Reference Field" related to your gallery files to the Article Content Type.

Then, for each Article, you can add 1 or more images among those already loaded.


Why is Views "Query Execute Times" so high?

When testing be sure to turn off the query cache  SET SESSION query_cache_type = OFF

Next step is to run EXPLAIN on the sql.

EXPLAIN SELECT users.picture AS users_picture, users.uid AS uid, users.name AS users_name, users.mail AS users_mail, users.created AS users_created, userpoints_total.points AS userpoints_total_points, 'user' AS field_data_field_motorcycle_user_entity_type, 'user' AS field_data_field_review_count_user_entity_type, 'user' AS field_data_field_address_user_entity_type


Getting literal ampersands from summary field in a view of fields

Override the template and use the twig filter "raw":

Add template file to your custom theme. E.g. /themes/custom/MYTHEME/templates/views-view-field.html.twig
In the above template file add {{ output|raw }}
Clear cache and refresh

  The raw filter marks the value as being "safe", which means that in an
  environment with automatic escaping enabled this variable will not be
  escaped

Source: https://twig.symfony.com/doc/2.x/filters/raw.html


Fixed by adding this function to my theme

function YOURTHEME_preprocess_node(&$variables) {

$block = \Drupal\block\Entity\Block::load('views_block__sidebar_meetings_group_page');
$variables['block_output'] = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);

}

thanks @ivan jaros and @berdir


What is the most sustainable way to obtain aggregate information on fields?

The View field module allows you to expose field tables as base tables to views. This differs from Views default behavior in that the base table is the field table and not an entity to which the field data is then loaded from. For example when selecting node as a base table you can then add fields, but the primary (base table) in the query is still node which depending on your data can screw up the aggregate functions (aka a many-to-one relationship of some fields to the node).

Views field allows you direct access to the field tables which means aggregate functions work properly. Additionally if you need to do "interesting" joins to other field tables you can control them completely using the following.

/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(&$data) {
  views_field_add_multi_join($data, /* see docs */);
}

Which is fairly simple to use and allows you to then perform aggregate functions across multiple field tables at once. You can then manually invoke a view $view->execute() and pull the results off the view. There are examples of this in the views documentation.

The benefits of this approach over EntityFieldQuery is that you can manage the process in Views (which almost everyone will already be using) and allow it to perform the physical query building in less direct way which helps elevate possible breakage down the road. In addition many times you will want to display such aggregate data on an admin screen which you can then use the view to provide both a display and access the results in code for additional purposes.


Action when a comment has been replied to

I've got something similar in setting up a forum, where all posts on a topic are really just comments. We've set it up to allow people to "subscribe" to the topic via the Flag module and then have a Rule set up to notify all subscribers after a new comment is added. Here's the Rule (from /admin/config/workflow/rules )

And here's how it looks when you click "Edit" in the screen above:

So basically, I've set up an event for a comment being added to a forum topic, then under actions, fetch all the users who have flagged that node and loop through, sending them an email (which can be customized with tokens based on the newly added comment). You can automatically flag a user to a node when they create it or comment on it.


Using Rules module to Auto Post the content to Linkedin Account

Have you tried the LinkedIn Module?

  This module provides integration with the LinkedIn API. At the moment
  it supports the following features:

  Per-user OAuth authentication between LinkedIn and Drupal Post
  LinkedIn status from node edit form (like the Twitter module)
  Synchronise LinkedIn user profiles with a user profile tab in Drupal

For Drupal 7 it's still dev and there may or may not be any updates coming. But it would be a good place to start.


How to programmatically list users with a certain role?

In Drupal 7, user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE)
will load the user details for the given user IDs.
In Drupal 6, there isn't that function, but you can use $user = user_load(array('uid' => $node->uid));.


Proper way to alter field value from submit handler

Consider using the Force Password Change module which can already keep track of that.

First, add your custom submit handler to the beginning of the submit handlers array and not to the end, to ensure you "inject" the data before the user entity gets saved.
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  array_unshift($form['actions']['submit']['#submit'], 'user_form_submitted');
}

Second, depending a little bit on what field type exactly you added to the user entity, the form value needs to be an array of values. In the sample below I used a simple plain textfield to store the data.
function user_form_submitted(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form_state->setValue('field_password_changed', [['value' => 'test22']]);
}

Third, you somehow need to check if the password got changed at all or if just the user form got submitted. Again, have a look at the force_password_change.module to get an idea of what exactly you may need to check for.


Aside from just checking off those boxes on the search api page, you have to also mark it in the View exposed filter that your creating as seen below:


Views formatting: liquid number of columns?

You'll need to move away from using a table layout to one that uses divs instead, e.g an 'unformatted list' views style.

It's quite easy by piling a set of floated divs into a container.

If the container width changes, the number of items per 'row' also change.

e.g, something like this for the view items.

.views-row{
  float:left;
  margin:8px;
}


Error during entup when removing a field added in entity_base_field_info

drush entup is the wrong tool (I hope you have a database backup from before you've executed this command). After uninstalling the module containing the node base field, wait until cron has gradually purged the existing field data, see the change record Base fields with existing data can now be uninstalled.


You don't need any hook for this. Go to Configuration > Text formats (path may vary slightly, but it is available in versions 6 to 8) and simply add tags to the list:


In the file your_theme.info you should add

regions[new_region] = New Region

regions[new_region] this is the machine name so the variable will be $new_region

Then on page.tpl.php you should add the html and the php like

<?php
if ($new_region) :?>
<div id="new-region">
<?php print $new_region; ?>
</div>
<?php endif; ?>

Remember to flush the cache and do the performance after you modify page.tpl.php


Blacklisting specific tags from an input format instead of whitelisting

You can get that functionality out of the box with the HTML Purifier module.

Once you've installed the module, go to the admin/config/content/formats page, choose the text format you want to edit, and select the "HTMLPurifier" checkbox. In the settings below, quite a bit further down the page, you'll find the ForbiddenElements textarea:

That's where you need to put your disallowed tags. It's probably worth looking at the rest of the settings to make sure they match up with your expectations (there are a lot of them though, HTMLPurifier is pretty configurable).


Drupal Commerce payment transaction: execute script and pass variables

the transaction is meant to be created on a successful response of your provider (this could be payed, denied or whatever), usually an IPN.
meaning you have to provide a MENU_CALLBACK item in hook_menu.
most likely information about the order will be posted, make sure you get the order id back.

if you really want that on the payment form submission, just call the method (commerce_payment_ideal_transaction) in the hook_redirect_form. the question here is, how do you decide if a payment was successful or not ;)


There is more than one way to do it - for instance, it depends on where the images are coming from. You could do it with Views for instance, creating a list of images, adding the correct classes, and applying the js from your custom theme.


Re-writing View Comment link to display node title

If you are using Drupal 7 you can take advantage of core's new API to create permalinks to comments.

From the patch on d.o

  Since comments are paged there is no way to guarantee which page a
  comment appears on. Comment paging and threading settings may be
  changed at any time. With threaded comments, an individual comment may
  move between pages as comments can be added either before or after it
  in the overall discussion. Therefore we use a central routing function
  for comment links, which calculates the page number based on current
  comment settings and returns the full comment view with the pager set
  dynamically.

In drupal 7, this routing function is

comment/%comment

So it would be best in your view (with comment as a base table) to pull out:

cid (display none)
title (node relationship, required)

Display title as a link, path it to

comment/[cid]

If you are using Drupal 6, I would suggest rolling with contrib to fix core - with https://drupal.org/project/permalink which backports the above functionality


Update the date field to the date & time of the node being updated

Nodes already have a 'changed' property that would track this. Any reason why you don't want to use that? You can use {{ node.getChangedTime() }} in a Twig template for the raw value, or you can preprocess the node and take the changed value and format the date to your need into a new variable for the template. This way you don't need another field and Rules and reduce a lot of overhead.


How do I migrate a custom field from WordPress?

Neat. It looks like wordpress is storing a small fragment of the youtube url in the DB. I'm not sure how the the cck video field stores content -- probably in its own field, and it probably has to be set for "Youtube" before you attempt a migration.

Once you figure out where the youtube ID will be stored in a drupal field. See the documentation on how to extend worpress migrate:

  Extend the appropriate class, such as the WordPressBlogEntry class with your custom behavior - add field mappings in __construct(),
  manipulate the body ($row->content) in prepareRow(), etc.
  Extend the WordPressBlog class, and override migrationClasses to point to your custom classes:

<?php class MyCustomBlog extends WordPressBlog {
public function migrationClasses() {
    $classes = parent::migrationClasses();
    $classes['WordPressBlogEntry'] = 'MyCustomBlogEntry';
    $classes['WordPressPage'] = 'MyCustomPage';
    return $classes;
} }

In your custom migration class you would then define the migration of a field using a Mapping as something like:

 // dest (a field in the node) <- source
 $this->addFieldMapping('youtube_url', 'source_yt_value');

In your custom migration class you will of course have access to the typical helper methods used in migrations to "prep" the data (retrieve the youtube url from that CDATA crud), and translate it into a valid video blurb for drupal.


Making a custom theme and want to know how to style first post different from the rest

What you can do is:

Create a custom page using hook_menu.
Use Drupal's Database (DBTNG) to get your list of contents. You can do two separate queries for this. The first one would just return one result with more fields than the second. Also you could add the Drupal's pager functionality right out of the box here since you will be using db_select.
Use hook_theme to create the template for your "node teaser" so that it makes your raw data manipulation separate from your presentation hence the need for a custom template.

Your main code would somewhat look like:

function YOURMODULE_page_view() {
  $special_node = db_select(...);
  $nodes = db_select(...);
  $output = array();

  // do stuff here for $special_node_fields
  $output[] = theme('custom_node_theme', $special_node_fields);

  // look through all remaining nodes
  while($nodes) {
    // do stuff here for $node_fields
    $output[] = theme('custom_node_theme', $node_fields);
  }

  return $output;
}

This gives you better view on the data manipulation you need to get the list you need.

Also don't forget to replace the Default front page value with your custom page in the Site Configuration page.


why cannot I edit admin permissions for the permission page in D8?

That's because administrator is an admin role, that means it has all the permissions all the time. Editing it via drush won't do anything.

If you want a role not have all permissions it must not be an admin role, but that means you need to manually add new permissions.


How do I get the placeholder attribute into a Search API Solr Search field?

The problem is the views exposed filter form always has an ID of "views_exposed_form", nothing more specific. My low-rent way round it was this:

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['search_api_views_fulltext'])) {
    $form['search_api_views_fulltext']['#attributes']['placeholder'] = t('blah');
  }
}

That works fine for my use case, but if you need something more specific you should be able to look in the $form or $form_state and find the View object, which you can use to identify which view/display is currently being altered.


Well, the code in tutorial that beth mentioned has bugs and does not work. The best solution I've found up to now is this:

<?php
function YOUR_THEME_menu_tree($tree) {
  if (preg_match('/A unique string in your menu/', $tree)) {
      return '
' . $tree . '
';
  } else {
    return '
'. $tree .'
';
  }
}
?>

You can use any unique path or link title as string to identify the menu. This solution was inspired by a comment in the cited tutorial.


How can I set per file access controls by role to files on a node

The first thing to understand when you want to shield files from unauthorized access in Drupal is the difference between the Public and Private stream wrapper. By default files are uploaded in Drupal in a public directory and no matter what you do with access control on entities the files will be publicly available directly via the url to the file. So first make sure you setup Drupal to be able to serve files through Drupal via the Private file system (stream wrapper), instead of directly through the web server (public).
Take a look at "/admin/config/media/file-system". You can read more about this on Drupal.org.

In any case you will need an extra access control module (and/or custom code). If you don't use Media and only use the Private files stream wrapper you will be able to shield files per role using the Content Access module.

If you want Media not only for access but also for the other nice features it brings think about this: it will not solve your file access issue out of the box. And the Content Access can't help you anymore because it really only works for nodes and not for File entities. Because Media depends on File Entity (separate module since version 2.x) you are no longer required to create node types for documents that need to be fieldable, this is nice. But currently there are no good contributed modules I know of that add granular access control to file entities. So you will need custom code to manage access. I could help you out in this case, but I guess it should be a separate question.

Edit:

I extracted a custom sample module from a project of mine which adds role based permissions to File Entities (untested), see:
https://github.com/dmsmidt/drupal_file_entity_access


Insert the the value in $form_state:

$form_state->set('store_value', 1);

And then later for example in submitForm():

$value = $form_state->get('store_value');

Don't use getValue() or setValue(), because this is for submitted values.

If you are migrating more forms from D7 to D8, use this as reference:

$form_state is now a classed object


How can I preview the Drupal page as specific users?

The module called masquerade can do it. Not sure if it is the one you are refering to though.

  The masquerade module is designed as a tool for site designers and
  site administrators. It allows a user with the right permissions to
  switch users. While masquerading, a field is set on the $user object,
  and a menu item appears allowing the user to switch back. Watchdog
  entries are made any time a user masquerades or stops masquerading.


Some nodes served headless Drupal and some nodes served with Drupal

Take a look at the Permissions by Term module.  You can add a term field that defines the site(s) the node is accessible by and limit access to content authors on the main site.

Your API for the microsites can use this to limit access by site as well.

If that one doesn't work, it's description lists another module that might work.


The easy way then is to hard code this into your theme.

Open your template.php file in your theme's root folder. Add the following function in that file:

function MYTHEME_preprocess_user_picture(&$vars){
  if (!$vars['logged_in']) {
    // user is anonymous
    $path = variable_get('user_picture_default', FALSE);
    $style = variable_get('user_picture_style', FALSE);
    if ($path && $style) {
      $vars['user_picture'] = '<img src="' . image_style_url($style, $path) . '" />';
    }
    else {
      $vars['user_picture'] = '';
    }
  }
}

Replace MYTHEME with the machine name of your theme (similar to the MYTHEME in MYTHEME.info file). Then make sure you add a default picture at:

admin/config/people/accounts

The easiest is to just paste in this in the Default picture text box:

public://default-picture.png

and under the folder sites/default/files include the default-picture.png file. But that is obviously just a suggestion and you can put your picture anywhere.

If you don't see any default picture when viewing the site as anonymous then your default picture path is incorrect. Test it by creating a new user without a picture.