Deciphering Views SQL I am trying to understand Views SQL, and am using a query of some Commerce data to increase my understanding.  Here is the start of a query:

SELECT commerce_order.order_id AS order_id,
commerce_customer_profile_field_data_commerce_customer_billing.profile_id
AS commerce_customer_profile_field_data_commerce_customer_billi, ...

The first part of this is straightforward enough, it is just picking up the order_id from the commerce_order table. The second item, though is puzzling: the first part, commerce_customer_profile is just a table, but then the second part field_data_commerce_custom_billing is another table, and the two are connected by an underscore.

In other words, the construct looks like this: SELECT table1_table2.field. I have searched at length for an explanation of this syntax, but cannot find anything

how table aliases are created in joins is pretty simple - to have unique alias views takes names of both tables and combines them.
you can check more simple example:

SELECT node.created AS node_created, node.nid AS nid, users_node.mail AS users_node_mail
FROM
{node} node
LEFT JOIN {users} users_node ON node.uid = users_node.uid

users table is joined to node table and unique name becomes "users_node". For files table it would files_node.

I think it is the only way to have unique aliases. Also it is easy to understand from which join data is coming


How do you render a set of checkboxes without using drupal_get_form()? I want to use a '#type' => 'checkboxes' render array to display some checkboxes on the page. They aren't going to be part of a form that ever gets submitted, as they are purely for browser-side user interaction. So I don't need any of the extra functionality provided by drupal_get_form(). I just need a few <input type="checkbox"> elements.

Unfortunately, Drupal appears to simply refuse to render '#type' => 'checkboxes' render arrays unless you pass the array through drupal_get_form(). When I try, absolutely nothing except

 Landmarks

gets rendered.

Is there any way to get Drupal to render an <input type="checkbox"> element without using drupal_get_form()?

...I just need a few <input type="checkbox"> elements.

Just render it as plain html, and if you absolutely want a render array, then create your own theme function for it.

$variables['content']['checkboxes'] = array(
    '#markup' => '
 Please select every sport that you play.
 Soccer: <input type="checkbox" name="sports" value="soccer">
 Football: <input type="checkbox" name="sports" value="football">
 Baseball: <input type="checkbox" name="sports" value="baseball">
 Basketball: <input type="checkbox" name="sports" value="basketball">

'
);


Diff module not tracking fields that existed before module was installed I have a Drupal project in the final stages of development. It has quite a lot of content types and a lot of fields. I have recently enabled revisions and added the diff module (7.x-3.2). It isn't tracking changes on my existing fields. When I choose 'compare' it shows 'No visible changes' and the current revision area only shows the new fields.

If I add a new field diff starts working on it. If I remove a field and re-add it diff starts working on the new version of the field. Any idea why this is happening? Are there any ways I can get diff working on all my fields without removing an re-adding all of them?

I tried editing and saving a field without making any changes to it, but this did not make diff tracking start working on it. I have looked in the DB and both a field being tracked and a field that isn't being tracked have a revision_id.

I have tested in a sandbox server and the diff module works as expected. Therefore it must be a conflict or a bug that is being triggered by my install.

Did you read the README for the module and go through the module configuration? See CONFIGURATION section of the readme.

2) Field revisioning settings

   Global settings per field type can be found here:

   http://www.example.com/admin/config/content/diff/fields

   "Show field title" toggles field title visibility on the comparison page.

   "Markdown callback" is the callback used to render the field when viewing the
   page in the "Marked down" page view.

   "Line counter" is an optional. This shows the approximate line number where
   the change occurred. This is an approximate counter only.

   Other fields add additional settings here.

This Diff Issue Queue item describes a similar "No visible changes." problem encountered by another user.

From the issue it sounds like the diff comparison view, which is typically "Standard comparision preview" settings == "Full content" needs to be configured to show the fields you want, or be the correct view_mode for the content.


form_alter and #element_validate inside .module file Inside my .module file, I have created a hook for alter register_form and add a password field with a custom field-validation:

function xenforo_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['password'] = array(
    '#type' => 'password_confirm',
    '#size' => 25,
    '#required' => true,
    '#element_validate' => array('check_password'),
    );
}
function check_password($element, &$form_state) {
  if ($element['#value'] != 'test') {
    form_error($element, t('Error: TEST'));
  }
}

I use #element_validate, and when I submit my form with a bad value $element['#value'] != 'test', I don't have an error and the registration is completed, why #element_validate don't work here please ?

Thanks.

EDIT:

I have find a solution:

  function xenforo_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $form['password'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#required' => true,
      '#attributes' => array('autocomplete' => 'off'),
      //'#element_validate' => array('check_password'),
      '#process' => array('processPasswordConfirm'),
    );
  }

  function processPasswordConfirm(&$element, \Drupal\Core\Form\FormStateInterface $form_state, &$complete_form) {
    $element['pass1'] =  array(
      '#type' => 'password',
      '#title' => t('Password'),
      '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
      '#required' => $element['#required'],
      '#attributes' => array('class' => array('password-field')),
    );
    $element['pass2'] =  array(
      '#type' => 'password',
      '#title' => t('Confirm password'),
      '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
      '#required' => $element['#required'],
      '#attributes' => array('class' => array('password-confirm')),
    );
    $element['#element_validate'] = array('check_password');
    $element['#tree'] = TRUE;

    return $element;
  }

  function check_password($element, &$form_state) {
    if ($element['#value'] != 'test') {
      //form_error($element, t('Error: TEST'));
    }
  }

But I have again the error with form_error() and password as displayed as two field without

As per @Clive comment, it's probably because password_confirm isn't a single element, it gets converted into two separate fields in a process callback, and doesn't apply the #element_validate to either of those because it can't reconcile which one you were referring to.


Menu on mobile phone - How to directly show second level of menu? Following configuration: Drupal 7, tb corpal theme, superfish menu

For mobile phones I get a menu as shown in the image. If I press the menu icon (1, red on image) I get first the "Main menu" level (2, red on image). After pressing "Main menu" the menu expands and one gets to the desired next level.

What do I have to change to get directly to the "second level" after "Main menu" level?

You can force the desired behavior via CSS or via Javascript (jQuery). For instance, check with jQuery if main menu is displayed on mobile. If so, then display its children, too. The CSS way would work if "main menu" is displayed by adding a class. If so, then you can, from CSS, display the second level when that class is present.


Webform CKEditor add color I would like to add the possibility to change color in CKEditor, mainly for Webforms. The instructions at https://www.drupal.org/project/colorbutton suggest to download manually the CKEditor colorbutton plugin and then add it to /libraries: would it instead be possibile to modify composer.libraries.json and install the plugin via Composer ?
Thanks a lot

Yes. As Clive says in his comment above, you can certainly use Composer to manage other code besides Drupal core and contrib modules.

If you are keeping your code in version control such as git, this also has the advantage of keeping third-party code out of your project's version control repository. Just commit your composer.json and composer.lock and you can rebuild all your project dependencies when you deploy.


Third party library added via composer.json but how can I load it in a module now? I have set up a module in my Drupal 8 project to handle some tasks I need doing using AWS.

I added the awssdk (for PHP) to my composer.json and ran the composer update command successfully. the AWS SDK is now sitting nicely in my /vendor directory under the folder aws.

Composer entry

'aws/aws-sdk-php': '^3.0'

I cannot seem to get this to load within my custom module. I have tried referencing the SDK as follows at the top of my one Controllers (After the use keyword but before the class keyword)

require_once (\Drupal::root() . '/vendor/autoload.php');

The result of trying this gives me a blank white page with this error in the apache log:

  PHP message: PHP Fatal error:  require_once(): Failed opening required '/home/dash/public_html/docroot/vendor/autoload.php' (include_path='.:/usr/share/php') in /home/dash/public_html/docroot/modules/custom/awsintegration/src/Controller/AwsiInstanceListController.php on line 9

Also tried using an absolute path as

require '/home/dash/public_html/vendor/autoload.php';

Result: Page loads no watchdog error but I get an apache php error as soon as I try reference one of the SDK classes:

  PHP message: PHP Fatal error:  Class 'Drupal\awsintegration\Controller\Aws\Sdk' not found in /home/dash/public_html/docroot/modules/custom/awsintegration/src/Controller/AwsiInstanceListController.php on line 27

UPDATE

After Clive's suggestion in comments I removed the require calls. I then added some simple code that used AWS to try create a credentials provider, I simply get errors in the apache log about missing Class as per:

  PHP Fatal error:  Class 'Drupal\awsintegration\Controller\Aws\S3\S3Client' not found in /home/dash/public_html/docroot/modules/custom/awsintegration/src/Controller/AwsiInstanceListController.php on line 21

My code is as follows:

namespace Drupal\awsintegration\Controller;

use Drupal\awsintegration\AwsInstances;
use Drupal\Core\Controller\ControllerBase;

use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

class AwsiInstanceListController extends ControllerBase {

    public function content() {

        $s3 = new Aws\S3\S3Client([
            'version'     => 'latest',
            'region'      => 'eu-west-2a',
            'credentials' => [
                'key'    => 'AbAbAbAbDcDcDc',
                'secret' => 'QwertyQweRty'
            ]
        ]);

        return array(
            '#type' => 'markup',
            '#markup' => $this->t('Hello, World!'),
        );
    }

}

You don't need to use require_once for autoload. It handles by the composer automatically. You should create a use statement in your php file.

As an example if you want to use a class s3 module of aws;

use Aws\S3\SomeClassName;


