In Drupal 6, how to display two grouping fields such as Country then Province?

If you are comfortable with theme templates, you could do this by modifying the Style output, eg:

for your View.  Here I created a quick View called for-da-grouping like this:

which has the node title and then two fields, country and province which are excluded from display.  I am sorting first on Country and then within that Province, so, given the same information in your example, this produces:

But, if you add some logic to your new Views template:

<?php
/**
 * @file views-view-unformatted.tpl.php
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */

$country='';
$province='';

/*
  drupal_set_message('
' . print_r($view->result[0], TRUE) . '
');

    [node_title] => object 1
    [nid] => 660
    [node_language] =>
    [node_data_field_da_country_field_da_country_value] => Canada
    [node_type] => page
    [node_vid] => 660
    [node_data_field_da_country_field_da_province_value] => Ontario

*/

?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php if ($view->result[$id]->node_data_field_da_country_field_da_country_value!=$country): ?>

      <?php print check_plain($view->result[$id]->node_data_field_da_country_field_da_country_value); ?>
      <?php $country=$view->result[$id]->node_data_field_da_country_field_da_country_value; ?>

  <?php endif; ?>
  <?php if ($view->result[$id]->node_data_field_da_country_field_da_province_value!=$province): ?>

      <?php print check_plain($view->result[$id]->node_data_field_da_country_field_da_province_value); ?>
      <?php $province=$view->result[$id]->node_data_field_da_country_field_da_province_value; ?>

  <?php endif; ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>

You can get:

Now, things to look at in specific:

You need to sort your View first by country and then by province so the data is in the right order to begin with.
You need to know your Views results, they are stored in $view->result and you can get what you need out of looking at $view->result[0] and in my view, my two fields I want to group on are called node_data_field_da_country_field_da_country_value and node_data_field_da_country_field_da_province_value  but yours are most probably going to be different but the logic is still the same:  Only display the country and/or province if it has changed since the last time it was displayed.
Add some css to your new group headings and you should be all set.

If not, you can investigate the Views Field Module and so forth mentioned in https://stackoverflow.com/questions/9015500/how-to-group-by-more-than-one-field-in-drupal-view for alternative methods.


Maybe View Reference ?
Please refer to this page


How can I print Views language-specific $field variable values inside a views template?

Use dpm() to output $field in your template.

To make PHP not die with an out of memory error, use a static flag to ensure it only prints once.

static $_foo;
if (!$_foo) {
  dpm($field);
  $_foo = TRUE;
}


Load all nodes from content type on front page without views

I use the following code to retrieve all nodes of a type:

$type = 'example';
$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('type', $type)
  ->condition('status', 1);
$nids = $query->execute()->fetchCol();
$nodes = node_load_multiple($nids);


Have a look at the Computed Field module. Some details about it (from its project page):

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

You may also want to look at its Community documentation, especially its child page about "Calculating a duration given a start and end time", here is a quote from it:

  ... create a new computed field to calculate the duration as a decimal number of hours (where 1.5 is 1 hour and 30 minutes).


Try:
The first thing you’ll need is to import the dependency for “child process.” Next, you’ll want to set up an array variable containing all the paths to files you want auto-cache clearing setup for. This will basically be any Drupal template file. I would start with the main template directories you know you need it set up for and then add the additional paths along the way. Once we have our variables set, we then build our “clearcache” task using the “child_process” dependency that is shown below. Once we have all the pieces setup, we combine them in a watch task and let the magic happen! Using this task in your workflow will save you so much time, and even more importantly, save you the headache of clearing your cache every 2 minutes.
If you do run into some issues having your task running, make sure your Drush is setup and working in your command line as these Gulp task relies on Drush to complete its work.
code:

var cp = require('child_process');
var drupal_files = "paths/to/your/drupal/files/you/want/auto-cache-clearing";

// Clearcache Task
gulp.task('clearcache', function(done) {
  return cp.spawn('drush', ['cache-rebuild'], {stdio: 'inherit'})
  .on('close', done);
});

gulp.watch(drupal_files, ['clearcache']);

Source: http://serversideguy.com/2018/02/05/how-can-i-automatically-clear-cache-for-drupal-using-gulp/


Why not just set up a workflow that includes a default "no_workflow" state?  Use rules to automatically set all nodes to the "no_workflow" state upon creation.  Then, when a node is flagged, use rules to set it to the appropriate state.  That way, all nodes are subject to the workflow, but by default they don't move through the states until they are flagged.


What file and directory permissions do I need in my Features directory?

This is because Feature is doing something that's a little bit out of the ordinary ;-)

This is also one of the reasons I have my filesystem laid out as follows:

 sites/all/modules/
  - custom // Custom code.
  - contrib // The actual features.module is here.
  - features // This is for my Feature modules.

Because this means I can set the permissions on my Features differently to the contributed modules directory. Usually 760 I think. Then so long as the features directory is owned by a group that Apache is a member of, everything should work as expected. I do sometimes have to run a chown -R from my Drupal root, but that's because *nix admin has never been a strong point of mine.

Obviously everything on my world facing servers (read: not my local machine) is more secure than this, as should yours be.

That said, on my local machine I always end up forgetting something and just chmodding everything to 775 because I'm in a hurry.


How to add class to the options for type radio present under radios?

You are almost there just you should change $variables['element'][$tid]['#attributes']['class'] instead of $value['#attributes']['class'] try with:

/**
 * Implements hook_preprocess_HOOK().
 */
function template_preprocess_bef_radios(&$variables) {
  // No need to this two lines
//  $variables['children'] = Element::children($variables['element']);
//  _bef_preprocess_nested_elements($variables);
  foreach($variables['element'] as $tid => $value) {
    if (is_numeric($tid) || $tid === 'All') {
      $variables['element'][$tid]['#attributes']['class'][] = Html::cleanCssIdentifier($value['#title']);
    }
  }
}


Why 'excluded from display' fields in views are not available in template files?

If you exclude any field that means you don't want to display that fields.
So obviously that fiels is not avilable to any template for exclude's default behaviour. That field only available as token in views.


Drupal sites in subdirectories are now fully supported in Aegir 2.x since version 2.0


Can do it with drush

cd path/to/project
drush status

look for  Database name line

or look in your Drupal Settings File sites/default/settings.php and look for database found in the databases array

$databases['default']['default'] = array (
  'database' => 'database_name',


How to restore private file structure after major version update?

Edit: We have a workaround, I hope this question can serve as a good practice guide of good to debug complex software like Drupal showing unexplainable errors or WSOD. Wish we had followed our own advice to not waste time on our futile attempts time.

tl;dr It was the core module Database logging 7.42    Logs and records system events to the database. which is interfering with private files in our specific setting. We disabled most modules including core, and brought them back one-by one. Database logging is reproducibly inducing the error on activation.

Don't panic and make a debugging plan, listing options of what could be checked, and then stick to it until everything has been checked. If out of options, try to shake things up
Compare your system to a vanilla system and note down what is does differently
Modules might interfere with each other in unexpected ways or with your specific configuration. That doesn't mean there is a bug in any of those modules. Boil down your system to the least complex configuration possible, remove any unneeded entry in your configuration file, disable any module that can be disabled including core modules, suspect everyone.
Check if error still present, if not re-enable all modules one-by-one, and note down which configuration change causes the error. Otherwise, start debugging going to 1.

Cheers


How to get node Bundle in hook_form_alter on field config form?

You're looking for FieldDefinitionInterface::getTargetBundle

  Gets the bundle the field is attached to.

  This method should not be confused with EntityInterface::bundle() (configurable fields are config entities, and thus implement both interfaces):

  FieldDefinitionInterface::getTargetBundle() answers "as a field, which bundle are you attached to?".
  EntityInterface::bundle() answers "as a (config) entity, what is your own bundle?" (not relevant in our case, the config entity types used to store the definitions of configurable fields do not have bundles).

e.g.

$target_bundle = $field->getTargetBundle();


Why doesn't watchdog() run when I execute my custom module from Drush?

This is working for me, using the latest Drush dev-master:

drush @dev ev 'watchdog("system", "test watchdog message.");'

What I am doing here is just calling the 'watchdog' function directly with the php-eval command, after bootstrapping a dev site.  This should produce the same results as a watchdog function called from a module, and in fact I see the message logged in the Drupal admin/reports/dblog page.

Drush does install a watchdog handler, so that it can log the watchdog messages to the console in addition to the dblog page; however, many of these messages are ignored by Drush as uninteresting.  To see the full range of watchdog messages that Drush sees, set the --watchdog flag to 'print':

drush @dev --watchdog=print ev 'watchdog("system", "another watchdog message.");'

You should see this message printed in the console, and it should also appear in the dblog page.

I'm not sure why you are not seeing anything in your dblog page, but you might try upgrading Drush (if you're running an old version), and try some of these commands and see what results you get.  This should give you some indication of where the problem is, at least.

UPDATE:

It seems impossible that the Drush hook should be called, but that nothing should be added to the dblog.  The watchdog function in core does nothing but call hooks:

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/watchdog/7

The actual database write happens in function dblog_watchdog(), which is in dblog.module.  It invariantly writes the entry to the database.

The only guess I have at this point in time is that perhaps you have multisite set up, and Drush is targeting the wrong site or database when you call your menu hook via a drush command.  drush status might help determine if this is the case. Next step would be to put a breakpoint on dblog_watchdog(), or add some sort of print statement there and see what happens when you run your function from Drush.


How to handle a node translation containing an entity reference with a managed field property

There are a number of issues with reference counting files: see this overview. You might be affected by $entity->isDefaultTranslation() behaves incorrectly when changing default translation, causing file/image field usage to be set to zero, causing files to be deleted.

Note that due to the potential for lost data, as of 8.4 the default behaviour has been changed to not delete files even if their ref count reaches zero. See the CR for more.


How to manage the display of a multiple value field in a individualy way?

I got this creating Dynamics Fields with the Display Suite module. Here is a quote about it (from the module's project page):

... allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.


This should do it:

$redirect = new TrustedRedirectResponse($url);
return $redirect->send();


Access denied occurs after translate menu link

You need to make sure the menu is translatable.  Do this by clicking on the "Edit Menu" option and clicking on "Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized."

The click "Save".

The path would be as follows: site/admin/structure/menu/manage/menu_id/edit


You need to clear the cache before any templates you add will be recognized.


Full name field on node using Display Suite

It sounds like you need a field formatter. You have a few options:

Use Drupal's mechanism and create one yourself.
Use the Custom Formatter module to create a custom formatter.
Use Display Suite to create a custom code field.

If you aren't comfortable with coding, options 2 and 3 are good choices. Option 1 is leaner since if you already have a custom module it wouldn't add the overhead to your site of enabling another module.


what is #target_type in EntityAutocomplete?

The ID accepted from EntityAutocomplete is the ID of any entity defined from Drupal core, or third-party modules.

You don't normally need to have a list of all possible entity IDs, since you normally know which entity your code is going to autocomplete, but the list can be easily obtained using the following code.

print_r(array_keys(\Drupal::entityTypeManager()->getDefinitions()));

I ran drush ev "print_r(array_keys(\\Drupal::entityTypeManager()->getDefinitions()));" on my test site, and I got the following.

[0] => block
[1] => block_content
[2] => block_content_type
[3] => comment
[4] => comment_type
[5] => editor
[6] => field_config
[7] => field_storage_config
[8] => file
[9] => filter_format
[10] => image_style
[11] => configurable_language
[12] => language_content_settings
[13] => mollom_form
[14] => node
[15] => node_type
[16] => rdf_mapping
[17] => responsive_image_style
[18] => search_page
[19] => shortcut
[20] => shortcut_set
[21] => action
[22] => menu
[23] => taxonomy_term
[24] => taxonomy_vocabulary
[25] => tour
[26] => user_role
[27] => user
[28] => view
[29] => menu_link_content
[30] => date_format
[31] => entity_form_display
[32] => entity_form_mode
[33] => entity_view_display
[34] => entity_view_mode
[35] => base_field_override


Wrapping multiple cck fields into a single div tag for theming?

In your node templates, you have access to the $content variable, which includes all of your fields mushed together as CCK et al wants them, but you also have the $node object which includes all the raw information about your node.

So, first thing to do is to put a

<php drupal_set_message('
' . print_r($node, TRUE) . '
'); ?>

at the beginning of your node-TYPE.tpl.php file to see what you have to work with fieldwise.  There you will see lots of information, but basically, it is broken down into stuff like

 field_name[0]['value'] = // raw information stored in the database
 field_name[0]['safe'] =  // the above info in a safe format
 field_name[0]['view'] =  // the above info passed passed through the widget

So.  If you want to put some of the fields in one
 and some in another you can do something like

   <?php print $node->field_name[0]['view']; ?>
   <?php print $node->another_one[0]['view']; ?>

   <?php print $node->yet_another[0]['view']; ?>
   <?php print $node->one_more[0]['view']; ?>

Now, of course, you probably don't want to create everything yourself, so you then add

 <?php print $content; ?>

but lo and behold, you get the fields you printed manually in there as well.  To get rid of that duplication, go into your content edit screens and in the Display Page (admin/content/node-type/NODETYPE/display) just exclude them from $content in your teaser and/or full node display) and they should be displayed just once now in your custom
s.

When all is working, take out that drupal_set_message() so you don't totally confuse your users :)


I have redone my code as suggested in the comments so that it uses Drupal behaviors and the Drupal's javascript-api. I also moved my code out of the existing theme's script.js to its own file, and added that file to the scripts array in the theme's .info file.

Below is my updated code, in case it should help anyone that encounters this same sort of problem and is unfamiliar with Drupal behaviors. This has solved my problem with my code no longer working once the JS is aggregated and/or cached.

   (function($) {
     Drupal.behaviors.contactLinkHoverPopout = {
         attach: function(context, settings) {
             var div = '
' +
                 '10320 Globe Road
Morrisville, NC 27560
' +
                 'Phone: 919-361-4333
' +
                 'Fax: 919-361-4388
' +
                 'info@dosoffice.com';

             var popupVisible = false;

             // we only want mouseovers applied once!
             $('a.contact-link', context).once(function() {
                 // add the invisible popup div
                 $('body', context).append(div);

                 // add mouseover to contact-link
                 $('a.contact-link', context).mouseover(function() {
                     $('div.contact-popup', context).css('left', event.pageX + "px");
                     $('div.contact-popup', context).css('top', event.pageY + "px");
                     $('div.contact-popup', context).css('visibility', 'visible');
                     popupVisible = true;
                 });

                 $('div.contact-popup', context).mouseover(function() {
                     $('div.contact-popup', context).css('visibility', 'visible');
                     popupVisible = true;
                 });

                 $('a.contact-link', context).mouseout(function() {
                     if (popupVisible) {
                         $('div.contact-popup', context).css('visibility', 'hidden');
                         popupVisible = false;
                     }
                 });

                 $('div.contact-popup', context).mouseout(function() {
                     if (popupVisible) {
                         $('div.contact-popup', context).css('visibility', 'hidden');
                         popupVisible = false;
                     }
                 });
             });
         }
     };
 }(jQuery));


Hide fields from "address_field Module" form

in a hook_form_alter() add:

   hide($form['field_address']['und'][0]['street_block']);

you can use dpm($form['field_address']['und'][0]) to get the name of the city, and country fields.

You could also use CSS to hide the fields but I ran into problems where browsers prefilled those fields. It's better to hide it with a hook.


Just to break the process down a bit (based on your other questions:1,2); when you submit a node form:

node_form_submit() calls node_save().
node_save() immediately calls node_invoke_nodeapi($node, 'presave'); to inform other modules about the presave.
node_save() then sets up a few properties on the node object, and the node record is written to the node table in the database using drupal_write_record().
At the very, very end of the function (after the data has been written to the node table), node_invoke_nodeapi() is called again with either 'insert' or 'update', depending on the current operation being run.

If you look through those functions, and the summary above, you'll see that the node data is 100%, definitely committed to the database before the 'insert' or 'update' operations are run for hook_nodeapi().

If that's not happening for your installation I would strongly recommend replacing core with a fresh version, as it sounds like something's gone horribly wrong!

Getting to the actual question; the only way you can add a post-save hook is to add another line in the core node_save() function to invoke it. But you would be adding it immediately after the call to node_invoke_nodeapi($node, $op); (where $op is 'insert' or 'update') anyway, so I'm not sure that would help.


Enable Relationships in Views with Entities?

You will need to use (or override) the views_handler_relationship class to create the relationship, and also use hook_views_data_alter(&$data) to tell views how to use the handler and with which tables/columns it applies.


Multi step user registration form drupal 6

This blog post may help you: Multistep registration form in Drupal 6


Hide "language menu" next to search bar / login menu

Head over to relative path admin/build/block/list, to bring up a list of blocks configured for the theme that you're using. Pretty sure you'll find a block titled something like "language switcher" (or similar to that), which is locate in your "header" region (or some other theme region). Change that to <none> (to not show that block in any theme region. Then check if it solved your question.


How do I hide a field from a Profile2 form without deleting it?

You could do it using the Field Permissions Module, and set it to admin only. It can easily be changed later to allow everyone to see the field.

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


You can use Views slideshow module :

  Views Slideshow can be used to create a slideshow of any content (not
  just images) that can appear in a View... Potential uses :

  News item slideshow (such as the title, image and teaser of the last 5 news articles submitted)
  The last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).
  Rotate hottest new products, contact links, share links, entire nodes, categories, image galleries, etc.

There are many tutorials links on the project page , i.e how to create a simple slideshow with some node fields.

Define the relationship between your images & maps ( taxonomy ? fields of the same node ? ...), set a view showing them, then display it as a slideshow.

If you can't find how to join your content in a view query, have a look at Multiple nodes in one slide using views slideshow or another module ...


Did you double check that you installed the Facebook PHP library correctly per the README?

2. Upload facebook-php-sdk library (http://github.com/facebook/php-sdk/) into the libraries folder so that it looks like 'sites/all/libraries/facebook-php-sdk/src/facebook.php'.

The error you are getting looks like it is coming from a library function not in memory.

You can confirm whether this is loaded or not on your admin 'status' page. You should also check the drupal logs to see if there is any more descriptive error to share.

If its in the right place but not loading, you might want to check this thread:

http://drupal.org/node/1318296

for advice on how to get it to work with the libraries API.


Use Node clone module and remove the domains for which you don't want to publish the content.

This is what Node clone modules does:

  The clone module allows users to make a copy of an existing item of
  site content (a node) and then edit that copy. The authorship is set
  to the current user, the menu and url aliases are reset, and the words
  "Clone of" are inserted into the title to remind you that you are not
  editing the original content.

And this is what Domain override module does:

  Provides an "Override" tab on node pages that removes the current
  domain from the node's domain access, clones the node, and publishes
  the clone to only the current domain.


I'm not sure what the Change combine with field action does but if you want to set the value of an entity reference field can't you just use the "Set a data value" action in your product_display loop for the entity reference field?


#required attribute not letting me to redirect a drupal 7 form

Modifying $form_state requires passing it by reference to the function.

function mymodule_form_view(&$form, &$form_state) {
  $form_state['redirect'] = 'http://localhost/d7/?q=node/3';
}


I think you should use format_date() function that allows you add you own format and Drupal will translate it into the currently website site language.


In your "submitForm" method write below code

 $form_state->setRedirect('machine_name');
 return;

where machine_name is the machine name mentioned in the routing file.

I hope this helps .. :)


How can execute batch api over cron jobs

You don't. Batch API is to do long-running processing with user-interaction.

For cron, you either use queue API or you just process for N seconds/things in your hook_cron() implementation, and in both cases, cron will be calling you repeatedly until it is eventually done.

If you want to process as fast as possible then either use a different queue processing that doesn't run on cron or make a custom script/drush command that you execute separate from cron, so that you don't block other cron jobs.


Why are my $messages delayed one page refresh?

Most likely the problem is that you are calling the form when the messages already have been created, which is why they don't appear. You need to call the form, earlier in the process of the page being built or get the messages, with drupal_get_messages.

What you really should do it is to create this functionality in a module and theme the page instead, of doing this in your theme. You could potentially run into many more problems like this.


How do I prevent accessing a page with /node/37 directly when an alias has been set?

You don't want to deny access to it but simply redirect to the aliased URL.

That feature is provided by the Redirect module and there's also a core issue to make core do that automatically.


create drupal 7 webform programmatically?

See code below:

function _add_webform_components($node) {
  $components = array(
    0 => array(
      'name' => 'First name',
      'form_key' => 'first_name',
      'type' => 'textfield',
      'mandatory' => 1,
      'weight' => 1,
      'pid' => 0
    ),
    1 => array(
      'name' => 'Name',
      'form_key' => 'name',
      'type' => 'textfield',
      'mandatory' => 1,
      'weight' => 2,
      'pid' => 0
    ),
    ... and so on

  );

  webform_ensure_record($node);
  foreach($components as $component) {
    $component['nid'] = $node->nid;
    $component['extra']['title_display'] = 'inline';
    $node->webform['components'][] = $component;
    webform_component_insert($component);
  }
  $email = array(
    'nid' => $node->nid,
    'email' => 'name@example.ch',
    'subject' => 'default',
    'from_name' => 'default',
    'from_address' => 'default',
    'template' => 'default',
    'excluded_components' => array(),
  );
  webform_email_insert($email);
}


How can to make required the fields keywords and description of the metatags module?

You can use code similar to the following in a custom module/theme:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['metatags'])) {
    if (isset($form['metatags']['description']['value'])) {
      $form['metatags']['description']['value']['#required'] = TRUE;
    }
    if (isset($form['metatags']['keywords']['value'])) {
      $form['metatags']['keywords']['value']['#required'] = TRUE;
    }
  }
}


Drupal 8 : Render a field collection item in a Twig template

I've just started learning Drupal and encountered the same issue.
I solved it by creating custom field formatter:

public function viewElements(FieldItemListInterface $items, $langcode)
{
  $elements = array();
  foreach ($items as $delta => $item)
    if ($item->value !== NULL)
    {
      $builder    = \Drupal::entityTypeManager()->getViewBuilder('field_collection_item');
      $elements[] = $builder->build($builder->view($item->getFieldCollectionItem()));
    }
  return $elements;
}


How to create a custom 'fluid' layout in Display Suite

Just select the custom layout in the Manage Display page:

And add the required CSS in your theme. See the examples included in Display Suite:


Rules send email on entityform submission with current node field content

Add an entity reference field to the entityform in question and - using Entityreference Current module - check the option to reference current. This gives you access to current page data.

It's at this point you may want to install the Hidden Fields Widget module which will allow you to set the entity reference widget to hidden. Do this if you don't want the field to be visible on your entityform.

At the time of writing this, you also need to patch the Hidden Fields Widget module with https://www.drupal.org/node/1821008 to support the entity reference field type.

Next, create your rule with Event: After saving a new entityform submission, Conditions: Entity has field (select the entity reference field) and Actions: Send mail.

Now all you need to do is add another condition relating to the field token you want to use in your email body. Use the previous entity reference field condition as your data selector, then select the relevant field. This will now be available as a token in the Send mail action.

You can do this as many times as you want to get each field out.

I'm sure there's a more efficient way of doing this, but this worked for me.


and  tags in a text field of format Full HTML are not rendered in a field based view

I confirmed on 8.7 that the following basic snippet is able to be used in Full HTML out of the box:

<form><input checked="checked" name="gender" type="radio" value="male" /> Male

<input name="gender" type="radio" value="female" /> Female

<input name="gender" type="radio" value="other" /> Other</form>

It's possible your particular snippet is being hit by the "Correct faulty and chopped off HTML" Format setting, so try it without that and see if it lets the code stay. Of course, this is not an ideal setting for a commonly used text format filter, so this snippet may be better off in a custom plugin block, or creating a new text format w/ the "Correct faulty and chopped off HTML" turned off, that can be used sparingly as needed.

UPDATE based on Views usage:

If you're using rewrite, it won't be possible out of the box to have it not strip tags, it's something baked into Views. You can override it at the theme layer - if for example you are using the body field, you create a views-view-field--body.html.twig file in your theme, and then put the desired wrapper tags around the {{ output -}}, e.g.:

{{ output -}}

And turn off rewrite in Views UI.


Customizable combo select multiple and autocomplete

As you suggest you have achieved the first one so supposing you have a dropdown with values then you can use the jQuery plugin / javascript to make the select an Autocomplete field. You can use select2

Thanks


How do I use CkEditor layout on textfield input?

CKEditor only works on a textarea, you can’t attach an instance to a textfield.

You could implement hook_form_alter and change it from a textfield, but it’s hard to see what the point would be.

If you need long text, just use a long text field. It was designed for your use case, so will always work as expected.


At least two ways of doing this come to my mind:

1. "Masking" your subdomain and proxying the content. What you do in this case, is that besides your mod_rewrite's redirection, you use mod_proxy to show your other domain's content without changing your URL. Have a look at Using mod_rewrite for Proxying.

2. Using the Domain Access module. Another option, maybe overkill if you are going to use this only for one page, but useful if you have to repeat this with many domains/landing pages.

