Sunday, January 24, 2016

post data to the user register form

# vim test.js

(function ($) {
  $('#edit-submit').on('click', function(event){
    event.preventDefault();

    var _formData = $('#user-register-form').serializeArray();

    _formData.push({name: '_drupal_ajax', value: 1});
    _formData.push({name: '_triggering_element_name', value: 'op'});
    _formData.push({name: '_triggering_element_value', value: 'Save'});

    $.ajax({method: 'POST', url: '/userregisterform?ajax_form=1&_wrapper_format=drupal_ajax', dataType: 'json', data: _formData})
      .done(function(data) {
        console.log(data);
      })
      .fail(function(data) {
        console.log(data);
      });
  });
})(jQuery);

# vim TestController.php

<?php
namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;

class TestController extends ControllerBase {
  public function registeruser() {
    // register a new user
    //$values = [];
    //$values['name'] = 'robo-user';
    //$values['mail'] = 'robouser@example.com';
    //$values['pass']['pass1'] = 'password';
    //$values['pass']['pass2'] = 'password';
    //$values['op'] = t('Create new account');

    $form_state = new \Drupal\Core\Form\FormState();
    $form_state->setValues($_POST);

    \Drupal::formBuilder()->submitForm('\Drupal\user\RegisterForm', $form_state);

    $errors = $form_state->getErrors();

    if (empty($errors)) {
      // Return new user session to client.
      $uid = \Drupal::service('user.auth')->authenticate($_POST['name'], $_POST['pass']);
      return new JsonResponse(array( 'uid' => $uid, 'name' => $_POST['name']));
    }
    else {
      return new JsonResponse(array('errors' => $errors));
    }
  }
}
?>

Reference:

http://www.wembassy.com/blog/chris-mcintosh/create-angularjs-headless-drupal-8-application

No comments: