Form #states only work after change, but not on initial load I've got a paragraph with a select field field_colorschema, depending on its value two other fields field_image field_parallax  on the same paragraph are shown or hidden. The code I've written works for most parts, but only AFTER change of field_colorschema. It does not set the correct state on page load.

function wt_base_field_widget_paragraphs_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  /** @var \Drupal\field\Entity\FieldConfig $field_definition */
  $fieldDefinition = $context['items']->getFieldDefinition();
  $parentEntityType = $fieldDefinition->getTargetEntityTypeId();
  $parentEntityBundle = $fieldDefinition->getTargetBundle();
  $parentEntityFieldType = $fieldDefinition->getType();
  $parentEntityFieldName = $fieldDefinition->getName();

  /**
   * Conditionally hide background image and parallax depending on row colorschema
   * http://agaric.com/blogs/conditional-fields-paragraphs-using-javascript-states-api-drupal-8
   */
  if ($parentEntityFieldName == 'field_pagebuilder') {

    /** @see \Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget::formElement() */
    $widgetState = \Drupal\Core\Field\WidgetBase::getWidgetState($element['#field_parents'], $parentEntityFieldName, $form_state);

    /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
    $paragraph = $widgetState['paragraphs'][$element['#delta']]['entity'];
    $paragraphBundle = $paragraph->bundle();

    // Determine which paragraph type is being embedded.
    if ($paragraphBundle == 'row') {
      $dependeeFieldName = 'field_colorschema';
      /* field_colorschema option value is one of ['--color-default', '--color-bglight', '--color-bgdark', '--image-bglight', '--image-bgdark'] */
      $selector = sprintf('select[name="%s[%d][subform][%s]"]', $parentEntityFieldName, $element['#delta'], $dependeeFieldName);

      // Dependent fields.
      $element['subform']['field_image']['#states'] = [
        'visible' => [
          [
            $selector => ['value' => '--image-bglight'],
          ],
          [
            $selector => ['value' => '--image-bgdark'],
          ],
        ],
        'required' => [
          [
            $selector => ['value' => '--image-bglight'],
          ],
          [
            $selector => ['value' => '--image-bgdark'],
          ],
        ],
      ];
      $element['subform']['field_parallax']['#states'] = [
        'visible' => [
          [
            $selector => ['value' => '--image-bglight'],
          ],
          [
            $selector => ['value' => '--image-bgdark'],
          ],
        ],
      ];
    }
  }
}

I've also tried inverting everything negative logic (invisible...), because the default value on field_colorschema forces the other 2 fields to be hidden, but again it worked only after change, and not on the initial page load.

What am I missing so that field_image and field_parallax are correctly following field_colorschemas values on the intial page load?

PS: The paragraph subform is inside a Field Group tab, but I think that doesn't matter, because the given code works after selecting values.

My given code works correctly. However, there is a bug in Paragraphs that instantly re-shows hidden fields from form API, see:

https://www.drupal.org/project/paragraphs/issues/2868155#comment-12493576
https://www.drupal.org/project/paragraphs/issues/2946856

Applying the patch from issue #2946856 fixed it for me.


Required Modules by Translation Management Tool (tmgmt) I read the description for the translation management tool (tmgmt) and I found it requires many other modules. I'm wondering what the modules do specifically to make the tmgmt work? I read their respective project page descriptions, but that doesn't really help me understand how exactly it integrates with the module. Those modules are:

Entity API
Views
Chaos Tools
Views Bulk Operations
Content Translation
Locale
Internationalization
Entity translation
Rules

Is there quick explanations or examples regarding how they support tmgmt?

A explanation on what these modules do

Entity API: Provides API functions that makes working with entities easier (e.g. tokens for entity fields, CRUD functions, etc.). There's no visible functionality here.
Views: Provides a way to select into data tables (e.g. users, nodes, etc.), filter them, and display the data in different modes (e.g. as page, block, RSS feed, etc.)
CTools: A suite of API/utility functions to help with development tasks (e.g. creating modals, handle AJAX requests, etc.). The only visible functionality is Page Manager, a UI that allows you to override URLs paths with a different display).
Views Bulk Operations: Adds an option to Views to select multiple items and perform an operation on them (e.g. bulk unpublishing selected nodes).
Content Translation: A core Drupal module that enables the ability to translate node content into other languages.
Locale: A core Drupal module that enables the ability to translate the interface (e.g. button & label names).
Internationalization: A suite of UI tools that extends out Locale to provide more control with interface localization.
Entity translation: Provides a UI for the Content Translation module.
Rules: Provides UI and API for enforcing workflow. These enforcements are called Rules which has 3 parts: an event (something thing happened to your data), a condition (checks on the data to see it matches your scenario), & action (actions to take to enforce your workflow on your data).

There's much more to these modules than what a couple sentences can provide. Read the respective documentation pages for more information.


dump $variables in theme_preprocess functions In theme_preprocess functions (e.g. theme_preprocess_block, theme_preprocess_menu, etc) there is the $variables argument.

In Drupal 7 I could look at this variable using devel module and typing dpm($variables).

How I can do that in Drupal 8?

I tried kint, dump and var_dump, but for all of them I get a fatal error memory exhausted.

The best way would probably be a breakpoint with xdebug turned on. Which requires configuration efforts though.

What I was normally doing in similar cases was a step-by-step approach. I was printing out $variables keys first and then narrowing my var_dump with a specific key. E.g. var_dump($variables['key']). Slowly but surely.

In the end I think that in terms of efforts it is way better to set up debugger and use breakpoints to inspect variables.


Error when trying to delete user I installed the heartbeat module to track user activities on my website. It took me hours to configure it but everything seemed to be working as I wanted until I tried to delete a test user from the website. I was wondering if anyone is familiar with this error.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table
  'etuncel_drup4.drup_flag_content' doesn't exist: DELETE FROM
  {flag_content} WHERE (content_type = :db_condition_placeholder_0) AND
  (content_id IN (:db_condition_placeholder_1,
  :db_condition_placeholder_2, :db_condition_placeholder_3,
  :db_condition_placeholder_4)) ; Array ( [:db_condition_placeholder_0]
  => heartbeat_activity [:db_condition_placeholder_1] => 20097 [:db_condition_placeholder_2] => 20098 [:db_condition_placeholder_3]
  => 20101 [:db_condition_placeholder_4] => 20102 ) in HeartbeatFlagPlugin->activityRemoved() (line 106 of
  /home/public_html/sites/all/modules/heartbeat/modules/heartbeat_plugins/includes/heartbeatflagplugin.inc)

Turns out there is an error with the module but someone developed a patch for it.

Here;

https://www.drupal.org/project/heartbeat/issues/2102743


Views output into multiple columns based on variable of results Scenario:
I want to output a 3-column display, i.e. first 5 results on left column display, next 5 in middle column, last 5 on the final column.

I can do this with a fixed amount of results using different views + offest, but I want to do this with one view with a varied amount of results:

e.g.
Col-1: 4 items
Col-2: 3 items
Col-3: 3 items

Example is iTunes website:
https://itunes.apple.com/au/genre/podcasts-technology-tech-news/id1448?mt=2&letter=X

They even account for pagination
https://itunes.apple.com/au/genre/podcasts-technology-tech-news/id1448?mt=2&letter=T

What would the best way to approach this? Would you need to get a count of results then set the offset for the 1st, maybe 2nd column if it's not a divisible number?

not sure what you're asking is really possible just through the Views UI.

However, this should is reasonably simple with a views template file and a bit of PHP knowledge.

http://webpartners.es/en/drupal-7-views-templates-and-preprocess provides some info about how to override the output of the view. you'll need to apply a bit of logic on how to begin/close your columns/lists but that's just a bit of arrays in PHP.


Why isn't my hook_theme being called or rendering output? I am trying to use the hook_theme function to utilize some template files.  I have the following function defined in my theme:

template.php

function my_name_theme($existing, $type, $theme, $path) {
    return array(
        'testy' => array(
            'variables' => array('title' => NULL),
            'template'  => 'testy',
        ),
    );
}

And I have the following template defined:

testy.tpl.php

<?php print $title; ?>

I have a content type called "Page" with a corresponding template:

node--page.tpl.php

<?php
    print 'before theme call';
    $variables = array();
    $variables['title'] = 'my title';
    print theme('testy', $variables);
    print 'after theme call';
?>

When viewing one of my "Page" content types, the rendered page only shows the following, with no title:

before theme callafter theme call

I have cleared all caches.  Why isn't this working?

I had to add a path to my function, then it worked.

template.php

function my_name_theme($existing, $type, $theme, $path) {
    return array(
        'testy' => array(
            'variables' => array('title' => NULL),
            'template'  => 'testy',
            'path'      => drupal_get_path('theme', 'my_name') . '/templates',
        ),
    );
}


How can users block other users In regards 7.x.

Say a user that has a role of (registered user) wants to block another user with the same role that is harassing them and they don't want to see any more posts or comments from the harassing user. But, I as the "Admin" don't want to Block either user. The user just wants to block the other harassing users comments or posts to be viewable by them....

For example: Other websites offer a way for a user to block someone that is harassing them. They can even block that harassing user from ever seeing their information/profiles/comments or posts.... But, that blocked user isn't blocked to everyone else, just blocked to that specific user from being able to see their information/profiles/comments or posts.

Is there a way to do that in drupal? What modules would I use to make that work? How can I make that work?

I am concerned that users could start harassing one another in posts and comments, there should be a way to mute users posts or comments from being viewable.

For example: Say I start a conversation with you and you don't like what I'm saying and you don't want to see those type of posts anymore from me. How can you block me from me posting such things on the drupal about you? So if there was a way to mute me, then my posts or comments would nolonger be visible by you but still visible by everyone else.

Is this possible?

I think best and easy approach would be using Flag module. You can create a Flag for user entity and grant authenticated users to flag other users, then you can check if the user is flagged as below.

$flag = flag_get_flag('ban_user') or die('no "ban_user" flag defined');