Since this module allows you to create individual homepages on a per domain basis, you just have to add a second domain (domainB.com) and set /landing-page as Drupal's default homepage in the domain settings. Now when you go to domainB.com, your url bar will just show http://domainB.com but will render /landing-page's contents (since it's the homepage).


Create new page without using Views or Panels?

Yes, You can write a small custom module to create pages with out using heavy panels module.

Please see the hook_menu documentation.

function yourmodulename_menu() {
  $items['page_one'] = array(
    'title' => 'Title of Page',
    'page callback' => 'page_one_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['page_two'] = array(
    'title' => 'Title of Page',
    'page callback' => 'page_two_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

 function page_one_callback() {
   $content = "";
   return $content;
 }

 function page_two_callback() {
   $content = "";
   return $content;
 }

To make your life much more easy without any coding, just go to "node/add/page" and create a new page !


Is it possible to automatically add a taxonomy term for a content type?

In Drupal it is possible to associate a vocabulary to a content type: Once you created your vocabulary, and added the taxonomy terms, you go to admin/structure/types, and for the content type to which you want to associate the vocabulary, you click on manage fields; in my example, I am going to add a vocabulary to the Article content type.

In the Add new field column I fill the fields as follows (the value you use for the field name, and to the field title can be what you like better):

When you click on Save, you get the following page. (The shown error is just because I am creating a patch for Drupal 7; it's not something you should see.)

Select the vocabulary you want to associate with the content type, and click Save field settings. In the next page, you can select the default value for the taxonomy term, which by default is - None -; you can select the one that is automatically set. If the user doesn't change it, it will be the value associated with the node.

When a user will create a node of that content type, they will see something similar to what shown in the following screenshot:

In my case, I selected Overview as default taxonomy term.

When you create your vocabulary, you can set a taxonomy term that is the parent of all the other taxonomy terms, and select it as default value for the content type.

In this case, Golden apple is child of Apple, which is child of Fruits; Kaiser pear is child of Pear, which is child of Fruit.
As side note, the hierarchy of taxonomy terms that are shown in the node edit form is the one defined in the vocabulary you associated with the content type; this means that, if Apple is not child of Fruit in the vocabulary I am using, then it will not be shown as child, in the node edit form. The taxonomy term widget doesn't alter the vocabulary structure.


How to let an OG administrator contact (via email) all group members?

This question have been answer at -  How to loop over a list of Organic Group users using Rules

and at - How to send an email to Drupal 7 Organic Groups Role Members? in here is going to show you how to do it with a custom module.

There other alternatives:

1- You can use views_bulk_operations

  I would think you should be able to do it by adding views_bulk_operations to the mix-- that should give you the ability to email users in a view which you can setup with the criteria you need via filtering.

Source

2- You can do it with Rules

  Looping over a list can only be done in Rules (i.e. for Drupal 7).

Source


How to create nodes "emulating" form submit

Yep, look at drupal_form_submit.

  Retrieves, populates, and processes a form.
  This function allows you
  to supply values for form elements and submit a form for processing.
  Compare to drupal_get_form(), which also builds and processes a form,
  but does not allow you to supply values.
  There is no return value, but you can check to see if there are errors
  by calling form_get_errors().

// register a new user
$form_state = array();
$form_state['values']['name'] = 'robo-user';
$form_state['values']['mail'] = 'robouser@example.com';
$form_state['values']['pass']['pass1'] = 'password';
$form_state['values']['pass']['pass2'] = 'password';
$form_state['values']['op'] = t('Create new account');
drupal_form_submit('user_register_form', $form_state);

I find the easiest way to see what the form takes is to use the Net Panel in Firebug. Turn on Persist in Firebug and post your form, then look at the POST keys and values.


Change Views Display Title Programatically

Your code is working I believe, but it could be that "page_1" is not the correct page variant name...I had to use 'default', that was what I ran into when creating a test View and attempting to try your code out... in my case to verify, I enable kint, do a ksm($view) and check the 'display' array to verify the variants. You may need to alter 'default' to see the intended results. Also make sure to cache rebuild just in case drush cr afterwards, you may want to programmatically empty the cache bin for this View depending on the use case.

Also, you mentioned the hook affecting all the Views. That is true, but you could add some more granular logic to the hook to make it only affect specific View, by specifically drilling down to the ID (the 'machine name" in the Views GUI) and performing logic only if the machine name matches, e.g. if my View machine name is "foobar_view_custom", then you can do:

/**
 * Implements hook_views_post_render().
 */
function mymodule_views_post_render(ViewExecutable $view, &$output, CachePluginBase $cache)
{
  $display = $view->getDisplay();
  $id = $display->display['id'];
  if ($id === "foobar_view_custom") {
    $view->setTitle("PROGRAMMATICALLY CHANGED");
  }

}

The difference here is you are altering the actual data in the database for the title of the View entity in your first implementation, versus in the hook, it would only change it during rendering, so really depends on use case (if the title was dynamic based on date or something, the hook might be better. Long term alteration, like in an update hook or something, probably would want to alter the actual data with the entity method) Both implementations should cache just fine.


Here are three possible approaches to achieve your desired effect.

1. Hardcoding into a twig template for the custom block

If you don't need to modify the actual content defined within the body field of the custom block, and just want to hardcode the prepended text before the body content, creating a custom twig template for the block itself is probably easier for maintaining in the long run. This way it's easy to find and modify without the need to do any theme_hook function editing.

In your theme's template folder, add a block--[machinename-with-hyphens].html.twig template.
Copy the contents of the block.html.twig template that already exists in your theme or from a theme included with Drupal Core such as Bartik or Classy (/core/themes/classy).
Then in the template, add your markup and desired text before the {% block content %} section.  If your custom block has more than a body field, you can also render just the body field data using {{ content.body }}, and the other fields as {{ content.[field_machinename] }}

2. Hardcoding the text into a theme hook preprocess function

If you would rather avoid setting up a custom one-off twig template for the block and just want to hardcode the prepended text using a preprocess hook, you could:

Add a [custom_theme]_preprocess_block function. If your function doesn't explicitly inlcude the block's machine name in the function name, be sure to check the block machine name before prepending text and setting the content.
Create a variable for your custom markup/formatted text.
Concatenate that with the existing block content.
Set the 'content' variable in the preprocess function

See Drupal.org documentation for template_preprocess_block or hook_preprocess_block

3. Recommended Approach: no template or preprocess code required.

The easiest method to approach this might be to just add a custom field to the custom block type with the default value reflecting the prepended text. To do this:

Go to Structure > Block Layout
Select the Custom Block Library tab
Select Block Types
Choose Edit next to your existing custom block type or Add custom block to add a new custom block type.
In the Manage Fields section, add a field for the predefined text (or markup) to prepend.
In the Manage Display section, set the desired order for the fields to render.


Does the summary area support input filters?

Text filters should definitely work in the Summary. You can test this by creating a View that uses the formatter "Summary" or "Summary or Trimmed" and using an input format like Plain Text in the Summary. HTML tags should be stripped from your View.

It sounds like something else is at play here.

Edit your Content Type (Structure > Content Types > Your Content Type) and look for the field in question (probably the Body field.)

Make sure Text Processing is set to "Filtered Text (user selects text format)" and the "Summary input" box is checked.

In the "DEFAULT VALUE" fieldset, select the desired Text format (e.g., Full HTML).

EDIT:

I'm sorry, you are correct. The built-in summary is just a summary and it does not support text filters. HTML in that field will be stripped.

This thread on Drupal.org says this won't be fixed until Drupal 9:

https://www.drupal.org/project/drupal/issues/1529188

The workaround is to create a new field called "Summary" and set its text format to the desired WYSIWYG format:

Then, manage the display of your content type to hide the new field from the Default view mode.

In the Teaser view mode, hide the Body field and show the Summary field instead.

The other solution is to edit the "Filtered HTML" text format to allow the <span> tag and other HTML that you require.

Honestly, it's a bit ridiculous that you have to do this to get what you want. I guess it's just one more reason to look forward to Drupal 9!


You must have some kind of text filter that is acting on your text
see what filters are applied here:
admin/config/content/formats

Or you are using a WYSIWYG editor to add the link.  If that is ckeditor, you have to set relative links to "Other" rather than http in the link editor.


Additional field settings without creating a new field type

This works for me:

$field->setThirdPartySetting('mymodule', 'my_checkbox', $form_state->getValue('my_checkbox'));

After you save your field settings, the new third party setting should be available in your field config:

third_party_settings:
  mymodule:
    my_checkbox: 1

Here is a good article about this: https://www.webomelette.com/drupal-8-custom-data-configuration-entities-using-thirdpartysettingsinterface


Entity references linked to a wrong referent

I guess you need to enable entity translation for this field; it can be done in the field UI, after installing the Entity Translation module.


How to properly alter a field description in hook form alter

The difference is that $element['value']['#description'] is the description for the property value. If you have a field with multiple properties you can set a description for each property. This is the common practice, but a field widget doesn't have to do it this way. Check formElement() of the widget to see how the element keys are used. Most widgets copy the content of $element to the subkey value, but not all.


Form with AJAX callback to query database and display info in block['content']

You should do all the logic in the form function. However with your particular issue, I would approach it slightly differently. I would simply return the table HTML from displayMortgages() back to the form and display the table as part of the form. But just simply as a #type=> 'markup'. That way, your sort form and the results are one, and you don't need to worry about firing off another ajax command somewhere else.

So your form code would basically be:

function mortgage_multi_view_sort_form($form, &$form_state) {
  $form = array();

  // Default sort direction
  $sort_dir = 'DESC';

  $sortOptions = array(
    'DESC' => t('Mortgage Duration: Shortest to Longest'),
    'ASC' => t('Mortgage Duration: Longest to Shortest'),
  );

  $form['mortgage_sort'] = array(
    '#type' => 'select',
    '#title' => t('Sort By'),
    '#options' => $sortOptions,
    '#default_value' => 'DESC',
    '#required' => TRUE,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'ajax_select_callback',
      'wrapper' => 'replace_model_div',
      'method' => 'replace',
      //'effect' => 'fade',
    ),
  );

  // Check if a selection on the form has been made, if so then update the direction
  if (isset($form_state['values']['mortgage_sort'])) {
    $sort_dir = $form_state['values']['mortgage_sort'];
  }

  $result = db_query('SELECT * FROM {mortgage_database} ORDERBY duration '.$sort_dir);

  $form['result'] = array(
    '#markup' => (count($result)) ? displayMortgages($result) : '',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  return $form;
}

And you just need to return the part that's being replaced in your ajax callback:

function ajax_select_callback($form, &$form_state) {
  // Just a return of result is sufficient since it's being replaced
  return $form['result'];
}


By looking at the database commerce_order and commerce_order_revision I don't think order revision is implemented in a way that is revertible. Probably that is the reason we can't find revision revert functionality either in commerce core or as a contributed module.


Hide menu items from non-authenticated user

Follow Below things:

1) Make sure that in admin/people/permissions "View published content", "view own Unpublished Content are "Unchecked" for the "anonymous user".

2)  Still if you are getting those "Disclaimer and Policies" menu links.
   i) Create a  new menu and add those links in to that menu. While adding links Give the Parent menu link to "Main Menu". and save the menu.
   ii) Then admin/structure/block, configure the menu block: Give the permission to access only to Authenticated User  and save the block


I suggest you create a custom module and in hook_form_alter according to your expose filter module form_id  get your form element,then you can change the value of your expose filter without change the value of them (as what you want)
something like below code can help you

function yourmodule_form_alter(&$form,$form_state,$form_id){
   if ($form_id == "your_views_exposeform") {
            // first try dpm($fom); to see what you have there
            foreach($form['expose_your_field']['und']['#options'] as &$item){
            //  repalce label of select option items with what you want
            }
        }
        }


Truncate tables before uninstalling a module in Drupal 8

That's a known issue right now.

There's no way right now to hook into that automatically. And it came up a few times already here too. See this question for example: Module uninstall dependencies

Beside a form or a drush command to do the cleanup, there really isn't much that you do right now, other than improving core. What I'd like to see is a message on the uninstall confirmation form that tells you that it will delete all records of entity type N and then does so in a batch before actually uninstalling. See the referenced flag issue in the other question and my repeated suggestions to open an issue, but so far, nobody could be bothered with doing that. And I didn't find time myself either.

Update

Drupal 8.2 now offers a link on the uninstall form to delete all entities of the given type.


Yo Dawg, I heard you like $view->execute()

I searched on that error and you can increase the limit from 100 to something larger.
Increase the value of xdebug.max_nesting_level in your php.ini:

xdebug.max_nesting_level
Type: integer, Default value: 100
Controls
the protection mechanism for infinite recursion protection. The value
of this setting is the maximum level of nested functions that are
allowed before the script will be aborted.

Try setting it to 200

xdebug.max_nesting_level = 200

Thanks to Stack Exchange for the answer!


How to rewrite link to taxonomy term in Views when using Pathauto?

To get path of taxonomy term in default language (in your case it is English) you can use url() function, example:

$term_url = url('taxonomy/term/'. $term->tid, array('language' => language_default()));


SQL query the Drupal way, complex SELECT, conditional aggregate

Drupal does not provide database transposition, unfortunately. It's database access system is pretty good at filtering, joining and reordering the data, but not at restructuring them.

There are many patches and hacks for specific task, but none was general enough and needed enough to be accepted into core or views so far.

Your safest bet is to define a view, and then access it just like any other table. Drupal sees no difference as long as you don't write (and if you want to play, you could make MySQL to accept writes, too).


How to add multiple panel nodes to a panel page

Panel nodes was once totally awesome.

They could only do so much though, largely because of limitations in the underlying nodes.

With D7, Panelizer can what panel nodes could, but on any entity. I would strongly recommend you switch to panelize. Not only will you be able to easily use any regular method to list, but panel nodes have effectively been abandoned for years now.


adding or remove multiple classes with attributes.addClass

From the documentation for addClass and removeClass:

  attributes.removeClass()

  Removes a class from an Attribute object. Used similarly to addClass.
  Let's say you get the classes variable from somewhere else like a
  preprocess function.

  {% set classes = [ 'red', 'green', 'blue' ] %}

 outputs

.

So either you need to use an array to remove multiple classes or make multiple calls the removeClass and a single class.


Choose header content from entity-reference dropdown?

What I'm 99% sure you want is the Header Image module. It works by being able to select a piece of (node) content to place in some region thats been pre-defined.

Eg, put an image in some header region of your site. Or text or whatever ....


If you want a proper relative path your url must start with a / at the beginin of your url like this : /admin/commerce/products/add/


Multiupload widget - create more items inside single node

You can try out the Plup Upload module https://www.drupal.org/project/plup which gives a Plup upload widget for images where you can upload multiple images at once to a content.

You can follow the tutorial here:
https://www.ostraining.com/blog/drupal/multiple-image-uploads/

NB: To fix the missing thumbnail bug add $conf['image_allow_insecure_derivatives'] = TRUE; to your settings.php


Drupal 7 aggregator module with BBC persian feed

After you add new feed, make sure you update the items twice after removing them in the first time.

steps as follow:

add new feed
go to feed aggregator page admin/config/services/aggregator
update items manually by clicking on update items for the added feed
remove items by clicking on remove items for the updated feed
then update feed again update items

these steps worked for me while importing BBC persian and arabic feeds


The ability for file_get_contents() to fetch contents from an HTTP server depends on the allow_url_fopen parameter in php.ini

If it's not set, $image will be false and saving this leads to an empty file.

You may use Drupal's system_retrieve_file() instead. It's a wrapper on top of drupal_http_request() that comes with its own HTTP client implementation.

Example:

$file = system_retrieve_file('http://drupal.org/files/issues/druplicon_2.png',
                             'public://druplicon.png', false,  FILE_EXISTS_REPLACE);


How to override prepareTranslation method in Drupal\content_translation\Controller in drupal 8?

You can use hook_entity_prepare_form() to override the values from prepareTranslation() on $form_state.


How to create a Bean type programmatically?

Bean uses ctools plugins for its types. Per the docs:

/**
 * Implements hook_bean_types().
 *
 * Beans uses ctools plugins to define the block types.
 * All plugin files must be registered in the .info file.
 */
function hook_bean_types() {
  $plugins = array();
  $plugins['plugin_key'] = array(
    'label' => t('Title'),
    'description' => t('Description'),
    // This is optional. Set it to TRUE if you do not want the plugin to be
    // displayed in the UI.
    'abstract' => FALSE,
    'handler' => array(
      'class' => 'ClassName',
      'parent' => 'bean',
      // This should be pointing to the path of your custom bean plugin module.
      'path' => drupal_get_path('module', 'example_bean') . '/plugins',
      // Class files should be named accordingly in order to support ctools
      // autoloading procedures.
      'file' => 'ClassName.class.php',
    ),
  );
  return $plugins;
}


This would be very easy to do by either running a run cron job or a jenkins job on the server/node you want to run drupal cron on.  This is very common practice in all of our projects.

If you are doing a large data import on cron, be sure you are using cron queue. http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_cron_queue_info/7


Change permissions or add roles on the fly

Adding permissions on the fly would be hard without writing your own module.

However, maybe there are round-about ways of accomplishing what you need.  Two suggestions:

1) You can add a taxonomy field to your user account that can be set and then use the rules module to automatically add new users to a certain group based on the terms they were tagged with during creation...