Pagination using XML Views Backend We're using the Views XML Backend module to display XML data in our Drupal site from an XML-based Web API.  (We actually have an integration tool wrapping the API, so we can transform data going into the Web API call.  For example, I'm transforming JSON data into XML.)

I'd like to be able to use pagination in Drupal so that the users see that they are viewing results 1-20 of 500 results (for example), then pass the pagination information along to the Web API.  The API (which was written in-house) can take the number of results to retrieve and either the page number or the first result to retrieve.

How can I achieve this?

I'm relatively new to Drupal, so please be patient.  Thanks!

Searching for pager in the issue queue of Views XML Backend shows that the plugin can output the info you want.

You should be able to add to the Header region of the view a Global Results Counter which shows text like "Viewing X of N to M records". All of this is done in the Views Administration UI for your View.

You could then call the page via curl or via views_embed_view using php programatically to pass and or set the page number and records per page as needed to get the results you want.


Admin pages including content edit are exremely slow I am using latest 7/16 version of core and complicated field collections with all kind of stuff. The problem is it takes up to 1 minute to load all kind of pages in admin section. All dev modules and update manager are disibled.

How could i know what exactly cause such a low performance? What can i do to improve it?

best answer: You need to profile the PHP code in order to see what is causing the slowdown. Also check firebug to see if anything is taking a long time to download. Go through all the slides  from my DIY Drupal 7 Performance presentation.

quick answer: You can try the first 4 patches listed in the Performance wiki as these are things that I identified on our setup as being slow.


How to disable required fields in form? I am building a multi-step form.  For one of the steps, I have some required fields.  When the user goes back, I'm skipping the validation, but it gets hung up on my required fields.  Is there a way to disable or ignore my required fields so my user can go back a step?

Yes, you can use

#limit_validation_errors

  Used by: button, image_button, submit

  Description: Provides an array of sections which are parts of
  $form_state['values'] which should be validated, implying that
  sections which are not listed should not be validated.

  This is normally used in multistep forms in the case of a "back" button, for
  example, where '#limit_validation_errors' => array() would mean not to
  validate anything as form values on the current page are to be
  discarded anyway.

  #limit_validation_errors does not have any effect if #submit is not set. More discussion is in the form_set_error() documentation.

  Values: array indicating sections of the $form_state['values'] which should be validated.


limiting shipping method if a specific product is selected I am trying to limit a number of shipping methods (from 5 to 3) if a specific product is chosen and inserted into cart. What is the best method to do it (I am using drupal commerce)

You are looking for how to add a condition to each of your shipping services for a specific product or two? Here's a quick animated gif that shows you the gist of what you want:

Locate your shipping services
Click "edit component" to control which service needs to be hidden based on a particular product
Add a condition called "Order contains a particular product"
You would need to check the "Negate" checkbox before saving to "show all the things unless this product is on the order." Which sounds like what you are attempting.

Good luck!


How to unset or hide a view header / footer when an exposed filter is being applied? I have a header in a view that should be visible only if there are no values in the exposed filters. So, once the user enters any value in any filter and sends the form, this header should not be visible. And the same for a footer in other views.

How to unset or hide a view header / footer when an exposed filter is being applied?

I found this solution that is really very simple:

use Drupal\views\ViewExecutable;
/**
 * Implements hook_views_pre_view().
 */
function MODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'nouvelles' && $display_id === 'block_1' && !empty($view->getExposedInput())) {
    $view->removeHandler($display_id, 'header', 'view');
    //or
   // $view->removeHandler($display_id, 'header', $view->getHandlers('header')['view']['id']);
  }
}

With the getExposedInput() function you can figures out what the exposed input for this view is, so wee need to check if the returned value is not empty.

The function removeHandler() is the key here, but wee need to know:

  public ViewExecutable::removeHandler($display_id, $type, $id)

$display_id -> is in the function params
$type -> can be header or footer
$id -> view (see the getHandlers() output)

You can found additional info with the getHandlers() function:

dpm($view->getHandlers('header'));

Array (
    [view] => Array
        (
            [id] => view
            [table] => views
            [field] => view
            [relationship] => none
            [group_type] => group
            [admin_label] =>
            [empty] => 1
            [view_to_insert] => en_vedette:block_1
            [inherit_arguments] =>
            [plugin_id] => view
        )

)


How to create custom node edit form protected function alterRoutes(RouteCollection $collection) {
    if($route = $collection->get('entity.node.edit_form')) {
      $route->setDefault('_entity_form', '\Drupal\alerts\Form\EditAdvisoryForm');
    }
  }

Causes a permission error. The logs say

Path: /node/1277957/edit?destination=/admin/content.
Drupal\Core\Http\Exception\CacheableAccessDeniedHttpException: in
Drupal\Core\Routing\AccessAwareRouter->checkAccess() (line 117 of
/app/web/core/lib/Drupal/Core/Routing/AccessAwareRouter.php).

It doesn't seem to prefill the form with the editable info. This is also not content type specific.
Please advise. Other posts close to this do not have an answer.

_entity_form doesn't accept a form class directly, only via a form handler. See https://www.drupal.org/docs/drupal-apis/routing-system/structure-of-routes

_entity_form: It is similar to _form, but it will provide an edit form for an entity. Entity form handlers are defined in the entity metadata
(annotation). For example, _entity_form: node.default will display the
default node form. "node" in node.default refers to the entity ID, and
"default" refers to the form handler key.


How can I exclude some entities in "drush entity:delete" command? I want to delete all content of custom entity type except some specific items, I found drush entity:delete CUSTOM_TYPE command to delete all contents but couldn't exclude some items from deletion in this command, does it have any option like --exclude ID1, ID2, ID3, ...?

Or is there any other way to do this?

ok mate you want other options and here is the answer:

if you look at

vendor/drush/drush/src/Drupal/Commands/core/EntityCommands.php

you can see the what the function does....

now you need to learn how to make a custom drush commands i assume you are using drush 9  so you can just run:

"drush  generate drush-command-file"

or read: https://www.axelerant.com/resources/team-blog/how-to-write-custom-drush-9-commands-for-drupal-8

this will create:
modules/custom/YOURMODULE/drush.services.yml
and
modules/custom/YOURMODULE/src/Commands/YOURMODULECommands.php

now have a look at the following working example ...

<?php
/**
 * Command delete some stuff
 *
 * @param $entity_type
 *   Argument for entity type.
 * @param $exclude
 *   Argument for exclude delete of ids.
 *
 * @param array $options
 *   An associative array of options whose values come from ...
 *
 * @option option-name
 *   Description
 *
 * @usage deletethings-commandName foo
 *   Usage description
 *
 * @command deletethings:commandName
 * @aliases delete-my-stuff
 */
 public function commandName($entity_type, $exclude,  $options = ['option-name' => 'default']) {
$this->logger()->success(dt($entity_type));
$this->logger()->success(dt($exclude));
$exclude_ids= [];
if ($exclude !== 'none') {
  $exclude_ids = explode(',', $exclude);
}

// now do the delete stuff
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
if (is_object($storage)) {
  $all = $storage->loadMultiple();
  if (count($all) !== 0) {
    foreach ($all as $entity) {
      $id = $entity->id();
      if (!in_array($id, $exclude_ids)) {
        // kill with fire.
        $entity->delete();
      }
    }
  }
}
}

With that you can run:

drush  delete-my-stuff ENTITY_TYPE 5,6,10

example: drush  delete-my-stuff node 5,6,10

this would then allow you to delete all items of your entity except for "5,6,10" - which are ids you want to keep

or drush  delete-my-stuff ENTITY_TYPE none (to delete all)

remember to run drush cr and drush cc (1) so drush will recognise the new command


About the Media Gallery Module Right now in each gallery, when a user clicks on the thumbnail, a larger version will show up in the middle of the screen. With it are arrows to navigate, a "1 of x" caption, a link to start a slideshow, and an x to close it. When I click the image, it takes me to the page of the media. What I want it to do is take me to the next image in the slideshow (like the arrows would have done). I tried looking at the configuration of the Media Gallery Module but there were only options on column and row layout. When I tried to check the settings in the gallery content type, all of the fields were locked and could not be edited. I tried Google for a solution, but not really anything turned up for this specific problem.

You should use Firebug and take a look at the function that gets called, when clicking on the "Next"-Button.(Something like onClick() )

Now take a look at the function, that gets called, when you click on the image.

Now just place the "Next"-Button function into the image. Delete the old one.

The functions are usually in a .js-File.

This is not so hard, i am a beginner and managed it with the shadowbox.


How can I require a custom module hosted elsewhere with its contrib dependencies being downloaded too? Hi I am trying to setup my new Drupal 8 site with composer, but I got few issues.
I tried to setup the site site by following the Guide from here and was able to setup the site successfully.
After that I tried to install a custom module which is hosted on Bitbucket and I am able to download the package using Composer, but the problem is the module has some other contributed module dependency but the dependency module is not downloaded along with the custom module.
I followed the guide from here and added composer.json file to my custom module along with the dependency, but after running composer require custom/custom_module only the custom module is installed but not the dependency.
My root directory composer.json file repositories section looks like this.
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
      "type": "package",
      "package": {
        "name": "custom/custom_module",
        "version": "master",
        "type": "drupal-custom-module",
        "source": {
          "type": "git",
          "url": "git@bitbucket.org:username/custom-module.git",
          "reference": "master"
        }
      }
    }
],

