How to log user in when in the middle of Drupal Commerce Checkout I have created a commerce checkout page which, under certain conditions, is presented to the user with a custom login screen

$form['username'] = array(
    '#title' => t('Username'),
    '#type' => 'textfield',
    '#size' => 30
  );
  $form['password'] = array(
    '#title' => t('Password'),
    '#type' => 'password',
    '#size' => 30,
  );

In the submit handler, I log the user in

$username = $form_state['values']['user_login']['username'];
  $password = $form_state['values']['user_login']['password'];
  $login_array = array($username, $password);
  if($uid = user_authenticate($username, $password)) {
      global $user;
      $user = user_load($uid);

      $login_array = array ('name' => $username);
      user_login_finalize($login_array);
    }
  else {
    drupal_set_message('Invalid username or password');
  }

However, what happens is, is on next page, /checkout/order-id/review, it says the user is logged in but page not found. This is because the newly logged in user doesn't have anything in his cart. Is there an easy way of transfering the old cart to this new user? I see that there is a Rule - Assign an anonymous order to a pre-existing user, which I enabled and thought it would do the trick, but it doesn't

In case it helps: there is one rule defined by commerce -- Create a new account for an anonymous order -- which I disabled because I don't want that functionality. I don't know why this would effect anything, but just mentioning it in case it does.

I ended up simply using commerce_cart_order_convert($order, $user); I was able to assign the order to the correct user, and I decided not to log him in at point in time. If I really need to log him in, I will do so after checkout is over when I don't need to access the checkout review page anymore.


showing translation of the related node in view I have a node type called Match. Each match have two entity reference fields that points to  two nodes that has the type of Team. I built a view and use the relationship to show the matches and the information of the host team and guest team and it's fine.
My problem is that the Team node is multilingual and I want to show the translation of Team fields in the view. It is obvious that the fields has a reference to the original untranslated node ID and when I use the relationship in the view it will grab that node even if it has translations.

You can use the Translation redirect module (part of the Internationalization module) if your users are anonymous (unauthenticated). It just issues a 301 redirect whenever translated content exists.

If your users are logged in then there is another approach I have used, use an URL alias for your nodes. Set the alias to be the same for all translated content of a node and when linking to that node use the URL alias instead of the node number.


New custom content type: place image above body I would like to create a content type in which an image is inserted after the title and before the body. When I add an image to the image field, that image is placed after the body...

On Drupal 7, you can change the placement of the image from within the interface by navigating to Structures-> Content Types-> Name of your content type and then clicking Manage Display.  Drag the image above the body to show it first.


Calling a grandparent JS function that includes jquery from a nested iFrame. D7 I'm calling the grandparent_func from a second-level nested iframe like so.
This works in a non-Drupal environment, but am getting the following errors when running in drupal. (yes. I did remember to include the jquery file ;-)

parent.parent.grandparent_func( Date.now(), Date.now());

ERRORS:

For the following, I get a "TypeError: $ is not a function" error

<script>
    function grandparent_func(){
        $("#fancy_regit_link").attr("href", "/my/actual/path");
        $("#fancy_regit_link").trigger('click');

    }
</script>

So, I enclosed jquery like so to make it drupal-friendly and get:
TypeError: parent.grandparent_func is not a function

<script>
(function($) {
    function grandparent_func(){
        $("#fancy_regit_link").attr("href", "/my/actual/path");
        $("#fancy_regit_link").trigger('click');

    }
})(jQuery);
</script>

For good measure, I double enclose it with jquery's ready function.
TypeError: parent.grandparent_func is not a function

<script>
(function($) {
    $( document ).ready(function() {
        function grandparent_func(){
            $("#fancy_regit_link").attr("href", "/my/actual/path");
            $("#fancy_regit_link").trigger('click');

        }
    });
})(jQuery);
</script>

Any thoughts?

Thanks.

Introducing a closure around the whole function (as in your 2nd and 3rd examples) will take it out of the global scope, so it won't be available on the window, and subsequently the iframe's parent (which are the same thing).

What you're looking for is more like:

function grandparent_func() {
  (function($) {
    $("#fancy_regit_link").attr("href", "/my/actual/path");
    $("#fancy_regit_link").trigger('click');
  })(jQuery);
}

That makes sure grandparent_func is global, while still providing you the jQuery object.


Style block based on configuration setting I'm writing a module for Drupal and a bespoke theme. The blocks of the modules either float to the left or the right of the region their in. Currently I do that by hard coding specific css styles, e.g.

#block-myModuleName-myBlockName {float:left; background: red;}
#block-myModuleName-anotherBlockName {float:right; background: blue;}

I want to be able to set left/right (and maybe something else like background colour). So I've created an admin form that saves a persistent variable, such as variable_get('myBlockName-left', 0).

I can use that in the block content. I can wrap the content in a div that is based on the var such as <div class="myModulesetToLeft">, but that will not include the title, and it's a bit messy because it's deeper into the DOM of the block.

Do I need to create a template file for blocks? But that code will need to know what block it is displaying, so that it can check the right variable to know which class to add to the block div.

I'd probably just use the Block Class module and assign a classes like block-left and block-right.

  Block Class allows users to add classes to any block through the
  block's configuration interface. By adding a very short snippet of PHP
  to a theme's block.tpl.php file, classes can be added to the parent
  <div class="block ..."> element of a block. Hooray for more powerful
  block theming!


How do I validate form elements via onblur events? I am trying to validate a form element when it loses focus. But I am having issues calling the validation script.
I have tried both:

drupal_add_js('(
    function ($)
        {
        $("#edit-field-organization-url").blur(
            function()
                {
                //alert(\'jQuery Exec!\');
                $(this).validate();
                }
        );
        }(jQuery));', 'inline');

and