2) If you go to: admin/config/group/permissions/node/group, you can see that you can set permissions for members, non-members and admin members of a group, and you can set the 'add user' permission depending on those user group roles.  If you set those to your liking, your workflow can then be a 2-step process: 1) create user account, 2) add user to whatever groups you need.  It's more cumbersome, since it's a 2-step process, but only members or managers of a group will be able to add users to that group.

Final note: creating/editing permissions on the fly like you're thinking may have unintended consequences.  You're saying that users should not be allowed to edit other groups, but if you try granting and revoking permissions based on opening and then submitting a form, you'll actually be giving users the ability to administer all groups until they submit that form!  If they forget and don't submit it or leave it open in their browser for a long time, they'll potentially have that admin-level permission and see all relevant links, blocks and associated admin sections for a long time.  So I suggest you try an approach like the above then attempting to grant 'temporary' permissions.  :-)


How do I access a function provided by a service resource module?

Functions are exposed via service resources, by a module implementing hook_services_resources().

You should take a look at whatever module your using to provide Services functionality for the private message module, specifically its implementation of hook_services_resources().

If you see an entry with a callback of _privatemsg_services_unread_count, then the function you want is available via a resource. If not, it currently isn't, and you can implement hook_services_resources() yourself to expose it.


How do I count the number of nodes in a View

In an executed view object, you can access how many rows or results are returned by looking at:

$count=count($view->results);

So, if your view returns 2 rows, $count would be 2, if 1, $count would be 1, etc. This can be accessed from a module that executed a view itself or from inside almost any of the views templates as well.


How can I get image url in a views field, D8

When setting up your view, under the advanced section you can create a relationship for the image field.

After you added the relationship, you can then add a File URI field, select the created relationship and you are good to go.


How to customize the input phase of a custom field

If you are building a curriculum vitae type website you might want to see the eRecruiter distribution profile.

What is does is makes separate groups of fields as entities with the Field Collection module. Keep in mind that taxonomy vocabularies are fieldable in D7 so they can be attached to an entity such as a field collection. The made a module called Term Level that gives an option to add superlatives to the taxonomy terms that are just an entity in a field collection that are added to a node as a field.

It's just another way to look at the same problem.


Entity reference in a content type for a taxonomy. Limit it to a single value

You should change the widget to a "Select list" instead of "Autocomplete (Tags style)".

You can find this on the "Manage form display" tab of the content type.


Upgraded to 8.8.3 and now all of my modules say "No available releases found"

Clicking "Check manually" once on the Available Updates page will resolve this issue.

Please see https://www.drupal.org/project/drupal/issues/3120168 for more info.


Views rows and entities are objects so I would think it should be this:

$view->result[0]->_field_data['nid']['entity']->event_calendar_status[LANGUAGE_NONE][0]['tid'];

but I'm guessing a little bit.

Also note the use of quotes in the array keys and the use of the LANGUAGE_NONE constant instead of 'und' for the field language.

If you still have trouble then try using the Devel module to see the structure of the view object variable.

There is information available via Google for how to use the Devel module to debug.


You can build RSS feeds easily with views, after creating your first display (generally a page), you can click "+Add" and add a feed display, then you configure your fields and you're almost done.

In the "Filter Criteria" section you select your Content Types and or the taxonomy you want to target.


Which megamenu supports i18n content translation?

At this time only tb_megamenu seems to support i18n.


different sidebars for different taxonomy vocabularies

If you have pathauto installed then go to the admin/config/search/path/patterns (You find this when in the URL Aliases in the Admin, There would we tab named as Patters)

There you can define a pattern for each vocabulary. Set different url patterns for each of the vocabulary and then you should be able to use than in the block configuration.

Please note that you would have to do bulk update on taxonomy before the urls can take effect on existing terms.

OR

You could use the context module with has much more control over what to display. You can create a context of the type Taxonomy Term and select the vocabularies you want the block to be shown when that condition is true display the required blocks.


Can we use a hook_update_N for a module without hook_install?

No module needs to implement every hook. You can use hook_update_n() and not have a hook_install() function just fine.

You'll probably at 1 point want to define hook_schema() for these tables. An easy tool to get the "drupal" schema for any mysql table (already defined) in your mysql database is the Schema module.

  Schema documentation: hyperlinked display of the schema's embedded
  documentation explaining what each table and field is for.
  Schema
  structure generation: the module examines the live database and
  creates Schema API data structures for all tables that match the live
  database.
  Schema comparison: the module compares the live database
  structure with the schema structure declared by all enabled modules,
  reporting on any missing or incorrect tables.

  Note for MySQL users:
  The Schema module requires MySQL 5. Prior versions of MySQL do not
  support the INFORMATION_SCHEMA database that the Schema module uses to
  inspect the database.


To do this, just create a copy of commerce-product.html.twig from the product module in commerce to your theme's template directory.

for more instruction to visit https://docs.drupalcommerce.org/commerce2/developer-guide/products/displaying-products/theme-product.


Allow node author to assign edit rights for other users

As is usually the case, "there's a "module for that": Node access user reference meets the requirements for this use case by allowing node authors to select other users from a user reference or entity reference field and assign view, update or delete rights to the referenced users. Hope this is useful for anyone else who runs into this issue.