if ($flag->is_flagged($GLOBAL['user']->uid, $user->uid)) {
  // The optional second parameter to is_flagged(), which allows
  // us to ask if an item is flagged on behalf of a certain user. If this
  // parameter isn't provided, the check is made against the current user.
  print "This user has banned you!";
}


Field sharing between translations of a node? Assume I have a content type which I want to be translated to 5 languages! And assume that my content type has 10 fields, with 7 of them being some numbers and 3 of them are text.

There is absolutely no need for these 7 fields to be translated to each language. But when I translate each content I should spend a lot of time on filling same values for each language.

How about storing the 7 fields in a 1st content type and the 3 remaining fields in a 2nd content type. And then use the References module to connect them to each other? That way you'd only have to "translate" the content type with the 3 fields.

A variation of this could be using entities, whereas you'd then use the Entity Reference module instead. And probably also the Entity Translation module, for which quite some Community Documentation is available to get you started.

Drupal 7's new multilingual systems compilation contains an interesting set of posts about multilanguage websites ...

PS: You may also want to look at Node translation vs. Entity (field) translation for a lot of extra info/details about both variations of translations.


Add the view mode to the CSS classes used for the body Is it possible to add the view mode used for a display into the body class?

At the moment, the view mode is being inserted into one of the region classes, but I would like to add it also to the body class. This would allow me to change the page to full width depending on the view mode.

I am using the Bootstrap theme.

If you are using sub theme of bootstrap theme then you can possibly add class to body tag of the node.

Go to SubThemeDirectory/and open template.php and add this hook_preprocess_html()

function THEMENAME_preprocess_html(&$vars) {
  if ($node = menu_get_object()) {
    $vars['body_attributes_array']['class'][] = 'mode-' . $vars['page']['content']['system_main']['nodes'][$node->nid]['#view_mode']; // Node ID class
  }
}

I hope this'll at least give an idea how to add class attribute.


Custom field validator comparing original and new values In my validator, I need to compare the new field value, that was submitted by the user, with the old value. How can I get the original value?
So far, I have this:
class CompareNewOldValuesValidator extends ConstraintValidator {

  public function validate($item, Constraint $constraint) {

    if (empty($item->getValue())) {
      return;
    }
    $value_new = $item->getValue()[0]['value'];

    /** @var ContentEntityInterface $entity */
    $entity = $item->getEntity();
    if (!$entity->isNew()) {
      $value_original = '???';
    }
  }
}

I need to get the field value that was filled in the form before the user changed it, no matter if it is the active version or a draft or an old revision.

Normally the original entity is stored in the entity object before the user input is applied. If not, you can get it via the loaded revision id, which is preserved when an entity is loaded to keep it save from changes:
if (isset($entity->original)) {
  $original = $entity->original;
}
else {
  $original = \Drupal::entityTypeManager()
    ->getStorage($entity->getEntityTypeId())
    ->loadRevision($entity->getLoadedRevisionId());
}

$value_original = $original->{$item->getFieldDefinition()->getName()}->value;


How to clone an entity? I created a custom entity type using entity_info_hook and associative hooks. It works fine. Now  I want to  create a clone of the entity when I press the button Duplicate. Is there any method for this? I read Replicate module do this finely. But I can't find any sufficient tutorial for the purpose. How can I use entity_ui_clone_entity() in my module?

You could call Replicate's  replicate_entity_by_id($entity_type, $id) method. And maybe hook it's API for custom behavior, see here.

entity_ui_clone_entity won't create the new entity, but only prepare your entity for creation, and could be used like this:

$my_clone = entity_ui_clone_entity('your_bundle', $my_entity);
entity_save('your_bundle', $my_clone);

Or if you created a method for saving your entity, use it direclty:

my_entity_save($my_clone);


Unable to uninstall an incompatible module I have 6.22 core and by mistake added the folder for quicktags 7.x-3.0 to the modules folder.

I deleted the folder, replaced it with 6.x but nothing seems to allow me to enable the quicktabs module under "Home » Administer » Site building » Modules."

All I get against the quicktab folder is:

  This version is incompatible with the 6.22 version of Drupal core.

How can I install the correct version of the module?

Install drush, and type

drush cc all

to clear the cache, then

drush en quicktags

to enable the module; sometimes drush saves my day, when the admin>>modules throws errors.


Dynamic filtration in tree hirarchy I want a tree structure like below:
-parent1
 +child 1
 +child 2
 -child 3
  +sub child 1
+parent2
+parent3
...
 and when a user click on lets say "child1" then items in views related to them will be filtered.
How can I achieve this?Can any one please help me?

Did you try Simple hierarchical select module. You can build your tree structure with Drupal taxonomy.

Unlike Hierarchical select this module provides a simple widget for taxonomy terms only. As an addition Simple hierachical select works as Views exposed filter.


How to add custom html inside form I need to put some custom html tags and code inside the form elements am creating using form api .  I defined a fieldset and need to come the html under this fieldset , code sample :

  $general_wb_vars = array(
        'wb_debug'=>array('type'=>'select','values'=>'ERR,OFF','default_value'=>'OFF','label'=>'Debug','description'=>''),
        'wb_cache'=>array('type'=>'radio','values'=>'Yes,No','default_value'=>'No','label'=>'Cache','description'=>''),
        'wb_ip'=>array('type'=>'textfield','values'=>'','default_value'=>'192.168.1.1','label'=>'IP','description'=>'')
        );
        $numofrepeat = 4;
        if($form_id=='my-form-id'){
                $form['fieldsetm'] = array('#type' => 'fieldset',
                                         '#title' => t('Weblogic configurations'),
                                         '#weight' => 10,
                                );

                for($i=1;$i<=$numofrepeat;$i++){
                foreach($general_wb_vars as $id => $setts){
                   $form['fieldsetm']['field_p_'.$id.'['.$i.'][value]'] = array('#type' => $setts['type'],
                                        '#title' => t($setts['label']),
                                        '#default_value' => $setts['default_value'],
                                        '#description' => t($setts['description']),
                                        '#attributes' => array('id'=>$id.$i),

                                  );
                                if($setts['type']=='select'){
                                        $form['fieldsetm']['field_p_'.$id.'['.$i.'][value]']['#options'] = explode(',',$setts['values']);                                      }
                                if($setts['type']=='radio')
                                        $form['filedsetm']['field_p_'.$id.'['.$i.'][value]']['#values'] = explode(',',$setts['values']);
                                        $form['fieldsetm']['some_markup'] = array(
                                           '#type' => 'item',
                                           '#markup' => '---------------------------------------------------------------------',
                                         );
                                }
                }

You're looking at Drupal 7 form api reference perhaps. For drupal 6 according to the form api you just need to put your HTML string in #value as the default D6 #type is markup


When using Views Bulk Operations, the options for Rule Components are not shown in the VBO drop down for all users When I am logged in as the root admin, I am able to create Rule Components (rule and rule sets) and have them appear in the View Bulk Operations (VBO) settings menu as an option for a VBO view table column.  As the root admin, I can also navigate to the view's page and successfully perform the Rule Component on table entries using the VBO interface.

However, when I log in as another user (seemingly regardless of role or permission) The Rule Component options which were enabled for the VBO column are no longer available.  It appears that some sort of permission is blocking them.  It is not obvious which permission (or if it is a permission) is blocking the Rule Component Options so they don't appear in the VBO list.

Does anyone have experience with this problem and knows a way to get Rule Components to appear in the VBO drop down in a view for all users?

If you are adding operations using Rules Component then you have to set the permission.

Edit your rule component and under the settings there will be Configure access for using this component with a permission, set your permission here.


Options in facets disappear when more than one value is selected We have setup a custom search with Search Api and Search API Solr Search. In a facet we want to allow the selection of multiple values, with the normal link widget. We have configured the facet to use the OR operator. Everything works as expected until we select more than one value. With more than one value selected, the search result is still correct, but all other options disappear. This is not the behaviour we want, we would like to continue displaying all options, in the same way it works after the user selected a single element.

This is a bug with solr 3.5 and the search_api_solr module, the bug is described here:https://www.drupal.org/node/2474661 the bug report includes a patch that fixes the issue. With the patch in place everything works as expected.


ajax_render() - CSS not adding/updating in IE I'm using AJAX to update page content. In my page callback I have a few commands and end with ajax_render().

When I click the AJAX link from another page, the content updates, all my JS and CSS for that page are added, and everything works perfectly. However, the CSS is not being applied in IE.

It appears that the following two lines in ajax.js are causing the problem:

var new_content_wrapped = $('

').html(response.data);
var new_content = new_content_wrapped.contents();

If I hack ajax.js and change (line 519):

wrapper[method](new_content);

to:

wrapper[method](response.data);

it works!! Any ideas?

The solution for me was CSS aggregation in Drupal: It needs to be on to work.
When it is disabled, it uses @import, which IE does not like if that is used to append to the head. When it is enabled, it appends links instead, which then works with IE.

The same problem is described here.


Adding some new custom variables to page.tpl.php I want to add some variables to page.tpl.php via template.php so i guess i need to use my_theme_preprocess_page. But my variables does not seem to be passing through.

I am using something like this :) In template.php

function my_theme_preprocess_page(&$vars) {
$vars['myvar'] = "value";
}

and in page.tpl.php

print $myvar;

and $myvar fails; also tried defininig it with $vars['page']['myvar'] = "value";
and reading it back with print ($page['myvar']);
but with no luck, variable (or index) stays undefined.

I cleared cache.

Any clues why this does not work ?
Thanks!

Drupal doesn't have code that checks if the theme is adding a new index in the array passed as reference to hook_preprocess_page(); every index added to that array from a preprocess/process function is then passed as PHP variable to the corresponding template file.

If what you are adding is then not passed to the template file, then the possible explanations are:

You are prefixing the function name with something that is not the short name of the theme.
You wrote the preprocess function for the theme that is not currently active. If the theme currently used is the Bartik theme, the preprocess function for a different theme would not be called. Keep in mind that the used theme could be different from the one you are expecting; this is what happens with administration pages, for which the used theme is the one set as administration theme in admin/appearance.

There are also modules that can set a different theme for a page implementing hook_custom_theme().

A possible mistake could be implementing a preprocess function for a theme when a sub-theme is actually used, or (vice versa) implementing a function for a theme when the parent theme is actually used.

References

theme()


Set minimum quantity in product I'm looking for a way to set a minimum quantity per product in a Drupal Commerce store.

I found this module which claims to do just this, but I can't get it working and the project seems abandoned:

I found this one which is useful if you need to set a minimum in the order but it doesn't help to set a minimum in products.

Is there any other way to do this?

I believe there's a quiet simple solution using rules.
More specific based on the existing commerce_stock by default enabled rules :
- Stock: validate add to cart
- Stock: validate checkout
These rules have both an action "Set the state of the checkout process (called once per item)", preventing add to cart or checkout when the stock conditions are not met.

In order to check line item quantity with on product level defined minimum order quantities,  you can clone these rules and alter the rule conditions.
There's a way to implement a custom rule condition using hook_rules_condition_info().

Example implementation could be :

/**
* Implements hook_rules_condition_info().
**/
function my_custommodule_rules_condition_info() {
  return array(
    'minimum_product_qty_applied' => array(
      'group' => t('Commerce Line item'),
      'label' => t('Min. product qty selected'),
      'parameter' => array(
        'commerce_line_item' => array(
          'type' => 'commerce_line_item',
          'label' => t('Commerce line item'),
        )
      ),
    ),
  );
}

function minimum_product_qty_applied($line_item) {
    return _check_minimum_product_qty($line_item); //returns TRUE or FALSE
}


Drush: difference between pm-update pm-updatecode What's the difference between pm-update and pm-updatecode? I reviewed this in the Drush documentation, but they sound the same.

pm-update also runs the update.php script to take care of any database schema changes that a module may need (same as drush updatedb), pm-updatecode doesn't.  Under many/most circumstances, you can just run pm-update.


In terms of performance, is it better to lazy load, inline, or hook_init a Javascript library? I'm working on a module to embed Highcharts into nodes. Other chart modules provide a PHP helper function to trigger the necessary library loading. To avoid enabling the PHP module, I tried creating an input filter with a token for loading the Javascript library. Unfortunately, filter output gets cached, so calls to drupal_add_js within a filter function don't get called on every page load.

I can think of a few workarounds:

a small inline script to load the library, after a node containing a chart has loaded
embed the whole library file inline, on pages where it's needed
load the library on every page, via hook_init

From a performance perspective, what is my best option?

For what it's worth, the compressed Highcharts library is 81k. The site I plan on using this on has Javascript aggregation enabled, but few content items will have charts, especially initially. Plus, I'd like to contribute the module on d.o, so I'd like to solve this in a way that would make sense on most sites.

You could also hook into the node's presave, check whether the body contains whatever it is, then set a flag on the node (perhaps using flag or taxonomy) if it does. Then on view, you look for the flag and use drupal_add_js if necessary. This will survive the cache and let you aggregate the script if you want to. If you'd prefer, rather than storing the flag in the DB, you can check for highcharts on every view (via hook_nodeapi()) and just add the JS there directly.

Btw, strongly recommend against the hook_init() approach - there are definitely better ways imho. hook_init is called on every full bootstrap, which includes eg. 404s and imagecache generation (as well as every normal node view). Generally it's a good idea not to use this if your code is only needed in specific circumstances (eg. only when there's Highcharts code embedded). In those situations, you want to find a way to add your code only to appropriate pages.