The composer.json file from the custom module is the following.
{
    "name": "custom/custom_module",
    "description": "This is a Custom Module with Different functionalities.",
    "type": "drupal-custom-module",
    "minimum-stability": "dev",
    "require": {
        "drupal/restui": "~1.16"
    }
}

I also chaged the line "drupal/restui": "~1.16" as "drupal/restui": "^1.16" but with no success.
I even tried running composer update in the custom module directory as I was not sure whether dependencies will be installed along with custom module.
After running composer update in the custom module directory I got this error.

Your requirements could not be resolved to an installable set of packages.

Problem 1

The requested package drupal/restui could not be found in any version, there may be a typo in the package name.

Potential causes:

A typo in the package name
The package is not available in a stable-enough version according to your minimum-stability setting
see https://getcomposer.org/doc/04-schema.md#minimum-stability for more details.
It's a private package and you forgot to add a custom repository to find it

Read https://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

On Drupal.org I can find the module with that version here.
EDIT 1
I have added below to the composer.json file from the custom module but still same issue.
"repositories": [
  {
    "type": "composer",
    "url": "https://packages.drupal.org/8"
  }
],

EDIT 2 : Seems recursive package download is not possible with composer. Refer Why can't Composer load repositories recursively? and Add support for installing libraries via asset-packagist

Just for this question I created a dummy module at https://github.com/leymannx/custom_module which has a composer.json similar to yours with drupal/restui in the "require" section and "type": "drupal-custom-module".
And then in a D8 project's composer.json I adjusted the "repositories" section to look like this:
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
        "type": "github",
        "url":  "https://github.com/leymannx/custom_module"
    }
],

In the "installer-paths" section I added:
 "web/modules/custom/{$name}": ["type:drupal-custom-module"]

I then simply ran composer require leymannx/custom_module and it downloaded the module and drupal/restui both to the right places. Of course you now can ignore the custom module with your repo's .gitignore file.
I guess the trick was to have the "repositories" section adjusted like above. And I guess you also can use proper versioning for the custom module when you tagged some releases. Right now it just downloads dev-main.


Prevent Serialization or Unserialize via ODBC Drupal, while a great CMS/Website/Intranet platform, is poor at providing users ability to edit datasets as one might in a spreadsheet or openly editable database table. We get forced into form update, form update, form update etc. Point, scroll and click time wasted. I've yet to find the module or View to edit data like a spreadsheet but still maintain database structure.

In Drupal 6, via ODBC we could easily edit node title, node body, comments or other text fields through programs like OpenOffice Base, LibreOffice Base, Microsoft Excel/Access or HeidiSQL. With Drupal 7 the text/data is serialized (BLOBs) and therefore what was easy changes to many text fields at once is now not possible, easily anyway.

What Drupal View setting, module or api/hook allows datasets to be edited, or
How to unserialize BLOB data for viewing in external programs
Stop Drupal 7 from serializing in the first place? or,
Other

In normal circumstances you shouldn't edit raw database tables to make changes; there's an extensive API in place which you should use instead (whether that be via the UI, through custom code, interacting via REST, whatever).

Updating tables manually means you deny module hooks the chance to run, potentially leaving your site in an inconsistent state. Not to mention the fact that caches won't be invalidated, leaving your front-end inconsistent for a time.

To directly answer your questions:

A) I'm not sure what you mean by 'datasets' here. If you mean, how do you update a bunch of values for a bunch of entities (e.g. nodes) in one go, then the Views Bulk Operations module should be useful.

B) The data you're referring to is serialised using PHP's serialize() function. You can decode it with unserialize(). I can't comment on how you'd do that in, for example, Excel. Perhaps you could write VBA functions to mirror serialize()/unserialize() and apply them to the incoming/outgoing data?

C) You can't stop Drupal from serialising that data, it's baked right in. Well, you could theoretically do it, but it would be an awful lot of work. You'd probably also find the need to change a lot of contrib modules who rely on the known schemas.

D) I haven't used it personally, but I've heard good things about the Data module. Might be worth checking in to. Feeds might be of interest too.

To sum up: Providing users the ability to make changes to the site by directly manipulating database tables, outside of the API, isn't really one of Drupal's goals (or not one that I've seen mentioned before). If anything, I'd imagine they want to discourage that for the reasons I've mentioned above.


How can i authenticate a user without using Drupal functions? I need to authenticate a D7 user from a php page from outside a Drupal session. In D6 i could have used the md5() function, now i've seen that this is not possible due to changes to D7 authentication. How can i do it without using Drupal functions?

If you look in the includes/password.inc file in your drupal 7 installation, you can see how drupal 7 hashes up the password and then code that up separately or just include that file in your other script.  A quick tutorial on this can also be found here.


Converting db_query from Drupal 6 to Drupal 7: Invalid parameter number: number of bound variables does not match number of tokens I have a custom localisation function in a Drupal 6 module that I would like to convert to Drupal 7 but I have hit a wall with the db_query function. I have the following code (in d6 and d7):

// Drupal 6
db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = '%s' LIMIT 1), '%s', 'sv')", $name['eng'], $name['swe']);

// Drupal 7 (not working)
db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = :source_eng LIMIT 1), ':source_swe', 'sv')", array(':source_eng' => $name['eng'], ':source_swe' => $name['swe']));

I get the following error message when I try to use the d7 version:

  PDOException: SQLSTATE[HY093]: Invalid parameter number: number of
  bound variables does not match number of tokens

D7 API for db_query

Could somebody help me out figuring why the db_query isn't working?

You've quoted one of the parameters when you shouldn't have.

PDO interprets this:

':source_swe'

as a string, and it (correctly) doesn't try to change it.

What you're looking for is simply

:source_swe

So that parameter replacement can occur. As in,

db_query("REPLACE INTO {locales_target} (lid, translation, language) VALUES ((SELECT lid FROM {locales_source} WHERE source = :source_eng LIMIT 1), :source_swe, 'sv')", array(':source_eng' => $name['eng'], ':source_swe' => $name['swe']));


What's the difference between globals $base_root and $base_url Can't seem to find the difference between these.  D6 is what I need to know, but would love to know how those looks into 7 and even 8.

$base_root is:

  The root URL of the host, excluding the path.

e.g. http://localhost

$base_url is:

  The base URL of the drupal installation.

again, e.g. http://localhost

The only situation I can think of where these would be different is if your Drupal installation is in a sub-folder of the web root. In that case $base_url would also contain the sub-folder in the path, e.g. http://localhost/drupal

The descriptions in the documentation are exactly the same for both across versions 6, 7 and 8.


What content type select in View related to email? I want to create a View. In my site there are lots of users are there, there is an email system i.e. send mail in these events : At the time of registration, At the time of password reset, etc..

I want to create a View of type Email or related to Email so I want to show the following things inside View related email :

  Mail ID

  Subject

  Body

May anybody please help me to find out that what content type am I select for email while creating View. Please help. Thanks

I think you want to use the content of users table so create a view as below

Add the field user:E-mail field to list users E-mail ID's
You could make use of Views Send Module
Check this Link this might help you understand Views Send Module


Is there an opposite / reverse of entity_uri()? I understand that entity_uri() generates a uri for a profied entity

http://api.drupal.org/api/drupal/includes--common.inc/function/entity_uri

However, is it possible to go the other way? is there a function in drupal to pass a system uri and see if it's an entity? and then return the entity object?

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

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

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

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


\Drupal::currentUser() returns information about the anonymous user, even though I am logged in I'am trying to check whether a user is logged-in or not; with \Drupal::currentUser()->id() I am getting the user ID for the anonymous user (i.e. 0), even though I'm logged in.

How can I resolve this?

I'm just calling this function in the .module file, and it is not run from cron. I am using the following code.

use Drupal\Core\Session\UserSession;
use Drupal\Core\Session\AccountInterface;

$user = \Drupal::currentUser();
if ($user->isAuthenticated()) {
  echo 'logged-in';
}
else {
  echo 'guest';
}

To determine if a user is logged-in (authenticated), it would be best to use:

\Drupal::currentUser()->isAuthenticated()


Exclude node from search API results based on values in existing fields My content node includes a verified checkbox that's marked by a human reviewer who then also enters a date. The node is verified only when the box is checked and the date is entered. A content node may be published before it is verified.

How can I keep an unverified content node from appearing in search API results?

One solution is to add a search API exclude entity field to the content node and to set the value of the exclude field in a presave hook based on the verified checkbox and date. This isn't difficult, but it seems there should be a more straightforward way of accomplishing what's needed.

I've looked at modules, but those I've seen don't seem to fit the need. I imagine I'm just missing something obvious, but what is it?

I don't think it's relevant, but I'll mention that I'm using Solr search.

Given no alternative answers, I solved this problem by

installing the Search API Exclude Entity module
adding a field of type Search API Exclude Entity named search_exclude to the content node
adding the following to my custom rsc module

function rsc_node_presave(EntityInterface $node) {
  switch ($node->getType()) {
    case 'content':
      $node->field_search_exclude->value = <conditions to exclude node>;
      break;
  }
}

going to /admin/config/search/search-api/index/default_solr_index/processors
checking the Search API Exclude Entity box
selecting the Search API Exclude Entity tab at the bottom of the page
checking the field_search_exclude (content) box
reindexing the content

Seems to be working well. When unverified nodes are saved, the search_exclude field is set and that keeps the nodes out of the search results.


How to specify the order of Javascript calls? I have a call to drupal_add_js() in hook_block_view_alter() and another one in template_preprocess_page().

I need that the order in which the Javascript is printed in the screen of the browser is just as written. What is the preference in which the content is loaded in the page? Can it be controlled?

