Rus
Eng
Адаптивная всплывающая форма с проверкой на лету в общем виде на примере формы "Заказать в 1 клик"

All English-language materials have been translated fully automatically using the Google service

Template for outputting a pop-up form with the necessary checks. I use it constantly, I decided to describe the process to reduce the cost of my own time.

Part of the given code is redundant and was used by me in one of the projects. Use wisely.

The code is provided as is. Use it at your own risk.

First of all, we prepare the button to which the reaction will occur. In the data-id parameter, write the product id:

 <div class = "btn orderOneClickFormShow" data-id = "<? = $ arResult ['ID']?>"> Order in 1 click <i class = "fas fa-shopping-cart"> </ i > </div>

Adding Button Styles

  .orderOneClick {padding: 10px 15px 10px 15px; color: #fff; display: flex; align-items: center;}  

Place a form container in the footer

  <div class = "topWindowOuter absoluteCenter">
    <div class = "topWindowInner">
// Insert the form code here
    </div>
</div>

Place our form in a container:

 <div class = "modal-close js-close-form"> <span class = "fas fa-times-circle"> <svg version = "1.1" id = "Layer_1" xmlns = "http: // www.w3.org/2000/svg "xmlns: xlink =" http://www.w3.org/1999/xlink "x =" 0px "y =" 0px "viewBox =" 0 0 512 512 "style =" enable-background: new 0 0 512 512; " xml: space = "preserve"> <path d = "M256,0C114.844,0,0,114.844,0,256s114.844,256,256,256s256-114.844,256-256S397.156,0,256,0z M256,490.667 C126.604,490.667,21.333,385.396 , 21.333,256S126.604,21.333,256,21.333S490.667,126.604,490.667,256S385.396,490.667,256,490.667 z "/> <path d =" M359.542,152.458c-4.167-4.167-10.917-4.167-15.083,0L256,240.917 l-88.458-88.458c-4.167-4.167-10.917-4.167-15.083.0 c-4.167.4.167-4.167.10.917.0.15.083 L240.917.256l-88.458.88.458c-4.167.4.167-4.167.10.917.0 , 15.083 c2.083.2.083.4.813.3.125,7.542.3.125s5.458-1.042,7.542-3.125L256,271.083l88.458.88.458c2.083.2.083.4.813.3.125,7.542.3.125 c2.729.0 , 5.458-1.042,7.542-3.125c4.167-4.167,4.167-10.917,0-15.083L271.083,256l88.458-88.458 C363.708,163.375,363.708,156.625,359.542,152.458z "/> </svg> </ span> </div>
        <form id = "buyOneClickForm">
            <? = bitrix_sessid_post ();?>
            <input type = "hidden" NAME = "PRODUCT_ID" class = "field_product_id" />
            <div class = "row js-oneClickForm js-formDiv active">
                <div class = "col-xs-12">
                    <h2 class = "modal-title"> Order in 1 click </h2>
                </div>
                <div class = "col-xs-12">
                    <label> Name: </label>
                    <input type = "text" class = "field_name" name = "NAME" placeholder = "Name" autocomplete = "name" />
                </div>
                <div class = "col-xs-12">
                    <label> Phone: </label>
                    <input type = "text" class = "field_phone required" name = "PHONE" placeholder = "Phone *" autocomplete = "tel" />
                </div>
                <div class = "col-xs-12">
                    <label> Mail: </label>
                    <input type = "text" class = "field_mail required" name = "EMAIL" placeholder = "Mail *" autocomplete = "email" />
                </div>
                <div class = "col-xs-12">
                    <label> Comment: </label>
                    <textarea class = "field_comment" name = "COMMENT" placeholder = "Comment"> </textarea>
                </div>
                <div class = "col-xs-12 orderPolitika">
                    <input type = "checkbox" class = "field_check required" name = "POLITIKA_AGREED" value = "Y" id = "politika"> <label for = "politika"> I have read <a href = "/ help / politika- konfidentsialnosti / "target =" _ blank "rel =" noopener noreferrer "> Privacy Policy </a> and agree with all clauses </label>
                </div>
                <div class = "col-xs-12 orderButtonBlock">
                    <div class = "orderOneClickSubmit js-order-submit"> Submit <i class = "fa fa-long-arrow-alt-right"> </i> </div>
                </div>
            </div>
            <div class = "js-buyOneClickFormSuccess js-formDiv">
                <h2> Success! </h2>
                <p> Thank you, we will contact you within n minutes </p>
            </div>
            <div class = "js-buyOneClickFormError js-formDiv">
                <h2> Error! </h2>
                <p> Please try again after a while </p>
            </div>
        </form>
        <script>
            (function ($) {
                // Activate the phone mask
                $ ('. field_phone'). inputmask ({"mask": "+7 (999) 999-9999"});
            }) (jQuery);
        </script>

Add styles to the form:

  .absoluteCenter {display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-align: center; -moz-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; -webkit-box-pack: center; -moz-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; text-align: center; flex-direction: column}

.topWindowOuter {background-color: rgba (0,0,0,0.5); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000; display: none; }
.topWindowInner {background-color: #fff; padding: 80px 100px; position: relative; min-width: 420px; max-width: 600px; -webkit-box-shadow: 0px 5px 10px 0px rgba (0,0,0, 0.2); -moz-box-shadow: 0px 5px 10px 0px rgba (0,0,0,0.2); box-shadow: 0px 5px 10px 0px rgba (0,0,0,0.2); text-align: left}
.topWindowInner h2 {font-family: Gotham-Pro-Bold, "HelveticaNeueCyr", "PT Sans", sans-serif; font-size: 24px; font-weight: 600; line-height: 32px; margin-bottom: 14px; text-align: left}
.topWindowInner .formClose {position: absolute; right: 0; top: 0; background-color: # E31D23; border-radius: 50%; width: 28px; height: 28px; -webkit-transform: translate (50%, - 50%); -moz-transform: translate (50%, - 50%); -ms-transform: translate (50%, - 50%); -o-transform: translate (50%, - 50%); transform: translate (50%, - 50%); cursor: pointer}
.topWindowInner .formClose .svgBox {margin-top: 3px;}
.topWindowInner .formClose svg {width: 8px; height: 8px; fill: #fff; stroke: #fff;}
.topWindowInner .formClose: hover {background-color: # d21a20}

.topWindowInner input [type = "text"] ,. topWindowInner textarea {width: 100%; display: block; border: 1px solid # b7b7b7; font-family: Roboto, 'Open Sans', sans-serif; padding: 10px 13px ; font-size: 14px;}
.topWindowInner input [type = "text"] {margin-bottom: 16px; position: relative;}
.topWindowInner input [type = "text"]. error {color: # d21a20; border: 1px solid # d21a20;}
.topWindowInner input [type = "checkbox"] {display: none}
.topWindowInner label {width: 100%; display: block; font-family: Roboto, sans-serif; font-weight: 400; font-size: 14px; line-height: 1.5; color: # 2d2d2d; margin-bottom: 4px; border-bottom: 1px solid transparent}
.topWindowInner label.error {text-decoration: underline; text-decoration-color: # d21a20;}
.topWindowInner .orderPolitika {padding-top: 10px}

.topWindowInner .row .col-xs-12: nth-child (4) {display: none}
.topWindowInner h2 {text-align: center; font-size: 2em; font-family: 'Roboto Condensed', sans-serif; position: relative; text-transform: uppercase; margin-bottom: 60px;}
.topWindowInner a {color: # e62d19}

.orderOneClickSubmit {font-size: 12px; color: #fff; text-align: left; padding: 9px 10px; padding-left: 24px; background: linear-gradient (116deg, # 2d2d2d 0, # 2d2d2d 70%, # e62d19 71%, # e62d19 100%); font-weight: 700; font-family: 'Roboto Condensed', sans-serif; display: inline-block; cursor: pointer; text-transform: uppercase; letter-spacing: .15em ; margin: 44px 0 0 0; display: inline-block}
.orderOneClickSubmit: hover {opacity: 0.8}
.orderOneClickSubmit [class ^ = fa] {margin-left: 40px; font-size: 16px; line-height: 21px; font-weight: 900;}
.orderButtonBlock {text-align: center}

.js-formDiv {display: none}
.js-formDiv.active {display: block}

.modal-close {position: absolute; top: 12px; right: 24px; cursor: pointer; width: 24px; height: 24px; fill: # 333}
.modal-close: hover {fill: # FFEDF1}
.modal-close svg {-moz-transition: all 0.5s; -webkit-transition: all 0.5s; -o-transition: all 0.5s; -ms-transition: all 0.5s}

@media all and (max-width: 545px) {
    .topWindowInner {min-width: 320px; max-width: 320px; padding: 40px 20px 40px 20px;}
}  

Let's add a script in which all the logic of the form will be processed

 <script src = "<? = SITE_TEMPLATE_PATH?> / js / main.js? <? = time ()?>"> </script> 

or like this:

  use Bitrix \ Main \ Page \ Asset;

Asset :: getInstance () -> addJs (SITE_TEMPLATE_PATH. "/Js/main.js?". Time ()); // Add a single script  

Let's write scripts that process the form

Filling in the main.js

file
  / * But 1 click starts * /
function IsJsonString (str) {
    try {
        JSON.parse (str);
    } catch (e) {
        return false;
    }
    return true;
}

/ ******************************** /
/ * General functions for working with the form * /
/ ******************************** /
// When the state of the input of the popup form changes, do the validation
$ ('body'). on ('keyup input change', '. topWindowOuter input, .topWindowOuter textarea', function () {// Call the state of input fields when they are edited
    formSubmit ($ (this) .parents ('form'));
});

// Close the window when clicking outside
$ ('body'). on ('click', '. topWindowOuter', function (e) {
    if ($ ('. topWindowOuter'). has (e.target) .length === 0) {// Tracking the click on the element
        closeGallery ();
    }
});

// Show the popup
function showModal (el) {
    el.stop (). css ("display", "flex"). hide (). fadeIn (600);
}

// When pressing Esc, hide the form
$ (document) .keydown (function (e) {
    if (e.keyCode === 27) {

        var popup = $ ('. topWindowOuter: visible');
        if (popup) {
            closeGallery (popup);
            return false;
        }

    }
});

// Hide the form
function closeGallery () {
    $ ('. topWindowOuter'). fadeOut (400, function () {
        $ ('. js-formDiv'). removeClass ('active'). fadeOut (0);
        $ ('. js-oneClickForm'). addClass ('active'). fadeIn (0);
    });
}

// Do form validation
function formSubmit (form) {// generic form validation function

    var THIS_FORM = form;

    var req_input = $ (THIS_FORM) .find (". required");
    var flag = 0;


    $ .each (req_input, function (index) {
        var THIS_VALUE = $ (this) .val (),
            reg_email = /^^^^^^^^^^^^^^^.-zA-Z0-9\._-...+@ [a-zA-Z0-9_\. $ /;
        reg_phone = / ^ (\ s *)? (\ +)? ([- _ (): = +]? \ d [- _ (): = +]?) {10,14} (\ s *)? $ /,
            cc = / [0-9] {4} {0,1} [0-9] {4} {0,1} [0-9] {4} {0,1} [0-9] {4} /, // Credit card number
            cdate = /^\d {2} [./- *\d [2 ]$$/, // Credit card Date
            smsCode = / ^ \ d {3} \ d {3} $ /, // SMS Code Verification
            cvc = / ^ [0-9] {3,4} $ /; // Credit card CVC



        if ($ (this) .is (". field_phone")) {
            if (reg_phone.test (THIS_VALUE)) {
                $ (this) .removeClass ('error'). addClass ('succeed');
            }
            else {
                $ (this) .addClass ('error'). removeClass ('succeed');
                flag ++;
            }
        } else if ($ (this) .is (". field_email")) {
            if (reg_email.test (THIS_VALUE)) {
                $ (this) .removeClass ('error'). addClass ('succeed');
            }
            else {
                $ (this) .addClass ('error'). removeClass ('succeed');
                flag ++;
            }
        } else if ($ (this) .is (". field_name")) {
            if (THIS_VALUE.length> 2) {
                $ (this) .removeClass ('error'). addClass ('succeed');
            }
            else {
                $ (this) .addClass ('error'). removeClass ('succeed');
                flag ++;
            }
        } else if ($ (this) .is (". field_pass") || $ (this) .is (". field_pass_confirm")) {
            if ($ (". field_pass_confirm"). length> 0) {
                if (THIS_VALUE.length> 5 && ($ (". field_pass"). val () == $ (". field_pass_confirm"). val ())) {
                    $ (". field_pass"). removeClass ('error'). addClass ('succeed');
                    $ (". field_pass_confirm"). removeClass ('error'). addClass ('succeed');
                }
                else {
                    $ (". field_pass"). addClass ('error'). removeClass ('succeed');
                    $ (". field_pass_confirm"). addClass ('error'). removeClass ('succeed');
                    flag ++;
                }
            } else {
                if (THIS_VALUE.length> 5) {
                    $ (". field_pass"). removeClass ('error'). addClass ('succeed');
                }
                else {
                    $ (". field_pass"). addClass ('error'). removeClass ('succeed');
                    flag ++;
                }
            }

        } else if ($ (this) .is (". field_card_number")) {
            $ ('. field_card_number'). mask ('0000 0000 0000 0000');
            if (cc.test (THIS_VALUE)) {
                $ (this) .removeClass ('error'). addClass ('succeed');
            }
            else {
                $ (this) .addClass ('error'). removeClass ('succeed');
                flag ++;
            }
        } else if ($ (this) .is (". field_card_date")) {
            $ ('. field_card_date'). mask ('00 / 00 ');
            if (cdate.test (THIS_VALUE)) {
                $ (this) .removeClass ('error'). addClass ('succeed');
            }
            else {
                $ (this) .addClass ('error'). removeClass ('succeed');
                flag ++;
            }
        } else if ($ (this) .is (". field_card_cvc")) {
            $ ('. field_card_cvc'). mask ('000');
            if (THIS_VALUE) {
                $ (this) .removeClass ('error'). addClass ('succeed');
            }
            else {
                $ (this) .addClass ('error'). removeClass ('succeed');
                flag ++;
            }
        } else if ($ (this) .is (". field_sms_verify")) {
            if (smsCode.test (THIS_VALUE)) {
                $ (this) .removeClass ('error'). addClass ('succeed');
            }
            else {
                $ (this) .addClass ('error'). removeClass ('succeed');
                flag ++;
            }
        } else if ($ (this) .is (". field_check")) {
            if ($ (this) .prop ("checked") == true) {
                $ (this) .next (). removeClass ('error'). addClass ('succeed');
            }
            else {
                $ (this) .next (). addClass ('error'). removeClass ('succeed');
                flag ++;
            }
        } else if ($ (this) .is (". field_mail")) {
            // Skip dummy fields to stop bots
            // I recommend that you change the name and type of check for bots
        } else {
            if (THIS_VALUE) {
                $ (this) .removeClass ('error'). addClass ('succeed');
            }
            else {
                $ (this) .addClass ('error'). removeClass ('succeed');
                flag ++;

            }
        }

    });
    if (flag) {return false;}
    else {return true;}
}
/ ******************************** /
/* Order Processing */
/ ******************************** /
(function ($) {
    // Buy button in 1 click, show the form
    $ ('body'). on ('click', '. orderOneClickFormShow', function (e) {
        e.preventDefault ();

        // Show the form
        showModal ($ ('. topWindowOuter'));

        // Write the id of the required element to the form
        $ ('. field_product_id'). val ($ (this) .attr ('data-id'));
    });

    // Click on the button to close the form
    $ ('body'). on ('click', '. js-close-form', function (e) {
        e.preventDefault ();
        closeGallery ();
    });

    // mark the checkbox as checked. The script is needed because the checkbox is hidden and its emulation is used
    $ ('body'). on ('click', 'label [for = "politika"]', function (e) {
        e.preventDefault ();

        var el = $ (this),
            parents = el.parents ('. orderPolitika'),
            input = parents.find ('input [type = "checkbox"]');

        parents.toggleClass ('active');

        if (parents.hasClass ('active')) {
            input.prop ('checked', true) .val ('Y');
        } else {
            input.prop ('checked', false) .val ('N');
        }

        input.trigger ("change");
    });

    // To shorten the code and increase readability, we move this fragment into a separate function
    function formError () {
        $ ('. js-formDiv.active'). fadeOut (400, function () {
            $ ('. js-formDiv'). removeClass ('active');
            $ ('. buyOneClickFormError'). fadeIn (400, function () {
                $ (this) .addClass ('active');
            });
        });
    }

    // To shorten the code and increase readability, we move this fragment into a separate function
    function formSuccess () {
        $ ('. js-formDiv.active'). fadeOut (400, function () {
            $ ('. js-formDiv'). removeClass ('active');
            $ ('. js-buyOneClickFormSuccess'). fadeIn (400, function () {
                $ (this) .addClass ('active');
            });
        });
    }
// Submit button
    $ ('body'). on ('click', '. js-order-submit', function (e) {
        e.preventDefault ();

        var el = $ (this),
            parents = el.parents ('form');

        if (formSubmit (parents)) {
            var data = parents.serialize ();

            $ .ajax ({
                type: 'post',
                url: '/local/buyOneClick.php', // Remember the location of the buyOneClick.php file
                data: data,
                // dataType: 'json',
                success: function (data) {
                    console.log (data);
                    if (IsJsonString (data)) {
                        data = JSON.parse (data);
                        if (data.success === 'ok') {
                            // There were no errors, the order was placed
                            formSuccess ();
                        } else {
                            // An error flag was returned
                            formError ();
                        }
                    } else {
                        // Not json, then an error occurred
                        formError ();
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log ("Status:" + textStatus);
                }
            });


        }

    });
}) (jQuery);
/ * But 1 click ends * /  

Now let's place and fill in the buyOneClick.php

file
  require_once ($ _ SERVER ['DOCUMENT_ROOT']. '/ bitrix / modules / main / include / prolog_before.php');

use Bitrix \ Main,
    Bitrix \ Main \ Loader,
    Bitrix \ Main \ Config \ Option,
    Bitrix \ Main \ Mail \ Event,
    Bitrix \ Sale,
    Bitrix \ Sale \ Order,
    Bitrix \ Main \ Application,
    Bitrix \ Sale \ DiscountCouponsManager;

function sendNotification ($ name, $ phone, $ orderList, $ orderId, $ email, $ price) {
    global $ USER;

    $ arEventFields = array (
        "ORDER_ID" => $ orderId,
        "SOSTAV" => $ orderList,
        "ORDER_USER" => $ USER,
        "EMAIL" => $ email,
        "BCC" => 'aleksandrpleskachevskiy@gmail.com',
        "PRICE" => $ price,
        // "PRICESS" => $ savoi
    );

    // CEvent :: SendImmediate ("SALEINFOADMIN", 's1', $ arEventFields, "N"); // Immediate notification of the admin about a new order without writing the event to the database
    CEvent :: Send ("SALEINFOADMIN", 's1', $ arEventFields, "N"); // Admin notifications about a new order
}

if (check_bitrix_sessid () && $ _SERVER ["REQUEST_METHOD"] == "POST") {
    if (htmlspecialchars ($ _ POST ['EMAIL'])) {
        echo json_encode (array ('success' => 'Y'));
    } else {
        CModule :: IncludeModule ("sale");
        CModule :: IncludeModule ("catalog");

        $ data = array (
            'PRODUCT_ID' => $ _POST ['PRODUCT_ID'],
            'NAME' => htmlspecialchars ($ _ POST ['NAME'])? htmlspecialchars ($ _ POST ['NAME']): 'Buy in 1 click',
            'PHONE' => preg_replace ("/ [^ 0-9] /", '', htmlspecialchars ($ _ POST ['PHONE'])), // Leave only numbers
            'COMMENT' => htmlspecialchars ($ _ POST ['COMMENT']),
            'POLITIKA_AGREED' => htmlspecialchars ($ _ POST ['POLITIKA_AGREED']),
            'QUANTITY' => 1,
        );

        if (! $ data ['PHONE']) {
            echo json_encode (array ('success' => 'N', 'type' => 'phone is not full'));
            die ();
        }

        global $ USER;

        if (! $ USER-> IsAuthorized ()) {

            $ rand = randString (15);

            $ registeredUserID = $ USER-> Add (array (
                "NAME" => $ data ['NAME'],
                "EMAIL" => 'one_click@'.$rand.'.com',
                "LOGIN" => $ rand,
                "PERSONAL_PHONE" => $ rand,
                "LID" => "ru",
                "ACTIVE" => "Y",
                "GROUP_ID" => array (2,3,4),
                "PASSWORD" => $ rand,
                "CONFIRM_PASSWORD" => $ rand,
            ));

            if (! $ registeredUserID) {
                echo json_encode (array ('success' => 'N', 'type' => 'User already exists'));
                die ();
            }

            $ USER-> Authorize ($ registeredUserID);
        } else {
            $ registeredUserID = $ USER-> GetID ();
        }
$ siteId = \ Bitrix \ Main \ Context :: getCurrent () -> getSite ();
        $ currencyCode = Option :: get ('sale', 'default_currency', 'RUB');

        DiscountCouponsManager :: init ();

        // --- empty the basket
        CSaleBasket :: DeleteAll (CSaleBasket :: GetBasketUserID ());

        // Get the cart for the user
        $ basket = Sale \ Basket :: loadItemsForFUser (Sale \ Fuser :: getId (), Bitrix \ Main \ Context :: getCurrent () -> getSite ());

        if ($ item = $ basket-> getExistsItem ('catalog', $ data ['PRODUCT_ID'])) {// Check if there is such a product in the basket
            $ item-> setField ('QUANTITY', $ item-> getQuantity () + $ data ['QUANTITY']); // if there is, increase its quantity
        } else {
            $ item = $ basket-> createItem ('catalog', $ data ['PRODUCT_ID']); // add the product to the basket
            $ item-> setFields (array (
                'QUANTITY' => $ data ['QUANTITY'],
                'CURRENCY' => \ Bitrix \ Currency \ CurrencyManager :: getBaseCurrency (),
                'LID' => \ Bitrix \ Main \ Context :: getCurrent () -> getSite (),
                'PRODUCT_PROVIDER_CLASS' => 'CCatalogProductProvider',
            ));
        }
        $ basket-> save (); // save the basket

        $ order = Order :: create ($ siteId, $ registeredUserID);
        $ order-> setPersonTypeId (1);
        $ basket = Sale \ Basket :: loadItemsForFUser (\ CSaleBasket :: GetBasketUserID (), Bitrix \ Main \ Context :: getCurrent () -> getSite ()) -> getOrderableItems ();

        $ order-> setBasket ($ basket);

        / * Shipment * /
        $ shipmentCollection = $ order-> getShipmentCollection ();
        $ shipment = $ shipmentCollection-> createItem ();
        $ shipment-> setFields (array (
            'DELIVERY_ID' => 2, // ID of the delivery option (we have it self-pickup)
            'DELIVERY_NAME' => 'Pickup',
            'CURRENCY' => $ order-> getCurrency ()
        ));


        $ shipmentItemCollection = $ shipment-> getShipmentItemCollection ();

        foreach ($ order-> getBasket () as $ item)
        {
            $ shipmentItem = $ shipmentItemCollection-> createItem ($ item);
            $ shipmentItem-> setQuantity ($ item-> getQuantity ());
        }


        / * Payment * /
        $ price = $ order-> getPrice ();
        $ paymentCollection = $ order-> getPaymentCollection ();
        $ extPayment = $ paymentCollection-> createItem ();
        $ extPayment-> setFields (array (
            'PAY_SYSTEM_ID' => 2,
            'PAY_SYSTEM_NAME' => 'Cash to courier',
            'SUM' => $ price
        ));

        / ** /
        $ order-> doFinalAction (true);

        $ propertyCollection = $ order-> getPropertyCollection ();

        $ orderProperties [6] = $ USER-> GetFullName ();
        $ orderProperties [8] = $ USER-> GetParam ("PHONE");
        // $ orderProperties [28] = "Y"; // this is our property, which is filled with a quick order, so that managers are not stupid
        $ orderProperties [7] = $ USER-> GetParam ("EMAIL");
foreach ($ propertyCollection-> getGroups () as $ group)
        {
            foreach ($ propertyCollection-> getGroupProperties ($ group ['ID']) as $ property)
            {
                $ p = $ property-> getProperty ();
                if ($ p ["CODE"] == "CONTACT_PERSON")
                    $ property-> setValue ("VASYA");

                if ($ orderProperties [$ p ['ID']]! = "") {
                    $ propertyCollection-> setValuesFromPost (array ('PROPERTIES' => Array ($ p ["ID"] => $ orderProperties [$ p ['ID']])), array ()); // set the required properties
                }
            }
        }

        $ order-> setField ('CURRENCY', $ currencyCode);
        $ order-> setField ('COMMENTS', 'The order was placed through the API from s "Buy in 1 click". Then the user's comment:'. $ data ['COMMENT']);

        $ order-> save ();
        $ orderId = $ order-> GetId ();

        if ($ orderId) {
            sendNotification ($ data ['NAME'], $ data ['PHONE'], '', $ orderId, 'one_click @'. $ rand. '. com', $ price);
            echo json_encode (array ('success' => 'ok', 'order_id' => $ orderId));
        } else {
            echo json_encode (array ('success' => 'N', 'type' => 'Error creating order'));
        }

    }
}  

Adding form results to infoblock with administrator notification

Suppose we have not a 1-click order form, but a standard feedback form. Then go to Content -> Infoblocks -> Types of infoblocks and create a new type of infoblock with the name "Appeals" and the code "appeal"

Go to Content -> Appeals and add a new infoblock with the name "Feedback [Art. Contacts]". We will store the parameters in a separate table.

In my case, it was necessary to add 3 properties. 2 types of string (Name, Contact) and 1 type of Html (Comment). Let's create these properties in the infoblock and remember their ID. In my case, these are 251, 252 and 253

Go to Settings -> Product settings -> Mail and SMS events -> Event types and add a new event

  Event type = FEEDBACK_FORM_NEW
Title = Send a message via a new feedback form
Description = # AUTHOR # - Post author
# HOW_TO_CONTACT # - How to contact
# TEXT # - Message text
# EMAIL_FROM # - Email sender
# EMAIL_TO # - Email of the recipient of the letter

Title = Sending a message using a new feedback form
Description = # AUTHOR # - Message author
# HOW_TO_CONTACT # - How to contact
# TEXT # - Message text
# EMAIL_FROM # - Sender's e-mail address
# EMAIL_TO # - Recipient's e-mail address  

Go to Settings -> Product settings -> Mail and SMS events -> Mail templates and add a new template

  Active = Y
Site = Your Site
From = # DEFAULT_EMAIL_FROM #
To = # EMAIL_TO #
Template = Informational site message # SITE_NAME #
------------------------------------------

You have been sent a message via the feedback form

Author: # AUTHOR #
Contact: # HOW_TO_CONTACT #

Message text:
# TEXT #

The message was generated automatically.  

Form handlers and scripts are used from the example above. Then a script that accepts form values, sends a message to the administrator and adds an infoblock element will look like this:

  require_once ($ _ SERVER ['DOCUMENT_ROOT']. '/ bitrix / modules / main / include / prolog_before.php');

function sendNotification ($ name, $ how, $ mes) {
    $ arEventFields = array (
        "AUTHOR" => $ name,
        "HOW_TO_CONTACT" => $ how,
        "TEXT" => $ mes
    );

    CEvent :: Send ("FEEDBACK_FORM_NEW", 's1', $ arEventFields, "N"); // Event type: Sending a message through a new feedback form
}

$ result = array ('success' => 'Y'); // We always give up success so that possible attackers don't debug their scripts

// $ _ POST ['FAKE_FIELD'] - check for a bot

if (check_bitrix_sessid () && $ _SERVER ["REQUEST_METHOD"] == "POST" &&! $ _ POST ['FAKE_FIELD']) {

    $ name = htmlspecialchars ($ _ POST ['field_name']);
    $ how = htmlspecialchars ($ _ POST ['field_contacts']);
    $ mes = htmlspecialchars ($ _ POST ['field_message']);

    if ($ name && $ how && $ mes) {
        sendNotification ($ name, $ how, $ mes); // Send a message to the admin

        if (CModule :: IncludeModule ("iblock")) {
            $ el = new CIBlockElement;

            $ PROP = array ();
            $ PROP [251] = $ name; //Name
            $ PROP [252] = $ how; // How to contact
            $ PROP [253] = $ mes; //Comment

            $ arLoadProductArray = Array (
                "MODIFIED_BY" => 1, // item changed by the current user
                "IBLOCK_SECTION_ID" => false, // the element is at the root of the section
                "IBLOCK_ID" => 23,
                "IBLOCK_TYPE" => 'appeal',
                "PROPERTY_VALUES" => $ PROP,
                "NAME" => "New message. Author:". $ Name,
                "ACTIVE" => "Y", // active
                // "PREVIEW_TEXT" => "text for the list of items",
                // "DETAIL_TEXT" => "text for detailed view",
                // "DETAIL_PICTURE" => CFile :: MakeFileArray ($ _ SERVER ["DOCUMENT_ROOT"]. "/ Image.gif")
            );

            $ PRODUCT_ID = $ el-> Add ($ arLoadProductArray);
        }
    }
}

echo json_encode ($ result);  

The solution was applied on the Business v20.0.600 edition

Comments

There are no comments yet, you can be the first to leave it

Leave a comment

The site uses a comment pre-moderation system, so your message will be published only after approval by the moderator

You are replying to a user's comment

Send

FEEDBACK

Email me

Are you developing a new service, making improvements to the existing one and want to be better than your competitors? You have come to the right place. I offer you a comprehensive studio-level website development. From me you can order design, layout, programming, development of non-traditional functionality, implementation of communication between CMS, CRM and Data Analitics, as well as everything else related to sites, except for promotion.

Contact, I will always advise on all questions and help you find the most effective solution for your business. I am engaged in the creation of sites in Novosibirsk and in other regions of Russia, I also work with the CIS countries. You will be satisfied with our cooperation

An error occurred while sending, please try again after a while
Message sent successfully

Phones

+7(993) 007-18-96

Email

info@tichiy.ru

Address

Россия, г. Москва

By submitting the form, you automatically confirm that you have read and accept the Privacy Policy site

Contact with me
Send message
By submitting the form, you automatically confirm that you have read and accept Privacy policy of site
Sending successful!
Thank you for contacting :) I will contact you as soon as possible
Sending failed
An error occurred while sending the request. Please wait and try again after a while or call my phone number