What is the purpose of drush entity-updates? After updating Drupal 8 modules, I have been warned on the Drupal 8 status page that:

  Entity/field definitions: The following changes were detected in the
  entity type and field definitions.

After a bit of Google rummaging, it seems the solution to this is to run drush entity-updates. However I find this a bit strange as it seems to be another command that one needs to remember or incorporate into one's workflow after updating the database, not to mention it didn't seem immediately obvious about how to address the original warning.

What's more, it's often the case that in development you'll have an alert for other actions in the Status page which will mean you won't immediately know if you need to action this.

Can anybody explain what is this warning is for - or rather, why has this feature been introduced into D8, and why isn't it factored into the database update operation but must be run seperately?

drush entity-updates is a developer tool. If you change entity/field definitions in your custom module you can quickly apply this.

In production this should not happen. If you update a module between official releases, then the update code in the module should handle this.

But in your case you are mentioning that your site is in developing. So there are a lot of things, which could have caused this. Either in your own code or in dev or alpha versions of contrib modules.

I found this example from the CR Write update functions for entity schema updates, automation removed (where there are further examples):

/**
 * Add 'revision_translation_affected' field to 'node' entities.
 */
function node_update_8001() {
  // Install the definition that this field had in
  // \Drupal\node\Entity\Node::baseFieldDefinitions()
  // at the time that this update function was written. If/when code is
  // deployed that changes that definition, the corresponding module must
  // implement an update function that invokes
  // \Drupal::entityDefinitionUpdateManager()->updateFieldStorageDefinition()
  // with the new definition.
  $storage_definition = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Revision translation affected'))
      ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
      ->setReadOnly(TRUE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('revision_translation_affected', 'node', 'node', $storage_definition);
}


Selecting nodes by content type and value of a custom field I need to select nodes (1) of a certain content type and (2) satisfying a test against a custom field's value. Pseudo-code would be:

select all nodes of type TYPE_X which are published and where MY_FIELD = 'x'

I tried that with the EntityFieldQuery suggested here: How do I query a content type with custom fields in the 'condition' statement
but Drupal/php crashes with "Fatal error: Allowed memory size of x bytes exhausted..."

So - what would be the correct code to use? I would appreciate a query which takes revisions into account.

In Views, you could do this:

Create a view, filter on node TYPE and node PUBLISHED
Create an argument/contextual filter using your CUSTOM FIELD
In Fields, select NID (and/or TITLE or whatever you want to work with in the node(s))

Preview the view, putting FILTERONTHIS in the arguments/contextual filter area.

Look at the SQL it generated in the Preview and cut/paste it into whatever you need, substituting FILTERONTHIS for a variable of your chosing. Or, save the view and then use views_get_view_result() to access the result.


CAPTCHA session reuse attack detected error message when form is submitted I am experiencing problems with the captcha module 7.x-1.0-beta1 version. I have enabled captcha in webforms for anonymous users. After submitting the form it repeatedly gives me the error message,

  CAPTCHA session reuse attack detected

.. This happens for only one of the webform in which captcha is placed. I am using Drupal 7.2 version.

Any solution for this issue will be really helpful.

I had the same problem because I have an ajax file upload on the form. The solution is to patch the captcha module with the patch found here http://drupal.org/node/918856#comment-6353912 .
You just need to download the patch and put it in the same folder and run in command line:

patch < captcha-patch-10022012.patch

if using git, you can just use :

git apply --directory=your/module/derectory captcha-patch-10022012.patch


What do array keys in the database definition array mean? I have following code in my settings.php file:

$databases['default']['default2'] = array(
  'driver'    => 'mysql',
  'database'  => 'rotary',
  'username'  => 'root',
  'password'  => 'root',
  'host'      => 'localhost',
  'prefix'    => '',
);

$databases['rotary2']['default1'] = array(
  'driver'    => 'mysql',
  'database'  => 'rotary2',
  'username'  => 'root',
  'password'  => 'root',
  'host'      => 'localhost',
  'prefix'    => '',
);

I know that the first keys i.e. default & rotary2 are the database names.

What are the keys default2 & default3 for?

Here is the explanation from the setting.php file:

  For each database, you may optionally specify multiple "target" databases.
  A target database allows Drupal to try to send certain queries to a different database if it can but fall back to the default connection if not. That is useful for master/slave replication, as Drupal may try to connect to a slave server when appropriate and if one is not available will simply fall back to the single master server.

  The general format for the $databases array is as follows:

$databases['default']['default'] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['extra']['default'] = $info_array;

  In the above example, $info_array is an array of settings described above. The first line sets a "default" database that has one master database (the second level default). The second and third lines create an array of potential slave databases. Drupal will select one at random for a given request as needed.  The fourth line creates a new database with a name of "extra".

I hope this will give you clear idea about default2 and default3.


Why doesn't the overlay background show? I created a fancybox gallery as block using the Views module and inserted that block into the node using the Insert Block module. Everything works fine, but the overlay background doesn't show.

How do I fix this?

Edit: The problem has been resolved: The 'Overlay helper' was disabled.


How to change the title and add a placeholder to password and confirm password field through hook_form_alter? How can i remove the label of the password and the confirm password field through hook_form_alter functionality ?
Tried the below:

$form['pass']['#title']= t('');   $form['pass']['#description']=
t('');
$form['account']['pass']['pass1']['#attributes']['placeholder']=
t('Password');
$form['account']['pass']['pass2']['#attributes']['placeholder']=
t('Confirm Password');

But no change in the behavior.
This is the exact code that i have written in my .theme file.
   function THEMENAME_form_user_pass_reset_alter(&$form, &$form_state, $form_id) {
  // Get default process function array:
  $element_info = element_info('password_confirm');
  $process = $element_info['#process'];
  // Add our process function to the array:
  $process[] = 'port_process_password_confirm';
  $form['account']['pass']['#process'] = $process;
}

function port_process_password_confirm($element) {
  $element['pass1']['#title'] = t('New password');
  $element['pass2']['#title'] = t('Confirm new password');
  return $element;
}

The output that  i am getting is as per the below image

In D8 You can try the code below:

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\PasswordConfirm;

function mymtheme_form_user_pass_reset_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['account']['pass']['#process'][] = 'mytheme_form_user_register_form_process_pass';
}

function mytheme_form_user_register_form_process_pass(&$element, FormStateInterface $form_state, &$complete_form) {
  $element = PasswordConfirm::processPasswordConfirm($element, $form_state, $complete_form);
  $element['pass1']['#placeholder'] = t('Password here please');
  $element['pass2']['#placeholder'] = t('Password again here please');
  $element['pass1']['#title'] = t("New password");
  $element['pass2']['#title'] = t("New password confirm");
  return $element;
}