If you want to enforce the order of your scripts, declare them as libraries via hook_library() and list one as dependency for the other.


Site crashes after running 'composer install' to update modules My website is running Drupal 8.8.x When upgrading to Drupal 8.9.x and then running 'composer install' on production everything seems to install as expected but the site then goes offline with a 500 error and running any Drush command outputs the below text. I suspect it may be an issue with something in my composer.json file but I have no idea what it could be. I have dozens of other similar Drupal sites and none have this issue.
I've spent a couple of days trying to figure out the cause or a fix without look. Any suggestions?
PHP Warning:  require(/home/WEBSITE/public_html/vendor/composer/../../load.environment.php): failed to open stream: No such file or directory in /home/WEBSITE/public_html/vendor/composer/autoload_real.php on line 73

PHP Warning:  require(/home/WEBSITE/public_html/vendor/composer/../../load.environment.php): failed to open stream: No such file or directory in /home/WEBSITE/public_html/vendor/composer/autoload_real.php on line 73

 PHP Fatal error:  require(): Failed opening required '/home/WEBSITE/public_html/vendor/composer/../../load.environment.php' (include_path='/home/WEBSITE/public_html/vendor/pear/pear_exception:/home/WEBSITE/public_html/vendor/pear/console_getopt:/home/WEBSITE/public_html/vendor/pear/pear-core-minimal/src:/home/ntgitc                                om/public_html/vendor/pear/archive_tar:.:/opt/alt/php73/usr/share/pear') in /home/WEBSITE/public_html/vendor/composer/autoload_real.php on line 73

Your composer.json probably has this in it (many do):
"autoload": {
  "files": [
    "load.environment.php"
  ]
}

But you don't have load.environment.php present in the file system.
Either remove the line from composer.json if you don't need to use dotenv, or add the file which typically contains something like this:
<?php
/**
 * This file is included very early. See autoload.files in composer.json and
 * https://getcomposer.org/doc/04-schema.md#files
 */
use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
/**
 * Load any .env file. See /.env.example.
 */
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->safeLoad();


How to access the fields in the comment reply page? I'm using Drupal 7.

I show the form of comments in a page different from that of the nodes.

In this page, having for url mysite/comment/reply/..., I would like to modify the fields of the node which appear before the form of comments.

For example, the page looks like :

        Add a comment
-
        Title of the node
        Field 1 of the node (display)
        Field 2 of the node (hide)
-
        Comment form

I tried to create a specific page template : page--comment--reply, but I have no access to fields and cannot thus change their appearance.

Do you know how can it be done?

I think comment.tpl.php is what you need

however you can also alter the display of comments in the display option on the content type.

look in "admin/structure/types/manage/CONTENT_TYPE_MACHINE_NAME/comment/display"


URL Pattern in node entity reference I have a content type A, which contains an entity reference field. That field references a content type B.
I have create automatic URL paths for both content types.

When I create a new node of type A, in the same page I can add a node of type B since it's referenced. The issue is URL alias for node type B won't create. If I want that pattern for B to work I have to create that node independently (not 'inside' of node type A) or create it 'inside' A and after edit it. It will work in that case, but I'd like not to have to edit every node of type B, and just create them once and have its URL working.

I have found similar threads but nothing exactly like this. I'd appreciate any help.

Thanks!

I suppose you use D7?
Do you use the Inline Entity Form module to add a new referenced node of type B? (https://www.drupal.org/project/inline_entity_form). I just tested the following workflow with the Inline Entity Form and Pathauto, and path aliases were successfully created for both nodes (type A and referenced type B):

enable inline_entity_form and pathauto modules
create the Entity Reference field on content type A that references content type B; select 'Inline entity form - Single value' as a widget type
create patterns for both content types in admin/config/search/path/patterns (ex: for A - 'news/[node:title]'; for B - 'people/[node:title]')
create a new node of type A, within it create a node of type B
both nodes should have the correct aliases


Redirect to custom URL while logging in user through Webform I am hoping to register/login a user based on the values entered in Webform and then redirect to a URL based on a user type.

The problem is that everything works but the redirection. Seems like this line is the culprit:-
$form['#submit'][] = 'my_submit_handler_for_registration';

Any help?

Thanks

Here is what I have done:-

function MYMODULE_webform_submission_insert($node, $submission) {

  $submitted_data = $submission->data;
    $full_name = $submitted_data[1][0];
    $user_name = $submitted_data[2][0];
    $password = $submitted_data[7][0];
    $fmno = $submitted_data[3][0];
    $role = $submitted_data[4][0];
    $where = $submitted_data[5][0];
    $when = $submitted_data[6][0];

    // For Redirection
    variable_set("redirect_to", $role);

    // Need to populate following data for registering the user.
    if ( empty($user_name)) {
      echo "
No Username Found.
";

      exit();
    }
    $user_data = array();
    $user_data['init'] = $user_name;
    $user_data['mail'] = $user_name;
    $user_data['name'] = $user_name;

    $user_data['field_full_name']['und'][0]['value'] = $full_name;
    $user_data['field_fmno']['und'][0]['value'] = $fmno;
    $user_data['field_interviewee_role']['und'][0]['value'] = $role;
    $user_data['field_where']['und'][0]['value'] = $where;
    $user_data['field_when']['und'][0]['value'] = $when;
    $user_data['pass'] = $password;
    $user_data['status'] = 1;

    $user_data['roles'] = array(); // You can specify any roles which you need

    $tomorrow_date = time() + (60 * 60 * 24);
    $date_after_two_days = time() + (60 * 60 * 48);

    // Check if any previous user with the same email exists?
    $previous_user = user_load_by_mail($user_name);

    if(!empty($previous_user)) {
      echo "
Another user exists with the same email. Please login or enter another user.
";
    }
    else {

      //It'll add a new user here.
      $user = user_save('', $user_data);

      /*
      $arr = array ('name'=>$user_name,'pass'=>$password);
      // Finalize user login (modify $_SESSION, set login time in db)
      user_login_finalize($arr); */

      $form_state = array();
      $form_state['uid'] = $user->uid;
      //$form_state['redirect'] = 'registration';
      user_login_submit(array(), $form_state);
      //$new_user = user_load_by_mail($user_name);

    }

    return theme('register', array('output' => $submission));

}

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webform_client_form_31') {
     $form['#submit'][] = 'my_submit_handler_for_registration';
  }
}

function my_submit_handler_for_registration(&$form, &$form_state) {

  $redirecting_to = variable_get("redirect_to");
  if($redirecting_to == "McKinsey Solutions") {
    $redirecting_to = "frontmso";
  }
  else {
    $redirecting_to = "";
  }
  $form_state['redirect'] =  $redirecting_to;
}

Another current question here inspired me for this short solution within your hook_webform_submission_insert():

 // Create user account.
 $my_user = user_save(NULL, $user_data);
 // Whether the user account was created successfully.
 if (!empty($my_user->uid)) {
   global $user;
   $user = $my_user;
   user_login_finalize($user_data);
   // Do the redirect here.
   drupal_goto('target_uri');
 }
 else {
   // User account could not be created. So do some error handling.
 }


Configure view to display a list of nodes with identical term id/name How could I configure the view to display a list of nodes that with the identical term id/name?

You can add a filter to display nodes that has term with name/id = X. This is done through the interface by clicking add filter and selecting either term name or term id.


Programatically assigning multiple user role ? I am trying to assign multiple role while creating a user programatically. I am successfully creating a user and assigning one role using below code

$user = \Drupal\user\Entity\User::create();
// Mandatory.
$user->setPassword('111');
$user->enforceIsNew();
$user->setEmail('abcd@gmail.com');
$user->setUsername('abcd');
$user->addRole('lecturer');
$user->save();

I want to assign two roles during this code execution and tried the below code but it did not work

$user->addRole(['lecturer','program coodinator']);

How do I assign this?

If you look at User::addRole it says

  User::addRole($rid)

  string $rid: The role ID to add.

Therefore, this cannot be an array. Thus, you must do this separate

$user->addRole('lecturer');
$user->addRole('program coodinator');
$user->save();

If you look at class User, there is no such thing as "addRoles" or any method that allows multiple way of doing it with an array.


Use Rules to give users a discount on their order after a few days (Commerce) I want to create a series of rules that will discount user's carts in specific time intervals after their cart has been created. I can think of two way to do this. I realize that I will most likely need the rules_scheduler module as well. This site is built using Commerce.

My first idea was to create discount codes for each discount level (5OFF for 5% off, 10OFF for 10% off, etc.) that will only be enabled for that specific user during each respective timeframe. This would require these codes to be both enabled and disabled in order to transition properly. However, from what I currently understand, these discount codes are global. So this method would not work.
My second idea will still read the order created date. Two days after that, the rule will multiply their oder by .95. After five days that amount will change to .9. continuing as necessary.

Essentially:
1) User creates an account and adds products to his cart.
2) After 2 days pass, they will be given 5% off of this order.
3) After 5 days pass, they will be given 10% off of this order.
and so on.

My question is has anybody has tackled this issue before? I would like to receive some insight or advice on how to best accomplish this type of functionality . So far, I have been unsuccessful in figuring out how to make an order creation be the event to react on for this/these rules. I also have not used rules scheduler yet, but I do not foresee that being too difficult to configure. Thanks!

I haven't done anything date related, but I have made some rules to apply discount based on various specifications. You should checkout the Commerce Discount module, it integrates in with rules.