Upon clicking save, how do I stop the node from inserting?

I would probably just use Unique field, as all of the legwork is done.

This module performs additional validation when a node is created or
updated by a user to require that a node's title, author, language,
and CCK fields are unique within a given context.

If you really want it in code though, I'd take a look through the source of this module and see how it adds the extra validation.
I know you said you'd prefer it in code, but I've left this here just in case it benefits anyone with the same question as you :-)


How to preserve a “target” attribute on links in overlays?

In general, all links can be excluded from being processed by the Overlay module. Just add a CSS class named overlay-exclude to the class attribute of the link.

That has also solved my target attribute issue:

 I agree to the site’s Terms of Use.


How to run custom function after clicking next on a multi page webform

One way to accomplish this task, because the webform module is so complex, is to just use jQuery and attach to that button and node id and run an AJAX query or whatever else you want to do like redirect the user away and then back.

Otherwise you would probably be neck deep in a custom module that extends Webform. In my experience to alter webform modules becomes a major pain and I generally just go another route.


I think I found a solution for this is a patch to the Location module here.


How can I add custom field validation for one of the fields "within" an addressfield?

I've just chucked a validation function into a dev site with an addressfield and you're right, it's a bit strange. It might be that the address field is marked as #tree => TRUE, and that's what's causing the long element key string.

Either way, it looks like you're checking the $form variable in your validate function, when the submitted data will actually be inside $form_state['values']. A couple of other minor alterations and you should be able to get it working:

function validation_function(&$form, &$form_state) {
  // Let's at least TRY to keep lines to 80 chars...
  $key = 'commerce_customer_profile|billing|commerce_customer_address|und|0';

  // Get the length of the
  $length = strlen($form_state['values']['addressfield'][$key]['locality']);

  if ($length != 0) {
    form_set_error('addressfield', t('No double-byte input.'));
  }
}

That example is based on the Commerce add customer form, so you'll need to inspect the $form_state['values'] array in your own form to find out exactly what the $key variable should be but hopefully that'll give you somewhere to start.

Just a note on your use of !== above...be careful with that, it will force PHP to make sure the types of the variables are equal, as well as the value.

strlen() returns an integer, and '0' is a string, so strlen('string') !== '0' will always return TRUE, regardless of whether the values are the same.


Should Text Format: "Full HTML" create a safe value?

The core text module does. This logic is driven by the text module's text_field_load(), an invocation of hook_field_load(). When the module loads text fields it looks up the filters used for the text format and sees if it's cacheable (i.e. if it saves to safe_value).