See more PasswordConfirm.php

In D7

function mymtheme_form_user_pass_reset_form_alter(&$form, &$form_state, $form_id) {
   // #process handler to modify the password element expanded by Field API.
   $form['pass']['#process'] = array('form_process_password_confirm', 'register_alter_password_confirm');
}

/**
 * Alter password and confirm password fields to remove title and insert placeholder.
 */
function register_alter_password_confirm($element) {
    $element['pass1']['#attributes']['placeholder'] = t("Password");
    $element['pass2']['#attributes']['placeholder'] = t("Confirm password");
    $element['pass1']['#title'] = t("New Password");
    $element['pass2']['#title'] = t("New password confirm");
    return $element;
}

See more https://www.drupal.org/project/drupal/issues/540340#comment-2782800


How to change menu item URL in menus for Drupal 7 multiiste I am using drupal 7 multisite (sharing the same database, same code base) i.e

1) one.example.com

2) two.example.com

Everything is working correctly and my site using the same menus for all the sites.

for primary domain, menus are working correctly like
there is one menu item named as test and published to both the sites
but
If I access the first site i.e one.example.com then my menu URL is
one.example.com/test

and same when I access the secondary domain i.e. two.example.com then my menu URL should be two.example.com/test instead of one.example.com/test
and currently, menu URL is one.example.com/test

Try to add menu links as "Relative Paths", then a domain name will be added automatically depends on sites.

E.g. use /test , not one.example.com/test.


How to move views pager to different region as a block? I created a page view and results are showing up in main page content block. Now i need to move the pager attached with view to different region.
I am not sure how to achieve this. Please suggest any preprocess or backend feature which can do this?

The easiest is probably the comment from @No SSsweat
Another easy option is to place the view in each region and hide the pager/content using CSS depending on region.
The javascript option may be possible depending if you have anything already in place, as you can move the DOM pager element programmatically.
The neater solution is to use some php code, the drupal way, probably someone has already done this for you, so look for a drupal contributed module related to view and pager or paging, and layout, those would probably be my keywords for a search.


How to autoload classes from a 3rd party PHP library I would like to use a 3rd party PHP library in my module and I wanted to ask what I need to do to autoload the classes?

Example:
Drupal\my_module\MyClass
wants to instantiate
ThirdPartyNamespace\Something\Else\Class1

The official Drupal 8 documentation doesn't really deal with more complex namespacing scenarios.

Drupal use composer to manage the 3rd party libraries (Symfony, guzzle, etc...).
The problem is Drupal has versioned the vendor folder into the core directory; it is a problem because, if you added a new library in the root composer, you change the vendor directory and change the composer.json/composer.lock. So, if Drupal releases a new version, your changes will be deleted.

The Composer Manager module is created to solve the problem. You need to include a composer.json file in your module; the Composer Manager module downloads the library and registers a new autoload file (the second autoload).
The problem with this is only when you need use a middle-ware library, since the Composer Manager module registers a new autoload in the Request Kernel Event. This event is called after the middle-ware so this library is not available in the middle-ware layer.

In most cases, the Composer Manager module is the best solution to add new vendors.

There is the issue Remove external dependencies from the core repo and let Composer manage the dependencies instead.


Product catalog in views that is hierarchical but not mutually exclusive I am trying to get views create a product catalog in taxonomy that is hierarchical but categories are not mutually exclusive.  For instance, lets say my hierarchy looks like this:

+---Color
|   +---Red
|   \---Blue
|       +---Sky Blue
|       +---Navye Blue
|
+---Shape
|   +---Cirlce
|   \---Quadrilateral
|       +---Rectangle
|       +---Square
|
+---Size
|   +---1"
|   +---2"
|   +---3"
|   +---4"

When browsing the view I want visitors to be able to drill down through the categories while still having the other categories exposed to be filtered without requiring the user to select size before shape or vice versa.  The site that is inspired me the most in this project is this: McMaster-Carr.  As you can see in that link, just browsing through the washer section is quite an adventure.

I would try to achieve this with an exposed filter in views, 'Has taxonomy terms' or 'Has taxonomy terms (with depth)' for example. Use this as an exposed filter (dropdown with multiple select) in a page display.
In the advanced settings in views you can choose to expose the form in a block. You can add this to the left sidebar and activate 'autosubmit'. So everytime they change something the results get filtered.

Since dropdown is not that nice, I would try on basis of this post https://stackoverflow.com/questions/9208997/drupal-7-creating-a-taxonomy-filter-using-checkboxes to change it to checkboxes.


Is there a way to alter only the printable invoice for Ubercart 3.8? Client would like to print order invoices from 'View Orders' page without their large logo at the top wasting ink. I do not seem to be able to isolate just the printed invoice without affecting the admin and customer invoice.

I see 2 possible solutions:

Create separate template called "when_client_prints" and link to this    template from Views Orders.
Edit current invoice template within your custom module with the logic like if user hasn't id * then show the logo. (* stands for the UID of client account)


How to add a new user badge after earning a certain number of user points? I'm using the User Badges and User Points modules. I want that when a user earns a certain number of user points, the user's old badge is replaced by a new one. For this, I have already created a rule with the actions "remove badge" and "add badge". The condition is "execute PHP code" and the code is:

$current_points = userpoints_get_current_points($userpoints_transaction->uid, 'all');
if ($current_points >=7) {
  return true;
}

I also want to display the badge with the username at the top like StackExchange.

Note: Using the above code, it is displaying a message each time when user getting more than 7 user points. I want the message only once.

First of all, add the badge(s) you'd like to use at Configuration > People > Badges > Add new badge. Afterwards, create a rule for every badge, similar to the following one:

{ "rules_new_badge" : {
    "LABEL" : "Add new badge",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules", "user_badges", "userpoints_rules" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "IF" : [
      { "php_eval" : { "code" : "$current_points = userpoints_get_current_points($userpoints_transaction-\u003Euid, \u0027all\u0027);\r\nif ($current_points \u003E=7) {\r\n  return true;\r\n}" } }
    ],
    "DO" : [
      { "add_badge_by_name" : { "badge" : "1", "user" : [ "userpoints-transaction:user" ] } }
    ]
  }
}

Import it and modify it, according to your needs. To delete a badge, you can add another Rule with the action 'Remove badge by name'. Mind that I used a PHP Evaluation condition in order to use your PHP code in the Rule. I would, however, advise against this and use the Conditional Rules module instead.

Displaying the user badges next to the user names can be achieved by theming the comments in the comments.tpl.php file. This answer might help.


How can I see multiple terms on a single view? I have a content type called "Listing". This listing has a taxonomy reference called "Amenities". A single listing can have several or no amenities and each term has a field on it called "icon".

I want to create a view that shows:

TITLE
Amenity 1, Amenity 2, Amenity 3

Instead of text, I want to show icons.

I was able to figure out that you can use "relationships" to get to the icon field on the term. However, it only shows ONE term from the list. There doesn't seem to be any aggregation or grouping by happening. Which means it shows the same listing over and over, for each term. Instead of showing the listing once, and all the term images below that.

What am I missing?

Grouping can be enabled in Format section of your View [Format > Settings]. Select title field for grouping and then exclude it from display to avoid rendering it twice.
Aggregation in this case will not give you the result that you're looking for.


db_query() and db_select() don't return any value I'm trying to run the following query.
SELECT floormap_counter_expected.counter_name, tls_connect_agent_counters.counter_stage,tls_connect_agent_counters.applicant_gwf, tls_connect_agent_counters.counter_ip, floormap_counter_expected.expected FROM tls_connect_agent_counters INNER JOIN floormap_counter_expected ON floormap_counter_expected.counter_name = tls_connect_agent_counters.counter_name;

When executed via the command line, MYSQL returns the information I need.
When I try the following code, I get an error saying that $center_counters is not set.
$get_counter_info = db_select('tls_connect_agent_counters', 't');
$get_counter_info->fields('t', array('counter_stage', 'applicant_gwf', 'counter_ip'));
$get_counter_info->fields('n', array('expected'));
$get_counter_info->join('floormap_counter_expected', 'n', 't.counter_name = n.counter_name');
$get_counter_info->execute()->fetchAll();
if (isset($get_counter_info)) {
  foreach ($get_counter_info as $results) {
    echo "Rest";
    $center_counters[$results->counter_name]['stage'] = $results->counter_stage;
    $center_counters[$results->counter_name]['counter_ip'] = $results->counter_ip;
    $i++;
  }
}
return $center_counters;

The same happens with the following code.
$counters_query = "SELECT floormap_counter_expected.counter_name, tls_connect_agent_counters.counter_stage,";
$counters_query .= "tls_connect_agent_counters.applicant_gwf, tls_connect_agent_counters.counter_ip, ";
$counters_query .= "floormap_counter_expected.expected FROM tls_connect_agent_counters INNER JOIN ";
$counters_query .= "floormap_counter_expected ON floormap_counter_expected.counter_name = tls_connect_agent_counters.counter_name";
$get_counter_info = db_query($counters_query);
$get_counter_info->fetchAll();
if (isset($get_counter_info)) {
  foreach ($get_counter_info as $results) {
    echo "Rest";
    $center_counters[$results->counter_name]['stage'] = $results->counter_stage;
    $center_counters[$results->counter_name]['counter_ip'] = $results->counter_ip;
    $i++;
  }
}
return $center_counters;

I tried wrapping the code with try{} catch(Exception $e) {echo $e-getMessage()}, but nothing is printed.
I assume the query is running without error because nothing is "caught".
I was thinking that maybe I'm just calling the information wrong in my foreach loop. Maybe I should identify the table name as well when I call the field name. I don't think that is the case as nothing is printed when I try to echo strings out of foreach.

$get_counter_info->execute()->fetchAll();

will execute the query...but what are you doing with the results, exactly? At the moment you're discarding them, instead you need to assign them to a variable.

$results = $get_counter_info->execute()->fetchAll();
foreach ($results as $result) {
  ...
}

Or at the very least actually use the return value from the execution:

foreach ($get_counter_info->execute()->fetchAll() as $result) {
  ...
}


Private nodes in Private group are visible to non-members by their URL I have a private group with private content which I set up with group visibility and group content visibility. Logged in as a non-member of this group I get access denied on the group page however when I enter the url of a node within that group I can see it fine.

I am using views cloned from the original OG views and I even tested it with the OG views and it is still allowing a non-member to see the nodes.

I have also rebuilt permissions a number of times.

I am unsure whether this is a bug in OG or a problem with my settings?

I had a similar issue too.  In the end, my mistake was having "group visibility" set as a field for the Post content type when it should have been "group content visibility."


Autocomplete textfield displays value when selected and not label I have a textfield autocomplete field that shows a list of full user names and email addresses as designed but when a user is selected, the user id is displayed in the field; not the name and email address.  This is the form element:

$form['people'] = [
  '#type' => 'textfield',
  '#placeholder' => t('Search by name'),
  '#autocomplete_route_name' => 'my_module.people',
];

This is the autocomplete handler in the controller:

public function handleAutocomplete(Request $request) {

  $query = $this->database->select('simplenews_subscriber', 'ss');
  $or = $query->orConditionGroup()
    ->condition('pa.address_given_name', '%' .$request->query->get('q') . '%', 'LIKE')
    ->condition('pa.address_family_name', '%' .$request->query->get('q') . '%', 'LIKE');
  $query->leftJoin('simplenews_subscriber__subscriptions', 'sss', 'sss.entity_id = ss.id');
  $query->leftJoin('profile', 'p', 'p.uid = ss.uid');
  $query->leftJoin('profile__address', 'pa', 'pa.entity_id = p.profile_id');
  $query->fields('ss', ['uid', 'mail']);
  $query->fields('pa', ['address_given_name', 'address_family_name']);
  $query->condition($or);
  $query->orderBy('address_given_name');
  $query->range(0, 10);

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

  $users = [];

  foreach ($results as $user) {
    $users[] = [
      'value' => $user->uid,
      'label' => $user->address_given_name . ' ' . $user->address_family_name . ' (' . $user->mail . ')',
    ];
  }

  return new JsonResponse($users);
}

The autocomplete textfield populates properly.  I just want the first name, last name and email address to show after a selection has been made.

To get this working I had to create a hidden field to store the value and use a custom selectHandler applied via class.

JavaScript File

(function ($, Drupal) {

  'use strict';

  /**
   * Override drupal selectHandler function
   */
  function customSelectHandler(event, ui) {
    var valueField = $(event.target);
    if($(event.target).hasClass('MYCUSTOM-autocomplete')) {
      var valueFieldName = event.target.name+'_value';
      if($('input[name='+valueFieldName+']').length > 0) {
        valueField = $('input[name='+valueFieldName+']');
        // update the labels too
        const labels = Drupal.autocomplete.splitValues(event.target.value);
        labels.pop();
        labels.push(ui.item.label);
        event.target.value = labels.join(', ');
      }
    }
    const terms = Drupal.autocomplete.splitValues(valueField.val());
    // Remove the current input.
    terms.pop();
    // Add the selected item.
    terms.push(ui.item.value);

    valueField.val(terms.join(', '));
    // Return false to tell jQuery UI that we've filled in the value already.
    return false;
  }

  Drupal.behaviors.myCustomAutocomplete = {
    attach: function(context, settings) {
      // attach custom select handler to fields with class
      $('input.MYCUSTOM-autocomplete').autocomplete({
        select: customSelectHandler,
      });
    }
  };

})(jQuery, Drupal);

Form PHP

$form['my_field'] = array(
  '#type' => 'textfield',
  '#attributes' => ['class' => ['MYCUSTOM-autocomplete'],],
  '#autocomplete_route_name' => 'mymodule.myfield_autocomplete',
);
// field value
$form['my_field_value'] = array(
  '#type' => 'hidden',
);

On our forms we also have an AJAX callback on the autocompleteselect event, and I've noticed the value for the hidden field is blank but the userInput on the $form_state has the value.

Problem with this is the splitValues function may not work well for the labels, since it appears to be comma-delimited. You may want to write your own to handle it. It also won't work well if using the same form twice on a page, but there may be a way to narrow down the selector on the hidden field.


Prorgrammatically generated quicktab does not display content I have programmatically created a quicktab but the contents of the tab do not display. I have followed the instructions and have looked at this related question but it does not work for me. I suspect I must be missing something simple. Here is the code for creating the quicktab:

function create_quicktabs() {

  $block_ids = array(
    'Books & Journals' => 'books_journals_search',
    'Articles' => 'articles_search',
    'Archives' => 'archives_search',
    'Databases' => 'databases_search',
    'Course Reserves' => 'course_reserves_search',
    'Institution Repository' => 'repository_search',
  );

  $tabs = array();
  foreach ($block_ids as $title => $block_delta) {
    $block = block_load('catalogue_search', $block_delta);
    $tabs[] = array(
      'title' => t($title),
      'type' => 'block',
      'bid' => $block->bid,
      'hide_title' => TRUE,
    );
  }

  // Configure the QuickTabs options
  $quicktabs_options = array(
    'style' => 'Bullets',
    'ajax' => FALSE,
    'sorted' => FALSE,
  );

  $quicktabs_name = 'catalogue_search';
  $quicktabs = quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs);
  return $quicktabs;
}

I get no errors when this is run, but it seems as though quicktabs can't find the block to display. I have verified that the blocks do exist and the block ids are valid. I have also tried using block_delta for the bid value - again same result. This is for Drupal 7 by the way. What am I doing wrong?

I have found the solution to the problem through some experimentation. It appears that the value for bid must take the form of: module_name_delta_block_delta. To illustrate this, here is an example:

$tabs[] = array(
  'title' => t($title),
  'type' => 'block',
  'bid' => 'catalogue_search_delta_books_journals_search',
  'hide_title' => TRUE,
);

The module name is: catalogue_search.
Then you need the text: delta
Finally the block delta name: books_journals_search.

I did not see this documented anywhere so hopefully this will help others with the same problem.


How to theme back end forms created by a custom module? I want to be able to theme a custom form I create using a custom module that builds a form. The form is created programmatically using the code below:

public function buildForm(array $form, FormStateInterface $form_state) {

    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
      '#required' => TRUE
    );

    $form['address'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Address'),
      '#required' => TRUE
    );

    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    );

    return $form;
}

This form is rendered on the Drupal 8 back-end and uses the admin theme classy BEGIN OUTPUT from 'core/themes/classy/templates/form/form.html.twig'. However there isn't a override file name suggestion.

How would I theme this form?

One option is to add a prefix and suffix to your form arrays

$form['name'] = array(
  '#type' => 'textfield',
  '#title' => $this->t('Name'),
  '#required' => TRUE
  '#prefix' => '
',
  '#suffix' => '
',
);

$form['#attached']['css'] = array(
 'path/to/my.css' => array(
   'group' => CSS_AGGREGATE_THEME,
   'weight' => 999
 ),
);

my.css

.something {
  border: solid red;
}


Views sum row for Degree I am trying to get the SUM of a group of fields in a view. We hold events and I wanted to create a view that showed How many degree types by total. See below image for quick idea.

So, If there are 20 MD's, I want one row that shows MD's with a total of 20 - versus 20 rows of MD's.

I have look at views aggregation but since it isn't a number I can not see it working. I have also looked at view calc but that just shows a total at the bottom.

I am looking to figure out the best way to handle this. If I have to custom code any help pointing me in the right direction would be greatly appreciated!

You want to try using the Views Aggregator Plus community module.

The example from the Project page (very similar to your own):

  Say the original View based on raw database results looks like below.

Industry    Company Name    Turnover
IT          AquiB           $25,000,000
Clothing    Cenneton        $99,000,000
Food        Heiny           $66,000,000
IT          PreviousBest    $5,000,000
Food        McRonalds       $500,000,000

  Then with the grouping taking place on, say Industry, and aggregation
  functions TALLY, ENUMERATE and SUM applied on Industry, Company Name
  and Turnover respectively, the final result with a descending sort on
  the last column will display like below. Note that the module
  identified three groups. It also added a totals row, Views Calc style.

Industry        Companies            Turnover
Food (2)        Heiny, McRonalds     $566,000,000
Clothing (1)    Cenneton             $99,000,000
IT (2)          AcquiB, PreviousBest $30,000,000
Totals              5                $695,000,000

At that point I think you just need to play with output settings of that module ...


Passing arguments to drupal_get_form() How can I pass arguments to drupal_get_form() in Drupal 7?

function new_menu_callback() {
  $vars = some_example_function(); // returns: array(1 => 'one', 2 => 'two');
  $output = $vars[2];
  $output .= drupal_render(drupal_get_form('new_form'));
}

function new_form($form, &$form_state) {
  // How can I access $vars[1] from new_menu_callback() here?
}

Just add $vars as second argument.

drupal_get_form('new_form', $vars);

and...