So you would just need to create a rule to add a scheduler item for each of the time periods that you are interested in when the user adds an item to their cart, or whatever event you need.

Then when each scheduled item goes off, you would have a rule to apply a discount to their order, and do whatever else you want (maybe notify them by email).

Then a final rule that would delete any additional scheduled items once the order is marked at complete.

You should be able to accomplish all this with a few rules.


Changing decimal field scale and precision using database I'm using a custom decimal field in a custom product type in Drupal commerce. It has a precision of 10 and a scale of 2 (2 digits to the right of the decimal place).

I have a client with a large number of products that use this field, but their specification has now changed to require a decimal to 3dp.

By default Drupal "locks" the field to avoid data loss:

  Because the field already has data, some settings can no longer be
  changed.

I took to editing the database, and it seems to have worked fine. I did three things:

Changed the structure type of field_THIS_FIELD_value field in the drupal_field_data_THIS_FIELD table from decimal(10,2) to decimal(11,3)
Repeated the same for the field revision table
I downloaded the BLOB from table 'drupal_field_config' for field_THIS_FIELD and altered {s:9:"precision";s:2:"10";s:5:"scale";s:1:"2" to {s:9:"precision";s:2:"11";s:5:"scale";s:1:"3"

I cleared cache and existing data now has an extra 0 after the decimal place, and when I alter the data it stores it to 3 decimal places.

So it seems to work fine. But am I missing anything? Is there anywhere else where field data is changed that I might need to change?

Does the system integrity remain intact? I think I've done what's necessary but don't want to inadvertently break something else or cause any weakness in the system.

you could create a new field with the settings you need and import the data from the old field.
see: https://www.drupal.org/node/1491590#comment-9682599


Remove an item from "menu local task" I need to remove "Create new account" from the tabs on /user page.

I was suggested to use hook_menu, but:

It seems that hook_menu can only add, not remove items.
hook_menu does not work for me as I described in Why my hook_menu does not work?

Further: I've found that there is also hook_menu_alter hook. But it does not work for me also. I created the following function for testing:

function cleanetica_advanced_menu_alter(&$items) {
    $items['user'] = array(
       'title' => 'blogs',
       'description' => 'Listing of blogs.',
       #'page callback' => 'blog_page',
       'access arguments' => array('access content'),
       'type' => MENU_DEFAULT_LOCAL_TASK
     );
    //$items = array();
}

I see no changes in /user page after I have added this function into the module,

If you need the registration feature and you need to just remove the link from the default tab, then use menu_alter hook.

function modulename_menu_alter(&$item) {
// Hide the "Create new account" tab
$item['user/register']['type'] = MENU_CALLBACK;
}


How to programmatically set the user timezone I am programmatically creating a user and wanted to assign a timezone for the user

I am able to successfully create a user by the following code

$user = \Drupal\user\Entity\User::create();
$user->setPassword('1233455');
$user->enforceIsNew();
$user->setEmail($item['Home - Email']);
$user->setUsername($item['First Name']);

How do I assign the timezone?

You can use Set method on user Entity like the following:

$user = \Drupal\user\Entity\User::create();
$user->setPassword('1233455');
$user->enforceIsNew();
$user->setEmail($item['Home - Email']);
$user->setUsername($item['First Name']);
//- Set Time Zone to London
$user->set('timezone','Europe/London');
$user->save();

NOTE : You can set other fields with set method, for example if you can activate the user with $user->set('status',1); or give him administrator role with $user->set('roles',['administrator']); .


Entity Query Condition for the referenced entity's type According to the documentation for the condition() function, you can append columns to a field name, but I haven't found a way to make a condition on the referenced entity's type.

// Something like this?
$query->andConditionGroup()->condition($referenceFieldName, $someId)
     ->condition("$fieldName.entity:type", ['character', 'movie'], 'IN')

Let's say with the above I am querying for articles that have a reference to the ID in $someId and that reference is to a content type of either character or movie. Is something like this possible with entityQuery?

Background: I'm using the Dynamic Entity Reference module, which allows me to make a reference field that can point to either a taxonomy term or a piece of content. I want to query for references to content in that field, but am concerned that there could be an ID overlap. That is, a taxonomy term and character for example that both have the ID 123. If I am searching for the ID 123, I would only want articles that have references to the characters or movies with the ID 123, not any taxonomy terms with the ID 123.

since the reference field is using DER, you can use $fieldName.target_type for finding the referenced entity's type.


Render node fields and labels in node template I'm familiar with the Drupal 8 theming API, including hook_preprocess_HOOK(), as well as all of the theme template suggestions available when Twig debug is enabled.

However, what I would love to be able to do is to control all of the individual fields and optional labels for a node, inside the node--tool--full.html.twig template. (My content type machine name is tool.)

I also know that I can simply leave out the call to {{ content }} in the Twig template and call fields individually like this.

{{content.body}}
{{content.field_application_purpose}}
{{content.field_application_uses}}

And of course, if I want complete control over a field, including rendered markup (for example, field_application_uses), I can create another template (field--node--field-application-uses--tool.html.twig) and then wrap the field and its label in any markup I'd like.

So far so good.

But how can I control all of this from within the node template, in this case node--tool--full.html.twig?

My node is translatable, including the field label.

What I'd like to do, instead of having to create field templates for every field on the node/content type/bundle, is something like this.

  ...

{{ node.field-application_purpose.label}}

{{ node.field-application_purpose.value }}

{{ node.field_application_uses.label}}

{{ node.field_application_uses.value }}

  ...

The above template snippet works for the value, but not for the label, and I spent hours trying to work out where to get the label.

In field--node--field-application-uses--tool.html.twig, the label is available as a variable, but how can I retrieve this at the node template level?

I'd ideally like to keep all of the fields and their markup in a single template, the node template, as opposed to having to create a template for each field.

The label is in the field definition, you have to add fieldDefinition before label:

{{ node.field_myfield.fieldDefinition.label }}

To explain this, node is the node object. Content is the render array of the fields, that are build as configured in the view mode. In node you find the raw values and definitions of all fields of the node. In content you only find those fields that are in included in the view mode and they are already formatted as configured in the view mode. You also find each of the fields as object in content, but you cannot be sure, that the field is there, because if someone later removes the field from the view mode, your code will get a null value.


How to theme a custom block I've created a block using hook_block_info and hook_block_theme and the like. But how can I theme it?

I have it working to return an array with the keys 'subject' and 'content'. But I created the markup directly in the hook_block_view() hook and that's not what I want.

In the docs it's said that content should preferably returned as renderable array and not as markup. But what is this renderable array? They say it should be data instead of markup, but all I see in the examples is that it's just used as a wrapper for markup, so nothing gained there.

I want to be able to have a block--MYMODULE--DELTA.tpl.php in my theme but how do I call it and how can I pass the data to the block?

The way I do this is as follows...

function MYMODULE_block_info() {

  $blocks = [];

  $blocks['my_block_machine_name'] = [
    'info'  => t('My Block Title'),
    // @see https://api.drupal.org/api/drupal/includes!common.inc/group/block_caching/7.x
    // You can use different caching options.
    'cache' => DRUPAL_NO_CACHE,
  ];

  return $blocks;
}

function MYMODULE_block_view($delta = '') {

  $block = [];

  switch ($delta) {
    case 'my_block_machine_name':
      // Good idea to check user permissions here.
      if (user_access('access content')) {
        $block['subject'] = t('My Block Title');
        $block['content'] = MY_BLOCK_CONTENT_CALLBACK();
      }
      break;
  }

  return $block;
}

function MY_BLOCK_CONTENT_CALLBACK()() {

  $items = [];

  // This is the simplest kind of renderable array.
  $items['VAR_ONE'] = ['#markup' => 'VAR_ONE_OUTPUT'];

  // Here I added a prefix and a suffix.
  $items['VAR_TWO'] = [
    '#prefix' => '
',
    '#markup' => 'VAR_TWO_OUTPUT',
    '#suffix' => '
',
  ];

  // This is where the $items get sent to your my-template.tpl.php template
  // that got registered below.
  return theme('my_cool_block', ['items' => $items]);
}

function MYMODULE_theme() {

  // Here you are registering your template for the block output above.
  $module_path = drupal_get_path('module', 'MYMODULE');

  // Drupal will now look up your modules /theme folder first to grab the
  // template.
  $base = [
    'path' => "$module_path/theme",
  ];

  return [
    'my_cool_block' => $base + [
        // Leave off .tpl.php.
        'template'  => 'my-template',
        // Define variables you want to pass to the template.
        // Here I just pass items, but you can pass any other data as well.
        'variables' => [
          'items' => NULL,
        ],
      ],
  ];
}

And then in a subfolder in your module called theme there should be a file called my-template.tpl.php which could have this in it:

<?php

$items = $variables['items'];

print render($items['VAR_ONE']);
print render($items['VAR_TWO']);

And if you wanted to, you could actually overwrite the "default" module implementation you just made for my-module.tpl.php in your theme as you wish in block--MYMODULE--DELTA.tpl.php.


Content type add node reference I am adding a content type in Drupal 7. I want to add a simple node-reference field. Isn't this included in Drupal 7?

Use the References module:

  This project provides D7 versions of the 'Node reference' and 'User
  reference' field types, that were part of the CCK package in D6

or Entity reference:

  Provides a field type that can reference arbitrary entities

or Relation:

  Relation is an API module and storage model for both simple and the
  most complex relations between entities. The module can handle both
  directional and symmetrical relations very well.


Migration Source YML File import date string into date and time field of content type I have a json file full of data exported from a wordpress site, one field being a string representing a date and time: "03/15/2012 14:46:19".  I would like to import that string into a date and time field of a drupal 8 content type.

I am using a Migration from Source YML file.

fields:
 -
  name: date
  label: 'Date'
  selector: date

Then in process:

process:
  field_press_release_date: date        # is it as easy as this?

Is there a special plug in I'm not seeing listed on:
https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins

I see format date, but couldn't get any format to work.  I have complete control over the format of the date string, I have to do some processing of data from wordpress before drupal so I can do pretty much whatever is needed, if it really is as easy as setting the date_field to the date_string from the fields list, what format does date_string need to be in?

I cannot find a simple example of importing a string into a date and time field, thank you for any assistance!

The migrate plugin that handles this is FormatDate.  It looks like you are missing the input and output date formats.  For date-only, you would do something like

process:
  field_date:
    plugin: format_date
    from_format: 'm/d/Y'
    to_format: 'Y-m-d'
    source: event_date

and for date+time, it would look something like

process:
  field_datetime:
    plugin: format_date
    from_format: 'm/d/Y H:i:s'
    to_format: 'Y-m-d\TH:i:s'
    source: event_time

When migrating into the core datetime/daterange fields, the to_format needs to be those strings (these were written to be generic, not just for those field types).  The from_format gets adjusted to your input source.  If you look at the references below, there is also a way to specify time zone.

That plugin is unit tested, so core doesn't provide any YAML example, but you may be able to glean samples from FormatDateTest.

References:

Added FormatDate migrate process plugin
https://www.drupal.org/project/drupal/issues/2820490
FormatDate migration process plugin now supports specifying of source and destination timezones
https://www.drupal.org/project/drupal/issues/2883892


How do you upload files using the RestWS module? I have a remote front-end application under development and I would like to interface with Drupal as a backend service, using the RestWS module to create a RESTful service to my Drupal instance (using JSON as my data format).

I have a node content type of type "article", that has an image field on it called "field_image".

I'm currently trying to figure out the proper way to upload a file to Drupal through the API created by RestWS.

I can retrieve a node with a file attachment via GET to the URL http://www.example.com/node/1.json, which retrieves the contents of node 1, including the information about the uploaded file:

https://gist.github.com/lhridley/8bbf95294aa529d74c74

I can also retrieve information specifically about the file attachment, using the FID returned when requesting information about the node, using the url http://www.example.com/file/1.json:

https://gist.github.com/lhridley/804eb93016845f369535

Now, my question:

How specifically do you upload a file using RestWS, so that you create a file resource to then use when creating a node?

i use services not restWS, but the steps are quite similar on every REST service.

with your REST client. ie, restsharp, in my case im using Http (plugin for unity).
your first need to be connected, to do that call your server.dominio.co/site/apiName/user/login.json (you need to tick the option on your rest api, that enables user login service). also need to tick file creation permission.
if your are using token rememter to save it, also the session name, and session id myForm.AddHeader(session_name,session_id) (is the cookie). in my case i dont send it because http already do it for me. after that this is how i upload a file with c# and services,

Hashtable hashdata = new Hashtable();

    WWWForm myForm = new WWWForm();
    myForm.AddField("file", base64Img);
    myForm.AddField("filename", name);
    myForm.AddField("filepath", "public://" + folderName);
    string path = server.dominio.co/site/apiName + "file";
    HTTP.Request theRequest = new HTTP.Request("post", path, myForm);

    theRequest.synchronous = true;
    theRequest.AddHeader("X-CSRF-Token", myTOKEN);
    theRequest.Send((request) =>
    {
        if (request.response != null)
        {
            request.response.GetHeaders();

            string result = request.response.Text;
            hashdata = new Hashtable();
            hashdata = (Hashtable)JSON.JsonDecode(result);

        }

    });
    return hashdata;

will return the fid of the file just uploaded... after that you will need to update the field of the node where you want the file to be attached to... you will need a new REST request to update that node, method update, etc, etc

Hopes this helps a bit.... know it's not THE solution... but hope it points you the right way.


how to select particular product from bunch of products I have two fields in my content type. one field(seat) has more than 10 products( product reference ) and another field (default). while selecting one product in the seated field ,should be shown in the default field. I do not know how to get that product from seat to default. How to solve this ?

You could use the Rules module to react on a node save, check if the field has only one value and alter the values of the node as needed.

Or you can write your own module and use the form_set_value() function to change the submitted values in a (custom) validation function. Your validation function can be attached to the node edit form by implementing hook_form_FORM_ID_alter() and adding the function to the $form['#validate'] array.


How to get the url from a link field in preprocess function I have a content type event.
It has a link field field_event_location_link
Both the link text and url are optional

By default Drupal uses the url as the title if there is no title typed in.

I want to show 'Location' if the title is not filled in.

How can I use a preprocess function to see if there is a title, and if not, use my string.

I tried ...

function my_module_preprocess_field(&$variables) {
  if ($variables['field_name'] == 'field_event_location_link') {
    if ($variables['items'][0]['content']['#title'] == '') {
     $variables['items'][0]['content']['#title'] = 'Location';
    }
  }
}

But it doesn't work and I think it's because by the time I get to that point, Drupal has already used the uri for the #title.

Question:
Can I catch it before that?
Or can I get a variable for the URL and use that variable in the '' above? Should I be checking if something is empty...?

If you inspect with $variables['items'][0]['content'] with Devel kint

kint($variables['items'][0]['content']);

  But it doesn't work and I think it's because by the time I get to that
  point, Drupal has already used the uri for the #title.

Correct, so all you gotta do is check if the title is equal to the url utilizing Url::toString.

  if ($variables['field_name'] == 'field_event_location_link') {
    $link_url = $variables['items'][0]['content']['#url']->toString();
    if ($variables['items'][0]['content']['#title'] == $link_url) {
      $variables['items'][0]['content']['#title'] = 'Location';
    }
  }


How to implement a secure video streaming website? I want to create a secure Video streaming website where people need to pay to play videos and they should not be able to download directly the video.
What are the possible solution to achieve this? I know there is a flowplayer secure streaming plugin http://flowplayer.org/plugins/streaming/secure.html but is this enough?

Thanks

This is quite a complicated problem with a lot of possible approaches; a whole book could be written about it (your question is probably too broad).

That said, have you checked out Videola?  Videola is a Drupal-based distribution for creating subscription-based websites.  It's made by Lullabot, one of the leading Drupal companies, and they use it to power their learning network, Drupalize.me.


Prevent users from editing or viewing their own profile What is the best way to disable access to the user's profile for viewing and editing? Basically users can create an account but won't be able to edit or view their own or other users' profiles.

Add this to a custom module:

function MYMODULE_menu_alter(&$items) {
  $items['user/%user']['access arguments'] = array('access user profiles');
  $items['user/%user']['access callback'] = 'user_access';
  $items['user/%user/edit']['access arguments'] = array('administer users');
  $items['user/%user/edit']['access callback'] = 'user_access';
}

This will put the user profile view under 'View user profiles' permission and edit under 'Administer users'.


How do I customize the flag/unflag links? I'm fairly new to Drupal theming, and I am trying to customize the HTML output the Flag module for Drupal 8 produces for flag/unflag links; more specifically, I would like to make the links appear as buttons using Bootstrap classes. Does anyone know a good way to do this? I'm placing the flag link on the user profile page to enable users to follow other users. Here are some approaches which I have tried, so far without success:

Using the Twig replace filter to modify the output. This does not work, apparently because a "lazy builder" is used, delaying the production of the actual HTML output until a later stage after Twig's rendering is already complete.
Overriding the flag.tpl.php template with a customized version. This has no effect; maybe this functionality is no longer active in Drupal 8 (which did away with PHP templates in general)?
Using flag_create_link in a theme preprocess function. I got an error that this function does not exist; maybe it no longer exists in the Drupal 8 version of the module? (or else maybe I'm missing a necessary import).

Here is a solution that ended up working for me. In my MYTHEME.theme file, I put the following:

function MYTHEME_preprocess_user(&$vars){
  $f = \Drupal::service('flag.link_builder');
  $link = $f->build('user',$vars['user']->id(),'followed');
  $link['link']['#attributes']['class'][]="btn";
  $vars['follow_link'] = $link;
}

Then, in the user.html.twig template, I put {{ follow_link }} in the appropriate place. It's not a perfect solution, though, because it is not compatible with AJAX links (in which case the button styling is lost after the button is clicked). But with normal links, it works.


Add a content type as a select list when creating a new user I have a content type called Location.

Each user needs a location assigned to them.

How do I go about attaching the Location to the user?

Basically I need to add a dropdown of locations that I can select from for each user I create/edit.

If you use/add the Content Profile module, you can use it to create a profile for each user. In that profile content, you can have a field that is a node reference back to the Location type you mention.

  This module builds user profiles as content (aka nodes), which opens the opportunity to use all the powerful modules for content for user profiles too, e.g. the Content Construction Kit (CCK). It's intended to be simple and useful, but extensible by further modules.

  Content profiles can be restricted to certain roles; the module also supports separate content profiles for different roles.


Drupal automatic TFA I want to setup the Two-factor Authentication (TFA) configuration automatically for each user that signs up in my site. Is that possible?

Because from what I have tried till now, all the users for whom I want TFA to be active needs to be configured individually. But shouldn't the ideal situation be such that the TFA will get active per user as soon as the user gets in the system?

What am I missing here? Isn't this a very obvious requirement?

There is currently no mechanism to require existing users to use TFA; if you use "authenticated user" with "Roles required to have set up TFA", then new users cannot set up TFA and existing users without TFA will not be able to log in.

TFA doesn't provide any mechanism for this, so I wrote a module that provides Rules integration and created a basic rule that would do it.

https://www.drupal.org/project/tfa_rules

Instructions on setting up basic TFA on a site:

Download and install Two-Factor Authentication, TFA Basic Plugins, Rules and TFA Rules

drush dl tfa tfa_basic rules tfa_rules

Enable.

drush -y en tfa tfa_basic rules rules_admin tfa_rules

Configure TFA: /admin/config/people/tfa

[X] Enable TFA
Default validation plugin: TOTP
[Save configuration]

Configure permissions: /admin/people/permissions

Set up TFA for account

[X] authenticated user

[Save permissions]

Visit /admin/config/workflow/rules to configure the rule.

Testing:

Log out
Create a user
Login
User will be redirected to the security page to set up TFA.


What can break quickedit, and how do I fix it? We hired someone else to make our theme, and they gave us something with the quickedit not working.  What can cause this to break, and how do I fix it?

Here's what my contextual-links ul looks like right now:

Quick edit

The entitynodeedit-form li is empty, as well as the delete li.  What is supposed to fill them in, and how do I fix it?

If there is not an obvious error in php or javascript, see the comment from @mradcliffe, then there are probably some attributes missing, because they were removed in twig templates.

The quickedit links are not delivered in html, they are build in javascript. For this the attributes to identify the involved entities and fields need to be present.

Look especially for the attributes data-quickedit-entity-id in node templates and data-quickedit-field-id in field templates.

This is the correct way to add attributes in twig:

{%
  set classes = [
    'red',
    'green',
  ]
%}
<div{{ attributes.addClass(classes) }}></div>

Source: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates


Is there a Drupal 8 alternative for Inline Entity Form (to create an item while adding a reference)? I have a Family content type and a Person content type. A Family has an Entity Reference field to one or more Persons.

The normal workflow requires me to first create the Persons, then create the Family and then add the Persons to the Family, but I want to create the Family first and create persons while adding them.

This is achieved in Drupal 7 with the Inline Entity Form. Is there something like that for Drupal 8? Any alternative?

You can use the alpha version and the dev version of the Inline Entity Form


How to get the users who did not submit articles? Every day people are expected to post 1 node of content type "Article" on my site. If they missed to post such article, then I need to somehow produce a message "Your article is pending" to those users.

Additionally, I need to be able to check which date a user did not submitted such article.So how can I get all users who did not submit articles? And also filter them on which date they have missed the submission of an article node?

Part 1 - Create an appropriate list of users

You could use an approach similar to my answer to "How to create a list of users who did not submit some webform?", i.e.:

Use the Flag module to introduce an article submission flag (similar to Step 1 in the above answer).
Register article submissions, using a Rules Event like "After saving content (of type article)", probably you don't need any special Rules Conditions.
List the users who have yes or no flagged "an" article with the flag from Step 1, using Views (similar to Step 3 in the above answer).

The above steps will allow you to create a list that is close to what you're looking for.

Part 2 - Filtering the list

To also filter them on which date they have missed the submission of an article node (as in your question), you would need to further enhance the view created in step 3. For that, there are various ways to do so. One of the possibilities is to use the DataTables module, and use its on-the-fly-filtering facility. This facility becomes available after you enable the "search" widget (somewhere within the datatables settings for your view). Refer to my answer to "How to display the data of a View in table format?" for way more details about DataTables.

Part 3 - Producing a message

To produce a message "Your article is pending" to those users (as in your question), you could enhance the view by adding the Views Bulk Operations (VBO) module to it, so that for the selected users you trigger a Rules Component which actually sends an appropriate eMail to those users. For an example of such rules component, refer to my answer to How to send an email notification when a subcription renewal is due? (within Step 2 of it).

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO.


How can I load a Store by user ID? I am building a multi-seller commerce site, where a user can register and sell their product.  I need to display a menu link if the user is anonymous to "become a seller", where they are directed to log in and a create store form.

If the user is logged in, I want to display a menu link that displays "My Store" if they previously created a store.  To determine if they have a store, how can I load a store via their user ID?

I have been unable to find an example where someone can load a user's store.

The user ID is saved on the store when it's created. Therefore you can load it with code similar to the following one.

$store = \Drupal::entityTypeManager()->getStorage('commerce_store')->loadByProperties(['uid' => \Drupal::currentUser()->id()]);

That will load the store based on the currently logged-in user.


How to acess node object in hook_form_alter I am trying to access the node object in hook_form_alter(), but it throws the following error:

  Notice: Undefined index: #node in themename_form_alter()

The code I am using is the following.

function themename_form_alter(&$form, $form_state, $form_id)) {
  $node = $form['#node'];
}

Is there any way to access the node object in hook_form_alter()?

Not all the forms contains a reference to a node. It is just some node forms which contain a node object, but hook_form_alter() is called for every form being output from Drupal.

What you need to do is the following:

Check $form['#node'] is set

if (isset($form['#node'])) {
  // …
}

Use a different hook, such as hook_form_node_form_alter() if you want to alter the node edit form for any content type, or hook_form_$type_node_form_alter() for the node edit form of the $type content type


In Drupal 7 Commerce, is there a way to populate an anonymous user's profile billing/shipping address data during checkout? This is for Commerce Core. Not Kickstart, but it can also apply.

Upon completing checkout with an anonymous user in Drupal Commerce. There is no billing / shipping data populated in the user's profile. What modules or rules are needed to have the user's billing / shipping address profile pre-filled upon successful checkout?

This is after the anonymous user completes a successful checkout and an account is automatically generated for them.

It sounds like you're wanting to set the default billing / shipping customer profiles for the newly created user to be the ones that were just used in checkout. I don't know if there's a Rules action for that, but if not, that sounds like a good feature request for the Commerce Addressbook module. If there is, then you just need to add a checkout completion rule to make it happen.


Create shipping charge based in produc weight' with Drupal commerce module? I just followed this Randy Fay video which shows how to generate a charge based in the products weight. I works fine. It multiplies the weight of products by a Cost Per Pound (CPP)

I need this CPP to be different based in the total weight of ALL products in the order.

Example:

Order up to 1 pound ........  CPP = 0,006

Order with weight higher than 1 pounds ........ CPP = 0,004

Easy, create two rules, one where the condition is that the total weight is more than 1 pound and one where the condition is less than or equal 1 pound.

You can setup the rest of the rules to be the same, with only the price (CPP) being different.


Get body summary in field's replacement pattern Is it possible to get the body's summary within a view field's replacement pattern?

What I am doing right now is this:

{{ field_icon }}

<div class="description">
    {{ title }}
    {{ body }}
</div>

As the body text is too long I tried using {{ body.summary }} instead of {{ body }} but that didn't work at all..

Could you tell me whether there is a possibility to do this inside of a replacement pattern?

Thank you!

You need to select Summary or trimmed as your formatter, then {{ body }} will print out your summary.


How do I create a cache context in Drupal 8 that varies on user/node field data? Let's say I have a complex render array that has two variations that depend on a simple if: whether the logged in user can edit a node inside it. There are two scenarios I look for:

The node was created by the logged in user, or:
The node's field_group (entity reference) matches the logged in user's field_group.

These two conditions are independent of roles/permissions so I can't fall back on those contexts. Originally, I simply used the "user" context but this would create far too much variation and potentially lead to a very large database table (not to mention it was inefficient to have to cache this again for every user).

I imagine I would need to create a context like: "caneditnode:nid" and somehow pass nid to a handler that would load the Node to check its fields and owner and compare to the data in Drupal::currentUser(). Is that possible? How would I go about doing this? Thanks!

A cache key is not the right solution as dynamic_page_cache won't vary on the right things.

What you do is:

You create a custom cache context (see core.services.yml for many examples), which itself is dependent on the [route] and [user] cache context (as it needs to check the node).

e.g. cookies:[cookie_name] is a good example. (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Cache%21Context%21CookiesCacheContext.php/class/CookiesCacheContext/8.1.x)

In that way you can have indeed a:

caneditnode:[entity_id]

Whenever this cache context is used, your handler is checked and needs to return the right information based on the given Context.

If caneditnode is given as cache context without context it could just throw an Exception or fallback to ['user', 'route'] as that is what it depends on.

In getCacheableMetadata you would just return the node cacheable metadata and the user.roles.

See https://api.drupal.org/api/drupal/core%21core.services.yml/service/cache_context.user.permissions/8.1.x for an example of a cache context, which itself depends on other data, which can be invalidated.


How to pass a variable about sufficient User Points to a Rules condition in another rule? I used this link to set up a UserPoints Store: Drupal 7 - How to Set up a Simple UserPoints Store.

For some reason when I buy (flag) a node (store item) and for quantity I put more UserPoints, than the transaction is not blocked, which results in a negative user points balance.

Problem:

Either this issue is addressed and I set some wrong settings(I double checked everything so I don't think so)
I need to make my own custom setting for the UserPoints not to enter negatives.

Is there a way I can set and pass a variable (enough_points=true) from (1st) rule "Check User Points" and then use it as a condition in (2nd) rule "Flag item"?

There is no Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which you could use in a Rules Conditionn Execute custom PHP code condition, e.g. to do some type of comparison):

global $user;
$current_points = userpoints_get_current_points($user->uid, 'all');
if ($current_points < 0) {return TRUE;}

However, there is a Rules Action "Load user points of a user", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.

If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user, after the user performed an update of some node (= the Rules Event, which you can change to any Rules event that you want):

{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Use the Rules UI to import the above rule in your own site if you want.


How to call a module in a block or give a module a block or put module form into a block? I have a module, and I would like its add form to be put into a block.  So my question is, how would you take a modules page (admin/build/mymodule/add) and give it a block?  So this module will now have its own block in the blocks admin page.  Do you do this by its url, by module, or by form id?

You can do this with the $form_id and the function drupal_get_form();

You need to create a module and use hook_block():

function mysecondmodule_block($op = 'list', $delta = 0, $edit = array()) {
  switch($op) {
    case 'list':
      return array(array('info' => 'mymodule add block'));
    break;
    case 'view':
      if($delta == 0) {
        return array(
         'subject' => 'Mymodule Add',
         'content' => drupal_get_form('form-id');
        );
      }
    break;
  }
}


$base_url variable in settings.php is not being read. How do i set this variable? On my laptop I recently moved my Drupal sites from Acquia Dev Desktop server to a standard MAMP setup. Problem is the root dir folder isn't being read. The root dir folder name would be, by default part of the base url. For example, the mission page URL should be  http://localhost:8888/mywebsite/mission. But instead it's trying to load as http://localhost:8888/mission.

Since using Drupal I haven't had to once set a base url variable. In the settings.php file I found a variable for this which I uncommented and set. On line 282 in the settings file it now reads as like so:

$base_url = 'http://localhost:8888/mywebsite';

but this is having no effect whatsoever.

How or where can this be set? Or is there something I should do within the MAMP set up?

Use a virtual host in your webserver configuration with the DocumentRoot to your drupal installation:

<VirtualHost *:8888>
   DocumentRoot "/var/www/website"


Multisite Drupal with Organic Groups problem.. custom /user and /user/register links for each group? I am using Organic Groups for as a solution for Drupal Sub sites, it is working perfectly, even themes are switching via Organic groups theme but I am having problem with /user/register and /user pages.

I want to pass context to user pages like user/groupname/register or user/groupname , so how can I do it ? because /user currently throws me out of the currently active theme for Organic Group.

Also one more thing, the Group Id which I want to pass should be as alias?like pathauto paths.

I would probably look at PURL for this, an API to make a part of a URL persistent.
PURL itself does nothing since it's an API, but you can get started with OG Purl.
Be warned, it's more advanced to be creating your own bridge like OG Purl does. A lot of motivation is required :)


How to prevent fake drupalcommerce orders We have a website developed using drupal commerce.All listing and details pages of products are custom made ones.Not drupal views.We have a issue with fake orders.We are getting nearly 1000 fake orders from this site.Doing nothing but only adding products to the cart.I can see that its from whole website.

We have used a hyperlink as add to cart button.Is there any problem with this?

This site is open for anonymous users.When we restrict the site only for registered users these fake orders dramatically reduce.I meant 0 fake orders.

Cant guess whats going on with this.Have installed some spam prevention drupal modules but no luck.

Any one suggest a method to prevent this.

Thanks

Your problem is due to robots, in particular spam robots (spambots). I've monitored these pests closely on my site for some time, and found that spambots (such as XRumer) will click on anything that's clickable.  I doubt that you need to be concerned about spammers of the human kind.

There is nothing wrong with the suggestions from Strae, but don't expect spambots such as  Xrumer to respect tags such as rel="nofollow".  (Nice robots such as googlebot do, so if your fake orders are from nice robots only, this will fix it.).

In my experience, the single most successful measure to filter out spambots is to add effective CAPTCHA to the site.  If the user is not logged in yet, the CAPTCHA must be present in the order submit form.  If a new user register, the CAPTCHA must be present in the registration form.  (You don't need to use CAPTCHAs in the order submit form for logged in users). If you set up a CAPTCHA, don't bother with "math challenge", "leave this field blank" and "ReCAPTCHA" - XRumer knows how to solve those.

On my site, the Captcha Riddler is by far the most successful robot guard.  Even blatantly obvious "riddles", such as: "What is Justin Bieber's  first name?" stops the spambots.

PS: If your site is big enough, your "riddles" and their answers will probably be added to the knowledge base of XRumer and other spambots. But if you run a small site you will probably be able to fly under the radar for a long time with "riddles" you create yourself (and you just watch the logs and retire and replace any "riddle" that is cracked by a spambot).


looking for a complete documentation for Drupal's database schema - need to have some overview well dear buddies,

i am pretty new to drupal. Just set up a drupal commons

now i 'd like to add some data to my drupal, and i dont really understand the database model/scheme. Can somebody point me to some documentation? For example i need to understand the role of node, vocabulary, and all the tables and what is tid,vid,nid fieds... Then i could add data the sql way.

Of course I don't think complete documentation for Drupal's database schema exists. Well does any body have a  very very first attempt:

An ongoing attempt with comments for Drupal 6 can be seen here
http://drupal.org/node/79874

An analysis with SchemaSpy i found here
http://webdevgeeks.com/schemaspy/index.html

and overview i have seen here.
http://upsitesweb.com/sites/upsites.co/files/drupal7_model_0.png

well who can give more hints - i love to hear from you -
Again: i want to have some overview on the options i have to extend the group
(running on http://www.schulcenter.org - and see here http://schulcenter.org/?q=group/schulen )

How can i configure / extend the groups (/on the database-level)?
How can i configure / extend the groups (/on the database-level)?

i wanna creat the following fields - (derived from the following shedule https://scraperwiki.com/scrapers/austrian-schools/ ) see the names of the collumns

name
adresse
schultyp
homepage
ergänzender schulname
beschreibung
schwerpunkte

can this be done best in groups !? Can i this set in the groups. Or should i do that in the so called - organic-groups

Note: as you see the site schulcenter.org should give an overview on schools
with a certain amount of data from the profile: the adress, the website..

a little image (a thumbnail of the website - shown in a block,)
a little description (approx 200 characters) what the site /the school does - some special programmes or something like that...

How to achieve this !? Love to hear from you any and all help will greatly be appreciated

love to hear from you
zero

Check Drupal's Schema API. Here is the link to it. Also the Book "Pro Drupal Development" has an excellent chapter on Working with Databases.You might find that one useful too.


Can I use Full-Text Search Functions in db_select()? Does it possible to use Full text search functions like match() against() with Drupal 8 database Api's OR any alternative to make it work?

No. If you look at the internal Condition::match() function that's used when building conditional statements with the condition() method, you can see the list of operators does not include the MATCH() AGAINST() operators. The cost of having a DB abstraction layer that supports different DBMS, is you can only support the greatest common feature among them; these operators are MySQL/Postgres specific.

In order to utilize these feature of your database, you'll need to use the Connection::query() method to perform the query directly.


Grab Data from non form elements and send as POST using AJAX I am looking for an alternative solution to the way my form is being submitted right now. The problem is that the validation function does not work because I gave the submit button on the form an attribute of onclick=return(false) and added the following AJAX code to listen for the submit button being pressed.

jQuery("#edit-submit-order").click(function() {
        var orderForm = jQuery("#order-form-form").serialize();
        var orderTable = JSON.stringify(hot.getData());
        var extraOrderTable = JSON.stringify(hot2.getData());
        var formType = jQuery("input:radio[name=form-type]:checked").val();

        jQuery.ajax({
            type : "POST",
            url : '/sites/all/modules/order_form/post-order.php',
            data : orderForm + "&orderTable=" + orderTable + "&extraOrderTable=" + extraOrderTable + "&formType=" + formType + "&orderTotal=" + parseFloat(updatePricing()).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'),

            success : function(result) {
                if (result) {
                    jQuery('#order-form-form').empty();
                    jQuery('#order-form-form').append(result);
                    //jQuery("#order-form-form").html("
Submitted Order Form Successfully
");
                } else {
                    jQuery(".message").html("
" + result.message + "
");
                }
                jQuery(".message").children().fadeOut(5000);
            }
        });
    });

The orderTable and extraOrderTable are the elements I need to send with the POST request. They are part of an HTML table I am using called Hands on Table. It is a very nice excel like table editor. The getData() command returns an array of all values in the tables.

Ideally I would like to remove the onclick=return(false) from my submit button and have the order form submit using Drupal's AJAX method, making sure to validate the fields I marked as required but also submitting the table data in a single POST request. Can this be done or is the solution I have already made the best way to do it?

Hopefully this answer will help someone else looking for the same thing. I found a solution and it works great.

The way that I solved it was by creating two hidden elements with id's in my form. One hidden element for each table that I have in my form.

Below is how I created the hidden form element

$form['orderTable'] = array(
        '#type' => 'hidden',
        '#attributes' => array('id' => 'orderTable')
);

Below is how I created the container that holds the table and is used to generate the table from the Java Script file.

$form['middle']['order-table'] = array(
        '#type' => 'container',
        '#attributes' => array(
            'id' => array(
                'testing-table',
            ),
        ),
    );

The Excel like table that I used Handsontable has an excellent method called afterChange this gets fired after something on the form changes. So what I did is create another Java Script function that gets fired each time inside of the afterChange function.

 function updateHiddenFields() {
    var orderTable = JSON.stringify(hot.getData());
    jQuery("#orderTable").val(orderTable);
}

What this does if your not familiar with Java Script is turn the data from Handsontable into a JSON string and places it in the value field of the hidden element. By doing it this way all of the data is accessible when the form is submitted just like  I wanted and I was able to use the validation function.