$form['field_organization_url']=array(
    '#type' => 'textfield',
    '#title' => t('Website URL'),
    '#weight' => 2,
    '#size' => 60,
    '#maxlength' => 128,
    '#value' => 'www.google.com',
    '#description' => t('Enter website URL.'),
    '#element_validate' => array('hook_node_validate'),
    '#attributes' => array(
        //'onblur'=> '$(this).validate();'),
        //'onblur'=> 'alert(\'jQuery Exec!\');')
    '#required' => TRUE
    );

but neither work. I'm guessing this isnt the proper drupal way to call the validation functions.

#########################

UPDATE

#########################

I still cant seem to get it working. The validation code now runs every time the page is loaded and doesnt seem to be tide to the onblur event even though I have it set in the clientside_ validation module:

  file - template.php:

function THEME_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'custom_content_type_node_form':
$form['custom_content_type_node_form']=array(
'#type' => 'textfield',
'#title' => t('Website URL'),
'#value' => 'http://www.google.com',
'#description' => t('Enter website URL.'),
'#element_validate' => array('hook_clientside_validate_url'),
'#required' => TRUE);`

file - custom.module:
`function hook_clientside_validation_rule_alter(&$js_rules, $element, $context) {
switch($context['type']) {
case 'element_validate':
if (in_array('hook_clientside_validate_url', $context['functions'])) {
hook_clientside_validate_url($js_rules, $element);
}
function hook_clientside_validate_url($js_rules, $element) {
//validation code here
}`

Drupal doesn't have any client-side validation by default, but you can get that functionality with the Clientside Validation module:

  This module adds clientside validation (aka "Ajax form validation") for all forms and webforms using jquery.validate.

According to the docs it has a "Validate on blur" option, so it should be just what you're looking for.


Dependent product variation type I have a question.
My site sells tours.
For each tour(product) a user can choose a flight  and some hotel rooms.
Example tour1:
user can choose: flight1 and flight2.
user can choose: double rooms and/or single rooms.
If the user choose flight1 then ->  double rooms costs 50, single rooms costs 100(a).
If the user choose flight2 then -> double rooms costs 150, single rooms costs 200 (b).
I have 3 dependent variation types(flight, doubleRoom, singleRoom). What I want is:
if the user choose flight1 I only show double rooms = 50, single rooms  =100 (rooms(a));
if the user choose flight2 I only show double rooms = 150, single rooms=200 (rooms(b)).
Flights and rooms have  a taxonomy terms called 'solution':solution1, solution2 ecc..
I think that a way should be use rules, with event 'After adding a product to the cart' but I can't write the condition('if flight  choose solution1') and the action(set visible=true where rooms solution= solution1).
Can someone help me please??
Thanks in advice

I am looking for this for Drupal 8, however it appears that the module Commerce Product Add-on provides a solution for Drupal 7 (I have not tested it).

  Commerce Product Add-On allows users to attach products as options to
  the add to cart form of another product. This is particularly useful
  for things like event sponsorship, optional accessories, and other
  up-sells.


Using entity query build to select entities applying conditions on all revisions Background

Best practice deems that you should use EntityFieldQuery (d7) for making queries that somehow involves fields on entites.

An example of such a query could look like this.

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_foo', 'value', REQUEST_TIME, '>')
  ->execute();

In the above example, we are looking for nodes which has a timestamp value set in the future, it works just fine and all is good.

Question

Is it possible using these APIs (which handles that fields potentially could be stored anywhere), and apply the condition on all revisions, instead of only the active revision?

When using SQL, you could make a custom query on the field_revision_FIELDNAME table, but doing this would require you to make some database assumptions and break best practice.

Yes. EntityFieldQuery has a property EntityFieldQuery::$age that is a flag for the age of the returned entity revision. It can be set to:

FIELD_LOAD_CURRENT (default): for only the current revision (e.g. $query->age = FIELD_LOAD_CURRENT;)
FIELD_LOAD_REVISION - for all revisions (e.g. $query->age = FIELD_LOAD_REVISION;)

Support for this flag ultimately depends on the EFQ's queryCallback function. In the default field_sql_storage_field_storage_query() function, it is recognized and queries the appropriate revision tables accordingly.


Panels Pane Content Added - Stacked, need Inline Hi I'm developing an Intranet in Open Atrium - Drupal 7. The distribution is heavy on Panels, so I am developing the Portal with them. However I have a Pane for one of the Panels and I want to upload 4/5 separate blocks into it. However the default behaviour is everything is stacked in the pane, and I would like to be able to control it so I can lay things out side by side, is there a way to do this within the Drupal System. At present I am using Negative Relative Positioning to move things where I want them. Then specifying a height for the body to get rid of the negative space it leaves - not ideal. I can't use Negative Margins because the company where the Intranet is uses a lot of IE7 and IE7 doesn't recognise negative margins.

You could use custom panel layouts (use the builder option) and create the regions you want with the size and position you want.


Is there a way to export all roles and permissions from testing environment to be imported/deployed on production environment? I have testing and production environments that host drupal-7. I have some roles and permissions settled on the testing environment. Can I export these roles and permissions to the production environment to avoid double effort?

Check out these modules Export Roles & Permissions or Features Roles & Permission


Field Collection Adding Values I'm confused by the field_collection API. I created a Field Collection and attached it to a node (in the GUI) but I can't figure out how to code an update/addition to the field collection. This is my scenario:

I have a node (request) that has product information and quantities. When users go to a product page they see a link to "Add to Request". This link should add the product (nid) to the node request. The difficulty lies in the fact that I need quantity information as well, hence the Field Collection. I added a quantities field and grouped it with the product field.

Node Type: request
Request ID: $requestid
Product ID: $productid
Field Collection = field_request_collection (Unlimited values)
Field Collection Field = field_products (Entity Reference, Max 1)
Field Collection Field = field_product_quantities (Integer, Max 1, Default 1)

My function looks like this (the values for $requestid and $productid are passed in the URL of the link: /my_request/5/12):

function _my_module_request_update($requestid,$productid) {
$nload = node_load($requestid);
$field_collection_item_value = $nload->field_request_collection[LANGUAGE_NONE][0]['value'];
$field_collection_item = entity_load('field_collection_item', array($field_collection_item_value));
$field_collection_item->field_products[LANGUAGE_NONE][0]['value'] = intval($productid);
$field_collection_item->save();
}

The error I'm getting with the above code is:

  PHP Fatal error:  Call to a member function save() on a non-object

Keep in mind that I'm attempting to ADD Field Collection values NOT replace them.  Please help, thanks!

Something like this ought to do the trick:

$nload = node_load($requestid);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_request_collection'));
$field_collection_item->setHostEntity('node', $nload);
$field_collection_item->field_products[LANGUAGE_NONE][0]['target_id'] = intval($productid);
$field_collection_item->save();

$nload->field_request_collection[LANGUAGE_NONE][]['value'] = $field_collection_item->item_id;


Render comments in a custom Twig template I rewrite the article tpl page--article.html.twig and I want to render the comments and the comments form.

I add the comments in the content type fields and try to render with {{ node.comment | render }}, but it's not work.

Is it possible to render it in a custom tpl?

After adding comments as field in your content type

In node--article.html.twig :

{{ content.field_myfieldnamecomments }}


Linking content types I need to link content from one content type to another automatically so that when one of the type is updated with new content, the other gets filled automatically. Any ideas?

You need to use Entity Reference module to connect two different content types content. Add a field Entity Reference in one content type and reference it to another content type.

To auto update another content type content, you need to use hook_node_insert and hook_node_update on first content type, and get referenced nid and update second content type content using node_save.


Show multiple drupal 7 'name field' in one view row? Using this on D7: https://www.drupal.org/project/name

The name field is on a 'book' content type. 1-to-many authors.

In views, I want to see the name of the book, and the authors. Currently, it shows one repeat row per author. How do I consolidate them into one row? The field setting does not seem to include anything for this.

Thanks, sorry if this is noob of the century territory.

The views aggregator plus module solved my problem https://www.drupal.org/project/views_aggregator


What version of PHP/MySQL? I just retrieve maintenance (archive FTP/SQL) of a website running Drupal 6.22…

But… I have an Debian 8 server with Apache 2.4, PHP 5.6 and MySQL 5.5... :)

==> So my question is : what is the upper version of these software (Apache, PHP, MySQL) can run Drupal 6.22 ?
I think PHP 5.3, but after ?
(I know that 6.22 is an old version but I will update after first run).

Really thanks for your help.

Per the d.o. requirements page, D6's requirements are:

Web server: Apache, Nginx, or Microsoft IIS
Database: MySQL 4.1 or higher, PostgreSQL 7.1,
PHP: PHP 5.x only (5.2.5 or higher recommended). Warning: support for PHP 4.x has been dropped. Drupal core should work with PHP 5.3.x, but PHP 5.3.x and higher may produce errors or unexpected behavior especially for contributed modules and themes.


How do I set the page title? I know I could change the page title with drupal_set_title(t('Amy page title')), but when I try it in Drupal 8 I get the There is no such function error.

How can I change page title in Drupal 8?

As reported in drupal_set_title() and drupal_get_title() were removed that function is deprecated in Drupal 8.
For a dynamic title set from a controller, the code the change record suggests is the following one.
mymodule.test:
  path: '/mymodule/test'
  defaults:
    _controller: '\Drupal\mymodule\Controller\Test::getContent'
    _title_callback: '\Drupal\mymodule\Controller\Test::getTitle'

The controller code is the following one.
class Test {

  /**
   * Returns a page title.
   */
  public function getTitle() {
    return  'Foo: ' . \Drupal::config()->get('system.site')->get('name');
  }

  /**
   * Returns a page render array.
   */
  public function getContent() {
    $build = array();
    $build['#markup'] = 'Hello Drupal';
    return $build;
  }

}

Alternatively, as the same change record suggests, you could use the #title property in a render array. This should be generally avoided, since the title for the page when fully rendered could be different from the title in other contexts (like in the breadcrumbs).
class Test {

  /**
   * Renders a page with a title.
   *
   * @return array
   *   A render array as expected by drupal_render()
   */
   public function getContentWithTitle() {
     $build = array();
     $build['#markup'] = 'Hello Drupal';
     $build['#title'] = 'Foo: ' . Drupal::config()->get('system.site')->get('name');
     return $build;
   }

}


User registration times out/doesn't exit on live centos+nginx server I have a bit of an edge case, but it's confusing me very much. I noticed that my services user/register.json POST calls would just endlessly freeze on my production server, but not on my local, however it would actually successfully create the user. Also, it would happily exit with a services_error() callback if the user couldn't be created (existing username, for example).

On further investigation, it seems that the user registration form itself on the drupal site does the same thing. No errors come up, nothing in the logs, just an endless timeout on successful save and drupal set message errors on unsuccessful save. Even when I go into the code and insert watchdog messages, they only actually get pushed through on the next successful request. It also only seems to be registration that is affected, and creating a new user from the admin interface is completely fine.

The production server is a CentOS 7 box running nginx with php-fpm, mariadb & memcached, seems to have enough memory, doesn't appear to have any weird low timeout values in the settings, etc.

Can always provide any conf files or anything if that helps, but I was wondering if anyone knew of any known issues where only user registration could be affected. Thanks in advance!

Issue was a faulty mail server. For some reason when it couldn't use mimemail properly it was choking without error, kinda annoying. Fixed by setting up a proper external mail transactor (mailjet module in my case).


how to create a "my comments" view I just want to create a view that show each user their own set of comments only. would I add something in contextual filters?

Thanks
Tony

Yes, add the contextual filter "Comment Author uid". Then, under the section "When the filter value is NOT available", select,

"provide a default value".

You can then select:

"User ID from logged in user"

or

"User ID from URL".

To use the latter, you will have to display the view as a block on a page that has the user->uid in the system path, such as the user account page (user/%uid). If you use the former, the view can be displayed anywhere, and will always show the current user's comments.


Field Taxonomy Reference full view is this possible to create full view formatter for taxonomy reference field? I've tried default formatters but it only prints title of the term and nothing else...

I see.

Try this, create a view of fields of content type (ie: Articles)

In your view, under Advanced, RELATIONSHIPS, add taxonomy terms on node.

Now under FIELDS add a field, and now you should have access to the tax term fields now.


Register only via a specific e-mail domain I need to allow users to register for a Drupal-6 site, but only if their email contains a specific domain. For example, only allow users with whatever.com in their  email address to register; a user with the email bob@whatever.com can register for the site, but bob@something.com cannot register for the site.

Is there a module for this? If not, which file would the PHP need to be altered for this?

the "user restrictions module" is supposed to offer that feature. But it doesn't seem ready for production yet. However you could use the code to write your own.

I also tried to do it with the rules module and setup a rule for the "event" "user: before saving account" with a condition "data comparison" on field "account:mail".
Add "value contains" and use "@whatever.com" and then check the "negate" box. That will basically trigger the rule for all emails that don't contain @whatever.com.

However I couldn't find a way to stop the username from getting saved. If you use the event "user: after saving account" you can show an error to the user and block the account. It prevents the registration but shows a second message to your user "you'll get notified by the administrator". Not a great experience for your customers.


How do I add Google +1 to Addthis Button? I am using the Addthis Module version 6.x-3.0-beta2, the problem is that google +1 doesn't appear as one of the services. Anyone knows how to fix this ? Thanks !

There is a tutorial http://www.addthis.com/features/google-plus1-button

Anyway, +1 is not a sharing service, I'm not sure that Addthis will add this (like there is no Facebook Like button). You can use the Customize service that addthis.module supports to add code described here.


How can I tell what is causing commerce to throw entity wrapper exception errors? I'm attempting to repair and reconfigure a site that was created by another admin. I ran across some issues with commerce coupon that I've been able to get past with help I received here first then here (referenced for insight into the current error).

When I enter edit mode for the "Commerce Coupon Review Pane" view, I get the same ajax error message as before but now with currency_code:

An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /admin/structure/views/view/commerce_coupon_review_pane/preview/checkout/ajax
StatusText: Service unavailable (with message)
ResponseText: EntityMetadataWrapperException:
Unable to get the data property currency_code as the parent data structure is not set.
in EntityStructureWrapper-&gt;getPropertyValue()

I'm also redirected to an error page with same exception when I click on the checkout button.

I don't think its a bug due to the way that this issue cleared up in the previously referenced issues. It seems more likely something happened to the data. It would also seem that getting help from the issue queues would be unlikely because it would be impossible for me to come up with steps to reproduce the error. Unfortunately I don't know how to attack the problem. However, I suspect that when the page tries to load, somewhere along the way, it fails to find data it expects to find. If this is too general of a problem what steps can I take to find out more precisely what is happening?

===============

Update:
Thank you for the responses @pcambra, @tenken and @Clive. It appears that there is a broken relationship. I am missing these settings in the Commerce Coupon Review Pane:

"FIELDS"

 (Commerce Order referencing Commerce Coupon) Commerce Order: Order ID

"CONTEXTUAL FILTERS"

 (Commerce Order referencing Commerce Coupon) Commerce Order: Order ID

"RELATIONSHIPS"

 Entity Reference: Referencing entity

When I try to add them into the view, there is no option to select them.

Also, when I try to load /admin/commerce/orders/carts/ I get the same error but it does not specify a field.

Where is this relationship made and how do I now fix the relationship so they show up in the configuration dialog?

===============

Update:

Following instruction I am now getting these errors. Although this is progress, I turned up nothing useful on restoring broken handlers that was not specific to a particular module.

//when I click on add under FIELDS in the view this error is produced
Notice: Undefined index: base in get_base_tables()
(line 717 of view.inc).

//otherwise these errors are produced each time I try to enter the view
Missing handler: commerce_coupon
reverse_commerce_coupon_order_reference_commerce_order relationship

Notice: Undefined property: views_handler_relationship_broken::$alias
in get_result_entities() (line 1604 of views_plugin_query_default.inc).

sounds to me like the rules the old developer put in place are still firing for coupons and since you tried to downgrade from 2.x to 1.x they're firing and its killing your page ........ look for rules that might be lingering about??

More debugging can be found by installing devel, finding this path in the sourcecode of commerce_coupon /admin/structure/views/view/commerce_coupon_review_pane/preview/checkout/ajax and using dd() on func_get_args() throughout that pages' page callback function to debug where php is trying to get currency_code.

In general installing and hitting the page with xdebug debugger, and stepping through the code, could be very helpful too -- learn how to set some breakpoints in the debugger.


Import data using ECK and feeds module Is it possible to import data from CSV file and insert all in two different entities
for example I have created two different entities, cadidates and exams entities, once I import data to exam entity i would like to make candidat entity updated also referencing to some field, i have tried many solution possible but in vain

Why not make two importers that you run on the same CSV dataset? Run it first on the first imported setup and then again on the next. Each imported can be configured to create the needed content type.


Inline entity form prepopulate I have a content-type A which has a reference field to another content-type B. When creating/editing content with type A I let the user create/edit content of type B using the inline_entity_form module.

In this scenario, I like to pre-populate one field in content-type B. Here I'm using the entityreference_prepopulate module, but when I add the field to my URL its not populated? As example, if the field in B has the name field_myfiled , I write in the URL:

example.com/mypage?field_myfield=value1

This has worked before on fields which are rendered "normally". Is there something I'm missing since the filed is rendered by the inline_entity_form module?

Please try Entity reference autofill with Entityreference prepopulate Module.

Add an entity reference field in your entityform.
The entity reference autofill will automatically fill reference value into field. We can load default value from URL. (?field_name = value)
Entityreference prepopulate will prepopulate the values. (you have to add existing fields for that.)

Hope this will help you.


How to update Twig - does it need to be updated? Does Twig will be updated automatically? Or does an updated version comes with a new Drupal 8.x release? Or does Drupal just stuck on the current version?
I'm just wondering because Twig will be further developed. Thanks.

Drupal core may update that dependency if it complies with the Allowed changes during Drupal 8 release cycle documentation page. A library may be updated to a more recent version in a minor release of Drupal (such as 8.1.0 or 8.2.0). Any feature requests or bug reports should be discussed in the issue queue for Drupal core.

Composer dependencies do not update automatically, but are based on running the composer command on the composer.json (or lock file).

However a contrib module may add its own Composer dependencies, which could alter dependencies added by Drupal core outside of a release. Composer looks through the entire dependency graph to choose a version to install, and this might update Symfony or Twig or Behat for instance. You can learn more about how Composer deals with semantic versions, which is similar to npm (node.js).

It is probably not safe to update to an arbitrary version of Twig because that may break core or contrib, but it is possible to update to a compatible version without waiting for an update in Drupal core.


Custom form "Data too long for column" I create a custom entity (pool) with a custom form.

In my custom form, i have a field (start_date)

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#default_value' => new DrupalDateTime()
];

When i want to save, i have the follow error :

"Data too long for column"

In the log, the value is : 2017-12-21 18:06:29 Europe/Paris
Instead of 2017-12-21T17:06:29

What i'm doing wrong ?

Drupal's DateTime field isn't ISO 8601 compliant, (doesn't save datetime values in the standard format you're expecting 2017-12-21T17:06:29).  You need to convert the value to UTC format for storage.  One approach is to initialize a date variable, convert it, and then pass as the value in your form field.

$currentDate = new DrupalDateTime();
if ($currentDate instanceOf DrupalDateTime && !$currentDate->hasErrors()) {
  $currentDate->setTimezone(new \DateTimeZone('UTC');
  $db_friendly_value = $currentDate->format('Y-m-d\TH:i:s');
}

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#default_value' => $db_friendly_value
];

Specific notes about working with the DateTime API in D8 can be found in this "New DateTime API" post.

This specific formatting issue was reported for the datetime module here.

Comment 6 shows the recommended approach to converting the date into the proper format for saving.


Why are Drupal hosting providers using Solr 3.x instead of 4.x or 5.x? As of April 2016,

Acquia offers Solr 3.5.
Pantheon offers Solr 3.6.
Platform.sh offers Solr 3.6 by default, with 4.10 as an option.

The current release of Solr is 5.5.0 (2016-2-20).

3.5 was released on November 25, 2011.

3.6 was released on April 11, 2012.

4.10 had its final release on October 14, 2015 (but it was first released on September 2, 2014).

Is there a reason to stick with 3.x vs. Solr 4 or 5?  Search API Solr supports all three versions.  Normally I would just use the latest version, but when major hosts that specialize in Drupal are on a version that is more than three years old, it makes me wonder.

It probably comes down to LTS and backwards compatibility, though you'd have to ask each organisation for their specific motivation.

Solr 5 is not backwards compatible with 4, 4 is not BC with 3. So if there are users on legacy systems using older versions, upgrading would require all customers to upgrade their schema/integration too. Installing newer versions on new servers might mean customers can't migrate from one server to another, might break the generic model of system deployment, etc, etc.

Some companies will offer newer versions, but you'll probably find the older versions are always available too, otherwise the company is likely to have at least a few pretty irate customers when they switch it off.

Basically, if you tell someone that you're going to support a version of software for the foreseeable future, you have to do that. It's why so many shared hosting companies support obsolete versions of PHP - because the people hosting there have no intention of upgrading their code, but their sites still need to work.

There's no Drupal-specific reason (that I know of) to choose one version of Solr over another, as long as the contrib module you're using has support for that version.


How do I prevent a "Page not found" error for URLs containing non-Latin characters? I have a site that uses non-latin characters in URLs, e.g. http://example.com/drupal/новости. When the URL is copy-pasted, some browsers change the URL to http://example.com/drupal/%ED%EE%E2%EE%F1%F2%E8, and this causes an Page not found error.

How do I make Drupal understand both http://example.com/drupal/новости and http://example.com/drupal/%ED%EE%E2%EE%F1%F2%E8?

Consider trying the Transliteration module. Here is a quote from its project page:

  ... it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

As a sample, it transforms an URL like mydomain.com/последние-новости-в-Украине-и-мире in something like mydoamin/poslednie-novosti-v-Ukraine-i-mire.

Other modules that might help to solve this question:

Global Redirect.
Pathauto.


Customize Error/Success Messages in Drupal 7 I need to customize the success/error message after submitting details. It needs to cover areas like contact form, forum create etc.,

Especially below message,

Drupal Version : 7.57

Theme : Bootstrap

Also, Is there is any possibility defining a new style for above messages?

This might be what you are looking for:

Using the String Overrides module replaces the current string with what ever given.


Entity query for distinct field I have an entity line_item with the following fields:

id
uid (entity reference)
product (entity reference)
...

I would like to get all distinct products (product ids) for a specific user.

I tried with entity query:

$query = $this->entity_query->get('line_item');
$query->condition('uid.entity.name', $username);
$entity_ids = $query->execute();

Unfortunately this results in all line_items from the given user, with multiple times the same product. But what I am interested in is just getting all different products for the given user.

I don't think it's possible to write a single entity query to accomplish this. You could take your $entity_ids result, use loadMultiple to load all the line_item entities, and then iterate through them to get all the products. Something like this:

$line_items = $this->entity_type_manager->getStorage('line_item')->loadMultiple($entity_ids);

$products = [];
foreach ($line_items as $line_item) {
  $product = $line_item->getProduct();
  if ($product && !isset($products[$product->id()])) {
    $products[$product->id() = $product;
  }
}

Another possibility would be to use the database service to construct a select query with actual database table names and fields (\Drupal\Core\Database\Connection).

See:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Connection.php/function/Connection%3A%3Aselect/8.2.x

and for the list of methods you can use to construct the select:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21SelectInterface.php/interface/SelectInterface/8.2.x


Allowing role permissions to a content type based on the date I'd like to allow a certain role can add new content of a certain content-type ONLY between two dates. Before or after these dates the role shouldn't be able to create a new content of this content-type.

Is it possible through the Drupal core or any module? I haven't found anything about it.

You can implement hook_node_access() (This is now a real hook in Drupal 7) and implement whatever you want.


Is there a way to remove tabs inside panels? This is a simple question, i know that there are many modules who can alter tab like tab tamer.

But i would like to avoid to install another module in my site because he's already slow and my server he's limited, it's why i'm asking this question.

I alter the user template profile, so i just want to remove the tabs : view and edit, i didn't find any setting to do that but maybe i missed something?

From memory, I believe the answer is no, because the tabs are rendered outside of the area that Panels is responsible for.

If you use Panels everywhere, then you can simply leave the tabs out however, "In panels". If you don't, the rendering is probably happening in page.tpl.php instead.


Link items from Feeds module to original blog I am using the Feeds module to publish the contents from a Wordpress blog to my site's home page. I'd like to have the items on the home page link directly back to the original blog rather than the nodes that the Feeds module creates. Is this possible? If so, how do I do it?

I'm assuming you're using an RSS/Atom feed, and that you're using the node processor in your feed importer. In your feed importer settings, you can edit the node processor mappings. Add a mapping from the "Item URL (link)) to some text field in the content type you import to. Then you can use that field to create links back to the external url in views, and in the template files for the content type.

Once you have the url field, go through the following steps.

create a view of feed items. /admin/structure/views/add

a. select "show CONTENT of type Feed Item". You can create a block or a page. Either way:

b. select "display unformatted list of fields"

c. click "continue and edit"
add fields.

a. add Feed item URL. select "exclude from display".

b. add  content title. Make sure it appears after the feed item url in the fields list. Select "rewrite results", then "output this field as link". Click on "replacement patterns" to reveal the tokens you can use. Insert the token for "feed item URL" in the "link path" field, and select "external URL". Save the view.
if you've created a page, you'll need to give it a path. If you've created a block, you need to go to structure > blocks and assign the block to a region.

Hope that helps.


When might a module's weight in the system table not affect its hook order? I am trying to implement hook_menu_alter in my module, but I am finding that revisioning_menu_alter is always being called after my hook, regardless of what I set my module's weight to.  It seems that this is because the revisioning module does not appear in the system table at all, even though it is enabled.

What is going on?  How can I make my module's hook get called after revisioning's hook?  Don't modules always have to have an entry in the system table?

If revisioning does not appear in the system table, it is considered not installed and hook implementations it provides are not executed.

Upon installation, the revisioning module updates its weight to 1, making its hook implementations run later than those of most other modules (which default to a weight of 0).

If you want to change the order in which implementations of a particular hook are executed, have a look at hook_module_implements_alter().


Drupal front page blog entries custom sort order I have two blog entries which as defaults displays in front page.

1.) Submitted by admin on Thu, 06/16/2016 - 13:32 displays second
2.) Submitted by admin on Thu, 06/16/2016 - 13:33 displays first

I would like to display these at any point of time in a custom order, probably using custom field

You may add your custom field "sort_order" to the blog content type, then create a page view (/admin/structure/views/add) for the blog content (just like node does it in the "frontpage" view - you may even copy that view and restrict the nodetype to blog in your copy).

Then change the "sort criteria" in the view to your sort_order custom field.

Then you're done.


Theming the output of multiple image upload widget in node create/edit form I need to theme the node create/edit page according to the user's specifications. To do so, I need to output of theme_file_widget_multiple($variables), I suppose. It gives out table format which I need to convert into grid or divs. If there is some other easier hook or function for the same thing, please suggest me.

Can anyone help out?enter image description here

One option is to use MYTHEME_image_widget. This theme function allows you to adjust the output of the image widget.

In combination with  MYMODULE_field_widget_form_alter and MYMODULE_image_field_widget_process you should be good to go.


Create successive Batch script? How can you create a successive batch job in the Batch API?

For example, if I wanted to queue and assemble 1000 nodes as a batch, then process them in a second batch when the first batch is done, automatically? Do I just call the second batch job in the finished callback? Can it be passed arguments?

I haven't tried to do exactly this before but something tells me it would be tricky. This is from the Batch docs:

The API is primarily designed to integrate nicely with the Form API workflow, but can also be used by non-Form API scripts (like update.php) or even simple page callbacks (which should probably be used sparingly).

I remember trying to set batches outside of a form context before and always resorted back to using a form as I could never get them to work.

You might have more joy than me though so you could try simply doing a batch_set in the finished callback like you suggest. Assuming you're adding some data to the $context variable in your first batch's callback function (such as the node ID) you should be able to pick that context data up again in the finished callback and pass it though to your second batch's setup function.

Hope that makes sense!


Change title head of the pages in Drupal 7 by path I need to change the title head of the pages in Drupal 7 by path.  NOt to all content type.  I need to change the title head to a specific page generated with views.

For example, I have a site http://www.mysite.com

<title>My favorite website </title>

I need the  for pages:

http://www.mysite.com/test

<title> My test today </title>

http://www.mysite.com/examples

<title> My examples for share </title>

Thanks.

It sounds for your limited set of pages maybe implement THEME_preprocess_html() and examine the url path and override $vars['head_title']. See this blog post as an example: How to set custom page title in Drupal 7

If you have some patterns for the head title try Page Title


How to implement a transaction process between users using the Privatemsg module? I am trying to develop a transaction process between two users who can do transaction using a form with two fields:

a text message to communicate back and forth
a virtual point to trade the product instead of regular currency.

So I customized the checkout process in the Drupal Commerce module. And I tried the Privatemsg module for messages. And Commerce userpoints for the virtual currency. I also customized the "Price" field in Commerce Product field.

I thought I might use Commerce Extra Panes to replace the default checkout steps, but I am stuck because the Privatemsg message text field may not display in the extra pane (I created a content for Privagtemsg to be attached and Extra pane may include the content node with Privatemsg).

This process allows the store owner to use messages and virtual currency to negotiate with the buyer back and forth, so we need a form for them to fill. I also wonder if Rules may provide a form that allows users to enter whatever they want in the checkout process?

I am new in Drupal so I am not sure if this is a good approach. Do you think if this way works? Or any other solution?

You may want to use the integration between the User Points module and the Rules module to "roll your own cookies", by writing some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

If you simply adapt the amount of points (-2 and -1) to something like (eg) +25 and -25, you've a prototype to transfer (25) user points from one user to another.

If you replace the Rules event by an event like "Something is flagged" (created with the Flag module, and the "something" being a product), then a simple click could be used to indicate "I want to transfer 25 user points of mine to this user" (probably to trade that product in your case).

You could take this even a step further: since flags are fieldable, you could add these fields to such flag (to implement a bidding-system):

A field to indicate the amount of points to be "moved" (= like the price to be payed for the product?).
A field to indicate the price requested by the seller.
A field to indicate the price offered by a potential buyer.
A field for some text to be used for storing some message text. Possibly you may want to "deliver" that message text using the Message module, which has a great integration with Rules also (though it's not obvious to get started with the Message module).

Note: The above Rules example may need further refinements, e.g. if you want to ensure that after moving points van User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.


User Relationships view showing each relationship more than once I'm trying to display a users relationships through Views(3). I'm getting duplicates for accepted relationships. Also, the current user show's up under his/her own relationships. Here's what I got so far:

Format: Unformatted list
Show: Fields

Fields
User: Name
User: Picture

Filter criteria
User: Active (Yes)
(rtid) User relationships: Requester or Requestee is current user (True)

Sort criteria
User: Created date (desc)

Block name: None
Access: Permission | View user profiles

Contextual filters
User relationships: Requester user  // I've tried (rtid) here with the same result

Relationships
User relationships: Requestee user
User relationships: Requester user
User relationships: RTID

Use AJAX:Yes

You can exclude current user from view by passing argument of current logged in user id and check exclude this argument from view.

You can avoid duplicates by enable distinct in basic settings.


How to access to node on form_submit I added a button to the page. I'm trying to get the values of the field when I click the button. But I can not understand how to access the node from submit? Am I on the right track or should I look for another solution? I tried to add $node to the function redirect_button_form_submit but this does not work.

function show_on_map_node_view($node, $view_mode, $langcode) {
    $url = url(current_path(), array('absolute' => TRUE));
  if (($node->type == 'addproblem') && (strpos($url, "problem"))) {
    $form = drupal_get_form('redirect_button_form');
    $node->content['redirect_button'] = $form;
 }
}

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Show on map'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
//How to access the $node here?

    $geofield = field_get_items('node', $node, 'field_location_exif');
    $location = array(lat => $geofield[0][lat], lon => $geofield[0][lon]);
    $path = '<front>';
    $options = array('query' => $location);
    drupal_goto($path, $options);
}

You can pass the node as an argument to your form builder and store it there.

$form = drupal_get_form('redirect_button_form', $node);

function redirect_button_form($form, &$form_state, $node) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Show on map'),
    );

    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    $node = $form_state['build_info']['args'][0];

    $geofield = field_get_items('node', $node, 'field_location_exif');
    $location = array(lat => $geofield[0][lat], lon => $geofield[0][lon]);
    $path = '<front>';
    $options = array('query' => $location);
    drupal_goto($path, $options);
}

drupal_get_form can take additional arguments besides $form_id.

  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.

Also, to do a form redirect you can use:

$form_state['redirect'] = path...

Instead of drupal_goto which should not be used here.

  When $form_state['redirect'] is an array it should be populated with
  arguments appropriate for drupal_goto() - which is to say, the second
  element in the array can itself be an array holding all the properties
  expected by url()'s $options argument, including fragment, query,
  absolute, etc.


Field translation works randomly I have a 3 language website and translated bunch of field labels, the thing is that it works just for some of them not all of them. I created the forms with Entity form module and even when I check the translation for other languages it's there, it just doesn't show the proper translation and keep showing the default language instead.

Any ideas what may have caused it?

The module used for translating fields (title, help text, description, allowed values) is i18n_field.

Internationalization 1.8 shipped with a broken i18n_field module, so in many cases nothing would get translated.

The first issue that fixed most of the failures was
[7.x-1.8 regression] Field translation fails in numerous situations
It has now been committed and is a part of the latest -dev release.

Contrib field types such as commerce_price might need the following patch:
Extend support for contrib field types

With those patches applied I had no problem with translating any part of a field.
For translating allowed values (radio or select fields), my process was this:
1) Go to manage fields, click edit next to my list(text) field.
2) Click the Translate tab on the next page.
3) In the table, find my language and click "translate".
4) I can translate the values under the "Field settings" vertical tab.

Also keep in mind that when showing one of those values on a rendered entity, you need to use the "Default translated" formatter (set under "Manage Display").


Spambots causing server crashes. How do I block them? I have a Drupal 7 website on a shared hosting account that uses an Apache server. It is getting continuously battered by spam bots who try to post junk comments and create fake accounts. What methods can I use to block them from accessing the site and/or doing any operations there.

Currently, I have the following modules installed to block and combat spam:

Spambot - https://drupal.org/project/spambot

Spamicide - https://drupal.org/project/spamicide

Hashcash - https://drupal.org/project/hashcash

AntiSpam - https://drupal.org/project/antispam

Cloudflare - https://drupal.org/project/cloudflare

I tried installing Bad Behavior (https://drupal.org/project/badbehavior), but there appears to be some error in its installation procedure.

I do not want to use captcha to block spambots.

This is better solved at the Apache level.  The industry standard method for doing this is to create a honeypot directory, make it off-limits to bots in robots.txt, then logging the IP-address of those who still go there, and block it.

For an example of this, see the this page: http://www.kloth.net/internet/bottrap.php. You can set up this on shared hosting as long as you can edit .htaccess.

For a more sophisticated solution, take a look at Project Honeypot (NB: no relation to the Drupal Honeypot module).  There is already an Apache module which interfaces with Project Honeypot's IP blacklist. To install this, you ned to have access to the Apache config (usually not available on cheap shared hosting).

Edit: There already exists a Drupal module, http:BL, that uses Project Honeypot's IP blacklist, that may save you some time setting this up (thanks to @vr3690 for pointing this out).


Remove link to user profile on content How do I remove the link to a user's profile on article content?  The  element is part of the article header and its classname is ".username".  I am new to Drupal but not to webdesign; I am just having trouble pinpointing which file to edit.

I tried:

function phptemplate_links($links, $attributes = array()) {
    unset($links['.username']);
    return theme_links($links, $attributes);
}

in my theme template.php file but it did not work.

Just to be clear: I am trying to remove the  element but not the text.  I still want the user's name to appear, just not the link to the profile page.  Also, I am looking for a PHP-based solution, not CSS, and trying to avoid adding any more modules.

Thanks!

You can't do this with CSS but you can do it without having to add another module.

If you want it exactly the same as default, but without the link, this would be it:

Just add this code to your template.php file in your theme (change YOURTHEME to be your theme name):

/**
 * Override or insert variables into the node template.
 */
function YOURTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  if ($node->type == 'article') {
    // This will replace the user name link with the same text but without the
    // link.

    // Set the name to a formatted name that is safe for printing and
    // that won't break tables by being too long. Keep an unshortened,
    // unsanitized version, in case other preprocess functions want to implement
    // their own shortening logic or add markup. If they do so, they must ensure
    // that $variables['name'] is safe for printing.
    $name = format_username($node);
    if (drupal_strlen($name) > 20) {
      $name = drupal_substr($name, 0, 15) . '...';
    }
    $variables['name'] = $name;
    // Display post information only on certain node types.
    if (variable_get('node_submitted_' . $node->type, TRUE)) {
      $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
    }
  }
}

if YOURTHEME_preprocess_node() already exists in your theme just add this to it:

  $node = $variables['node'];

  if ($node->type == 'article') {
    // This will replace the user name link with the same text but without the
    // link.

    // Set the name to a formatted name that is safe for printing and
    // that won't break tables by being too long. Keep an unshortened,
    // unsanitized version, in case other preprocess functions want to implement
    // their own shortening logic or add markup. If they do so, they must ensure
    // that $variables['name'] is safe for printing.
    $name = format_username($node);
    if (drupal_strlen($name) > 20) {
      $name = drupal_substr($name, 0, 15) . '...';
    }
    $variables['name'] = $name;
    // Display post information only on certain node types.
    if (variable_get('node_submitted_' . $node->type, TRUE)) {
      $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
    }
  }


Show facet filter even if there is no result Is there a way to show the facet filter, even if the Search API module returns no result?

Not really, the facets (both search api and solr) are made up from the results of the search, therefore if there are no results then it doesn't know what to populate the facets with.

Depending on your expected output you may be best creating a custom/views block to display some relevant content then re-write the urls to conform with the search query, acting like a search facet.


Convert link from node/nid to Pathauto url? Im using Pathauto to make my URLs nice and I may want to change the paths in the future. On some pages Im manually lining to other nodes.

The issue is that if I code the nice URL then the link will be broken if I change the Pathauto settings in the future. If I link to node/(the node id) then the link will always work, but its bad for SEO to not have keywords in the anchor text.

Is there a way to code in the NID so it always works but on the page show the nice URL?

I would, as Splat mentioned, check out the Global Redirect module, which will help out with google not seeing node/FOO and pretty/path pointing to identical content.  If, however you are wanting to make sure that when engines scan your page content and pretty/path shows up inside the HTML, you can either continue to hardcode the paths, or create a function that returns the aliased path based on the nid.

function make_my_path($nid) {
  $pretty_path=drupal_get_path_alias('node/' . $nid);
  return $pretty_path;
}

Then use that (or drupal_get_path_alias() directly) in your templates or preprocess functions, or just use l().  If it is passed 'node/FOO' as the path, it will return the aliased path if one is set. (Unless you explicitly tell it not to; see url().)

So, for example, print l('Hello World','node/23'); should return Hello World.


How do i run the equivalent of single configuration import from a hook? I have a hook_update_N that is changing a field.  It is deleting the field and recreating it with the same name but a different field, formatter, and widget.

The problem I'm having is that there is a view that is using my field and when I delete my field the view is being deleted and my site then throws an error.

I have the views.view.view_name.yml file saved in a directory.  Is there a function or set of  functions that will import the view from that file?

if (\Drupal::moduleHandler()->moduleExists('views') && !View::load('view_name')) {
    $config_path = DRUPAL_ROOT.'/configurationpathto/views_view_view_name.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('views.view.view_name')->setData($data)->save(TRUE);
  }


Keep left menu in every event node I created the event calendar using calendar view module. suppose If I click the particular event in calendar it will goes to particular event detail page but suddenly the left menu is disappear. How do I keep my left menu in all the event details pages?

Please assist me on this

You can use the Context module to set the block active on content types and url wildcards (ex. /event/*). There are also much more conditions available with Context.


hook_url_outbound_alter only for links in node body I'm building a site with drafts/revisions as a major component. For now I'm using hook_url_outbound_alter to check if "/draft" is at the end of the current URL, and if so to append "/draft" to all paths. The problem is that it's also altering the Menu URLs. Is there any way that I can explicitly target links in the node body using hook_url_outbound_alter?

For the googlers:

Module:

/**
 * Implements hook_url_outbound_alter().
 */
function draft_links_url_outbound_alter(&$path, &$options, $original_path) {
  // Internal URLs only
  if (!$options['external']) {
    // Check if current page is draft page
    if (preg_match('|/draft(/?)$|', current_path())) {
      $options['alias'] = $path;
    }
  }
}

/**
 * Implements hook_preprocess_page().
 */
function draft_links_preprocess_page(&$variables) {
  if (preg_match('|/draft/?$|', current_path())) {
    drupal_add_js(drupal_get_path('module', 'draft_links') .'/draft_links.js');
  }
}

JavaScript:

(function ($) {
    $(window).load(function() {
        $('.node__content a').each(function(){
            href = $(this).attr('href');
            // Internal URLs only.
            if (href.match(/^\/?[0-9a-zA-Z]*/) && !href.match(/^(https?:)?\/{2}/)) {
                $(this).attr('href', href+'/draft');
            };
        });
    });
})(jQuery);


Clearing the cache breaks the installation I just moved my Drupal 7 installation to another server. All the domain names are exactly the same. Everything seems to work fine until I click on clear caches. That results in a HTTP 500 error which I am unable to debug since the host does not display the errors.

I have sql dump for my db that is right before I hit the clear caches so whenever I fully restore the db in that state the site is back up again. That tells me that it is a database issues but I cannot figure out what it may be.

Any ideas?

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

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

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


Seat reservations for (recurring) events on given days I would like to let my users reserve seats (or a whole table) for events, and pay for the reservation via PayPal.

Different performances/shows would be advertised, users could choose which tables or seats they would like to reserve. A theater OR bar, restaurant, etc. would have "fix" seats and tables, so they would not change (or just rarely); events can be repetitive/recurring (e.g. concerts) - in some cases, locations can remain the same too, so only the date changes (e.g. a concert played in Example Bar 3 times a month); but one event can be played in other locations too.

I tried on Drupal.org first, but I got no answer; any help would be appreciated.

If there's no way to "bind" it to Ubercart, I'd solve it in another way (PayPal IPN), but I have to do it ASAP.

P.S.: I've already tried MERCI, Simple Reservation, Hotel Booking System for Ubercart and Reservation modules (the latter seemed OK from the picture), but unfortunately I couldn't figure out how to do something similar to  what I need - BUT THIS MEANS NOTHING, maybe I just overlooked some opportunities!!!

If you say I can solve it with one of these modules, please help! Even if you have a totally different suggestion! Thanks!

UPDATE:

In the meantime I found this very interesting article: Ubercart Event Registration
Let me quote from it:

  at the moment, the de facto Ubercart method for doing online event
  registration is with a module called UC Node Checkout. It's perfect
  for a one-and-done event registration site, but for a site that is
  hosting several events simultaneously and on an ongoing basis, it's
  awkward. This is due to the fact that it maps a content type to a
  product SKU - so for each event you'd need to create a new content
  type. Not really very good long-term, particularly when the site
  administrator is not overly familiar with Drupal or Ubercart.

  So, an alternative solution was devised using the Webforms module. The
  webform stores the registrant's organization's information - and also
  asks the registrant how many tickets to the event they want, which is
  the use case the client specified. The webform, after processing the
  form, adds the event 'tickets' to the cart. This is done with the
  'Webform advanced settings' field in the webform configuration, under
  'Additional Processing'.

Good to know. This means the article I found earlier doesn't describe what I need.

Another quote from uc_event_registration's readme:

  UC Node Checkout

  This is the approach that has been used alot for Drupal conferences
  and demo'd at drupalcons.  The huge problem here is twofold:  First,
  registrations are nodes.  That means we have to build views to create
  registration lists and that seems like unnecessary overhead when
  Webform is so much lighter weight.  Second, and most importantly, you
  need a new content type for EVERY event.  No thanks.  On sites that
  are doing dozens of events per year, this would mean, eventually, a
  huge amount of content types.  That's bad.

Here's another one related to Webforms: Drupal Webforms With Dynamic Select Boxes Tutorial
This seems very promising, maybe this could be the way one could solve what Andy suggested.
I'm still interested in suggestions for practical solutions - maybe this way!

I don't think you are going to find a solution that does 100% of what you need, I expect there will need to be custom development here.

Sounds like a custom content type (CCK) + ubercart + paypal (with ubercart) will be the most flexible solution. Perhaps read through the reservation module to see how it limits the available supply of tickets (i.e. sold out).

I would also suggest to remove the graphical part of the event registation, as this looks like it could be tricky, and instead focus on the core functionality of the app, i.e. the registration and payment workflow.

Every problem can be solved in drupal, but some of them are unique, and have their own solution.

If you need this solved ASAP, looks like you may need contractors, or some late nights ;) If you want to attract more quality answers, consider placing a bounty on this


How to customize Schema.org at node level? I am using the Schema.org module for schema tags, which allows me to customize schema tags at content type.

How can I customize schema tags at node level?

As I understand your question, you would like to be able to override the Schema.org types per each node separately.

This is not possible at least out of the box. You would have to write custom code to display a tab on each node form, store it somewhere and then load it when the node is about to be viewed.

This is because content types are generally used for storing the content of the same kind. For example: an article, a blog post, a static page, a webform and so on. This means that all nodes of certain type will need the same Schema.org declarations, and that's why it was implemented this way.

You are probably storing different kinds of nodes using one "generic" content type. This is not the most common use case. Unless you have strong reasons for doing this, I suggest migrating the content to separate content types. It will benefit you in case you want to use other similar modules as well, such as Metatag.

Hope I managed to explain it.


How can I quickly check Drupal 7 porting status of the contributed projects? How can I quickly check Drupal 7 porting status of the contributed projects ?

Answers should also guide readers if

a user is a developer and would like to help porting the most
frequently needed Drupal contributed modules, or
a user is a website owner
and would like to assess a possible upgrade from Drupal 6
to Drupal 7.

There is the Drupal 7 contributed project porting status website that uses data from the Upgrade Status module to show Drupal 7 porting status of the top 61 contributed projects.


How to hide the left tool bar of content type for non admin people? I want to hide the left tool bar of content type also revision message box, as shown in attachement, for non admin people.

I have gone through following https://www.drupal.org/node/1276698 but it's only for particular content.

Please suggest me how to hide from all content.

in yourwebsite.com/admin/people/permissions check that the following permission are unchecked under Node (click image to enlarge)

Edit: I did testing, and it's the Administer Content, make sure you uncheck it! Also administer content types as you don't want them to have that either.


How do I print out values from a select field with multiple values Currently I have a select field with multiple string values in a custom node. I'm trying to print them out without any html markup.

Currently I am declaring my variable like this:

$categories = $content['field_category'];

And I'm trying to print it like this:

foreach ($categories['und'] as $item) {
    echo $item['value'];
}

But nothing gets printed out. What am I doing wrong?

I ended up just making a custom loop like this and it works fine (Also added a custom if statement to change html output based on single or multiple categories in the field.

<?php
    $categoryCount = count($field_category);
    if ($categoryCount != 1):
?>

Categories:
<?php else: ?>

Category:
<?php
    endif;
    $i = 0;
    while ($i < $categoryCount) {
        if ($i != 0) {
            $html .= ', ';
        }
        $html .= $field_category[$i]['value'];
        $i++;
    }
    echo $html;
?>


Add class to a views field depending on image's being vertical or horizontal I have a view that outputs an image field. I would like to add a class to the .views-field div (for example, actually a views-row would also do the job) depending on whether the image is vertical (length > height) or horizontal (height > width).

I tried making a custom views-view-field-tpl.php for outputting the view's field, but I have no idea how to access the image or the image data.

EDIT: I've found that $field contains additional_fields, which in turns includes field_photo_width and field_photo_height. Those are arrays, though, and I have no idea how to get an actual value from them.

The answer could be approached from various angles. Simpler perhaps would be to target the template_preprocess_image itself, and add a div wrapper around it with the class, or just add the class on the img tag. I chose to do it via template_preprocess_field.

function THEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_IMAGE_NAME') {
    foreach($vars['items'] as $key => $item){
      if (_add_image_proportions_class($item)) {
        if ($item['#item']['width'] > $item['#item']['height']) {
          $vars['classes_array'][] = 'landscape';
        }
        else if ($item['#item']['width'] < $item['#item']['height']) {
          $vars['classes_array'][] = 'portrait';
        }
        else {
          $vars['classes_array'][] = 'square';
        }
      }
    }
  }
}

function _add_image_proportions_class($item) {
  return $item['#image_style'] == 'medium';
}

_add_image_proportions_class() is just a function you implement to test whether you want to add the class or not. In my example, I targeted the image style that is applied to the image. You could for instance create a specific image style that is used only for that view, and target it specifically. Or you could test the path you are on, etc.


Private files aren't blocking direct access to image files I'm currently very confused by how private files work:

I have a content type that has an image field and a file field.  Both
are set up to use private file access for their contents.
Node access on the content type is working correctly.
A user who does not have access to the node cannot get to the contents of the file field -- they get an access_denied page when they try to load the URL of the file.
However, they DO have access to the image file, via the image's url (/system/files/...): hitting the image URL in a browser brings it right up.

Are there any insights out there about why the image file is leaking through, and what I can do to stop it?   I've explored hook_file_download and hook_file_download_access, and have been putting watchdog statements throughout the image and files modules trying to track this down, but to no avail.  Thanks!

There are three implementations of hook_file_download(), in Drupal:

file_file_download()
image_file_download()
user_file_download()

The first two implementations always check the user has access to the entity to which the file is associated; the third one doesn't check that, but it only checks the directory containing the file is the one used for the user profile's pictures.

function user_file_download($uri) {
  if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
    $info = image_get_info($uri);
    return array('Content-Type' => $info['mime_type']);
  }
}

If there isn't any other module implementing hook_file_download(), I would expect the users to be able to access the files through http://example.com/system/files when the URI points to the same directory containing the images used for the user accounts.


Hide a list of blocks from Panelizer in-place editor (IPE) I have a list of blocks that shouldn't be added via panelizer IPE popup under manage content. Is there any way to remove them from the list?

One of the options is to extend the IPE controller to remove the unwanted blocks from display. Here are the code changes:

Route subscriber:

  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: 'event_subscriber' }

Update the IPE controller:

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\mymodule\Controller\MymoduleIPEPageController;
use Symfony\Component\Routing\RouteCollection;

/**
 * Subscriber to update IPE controller.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    /* \Symfony\Component\Routing\Route $route */
    if ($route = $collection->get('panels_ipe.block_content_types')) {
      $route->setDefault('_controller', MymoduleIPEPageController::class . '::getBlockContentTypes');
    }
  }

}

Controller:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\panels_ipe\Controller\PanelsIPEPageController;

/**
 * Extends IPE controller for site specific customization.
 */
class MymoduleIPEPageController extends PanelsIPEPageController {

 /**
   * {@inheritdoc}
   */
  public function getBlockContentTypesData($panels_storage_type, $panels_storage_id) {
    // Assemble our relevant data.
    $types = $this->entityTypeManager()
      ->getStorage('block_content_type')
      ->loadMultiple();
    $data = [];
    $blocks_blacklist = $this->getHiddenBlockList();
    /** @var \Drupal\block_content\BlockContentTypeInterface $definition */
    foreach ($types as $id => $definition) {
      if (in_array($id, $blocks_blacklist)) {
        continue;
      }
      $data[] = [
        'id' => $definition->id(),
        'revision' => $definition->shouldCreateNewRevision(),
        'label' => $definition->label(),
        'description' => $definition->getDescription(),
      ];
    }

    return $data;
  }

 /**
   * List of blocks not available to add via PIE.
   *
   * @return array
   *   An array of block IDs.
   */
  protected function getHiddenBlockList() {
    // Remove UUID and title fields from the list.
    return [
      'entity_field:node:uuid',
      'entity_field:node:title',
    ];
  }

}


Language Specific Site Is it possible to create a site that has multiple languages available to the user?

Preferably as similarly as possible to asp.net using .resx files (see here http://support.microsoft.com/kb/917414)

Is there any modules you have used that can provide this sort of functionality?

Thanks

The internationalization collection will allow you to offer full language support for the user in the form of variables and all sorts so it is more feature full than the solution you linked.


How to get the field settings values in filed constraint validator I have created custom type field with custom field settings, attached custom constraint successfully called its validator.

The question how to get the field settings values in the validate function, below code sample may explain

/**
 * Validates the CustomCheckConstraint.
*/
class CustomCheckConstraintValidator extends ConstraintValidator {
 protected $context;
 public function validate($data, Constraint $constraint) {
   //$data parameter holds the field value
   //how could I get the field settings here and validate the value based on
}
}

//attached constraint here
public static function    propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('integer')
  ->setLabel(t('type'))
  ->addConstraint('CustomCheck')
  ->setRequired(TRUE);
return $properties;

}

  Edit: After berdir answer

now the $data variable is an object holds the whole filedType object value and settings.

The problem is I couldn't get the field settings from getSettings() function returns

  Error: Call to protected method

The same error occurs when I tried to send field settings value from propertyDefinitions function

If they are field storage settings, then you could pass them along as arguments to the constraint.

If not, then add the constraint on the field type, not on the property. You can do that directly in the annotation, see \Drupal\file\Plugin\Field\FieldType\FileItem as an exampe. Then you get the whole field item in your validator and you can access the values and the definition/settings.


What is the correct procedure to restore database in Drupal 7? Reverting to a former database has been a tricky business with error messages and problems cropping up when I try to re-install modules that were installed or re-create content types, or re-do anything that was done since the back-up was made. In an attempt to avoid these problems I've been deleting the database using phpmyadmin before reinstalling the backup. Better, maybe(?) but now I've had other problems. Should I delete all the contributed modules also? Anyone direct me to the correct procedure for restoring database using phpmyadmin and ftp?

 -

Deleting the database and re-importing an earlier backup is the correct procedure. Module states (enabled/disabled/version), content types, and other settings are stored in the database, so if those changes are not part of the backup you have, they will be lost. That said, you should be able to re-create them without any problems.

Modules you've added since the backup will remain there as files, and you can re-enable them at will. There is no need to delete the files themselves.


What is admin_devel module in drupal? THis module is separate from the devel module that gives ability to dpm() variables etc. What is it?

The admin_devel module actually comes with the admin_menu module.

It adds a debug function for javascript debugging (along the lines of dpm for php), which you can include and use.

It also adds a button you can press to rebuild system links, which is on the admin menu settings page.

This rebuilds menu item links that are handled by the drupal core system module.


Retrieve a list of values from a lookup table using db_select I have a "jobs" table where each job can have multiple specialties. So I have a specialties table with a list of all available specialties and I have a lookup table that just has a job_number and a specialty_code in it so each job can be attached to multiple specialties. What I am trying to figure out is when I do a db_select, how can I have the job record print out once, but have a list of it's specialties print out also as part of that record? Here is what I have right now for my query:

$query = db_select("jobs", "j");
$query->fields('j');
$query->join('job_specialties', 'js', 'j.job_number = js.job_number');
$query->join('specialties', 's', 's.specialty_code = js.specialty_code');
$result = $query->distinct()->execute();

This gives me the correct records, but I want to display the list of specialties each job is attached to and that's where I'm not sure how to do that. Is there even a way using the database API to do that?

Essentially I would want to be able to display the records something like this. This is only one record, but you get the idea.

      Job Number
      Title
      Location
      Specialty

    12345
    Some Cool Job
    California
    SQL
HTML5
JavaScript

Add more fields to your query from the other tables that you have joined to:

$query->fields('js');
$query->fields('s');

Use hook_menu() to create your page if you want a custom one, then render it in PHP (I'm guessing at your result variable):

       ....

      <?php>$result['job_number']<?>
      .....


Views autocomplete exposed filter I am using autocomplete exposed filter in views for country/city with depth which is working fine but there are many identical city names.

When user types XYZ he sees 2 entries:
"XYZ"
"XYZ"
and has no clue which one belongs to which country.

I would like to show depth of the tree:
"ABC-XYZ"
"DEF-XYZ"
in autocomplete.

Hierarchical Term Reference Autocomplete module have the option to show the children with their parent.

  This module provides a new widget for a term reference field that
  displays the parents of a term matching the autocomplete as well as
  providing actual TIDs back to the form handlers.


Gift Certificates for Ubercart 3 & Drupal 7 We would like to add gift certificates to our Drupal 7 site running Ubercart 3.  There was a module (UC Gift Certificate) for Drupal 6, which has not been ported to 7.

There appears to be some talk about using UC Discount Coupons, which has been ported to 7, to achieve this functionality, but I am very skeptical (because it was not designed for this, and one immediate problem with it is that there does not seem to be a way to partially redeem a discount coupon.)

Has anyone successfully setup gift certificates on Drupal 7 with Ubercart 3?  If so, how?

There's an effort going on to port UC Gift Certificate to Drupal 7: link to issue


How to replace text about [node:url] within a Rules Action? I'm using the Rules module and have a Rule created that, upon saving of new content, an email is sent out containing the node title, as well as the URL of the node. Pretty straightforward. That said, I want to replace text in the URL before the message that's sent out. I'm using str_replace() but it isn't working.

Any suggestions?

Update:

The path currently look like this:
domain.com/cron.php/newsroom/press-release/[path-to-content]
However, I would need to replace out the "cron.php" from the URL, as that doesn't actually exist.
So the new URL should look like this:
domain.com/newsroom/press-release/[path-to-content]

Here's an export of the rule. I've removed any sensitive information:

{ "rules_press_release_notification_test" : {
    "LABEL" : "Press Release Notification Test",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "press_release" : "press_release" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "",
          "subject" : "[node:title]",
          "message" : "We've added a new press release to our Newsroom:\r\n\r\n[node:title]\r\n\r\n\u003C?php\r\n$releaseurl = \u0022[node:url]\u0022;\r\n$releaseurl = str_replace(\u0022newsroom\/\u0022, \u0022\u0022, $releaseurl);\r\n\r\necho $releaseurl;\r\n?\u003E\r\n\r\n[node:url]\r\n",
          "language" : [ "" ]
        }
      }
    ]
  }
}

I would transform your existing rule into 2 separated rules like so:

Create a Rules Component that only performs a Rules Action which is to send an eMail, similar to what you already have in your current Rules Action. But replace the node:title and the node:url by corresponding parameters to execute this Rules Component.
Replace the Rules Action of the rule you already have by the execution of your newly created Rules Component, in which you pass as parameter values:

the title of the node
the appropriate string that matches your domain.com/newsroom/press-release/[path-to-content]

With that, you don't need any PHP, so no str_replace() either.


using css in wysiwyg for custom page I want to allow my end users the ability to save custom css (sass would be better) along with the page content that they edit in a WYSIWYG. I know they can put styles inline but sometimes it's useful to be able to use css selectors instead. Is there a module that will allow this?

Module, no. At least none I know about. You can, however, add text field for css rules and output it inside style tag in your template. Would require some clever javascript to show it in realtime during edit, but should be possible without to much hacking.


Add custom permission to specific module "group" on permissions page Using a custom module, how can a permission be added to a core/contributed module "group" on the permissions page without hacking the core/contributed module?

Example:

As already said, it would not be a good idea to list a permission implemented by a module together the permissions implemented by another module; it would difficult for users to find the permissions implemented by, for example, custom_module.module, when it is listed together the ones implemented by user.module.

If you really need to change the order used to list the permissions (but then, is it really necessary), then I would suggest to change how the list of permissions is shown: instead of listing them basing on the module implementing it, you could list them basing on different criteria.
To do this, you would need to:

Implement hook_theme_registry_alter() to alter the theme function called when theme('user_admin_perm') is invoked.
Implement your theme function looking at the code of theme_user_admin_perm().

Is it worth doing it? It could be, depending on your customer.
Considering that the first official release for Drupal 7 has been released, and the code for Drupal 7 would change, it is probably not worth doing it. I would rather try to understand why the customer wants to change the order of the permissions listed in the administration page, and explain the reason why changing it is a bad idea; if the customer insists the code needs to be implemented for their own purposes, then I would make him understand that the code should be rewritten when the site passes to Drupal 7, and it is not worth spending time for such changes, when it is possible to use the same time to implement something that  it is really necessary.


How to add a new element in drupal 7 feed view I have created a simple feed with drupal 7 views and i want to add some more elements. currently it supports title, description, link, creator and pubdate. I DON'T want to use any other module.

Views doesn't provide that functionality, so if you want to configure this via the UI you need to install Views RSS (or another module that provides similar functionality); you don't have another option, apart from writing it yourself.

If you just want to hack something together you can use just manually append your extra elements to the output string, e.g.

function MYMODULE_preprocess_views_view_row_rss(&$vars) {
  // Add an image.
  $node = node_load($vars['row']->nid);
  if ($node) {
    $wrapper = entity_metadata_wrapper('node', $node);
    try {
      $vars['item_elements'] .= '<image>' . $wrapper->field_images[0]->file->url->value() . '</image>';
    }
    catch (\Exception $e) {
      // No need to recover, just means there's no image.
    }
  }
}

But it's not exactly ideal, better to use the purpose-built module.


Multiple "unused" Views displays I'm creating a heavily customised website in Drupal. I want to use Views as a data source for a page with several options, where each option corresponds to a different display in a View. The reason I want to use Views is that they are easily configurable through a UI, so they are easy to tweak/change later if the need arises.

Unfortunately though, it seems like I can't create a display of a view that doesn't have some form of side effect (ie, a page display will create a new page). Does anyone have any bright ideas?

http://drupal.org/project/embed_views  "This is a views display based on the default views display that does not have any additional features or "cruft" that you can use to create embed views for your site."


What are these mysterious core.xxx files doing in my site's root? I have never seen this before in my 2 years of building site's in Drupal. I just opened up one of my sites folder structure and found a large number of core.xxx files that I don't know what they do (and they are huge files, over 8GB worth). I found a couple of threads on this but no real answer. Any thoughts?

http://drupal.org/node/360867
http://drupal.org/node/115654

core.1688
core.2343
core.8485
core.3039
core.21233
core.23234

They are core dump files; they are files created when a program has terminated abnormally (crashed).


Disable the default username in the registration form I just installed and configured the logintoboggan module; I created extra fields and they are displayed just fine. I can't remember how to disable the drupal default username field on the registration form.

Can anyone assist me?

To disable a field in a form you must use hook_form_alter() like

MYMODULE_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'user_register_form' ) { // id of registration form
    $form['account']['name']['#access'] = FALSE;
  }
}

  #access

  Used by: All elements and forms

  Description: Whether the element is accessible or not; when FALSE, the
  element is not rendered and the user submitted value is not taken into
  consideration.

I would also like to mention for other people reading this that this can also be accomplished with the email_registration module


How to modify admin pages? Everytime I log in into the Drupal site there is a resume of the posts that I have written. I would like to modify it and show all the accumulated views of each user post.

I plan to use the Views UI to make the query but I am not sure which file modify to change the admin site.

Thanks.

If you are meaning the Drupal dashboard (admin/dashboard), there is a documentation page on how to customize the dashboard.

If you want to go further on the customization of the dashboard, there are modules like Homebox that can be useful.


Can the profile2 fields in registration be made obligatory? I have a profile2 profile type in which I want to expose some fields to the user when registering.

Is there a way to make a field obligatory?

Yes, as you do with any field make it as Required field.


how to migrate multiple taxonomy terms? I have a an array like this from json.
[terms] => Array
  (
    [0] => Array
      (
        [id] => 1
        [Name] => term 1
      )
    [1] => Array
      (
        [id] => 2
        [Name] => term 2
      )
    [2] => Array
      (
       [id] => 3
       [Name] => term 3
      )
    [3] => Array
      (
       [id] => 4
       [Name] => term 4
      )
  )

I want to migrate them as taxonomy terms.
name:
    - plugin: sub_process
      source: terms
      process:
        value: Name

but this only migrate the firs term. term 1.
how will I migrate all?

I have used the following code to fix my problem.
keywords:
    - plugin: sub_process
      source: keyword
      process:
        value: Name
    - plugin: entity_generate
      value_key: name
      bundle_key: vid
      bundle: keyword
      entity_type: taxonomy_term
      ignore_case: true

I put it in the nodes migration file.


How can I collapse the *sidebar first* region when the browser width is less than 900 pixels wide? How can I collapse the sidebar first region when the browser width is less than 900 pixels wide?
Within the theme's .info file the following is set:
settings[sidebar_first_width] = 4
How can I programatically change the above to 0 so that the sidebar first region does not take up any space within the page when the containing browser wide is less than 900 pixels wide?
One possible approach is to utilize the media query at the bottom of the themes associated .css file so that the sidebar first region is collapsed when less than 900 pixels based on the following link:
http://www.alistapart.com/articles/responsive-web-design/
but I am not sure if this is the best approach or what css to put in that would do this as an example from the above link:
@media screen and (max-device-width: 480px) {
  .column {
    float: none;
  }
}

John

A media query, just like the one you list, is indeed the proper way to do this.

Obviously you would first need to adjust the width from 480 to 900, but also, you may want to choose "max-width", instead of "max-device-width", as the former will work in a small browser window on a large screen as well. That's really up to you though.
You say that you want to collapse the sidebar, which means you may also want to "display: none;", instead of "float: none;".
Strictly speaking, the "screen and", is not necessary. If you want the rule to apply to all media types, such as print and handheld, you can just omit it.

Example 1, unfloat the sidebar, only on screen media:

@media screen and (max-width: 900px) {
  .sidebar-first {
    float: none;
  }
}

Example 2, hide the sidebar, all media:

@media (max-width: 900px) {
  .sidebar-first {
    display: none;
  }
}


Behavior to use .insertAfter() on load + after each ajax call? So I have a views page that outputs some elements in the grid. And I have a custom block on the page that needs to be inserted between those elements. On load it using .insertAfter() to randomly insert that block between view content element in the grid.
The problem is it works on load, but after each Ajax call on the pager i want to insert same block again in the grid, but that elements does not exist anymore. Not sure how to resolve this. Here is my code:
Drupal.behaviors.modalYoutubeVideo = {
  attach: function (context, settings) {
    function moveTileBetweenElements() {
      // Get random number between 1 and 23 and insert after that :nth-child.
      var rndInt = Math.floor(Math.random() * 23) + 1
      var wrapper = $('.view-products .view-content a:nth-child(' + rndInt + ')');
      var tile = $('.block-custom-order-tile');
      $(tile).insertAfter($(wrapper));
    }

    moveTileBetweenElements();

    $(document).once('weberAjaxViews').ajaxComplete(function (event, xhr, settings) {
      moveTileBetweenElements();
    });
  }
};

In Drupal ajaxComplete() is not required, as Drupal executes each iteration of Drupal.behaviors.*.attach() whenever an ajax call is complete. This function receives an argument, context, which on page load contains the entire contents of the document, and on AJAX calls contains the new part of the DOM being inserted into the page. This piece of the document can be parsed for the elements you are searching for. These two APIs are combined with jQuery.once() to ensure that code is not executed on any piece of the DOM more than once.
Example:
(function ($, Drupal) {

  /**
   * Does something.
   *
   * @param DOMelement context
   *   Contains a the full document on page load, or new parts of the
   *   DOM being inserted into the page after ajax calls.
   */
  function doSomething(context) {
    $(context).find(".some_dom_element").once("arbitrary-key").each(function () {
      // Do some stuff a single time on each instance of .some_dom_element that
      // appears on the page, both on page load and after any ajax loads.
    });
  }

  Drupal.behaviors.someArbitraryKey = {
    attach: function (context) {
      doSomething(context);
    }
  };
}(jQuery, Drupal));

Note that if you create your own ajax calls, you will need to pass any new parts of the DOM to Drupal.attachBehaviors():
$.ajax({
  url: '/path/to/ajax/callback',
  complete: function (data) {
    var newContent = $(data);
    // Pass the DOM element the jQuery object contains,
    // not the jQuery object:
    Drupal.attachBehaviors(newContent.eq(0));
    newContent.insertAfter($("#some_element"));
  }
});