function new_form($form, &$form_state, $vars) {
// ...

Quote from drupal_get_form()

  ... Any additional arguments are passed on to the functions called by drupal_get_form(), including the unique form constructor function. For example, the node_edit form requires that a node object is passed in here when it is called. These are available to implementations of hook_form_alter() and hook_form_FORM_ID_alter() as the array $form_state['build_info']['args'].


Show all group content of a specific group type I'm having a very difficult time figuring this out, and I'm wondering if it's even possible. I'm using organic groups 7.x-2.x, and I have two "group" types: a student group type and a faculty group type. I also have a "group content" type called blog posts which can post in either group type. What I would like to do is create two views, one to show all blog posts that got posted in all student groups, and another to show the same for faculty groups.

Can anyone provide me insight into how to do this?

Side note: Since OG has switched to using entity reference to assign group membership, I thought it would easy to use this relationship in views to accomplish this, but it looks like it is only using entity reference for the widget, and does not store the data as a normal entity reference field would. Everything I tried with the og_membership relationship seemed to fail, so I'm at a loss here. Any help would be appreciated!

Wow, I actually figured this out. Basically you need to do the following:

Add the "OG Membership: OG membership from Node" relationship to the view.
Add the "OG Membership: Group Node from OG membership" relationship, assigning the above relationship.
Add a Filter Criteria of "Content: Type" = the group content type you want to show, and (here is the trick) assign the above relationship for this.

Here is a screenshot that might be more helpful:


How to change URL images for CDN I have a website in Drupal 7 with "N" images in Sites/default/files and I need move this images to CDN.

Is this possible?

For S3
https://www.drupal.org/project/s3fs

In general
https://www.drupal.org/project/cdn

If you have origin pull then you should only need the CDN module


How to redirect anonymous user to 404 instead of 403? I'm new to Drupal so am struggling here. I've created a checkbox field and the goals is that when it is checked it redirects anonymous to the 404 page.

I have the following condition:

function page_module_preprocess_page(&$variables) {

 // code to retrive checkbox value

 if (user_is_anonymous() && $page_hidden_value == 1) {
    drupal_not_found();
  }
}

But this doesnt work.

However, interestingly enough if I do the reverse and check that the user is logged in (!user_is_anonymous()) it does work and does redirect to 404.

I can DPM the value of the checkbox ($page_hidden_value) so I know that's working correctly.

Would anyone know what could be going on here?

I have had some odd experiences with user_is_anonymous(). Try using negation with user_is_logged_in(). For example:

if (!user_is_logged_in()) {
    // Do stuff
}


CKEditor filtered HTML body field is not showing for non-administrator users when editing I am on drupal 7.56.

Something really disturbing happens.

I have created a custom content type named "Information" that uses the default body field. I granted access to this content to Administrator and to a newly created role that is "editor".

I made wrights configuration for both roles :

"Editor" and "Administrator" can "Edit own, Edit any" information ;
"Editor" and "Administrator" can "Edit own, Edit any" field body for that Information content type.

But only "Administrator" sees the body field in editing mode.

I am also using field_permission and content_access modules to make sure everything is fine in detail.

Still the same. On any browser, "Administrator" can see the body in edit mode but not the editor. Notice that body field text shows normally when displaying the node(s).

A help will be welcome!

The commonest reason for this problem (and OP has confirmed it in this case) is as follows.

The field that is inaccessible to some users has a filtered text format
The formats that can be set on that field include one or more that are not permitted to all users (typically "full html")
The content item in question has been edited by a user that has access to the restricted format and they have saved it with the field set to that format.
Now only users that have that privilege can edit the item because that field won't load for those who don't.

The solution is for a privileged user to edit the item and change the format and save it again, though that may result in the HTML changing in a way that's undesirable. If the item needs "special" HTML then it may not be possible for it to be maintained by the less privileged users.


Show facebook friends activities from my site I have connected Facebook on my Drupal site. My requirements are as follows.

Suppose user X log in using Facebook. He does different sorts of activities like creates an order, writes a review, likes a content etc.

When another user Y logs in to my site through fbconnect, I have to show him his friends' activities on my site. For example, in this case if X and Y are friends in Facebook, Y needs to see all of X's activities in my site.

How can I achieve this feature? I'm using Drupal 6.

I used Drupal for Facebook module, it provides a views filter 'Friend of current user'.
 For showing various activities, 'Activity' module used. Then with help of view the friends activities filtered.


Using user_load() and user_save() to change the status of a logged out user I'm fairly new to Drupal, and I am currently working on a Drupal user registration mechanism that involves authentication on a different website.
The flow is as follows:
- A user registers on a Drupal user/register form. Using user_register_submit() I set the the user's status to blocked.
- After registering, the user is being redirected to a different website where he is required to log in. In that redirect, I pass the newly registered Drupal username as a parameter. If the login on that external site is successful, I'd like to redirect the user back to a .php page on the Drupal site (also sending back the username parameter via POST), and then change the status of that user to Active.

In order to achieve that, I've tried using the following code in a page called auth.php I placed under my theme's root directory. This code is failing:

<?php
    $username = $_POST['user'];
    $user_to_activate = user_load(array('name' => $username));
    user_save($user_to_activate, array('status' => 1);
?>

After stumbling upon this http://drupal.org/node/820506, I realized core functions (such as user_load() and user_save() from the user.module) should be available from other modules. So I'd like to put my code inside a custom module, thing is I don't know in which function should I put it. Also, I wouldn't want this module to be called on every page load, only when being redirected from the external website I mentioned in the first comment.

Could someone offer some guidance?

In order to achieve that, I've tried
  using the following code in a page
  called auth.php I placed under my
  theme's root directory.

Normally in Drupal you don't create php files which are called externally. This can be done in some very rare cases. But most of the time you would define a menu callback in a module and have that call a function which you put your code in.

One of the issues that you have found is that Drupal is not bootstrapped from a generic PHP file.

It is fairly straightforward to do this.

Create a module, with a .module file and a .info file.
Turn on this module via the admin interface.
In your module implement hook_menu() and provide a path to be called, in your example this could be 'mymodule/auth'.
Create a function which will be called when your menu hook is fired.

There is a more in-depth tutorial here.


Fields API vs. fields in hook_schema Can someone please explain what is the advantage of using Fields API to create fields for an entity rather than just declaring them in hook_schema as values?

It's a bit of work to get all the fields defined, instances, options, allowed and default values, etc. and then you have to deal with getters and setters and finally uninstalling everything is not as simple as db_delete, esp if you have reference fields in use by other entities.

The most important advantage of using fields, rather than custom data in a custom table, is that your data has immediate integration with the rest of the system; including (but in no way limited to):

Automatic integration with Views
Potential to use EntityFieldQuerys
Fields can be managed using the standard system UI, even if built in code
Automatic integration with Features
There are many contributed widgets that can enhance the UI of a field (e.g. the Term Reference Tree widget
No need to load your custom data onto the node/entity in a load hook, the core field system does that for you
No need to define CRUD operations for your data

I'm sure there are many, many more.

Basically, if you want fine-grained control over the operation/performance of your extra data then use a custom table. If you want the system to handle all of that for you, use a field. For what it's worth I pretty much always use a field to store any entity data these days.


Get NID of newly created node from entity_metadata_wrapper I need to pull the nid immediately after it is created using entity_metadata_wrapper as a creation method.

Here is a brief example:

$values = array(
  'type' => 'content_type',
  'uid' => $user->uid,
  'status' => 1,
  'comment' => 1,
  'promote' => 0,
);

$entity = entity_create('node', $values);
$wrapper = entity_metadata_wrapper('node', $entity);
$wrapper->title->set('title');
$wrapper->save(true);
entity_save('node', $entity);

// From this, where can I get a NID value for the node that was just created?

You can simply use the entity_metadata_wrapper's integrated method to get the ID:

$wrapper->getIdentifier()


Kick Out Form builder module I have install Form Builder module and Webform module.

Webform module: Create form feature

Form Builder: Integrate into webform for more friendly user by click and drag

Recently I realize form builder is a annoying module.
Here are the problem cause by form builder:

  1) Problem: Unable to multiple select list.

  Solution: Webform module has a checkbox for multiple select. Just
  check will do. Unfortunately, does not appear in form builder.

  2) Install Webform Hints module(Placeholder feature): Does not appear
  in form builder.

As you can see without form builder, I realize all this features can be done by webform itself.

Now I uninstall form builder and face another stupid problem cause by form builder. Form component link is not working. Cant edit form unless I install back form builder module.
See the picture below. I super regret to install such a useless module.

What should I do?

First off, I think you misunderstand what form builder is for. As it's project page says ...

  ... [it] does not provide any permanent mechanism for saving data with the created forms. In other words, it does nothing but build the form....

It's a utility for building form data structures, not for creating and capturing data for forms.

The module you're looking for, as you've found, is webform. It provides an interface (albeit not as nice looking) to build web form content and capture data. That's the only module you need. It looks like from your image you've created a webform node. The form components tab link should present a form that allows you to add/edit components. As shown below...

If this interface isn't appearing I would make sure to uninstall both form builder & webform, remove form builder completely, make sure there is no node content type called webform, then try to reinstall webform again. It should work after a fresh install.


Importing epub as a node Is there a module that imports epub book as a node into drupal? Or a way to do something like this by converting epub into something else before?

It's in dev but the Epub module is probably your best starting-point.

  The new epub module for Drupal 7 provides displays for file entity and file fields and enables users to read epub/ibooks files inside their browsers like pdf module.

It doesn't import as a node, but you can take a lot of code from that module to build your own node-import version.

Interestingly, the reverse operation has already been implemented in Epub export, so you might want to have a look at the code for that one too.


Views exposed filter hide if less then 10 items I want to show the exposed filter only when there are more than 10 items to filter. Any suggestion to accomplish this?

Add this to your theme's template.php file:

function THEME_views_pre_render(&$view){
  if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAYID' && $view->total_rows <= 10) {
    $view->exposed_widgets = '';
  }
}

This will remove all of the exposed filters. If you have more than one and you only want to remove a single exposed filter, you will have to parse that filter out of the $view->exposed_widgets html string.


How to prohibit a view for specific languages? We've got a view like news with only English content and we're not planning to add content in other languages any time soon.
But we do have other languages (more static ones) on the page and therefore are using the language dropdown. If I'm in the view: /news.html (in English), Drupal and the language dropdown still provides es/news.html even though there are 0 news in Spanish.
How can I point the language dropdown to / in case I'm on the news view?
(I could do Drupal redirects I reckon - but maybe there is a smarter solution which solves the root, not the impact?)

Applying filter while creating views. Add a new filter & select "Node translation" from the "Groups" listed and check "Node translation: Language" and click "Add". Then you can choose languages which you want to show.

OR

  Create Block
  Under Visibility settings change to PHP (If PHP is not an option, go into modules and enable the PHP input method)
  Use below code & save :

 global $language;
    $lang_name = $language->language;
    if ( $lang_name == "en" ) { return TRUE; } else { return FALSE; }

NOTE:  Replace the "en" with the two letter name of what ever language you want the block to be visible for. For Example if you want your block only visible when the language is French, change "en" to "fr" .