In your case, the logic is being triggered by toggling the filtered_html / full_html formats. Because raw HTML is potentially unsafe, it's not stored in the save_value cache.
`


If you are talking about the location module you'll have a couple of barriers with profiles on D7. I think they are working on a fapi compatible version but it is not ready yet.

There is a D6 module (html5 user geolocation) which may provide a good starting point.

Given a location (lat long) the Google maps API can give you an address.

You can then just pick the administrative level you like and save that as a tag.


Manage display at entity reference field Drupal

It sounds like you want to create different display modes to be used in the different contexts that this entity's date field is being displayed.

Create a display mode for each different way you want it displayed with either of these possible methods:

Modules that let you create and customize view modes through the UI:

https://www.drupal.org/project/entity_view_mode
https://www.drupal.org/project/ds

Custom code

https://www.drupal.org/node/1577752 & https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_entity_info_alter/7

The entity_view_mode module is the simplest approach, as display suite (ds) has many more features and options.

Once you create the view modes, then you can select the mode to be used for the entityreference field when the entity is being rendered there.


How can I stop Google Analytics from tracking a certain user?

I would consider creating a separate user role for that purpose and disabling Google Analytics for that role. The setting can be found at the module config page (/admin/config/system/googleanalytics) under Tracking Scope -> Roles.


How to add a comment form in VBO to add the same comment to mutiple nodes?

Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to create an entity, of type "Comment", whereas you specify some relevant parameters for that Rules Component, such as:

The node to which the comment is to be added.
The relevant options for the actual comment (such as the actual text of the comment).

Below is an example of a Rules Action that creates a comment (in Rules export format, use the Rules UI to import it in your own site):

{ "rules_add_a_comment_to_a_node" : {
    "LABEL" : "Add a comment to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "comment_node" : { "label" : "Node to add comment", "type" : "node" },
      "comment_body" : { "label" : "Comment body", "type" : "text_formatted" },
      "comment_subject" : { "label" : "Comment subject", "type" : "text" }
    },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : [ "comment-subject" ],
            "param_node" : [ "comment-node" ],
            "param_author" : [ "site:current-user" ],
            "param_comment_body" : [ "comment-body" ]
          },
          "PROVIDE" : { "entity_created" : { "comment_created" : "Created comment" } }
        }
      }
    ]
  }
}

Step 2

Create a view of the nodes to which some comment is to be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.

PS: this answer is for D7 ...


How to stop users from flagging other users if they have a custom taxonomy term?

Finally I managed to solve my problem by creating a Rule.
Here are the steps you can follow to achieve this:

Create a new Rule and select as the Event "A user has been flagged, under 'your flag'";
Add a condition "Entity has field" and select "flagging-user" as the entity and your field as the "Field";
Add a new condition "List contains item" and select as a list your created field but it must be like this "flagging-user:field-your-field";
Now at the same condition select as the item one of your field value;
Add a AND condition;
Add two more conditions exactly like you did at step 2, 3 and 4 but change "flagging-user" to "flagged-user".
Finally, add an action with "Unflag a User" and select your flag first, then at the User select "flagged-user", at the "User on whose behalf to flag" select "flagging-user" and at "Skip permission check" check "True".

That's it. Hope I helped someone else.

As requested here's an exported code of the actual Rule:

{ "rules_nu_poate_vota_manager" : {
"LABEL" : "Nu poate vota manager",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "flag" ],
"ON" : { "flag_flagged_apreciere" : [] },
"IF" : [
  { "entity_has_field" : { "entity" : [ "flagging-user" ], "field" : "field_raion" } },
  { "list_contains" : { "list" : [ "flagging-user:field-raion" ], "item" : "18" } },
  { "AND" : [] },
  { "entity_has_field" : { "entity" : [ "flagged-user" ], "field" : "field_raion" } },
  { "list_contains" : { "list" : [ "flagged-user:field-raion" ], "item" : "18" } }
],
"DO" : [
  { "flag_unflaguser" : {
      "flag" : "apreciere",
      "user" : [ "flagged-user" ],
      "flagging_user" : [ "flagging_user" ],
      "permission_check" : "1"
    }
  },
  { "drupal_message" : {
      "message" : "Nu po\u0163i aprecia colegii de echip\u0103!",
      "type" : "warning"
    }
  }
]

}
}


I added metadata to the query, running it as user 1, which allowed it to get all of the nodes:

$query = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->addMetaData('account', \Drupal\user\Entity\User::load(1)); // Run the query as user 1.
$nids = $query->execute();

echo "count: " . $query->count()->execute() . "\n";

foreach ($storage->loadMultiple($nids) as $node){
  //do stuff
}

Also, since revisions are allowed for nodes, it was returning $nids as revision_id => entity_id as Berdir said in his comment.


Okay, I fixed it by doing the following:

$query->addField('sub1', 'data', 'date');
$query->addField('sub2', 'data', 'name');
$query = $query
  ->fields('sub1', array('nid', 'sid', 'data'))
  ->fields('sub2', array('data'))
  ->condition('sub1.nid', 32)
  ->condition('sub2.cid', 2)
  ->condition('sub1.cid', 1);

The issue was addField does not return an object so you can't chain the commands together. Also note that even though you aliased the colums to date and name you still need to refer to them as tablename.data. The aliased names will appear in the result of the query.


How do I do namespacing in a module from an external project which is not in the src directory?

From your post, it looks like you added the above composer.json file, then ran composer from the module root. This is not the way to do it. This will create a vendor folder inside your module folder, which is not what you want.
What you need to do is add the composer.json file to your module, then push that to the remote repository. Then use Composer to install and manage the module. Doing this will add the library to the vendor folder for your project, and the library will be available when calling \ccxt\ccxt


Is it considered bad drupal style to have a large number of 'static' pages scattered around the website?

Have you looked at panels for assembling smaller pieces of content into a larger piece? Or even panel nodes which is a bit more lightweight than panels but allows layout and inclusion of other page elements in a regular node.


Views entity reference based on passed in value

Ended up doing a somewhat convoluted hack with a custom module.

1) Used 2 Conditional Filters in the View (A- uid of logged in user, b- uid=0)

2) Used regular filter of the taxonomy type (C).
Since Conditional Filters are ANDed together as well as ANDed with any normal filters, the derived WHERE logic of View is (A AND B) AND C (which would never return results unless the logged in user was user 0, but the query isn't available to anonymous users).

3) Created a custom module and used the following in hook_views_query_alter:
$query->where[0]['type']='OR'
So the WHERE logic of the altered view becomes (A OR B) AND C, which gives me the results I wanted.


Upload image to commerce product on save?

I installed Commerce Customizable Products and created a new line item type. This enabled me to create another product type with an upload field in the add to cart form users can use to upload file to the site. Also use rules obviously to do some more backend stuff, like change file location (that's set with a token uid) to be updated on username change and lots more. Can do lots of fun stuff with media/file entity, but your fix also works, just adding this for the search bot arena ;)


How to sell digital goods (redeem codes) using Drupal?

There's a UC solution called UC Product Keys out there for this particular use case, but you're better off avoiding it; the project has no 7.x version and is minimally maintained.

The Drupal Commerce equivalent is Commerce Product Key...

  This module lets sites implementing the Commerce module, attach
  product keys to orders. Product keys / Vouchers are strings of text
  that are used to unlock or activate a piece of software.

  Right now we have an entity that can be attached to a product and then
  assigned via a rule to a product once it has been bought. The required
  actions and rules events are fleshed out and simply require the wiring
  up of the rules to meet you scenario.

It probably won't do everything you need (e.g. import license keys), but it should be a good starting point to build your own product key solution off of.


views_embed_view fails with contextual filters?

If you have devel installed , try checking with this syntax , if you do not see any result then try passing the arguments as 4/1(w.r.t given example) in the preview of views to cross check you have results with those combination of exposed filters.
Debugging at devel/php will save lots of your time.

dpm(views_embed_view("view_name", "view_display_type", 4, 1));


Views with tables have different column width with same setting

I think it is html table generic behaviour, as browser's determining widths of individual table cells are a complicated matter.  You would get the same widths if your columns had the same contents inside but since some columns are different you are getting different column widths.

Drupal views table display style outputs generic tables without any width specified.  You can influence widths by using something like the following in your theme's css

table.views-table td:nth-child(2) {
  width: 150px;
}

Above specifies width for the 2nd TD tag of a views table. Change position of TD and width to your liking.


The suggestion of using the book structure or field groups would be exactly the same in D7 as it would have been in D6. However, the CCK multigroup module would be a much better fit and would check on it's D7 status (I tried, but it's spread over several issues in the queue)


Get value for drupal date pager next or prev or current

I found a work around, keeping in mind that the pager works for calendar view by changing date in the URL.

I created a custom form with fields as day, month, year whose field type is select (dropdown).

This is the code for the form and the submission handler.

function mymodule_get_event_view_date_filter($form, &$form_state) {
  $form = array();
  $year = date('Y');
  $year_options = array(
    $year - 4 => t($year - 4),
    $year - 3 => t($year - 3),
    $year - 2 => t($year - 2),
    $year - 1 => t($year - 1),
    $year => t($year),
    $year + 1 => t($year + 1),
    $year + 2 => t($year + 2),
    $year + 3 => t($year + 3),
    $year + 4 => t($year + 4),
  );
  $month = date('m');
  $month_options = array(
    '1' => 'Jan',
    '2' => 'Feb',
    '3' => 'March',
    '4' => 'April',
    '5' => 'May',
    '6' => 'June',
    '7' => 'July',
    '8' => 'Aug',
    '9' => 'Sep',
    '10' => 'Oct',
    '11' => 'Nov',
    '12' => 'Dec',
  );
  $form['event-date-container'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['event-date-container']['year'] = array(
    '#type' => 'select',
    '#options' => $year_options,
    '#prefix' => '
',
    '#default_value' => isset($_SESSION['event']['year']) ? $_SESSION['event']['year'] : $year,
    '#suffix' => '
',
  );
  $form['event-date-container']['month'] = array(
    '#type' => 'select',
    '#options' => $month_options,
    '#prefix' => '
',
    '#default_value' => isset($_SESSION['event']['month']) ? $_SESSION['event']['month'] : $month,
    '#suffix' => '
',
  );
  $form['event-date-container']['submit_form'] = array(
    '#type' => 'submit',
    '#value' => t('Apply'),
    '#submit' => array('_mymodule_event_view_date_submit'),
  );
  unset($_SESSION['event']);
  return $form;
}

function _mymodule_event_view_date_submit($form, $form_state) {
  global $base_url;
  $_SESSION['event']['year'] = $form_state['values']['year'];
  $_SESSION['event']['month'] = $form_state['values']['month'];
  drupal_goto('calendar-node-field-event-date/month/' . $form_state['values']['year'] . '-' . $form_state['values']['month']);
}

Now call this form in your calendar view in view header print.

drupal_render(drupal_get_form(mymodule_get_event_view_date_filter));


Assigning OG group title to OG group image title field

Your event should be after saving new content of type: your group content type.
Then add a condition, entity has field: node > your image field.
You should then be able add a condition to check if that field is empty.

Your action would then be to set a data value on the image using the node title.


I done it like this:

$contact_countries = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('contact_country');

$terms = array();

foreach($contact_countries as $contact_countrie) {
    $terms[] = array(
        'contact_country' => $contact_countrie->name,
        'contact_phone' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_phone')->getValue()[0]['value'],
        'contact_flag' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_category_flag')->entity->uri->value,
    );
}

Here I have fields field_phone (text field) and field_category_flag (file field).


Cannot get role information in twig file

Displaying content if the user has a certain role:

{% if 'content_administrator' in user.getroles %}

Only displayed for the role Content Administrator

{% endif %}

More info: Restrict content to a user role in a template file


How do I attach a library to contact forms?

Enable twig debug in your develop environment, then you can see through HTML comments all theme suggestions, then create a twig file with based in what you want template.

Original post here.

  Debugging Twig templates

  The Twig templating engine offers a debug tool.

  The Drupal 8 implementation also adds an additional tool that allows
  you to locate the template that outputs the markup.

  Enable debugging

  You enable Twig Debugging in sites/default/services.yml. (If services.yml does not yet exist; copy default.services.yml and rename
  it to services.yml.)

  Set the debug variable to true.

parameters:
  twig.config:
    debug: true

Just pay attention, if you not using site's default folder, use that you created.

After turn on debug, clear the cache, then you will see something like this in your HTML

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form' -->
<!-- FILE NAME SUGGESTIONS:
   x form--feedback.html.twig
   * form.html.twig
-->

If you need create a new name suggestion for a element, use THEME_theme_suggestions_HOOK_alter in your .theme file, and add your suggestion.

Example:

function THEME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'form__' . $variables['element']['#form_id'];
}


You can do this with the special type of filter Has taxonomy terms (with depth).

Add a new Filter Has taxonomy terms (with depth)
Select your Vocabulary in the new filter settings,
Selection type: Dropdown
Show hierarchy in dropdown
Depth 2 (this will include 2 levels of children of a chosen term)
Expose this filter to visitors, to allow them to change it and Apply

You will get a drop-down that shows your terms with hierarchy.

If you don't want a dropdown you can use a module like Better exposed filters to use radio buttons instead.


You shouldn't be modifying any core files. Removing a declaration for a value that needs to be used elsewhere is causing your problem, and the solution is to make your changes using hooks and templates in custom modules and themes, which are Drupal's way of allowing users to modify behavior and output.

This thread contains discussion of theming the user edit page, and has links to helpful information.


I guess the answer depends on what that ajax call does, and if it is for a 'one site use' or for a contribution module.

If it s for a contribution module hook_menu might be the only way to go.

Though if it s just for a 'one site use' i would just add a JS snippet in your page.tpl.php or even html.tpl.php that launches the Ajax query. This would work on every page even when if cached.

EDIT
Actually you could also use the page preprocess function and add a js file to all your pages.


Why are custom User Account fields not shown after account is saved?

Turns out a developer had enabled the "og_field_access" module and this was preventing users from viewing custom fields on the user account pages.

We removed the module dependencies (they weren't needed!) and disabled the og_field_access module and the fields now appear again!


How to include Facebook feeds inside my page?

Go to the Facebook Developers site and configure the kind of feed you would like to have. Save the generated the HTML somewhere.

Create a new block in your Drupal installation with the Full HTML text format. Paste the generated HTML in your the content part of your block.

If you do not want to use the default Facebook feed, take a look at this drupal module.


First you have to Change the overlay permissions and make the overlay view accessed by Visitors and users

lets Implement Hook_admin_path_alter in your custom module...

function YOURMODULENAME_admin_paths_alter(&$path) {
  $path['VIEWPATH'] = TRUE;
}

Clear Drupal Cache..


Summary or trimmed body field formatter does not display anything when the trim length is anything below 888

Well I still don't know exactly what the solution to the issue with Drupal's own summary or trim option. I did however get the trim right using the Smart Trim Module. Thank you to the developers of the Smart Trim module.


I have successfully used $view->set_items_per_page() in hook_views_pre_build(). The problem might be that in hook_views_pre_execute() the pager settings have already been built, so you might have to update those as well, with something like $view->display_handler->get_plugin('pager')->get_items_per_page().


How can I insert search box in front html page?

I'm not sure if this is exactly what you're asking, but if you want to output a block directly in code you can use module_invoke().

IE.

Drupal 7

$block = module_invoke('block', 'block_view', 'current_search');

Drupal 6

$block = module_invoke('block', 'block', 'view', 'current_search');

Then render the contents of $block.


show fields after adding joins in hook_views_query_alter

If you want view to show your fields, you should not use a hook_views_query_alter. instead you should implement hook_views_data() to describe your audience_node_og_mvh_ti table to view and be able to use its columns as fields when building your views using the UI.

You can however access your view's query results in an hook_views_pre_render() implementations to add your additional field to the output.


Restrict admin/content view by organic group membership

You can add a module that implements hook_query_alter like:

function gestionsesion_query_alter(QueryAlterableInterface $query) {
global $user;
if (current_path() === 'admin/content'){
    if ($query->hasTag('tablesort')) {
        $query->condition('n.language', $user->language );
    }
    }
}

Here we filter by user language but you could do it by role...


Add a "Like" button after "Edit" and "Reply" links

Implement hook_node_view() in a custom module that you create.

$node->content['links'][] = array(
  '#markup' => flag_create_link('bookmarks', $node->nid),
);

Or use the function MY_THEME_preprocess_node() in your template.php and add:

function MY_THEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['content']['links'][] = flag_create_link('bookmarks', $node->nid);
}

Replace MY_THEME with the name of your theme.
Some reading that might help you: http://www.whenwhowhere.com/tech-blog/add-variable-theme-template-files-drupal-7


Loading taxonomy terms in a tree in Drupal 8

TermForm.php has an example of how to do this.

Basically you loop through the tree and add dashes according to the depth of the term.

Here's an example you can use:

$options = [];
foreach (\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid) as $item) {
  $options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
}

UPDATE: If you want a nested array of terms, you can do like this:

$result = [];
foreach (\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid) as $item) {
  $parents = array_reverse(\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadAllParents($item->tid), TRUE);
  $r = &$result;
  foreach ($parents as $k => $v) {
    if (isset($r[$k])) {
      $r[$k] = array_replace($r[$k], [$k => $v->label()]);
    }
    else {
      $r[$k] = [$k => $v->label()];
    }
    $r = &$r[$k];
  }
}

That will work regardless of how many levels your terms are nested.


Trying to submit a node add form via AJAX but failing

Solved it. The problem was this code:

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
        'wrapper' => 'apple-node-form',
        'callback' => 'node_add_callback',
        'method' => 'replace',
        'effect' => 'fade'
    )
  );

This overwrites the $form['actions']['submit'] array that already existed, recreating it with the values I specified. Since all I wanted to do was add an AJAX submission, the following code should replace the above:

    $form['actions']['submit']['#ajax'] = array(
        'wrapper' => 'apple-node-form',
        'callback' => 'node_add_callback',
        'method' => 'replace',
        'effect' => 'fade'
    );

In other words, we're just adding an #ajax item to the already created $form['actions']['submit'] array.


field_info_field() deprecated, what's the equivalent?

According to the change record:

field_info_field($entity_type, $field_name) -> FieldStorageConfig::loadByName($entity_type, $field_name)

So you should use \Drupal\field\Entity\FieldStorageConfig::loadByName from now on.

It's probably best to use change records and issues on Drupal.org itself for docs at the moment, rather than 3rd party websites - I think they have slightly more chance of being right and kept up to date when something changes.


For an event node type, should I use Datetime or Datestamp?

Especially in Drupal 7, you should use the Date field. Datestamp is almost useless, and there is no real need for Datetime.


First, that condition syntax is just wrong, you need to add that as a WHERE condition. Second, if you want the count per content id, you need to group by that.

And third, you need to collect the output in a variable instead of returning it directly.

Something like this:

$result = db_query("SELECT content_id, COUNT(*) AS count FROM {votingapi_vote} WHERE value_type = '%s'"  AND value = 1 GROUP BY content_id, "option");

$output = '';
while ($obj = db_fetch_object ($result)) {
  $output .= $obj->content_id.'<br>' . $obj->count;
}
return $output;


how to save new value of autocomplete field with hook_form_submit?

As you said if you're unable to find the tid then its a new term. You can save the new term using taxonomy_term_save()

For example,

$term = new stdClass();
$term->vid = <field city vid>;
$term->name = $form_state['values']['first']['field_city'];
taxonomy_term_save($term);

After saving the new term you can access the tid like this,

$term->tid

If you want to fetch the vid referenced with particular field then look at the following thread - How to get the field settings in drupal 7


You can iterate through the blocks in this way:

{% for block_key, block in elements if block_key|first != '#' %}
  <b>{{ block_key }}: </b>
  {{ block }}
{% endfor %}

If you just need to know the blocks that are present in a given region, you could use this:

{{ dump(elements|keys) }}

Then you can print each block as:

{{ elements.key }}


How to create twig files content type specific in Drupal8?

you can use this file for specific content type "node--{content type machine name}.html.twig".
Please check this url for Twig Template naming conventions.


Like @jimajamma said in the question comments, you most likely want to create a custom module that implements hook_menu(), creates a form, and handles the form submission. Also, notice the trick where you can use the drupal_get_form() page callback to build a page that is just rendering a form. To use this, you need to pass the name of the function that returns your form as a page argument.

/**
 * Implements hook_menu().
 */
function demo_menu() {
  $items['admin/config/demo'] = array(
    'title' => 'Demo page title',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('demo_form'),
    'access arguments' => array('administer content'),
    // Choose an appropriate permission or create your own using hook_permission()!
  );
}

/**
 * Provides an admin form to change the site slogan, put the site into
 * maintenance mode.
 */
function demo_form($form, &$form_state) {
  // Adapted from system.admin.inc line 1495.
  $form['site_slogan'] = array(
    '#type' => 'textfield',
    '#title' => t('Slogan'),
    '#default_value' => variable_get('site_slogan', ''),
    '#description' => t("Change the site's slogan."),
  );

  // Taken from system.admin.inc line 2201.
  $form['maintenance_mode'] = array(
    '#type' => 'checkbox',
    '#title' => t('Put site into maintenance mode'),
    '#default_value' => variable_get('maintenance_mode', 0),
    '#description' => t('When enabled, only users with the "Use the site in maintenance mode" permission are able to access your site to perform maintenance; all other visitors see the maintenance mode message configured below. Authorized users can log in directly via the user login page.', array('@permissions-url' => url('admin/people/permissions'), '@user-login' => url('user'))),
  );
  $form['maintenance_mode_message'] = array(
    '#type' => 'textarea',
    '#title' => t('Maintenance mode message'),
    '#default_value' => variable_get('maintenance_mode_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))),
    '#description' => t('Message to show visitors when the site is in maintenance mode.')
  );

  return $form;
}

/**
 * Submits demo_form().
 */
function demo_form_submit($form, &$form_state) {
  variable_set('site_slogan', $form_state['values']['site_slogan']);
  variable_set('maintenance_mode', $form_state['values']['maintenance_mode']);
  variable_set('maintenance_mode_message', $form_state['values']['maintenance_mode_message']);
}

The form elements for the logo are a bit more complicated, but I suggest you take a look at system_theme_settings() in system.admin.inc line 399.


Unique file system for multiple domains in Domain Access

There is a sandbox module that appears to do what you need: https://github.com/markwk/domain_files

Essentially it extends the DrupalPrivateStreamWrapper class to provide a file path for each domain.

There is more discussion on d.o here with other methods people have tried: https://www.drupal.org/node/198131


Aggregated javascript contains binary data, breaks site

Turns out the problem was caused by an external javascript file that had been added through drupal_add_js without specifiying it being external. In my case specifically the pinit module for Pinterest was the culprit.

The external server had recently enabled http gzip compression, so the end result was gzipped data being straight up being concatenated into the js aggregation.


Have yo check the domain module? I think is the best option to solve this.

Another option, but more complex will be to create a Drupal as publisher backend and also Drupal as front end to the differents domains, you can share the content with feeds.

Oskar


Does extending a class include the namespace of the extended class?

To answer the question in the title: no, extending a class does not inherit the namespace of the extended class.

Your class namespace must be declared for each class or your class will be placed in the global namespace.

A little bit more on namespaces since if you don't declare one your code will be placed in the global namespace. Since PHP 5.3 if you don't declare a namespace then the class will belong to the global namespace. From the manual here:

  Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

As this applies to you, if you don't put a class in a namespace it will simply belong to the global namespace thus it wouldn't clash with a class with the same name in another namespace.

In general, functions without a class won't interfere with functions with the same name in a class. The reason being is that you need a class object to call a function declared inside a class.


You can override theme_links__system_main_menu() by declaring a function in your theme's template.php file:

function MYTHEME_links__system_main_menu($vars) {
  $links = $vars['links'];

  $items = array();
  foreach ($links as $link) {
    $items[] = l($link['title'], $link['href']);
  }

  return theme('item_list', array('items' => $items));
}

The above is a very basic example, you'll probably want to take a look at the original code for theme_links() to make that a bit more bulletproof.


A hook_update_N implementation is generally supposed to be invoked by the system, not manually.

Instead of thinking of it as "run an update on install", you could think of it as "perform an action on both install and update". A fairly common pattern for that is:

function MYMODULE_install() {
  _MYMODULE_install_something();
}

function MYMODULE_update_8501(&$sandbox) {
  _MYMODULE_install_something();
}

function _MYMODULE_install_something() {
  // Shared functionality here.
}

You don't have to use a global function; you could implement the shared functionality in a service and make use of that instead. The point is to separate out the logic for what needs to be done, and consume it in the same way wherever you need to.

If you do want to continue with your current approach, just pass it any initialised variable - doesn't matter what it is if you're not using it, and if your code is the only caller, it won't have any side-effects.


Where can I declare the compute field function?


Programmatically change the available options in a views exposed filter

I think you are very nearly on the right track, and I don't think you necessarily need a hook. I was able to perform essentially the same task with the following code in a class method.

// Get reference to your view.
$storage = \Drupal::entityTypeManager()->getStorage('view');
$view = $storage->load($view_id);

// Be sure to get a specific display.
$view->getExecutable()->setDisplay($display_id);
$display = $view->getExecutable()->getDisplay();

// Retrieve filters. If the combine fields filter is present,
// edit it then assign back using `overrideOption`.
$options = $display->getOption('filters');
if (isset($options['combine'])) {
  $options['combine']['fields'][$field_name] = $field_name;
  $display->overrideOption('filters', $options);
}

// This is the critical missing step.
$view->save();

I hope this helps.


Search API - how to have blank page on initial page load

This is more of a Views question than a Search API or Solr one, since the answer applies even when not using the latter. You want to set your "Exposed form style" to "Input required." See this answer for helpful screenshots.


Unable to set drupal_set_message() after logout redirect

drupal_set_message() sets the message in $_SESSION. By logging out, you destroy the current session and thus wipe the message you just set.