How to calculate margins based on JSON and ONIX (XML) input and calculate points based on them? In a Drupal Commerce distribution based on Drupal 7 we sell books. First I want to calculate a margin price based on several given data. The JSON is imported or can be manually added. The ONIX (in fact XML) data is already imported in an earlier stage. In the ONIX data the tags Price, Weight and Publisher are available as variable. When an order is placed I need a rule that combines these data, makes a calculation and present the result after ordercompletion in the dashboard of the admin as a view.

After this I want to calculate how many points the buyer gets based on the order price per item in the order in relation with the previously calculated margin. The point that is earned is an equivalent to a maximum percentage of the price of a book AND cannot be more then the maximum % of the calculated margin.

Is there any way or technique in Drupal to do this?

Calculations

You should definitely have a look at the (fairly new) Math Field module, to use it for:

calculating the margin price.
the calculations after order completion.

Some more details about this module (from its project page), which also details when the calculations actually happen:

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

Known issues

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

The cTools math expression library causes an error when using function that take more than one parameter. This effects pow(), min(), max() (#1958538: Improve math expression engine).
Math Field does not yet support multivalue options fields (checkboxes, or multiselect) (#2483453: Add aggregate functions for multivalue fields).
Math Field does not yet support Field Collections (#2573643: Support the Field Collection module).

Bonus: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...

Dashboard

Depending on your actual requirements/expectations, you might be able to implement your dashboard with only the Views module, possibly complemented one of more add on modules for it. E.g... if you'd also want some sort of charts to be created, a module such as charts could be a good fit.

As an alternative (or possible complement?) you might also want to consider the Forena module (discosure: I'm a co-maintainer), e.g. because it comes with charting out of the box, and it would even allow you to integrate some of your data stored in XML (your ONIX data) without importing them.

Buyer points

These points could be implemented using the Userpoints module (that's obvious). And by using the Goals module (disclosure: I'm its maintainer) you can have the Rules module take care of granting the appropriate number of userpoints. So with that it seems that your question (challenge) is reduced to finding a way to configure the appropriate set of Goals and related Tasks. For a basic introduction about Goals, have a look at:

How to implement gamification in a Drupal site and award incentives?
Its video tutorial.

Bonus: even though your question doesn't seem to include that (yet) as requirements, it would be straight forward to implement some special reward(s) for your frequent buyers. Here is what it would take:

Goal = "New customer", with only 1 Task = "Buy 1 product" (say with machine name = buy_product).
Goal = "Silver customer", with Task = "Buy 10 products, on 10 different days, in a timeframe of 3 months".
Goal = "Gold customer", with Task = "Buy 100 products, on 25 different days, in a timeframe of 12 months".

The interesting part of this is that you'd only have to write 1 rule (related to that machine name = buy_product) to keep track of the progress of any user to become a new/silver/gold customer (check the video for a similar sample).


How do I migrate file entities into media entities? I am using the Migrate module for a D7 to D8 migration and I am writing the whole migration manually in code (rather than use the built in D7 migrate module, as I wanted more granual control on the migration.)

I have the following structure: the D7 site has a image field where images are stored as File entities. On the D8 site, the image field is an entity reference to a Media entity (and the Media entity in turn has a Image field.)

Originally, I had the following for my Images migration:

id: image_files

source:
  plugin: legacy_images
  constants:
    source_base_path: http://example.com/

destination:
  plugin: 'entity:file'

process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
    -     constants/source_base_path
    -     uri
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status

Inside my article node migration file, I had the following:

'field_article_image/target_id':
plugin: migration
migration: image_files
source: field_article_image

but I realized that this would not work. The target_id coming from the image_files migration were really File Entity ID's, not media entity ID's.
In the ideal world, I'd like to find a way to create a third migration, which would create this middle step, and migrate file entities into Media Entities and then map that migration to the Articles migration. However, I can't figure out a good way of doing this.

Plan B will simply be to create a process plugin for the images migration, which will manually create file entities, attach them to media entities, and pass that migration over to Articles (this removes the middle step). This would mean, though, that while Media entities can be rolled back, File Entities could not.

I ended up chosing to do it slightly different - I create a regular file import, set that migration as the source for my media entity reference field, and then applied a second process plugin 'MediaGenerate' to translate the FID to the new media target_id

<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\media_entity\Entity\Media;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Row;
use Drupal\migrate_plus\Plugin\migrate\process\EntityGenerate;

/**
 * Generate a media entity with specified metadata.
 *
 * This plugin is to be used by migrations which have media entity reference
 * fields.
 *
 * Available configuration keys:
 * - destinationField: the name of the file field on the media entity.
 *
 * @code
 * process:
 *   'field_files/target_id':
 *     -
 *       plugin: migration
 *       source: files
 *     -
 *       plugin: media_generate
 *       destinationField: image
 *
 * @endcode
 *
 * @MigrateProcessPlugin(
 *   id = "media_generate"
 * )
 */
class MediaGenerate extends EntityGenerate {

/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) {
if (!isset($this->configuration['destinationField'])) {
  throw new MigrateException('Destination field must be set.');
}
// First load the target_id of the file referenced via the migration.
/* @var /Drupal/file/entity/File $file */
$file = $this->entityManager->getStorage('file')->load($value);

if (empty($file)) {
  throw new MigrateException('Referenced file does not exist');
}

// Creates a media entity if the lookup determines it doesn't exist.
$fileName = $file->label();
if (!($entityId = parent::transform($fileName, $migrateExecutable, $row, $destinationProperty))) {
  return NULL;
}
$entity = Media::load($entityId);

$fileId = $file->id();
$entity->{$this->configuration['destinationField']}->setValue($fileId);
$entity->save();

return $entityId;
}

}


Get taxonomy name in cycle (performance) I have a subset of data ($query->execute) where 1 column is an ID of taxonomy.

I need to replace 'term id' on 'term name'. Right now I just make 'lookup' for each id and replace it with name:

foreach ($entries as $entry) {
  $row = array_map('check_plain', (array) $entry);

  // --> HERE I WANT TO AVOID LOOKUP FOR SAME ID
  $location = taxonomy_term_load($row['term']);
  $row['term']=$location->name;
}

However I'm not sure if it is a proper way to do that, since I have many similar ID and I want to avoid useless lookups (so I do lookup only for 'unknown' ID)

Should I build my own cache variable-list for every new ID or there is already an efficient way to do it?

You can use custom query like next:

$result = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name'))
  ->condition('t.tid', $tids, 'IN')
  ->execute()->fetchAllKeyed();

Or you can do join with entity table for single query.


Custom content entity: can't hide translation details in edit form I've created a multi-lingual custom content entity using Drupal Console. The basic stuff with editing/viewing works fine, also multi-lingual. But for some reason, I can't hide the "Translation" details form element (the one with the translation meta data) in the entity's edit form.

Screenshot of form display settings:

Screenshot of edit form:

In the config export core.entity_form_display.chunk.weather_daswetter.default.yml the translation also is listed correctly in the hidden section:

id: chunk.weather_daswetter.default
targetEntityType: chunk
bundle: weather_daswetter
mode: default
third_party_settings:
  stuff_from_field_group_module_here: nothing_with_translation
content:
  all_visible_fields_listed_correctly
hidden:
  changed: true
  created: true
  langcode: true
  translation: true
  uid: true

Into the blue I've tried relisting the fields from core's ContentTranslationHandler in my own src/Entity/Chunk.php->baseFieldDefinitions() and explicitly set them configurable, but this did not help either:

/**
 * @ContentEntityType(
 *   id = "chunk",
 *    ...
 *   translatable = TRUE,
 *   ...
 * )
 */
class Chunk extends ContentEntityBase implements ChunkInterface {
  use EntityOwnerTrait;
  use EntityChangedTrait;
  use EntityPublishedTrait;

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields += static::ownerBaseFieldDefinitions($entity_type);
    $fields += static::publishedBaseFieldDefinitions($entity_type);

    // tried adding this, did not help
    if ($fields['content_translation_status']) {
      $fields['content_translation_status']->setDisplayConfigurable('form', TRUE);
    }

    if ($fields['content_translation_outdated']) {
      $fields['content_translation_outdated']->setDisplayConfigurable('form', TRUE);
    }

    if ($fields['content_translation_uid']) {
      $fields['content_translation_uid']->setDisplayConfigurable('form', TRUE);
    }

    if ($fields['content_translation_created']) {
      $fields['content_translation_created']->setDisplayConfigurable('form', TRUE);
    }
  }
}

Why doesn't the form display mode control for "Translation" work?

I really want to keep this visible and configurable in the UI and therefore want to avoid using hook_form_alter.

UPDATE:
I've tried using hook_form_alter, but this doesn't work either:

function wt_chunks_form_alter(&$form, $form_state, $form_id) {
  if ($form['#entity_type'] == 'chunk') {
    /** @var $formMode \Drupal\Core\Entity\Entity\EntityFormDisplay */
    $formMode = $form_state->getStorage()['form_display'];
    $hiddenFields = $formMode->get('hidden');
    if (in_array('translation', $hiddenFields)) {
      //code goes into here, but the key 'content_translation'
      //does not exist in the $form array
      $form['content_translation']['#access'] = FALSE;
    }
  }
}

The translation field that you try to disable is not the one containing the metadata.

The translation metadata is generated in Drupal\content_translation\ContentTranslationHandler and is automatically applied if following access check is true:

'#access' => $this->getTranslationAccess($entity, $new_translation ? 'create' : 'update')->isAllowed(),

To solve this problem you can add a checkbox to your entity settings form that allows you to disable the translation.

You will also need to create a custom TranslationHandler for you entity.

In the annotations of your entity add this under handlers:

"translation" = "Drupal\MY_MODULE\MyEntityTranslationHandler",

Your custom translation handler can then be something like this:

namespace Drupal\MY_MODULE;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;

class MyEntityTranslationHandler extends ContentTranslationHandler {

  public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
    $form = parent::entityFormAlter($form, $form_state, $entity);
    if (// Some condition...) {
      $form['content_translation']['#access'] = FALSE;
    }
  }

}

Hope it makes sense.


User Login: login failed: 400 Bad Request I am trying the log in rest API with Drupal 8.4

For that, I am using angular 5

I have all the configurations working.

This is how I get the data from the form and send it to the UserServices. The UserServices will do the post method with the correct header, the user, and the password.

onSubmit() getting the data from the form:

onSubmit(name: string, pass:string): void {
    name = name.trim();
    if (!name) { return; }
    let user: any = {
     name: null,
     pass: null
    };
    user.name = {value: name};
    user.pass = { "": pass};
    console.log('Json from the form ' +JSON.stringify(user));
    this.UserService.login(user)
      .subscribe(user => {
        console.log('subscribed to login function' + JSON.stringify(this.user));
       });
}

this is the login() function, that send the post method

login (user: User): Observable<User> {
  const url = `${this.mainUrl}/user/login?_format=json`;
  const postReturn = this.http.post(url, user, httpHaljson);
console.log('Login return from the user service' + JSON.stringify(postReturn));
return postReturn
}

This is my header i have tested with aplication json and haplication hal json

const httpHaljson = {
  headers: new HttpHeaders({
  "X-CSRF-Token": "Qfnczb1SUnvOAsEy0A_xuGp_rkompgO2oTkCBOSEItM",
  "Authorization": "Basic Qfnczb1SUnvOAsEy0A_xuGp_rkompgO2oTkCBOSEItM", // encoded user/pass - this is admin/123qwe
  // "Content-Type": "application/hal+json"
  "Content-Type": "application/json"
  })
};

Now, this is what i get from the console: User Login: login failed: Http failure response for http://drupal.dd:8083/user/login?_format=json: 403 Forbidden

This is how I send the data from the form:
Json from the form {"name":{"value":"asd"},"pass":{"":"123"}}

Login return from the user service

{"_isScalar":false,"source":{"_isScalar":false,"source":

{"_isScalar":false,"source":{"_isScalar":true,"value":

{"url":"http://drupal.dd:8083/user/login?_format=json","body":{"name":

{"value":"asd"},"pass":

{"":"123"}},"reportProgress":false,"withCredentials":false,"responseType":"

json","method":"POST","headers":{"normalizedNames":

{},"lazyUpdate":null},"params":{"updates":null,"cloneFrom":null,"encoder":

{},"map":null},"urlWithParams":"http://drupal.dd:8083/user/login?

_format=json"},"scheduler":null},"operator":{"concurrent":1}},"operator":

{}},"operator":{}}

Any idea what am i doing wrong? thanks!

try

const headers= new Headers({
  'Content-Type': 'application/json',
  'X-CSRF-Token': 'Qfnczb1SUnvOAsEy0A_xuGp_rkompgO2oTkCBOSEItM',
  'Authorization': 'Basic Qfnczb1SUnvOAsEy0A_xuGp_rkompgO2oTkCBOSEItM'
})

let options = new RequestOptions({ headers: headers });

login (user: User): Observable<User> {
  const url = `${this.mainUrl}/user/login?_format=json`;
  return this.http.post(url, user, options ).map((res)=>{console.log(res)});
}


Apache Solr 6.x-1.2 re-index We have 90,000 nodes and it is currently re-indexing every hour (via cron) 200 pieces of contents. How can we have it do it all at once?

You could start by setting the number of items to index per cron run at 1000, and set the solr index cron hook to fire every 5 minutes using a drupal cron management module such as Elysia cron, which will allow you to set different intervals for all the other cron jobs on your site.

That's a reasonable setting to start with, which would be a big win over what it's currently set to, and would complete overnight. From there you could monitor for errors while tuning those 2 settings to see what the overhead on your system is.

Or you could just set that cron batch size variable on your Solr index to "-1" which is the magic setting that tells cron to index everything at once. Obviously, this has performance implications. Apache Solr Search in Drupal also has an "Index items immediately" option to force update the entire index as soon as you save the setting, and not wait for a cron run.


How can I add a textbox in Site Information configuration I'm altering the following form, admin/config/system/site-information.

I need a textbox in the site details section, below the email address textfield. The name of the textbox should be site_organisation. This textbox needs to save to variable when the save configuration button is clicked. Its saved value should be displayed when the page is reloaded.

How can I do this? Is there a module that can do this?

You need to add your own module if you're looking to alter this form. You'll need 2 things:

An alter form hook function to add the text field.
A submission handler to process the data.

Something like this...

function mymodule_form_system_site_information_settings_alter(&$form, $form_state, $form_id) {
  $form['site_information']['mymodule_site_organisation'] = array(
    '#type' => 'textfield',
    '#title' => t('Site Organization'),
    '#default_value' => variable_get('mymodule_site_organisation', ''),
  );
  $form['#submit'][] = 'mymodule_handler';
}
function mymodule_handler($form, &$form_state) {
  variable_set('mymodule_site_organisation', $form_state['values']['mymodule_site_organisation']);
}

Once implemented, you can reference your custom value by using variable_get('mymodule_site_organisation', '') anywhere you need it.


How to fix combination Dutch domain - English uri In Google Webmaster Tools I have 60 non-existing combinations of my Dutch domain and the English original blog. Example:

http://website.nl/enlish-blog

The from English to Dutch translated blog exists.

This problem leads to a degraded customer satisfaction, as Drupal reports the web-page not to be found.

I have checked the Global Redirect property to correct this, and automatically replace the English link with the Dutch link. To no avail.

I tried to correct it in Path redirect, but also to no avail. It is not allowed, because the module interprets it as the redirection of an alias, and advises the alias to be corrected. This does not work, because then the English web-page cannot be found.

My questions:

How do I fix this?
Why did I get it in the 1st place?

Thanks for any comment or suggestion.

My favourite way of dealing with 404 like that is to use module like Search 404:

  Instead of showing a standard "404 Page not found", this module performs a search on the keywords in the URL, e.g. if a user goes to http://example.com/does/not/exist, this module will do a search for "does not exist" and shows the result of the search instead of the 404 page. This should help retain visitors coming in from old URLs linked from other sites or from search indices.

That way user will see a link to an article on a proper domain, if he will enter bad URL.

To prevent creation of "interesting" links it's worth to use Global Redirect - with it even if you will have temporary misconfiguration, users and bots (including Google bot) will get redirected to content's main URL, and that's what will get indexed.

Last but not least, be sure to always set canonical URL for your content, if you care how it looks in search results.

I'm afraid you will never know what misconfiguration caused this in the first place, unless it still occurs. Things to check would be:

Canonical URL - are you sure it does not direct everyone to one single domain?
Web Archive - maybe they have a snapshot from time when your site was actually displaying something under these URLs. If so, you could use backups to unpack a copy on a dev machine, and examine configuration that made this.


Create a menu programmatically in Drupal 7 A newbie question guys.

Any thoughts how can I create a menu programmatically? Says I have 3 different menus I want to create. The first menu will be placed in the top left of the header. The second menu will be placed below the first menu. The third menu will be the main navigation.

Could these the menus be under the same group? Would it be a problem in styling?

Thanks

If you are trying to do this in an update script, this should work:

$menus = array(
  array(
    'menu_name' => 'menu_test_one',
    'title' => 'My Menu One',
    'description' => 'Lorem Ipsum',
  ),
  array(
    'menu_name' => 'menu_test_two',
    'title' => 'My Menu Two',
    'description' => 'Lorem Ipsum',
  ),
  array(
    'menu_name' => 'menu_test_three',
    'title' => 'My Menu Three',
    'description' => 'Lorem Ipsum',
  ),
);

$links = array(
  array(
    array(
      'link_title' => 'Link1',
      'link_path' => 'http://yourdomain.com/link1',
      'menu_name' => 'menu_test_one',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link2',
      'link_path' => 'http://yourdomain.com/link2',
      'menu_name' => 'menu_test_one',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
  array(
    array(
      'link_title' => 'Link3',
      'link_path' => 'http://yourdomain.com/link3',
      'menu_name' => 'menu_test_two',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link4',
      'link_path' => 'http://yourdomain.com/link4',
      'menu_name' => 'menu_test_two',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
  array(
    array(
      'link_title' => 'Link5',
      'link_path' => 'http://yourdomain.com/link5',
      'menu_name' => 'menu_test_three',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link6',
      'link_path' => 'http://yourdomain.com/link6',
      'menu_name' => 'menu_test_three',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
);

// Save menu group into menu_custom table
foreach ($menus as $menu) {
  // Look the table first if the data does exist
  $exists = db_query("SELECT title FROM {menu_custom} WHERE menu_name=:menu_name", array(':menu_name' => $menu['menu_name']))->fetchField();
  // Save the record if the data does not exist
  if (!$exists) {
    menu_save($menu);
  }
}

$item = '';
foreach ($links as $layer1) {
  foreach ($layer1 as $link) {
    // Build an array of menu link
    $item = array(
      'link_path' => $link['link_path'],
      'link_title' => $link['link_title'],
      'menu_name' => $link['menu_name'],
      'weight' => $link['weight'],
      'expanded' => $link['expanded'],
    );
    // Look the table first if the data does exist
    $exists = db_query("SELECT mlid from {menu_links} WHERE link_title=:link_title AND link_path=:link_path", array(':link_title' =>  $link['link_title'], ':link_path' => $link['link_path']))->fetchField();
    // Save the record if the data does not exist
    if (!$exists) {
      menu_link_save($item);
    }
  }
}

Comments are welcome if my approach is wrong. Thanks.


Showing fields or content with Views - which is faster? Say I'm building a view that lists 30 nodes. My understanding is that using fields in the view is faster than content (teaser), because the latter would need to call node_load 30 times? At least, I think this was the case with D6.

I appreciate the performance of both options depends on number of fields and types of fields used (entity reference, dates etc add query overhead). But does anyone have a general steer on this?

Thanks

In D7 it is the same, because the node (or any other parent entity) needs to be loaded in order for a field to be displayed (that's how Field API works in D7).