How to use the create api post submit to create nested data?

How to use the create api post submit to create nested data?

FroopleDesignFroopleDesign Posts: 21Questions: 3Answers: 0
edited September 2023 in Free community support

I am able to create contactInfo by editing an existing user, but i want to be able to create a user with contact info in one go. I have two mysql tables, user and contactinfo. The userid for user is auto incremented, and the id for contactInfo is autoincremented, userId is used as a foriegn key in contactInfo to link the contactInfo to the user.

( focus is on postSubmit)

    userEditor.on('postSubmit', function (e, json, data, action) {
    if (action === 'create') {
        // Get the `userid` of the newly created user from the JSON response
        var userid = 222; // Replace 'id' with the actual key for userid

        console.log('New User ID:', userid);

        // Create a new `contactInfo` entry using the `userid`
        var contactInfoData = {
            "contactInfo.userid": userid,
            "contactInfo.phone": userEditor.field('contactInfo.phone').val(),
            "contactInfo.email": userEditor.field('contactInfo.email').val()
        };

        console.log('Contact Info Data:', contactInfoData);

        // Use the contactInfo editor to create the `contactInfo` entry
        contactInfoEditor.create(contactInfoData, {
            success: function () {
                console.log('Contact Info created successfully.');
                // Refresh the user table to reflect the changes
                table.ajax.reload(null, true);

                // Trigger the initSubmit event manually after contactInfo creation
                userEditor.trigger('initSubmit');
            },
            error: function (xhr, err, thrown) {
                console.error('Error creating contactInfo:', err);

                // additional debugging for the AJAX request
                console.log('AJAX Request Status:', xhr.status);
                console.log('AJAX Response Text:', xhr.responseText);
            }
        });
    }
});
        

Why is contactInfo not being created postSubmit? Is the way im using the create function incorrect? I've attached the full js code as a file.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin
    Answer ✓

    There are a few errors in the code above:

    • The create() method doesn't accept the values for the field as the first parameter. Rather you should use val().
    • There are no success and error options for the second parameter passed to the create() method. It is a form-options object.
    • The contactInfoEditor form isn't being submitted. You need to add a call to submit().

    submit() does have a callback option for success and error (first and second parameters - not in an object), so you can move that logic to there.

    Allan

  • FroopleDesignFroopleDesign Posts: 21Questions: 3Answers: 0
    edited September 2023

    There are a few errors in the code above:

    The create() method doesn't accept the values for the field as the first parameter. Rather you should use val().
    There are no success and error options for the second parameter passed to the create() method. It is a form-options object.
    The contactInfoEditor form isn't being submitted. You need to add a call to submit().
    submit() does have a callback option for success and error (first and second parameters - not in an object), so you can move that logic to there.

    Allan

    I see, thank you.So it would be something like

        userEditor.on('postSubmit', function (e, json, data, action) {
            if (action === 'create') {
                // Get the `userid` of the newly created user from the JSON response
                var userid = 222; // need to replace '222' with the actual key for userid
        
                console.log('New User ID:', userid);
        
                // Set the values for the contactInfo fields using .val()
                contactInfoEditor
                    .create()
                    .val('contactInfo.userid', userid)
                    .val('contactInfo.phone', userEditor.field('contactInfo.phone').val())
                    .val('contactInfo.email', userEditor.field('contactInfo.email').val())
                    .submit();
        
        
            }
        });
    

    Is there a recommended method to fetch the userid from the user after submission since its created via autoincrement in mysql? I'd also need to enforce my server side validation

    Editor::inst( $db, 'contactInfo', 'id' )
    ->fields(
         Field::inst( 'contactInfo.id' ),
                    Field::inst( 'contactInfo.userid' ),
                   
                    Field::inst( 'contactInfo.phone' )
                     ->validator( Validate::notEmpty() )
                     ->validator( Validate::minMaxLen( 8, 15 ) ),
                
                    Field::inst( 'contactInfo.email' )
                     ->validator( Validate::email( ValidateOptions::inst()
                     ->message( 'Please enter an e-mail address' )  
                     ) )
                 
                )
    
  • FroopleDesignFroopleDesign Posts: 21Questions: 3Answers: 0

    Attached client side validation functions to check the fields before submitting, now i just need to fetch the proper userid, thank you :)

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    It should be in the json variable:

    json.data[0].userid
    

    I think should do it. Note that this would only work for single row editing / creation. That might or might not be an acceptable limitation for you. If not, then you'd need to handle it in a loop or with multi-editing.

    Alla

  • FroopleDesignFroopleDesign Posts: 21Questions: 3Answers: 0
    edited September 2023

    I think should do it. Note that this would only work for single row editing / creation. That might or might not be an acceptable limitation for you. If not, then you'd need to handle it in a loop or with multi-editing.

    Alla

    Oh no that doesn't work, it seems i have a problem with my POST data. My post response is empty, while my GET response shows all the data. So when i run json.userid or json.data[0].userid, it remains undefined as the response is empty.

    I used the generator to start the project

  • FroopleDesignFroopleDesign Posts: 21Questions: 3Answers: 0
    edited September 2023

    Im getting close, since userid is defined after the post, im attempting to fetch the userid via a get request by checking the latest username matching the username of the postSubmit.
    Something like

        userEditor.on('postSubmit', function (e, json, data, action) {
            if (action === 'create') {
                // Get the values for the phone and email fields
                var phoneValue = userEditor.field('contactInfo.phone').val();
                var emailValue = userEditor.field('contactInfo.email').val();
        
                // Validate the phone and email fields
                var phoneIsValid = validatePhone(phoneValue);
                var emailIsValid = validateEmail(emailValue);
        
                // Check if both phone and email are valid
                if (phoneIsValid && emailIsValid) {
                    // Make a GET request to fetch the updated data
                    $.ajax({
                        url: '/php/table.userinfo.php?_=' + Date.now(), // Include a timestamp to ensure a fresh request
                        method: 'GET',
                        dataType: 'json',
                        success: function (updatedData) {
                            console.log('updatedData:', updatedData);
                            console.log('data:', data);
        
                            // Find the latest occurrence of the username in the updated data
                            var latestUser = null;
                            console.log("latest username", data.data[0]['username']);
                            for (var i = updatedData.data.length - 1; i >= 0; i--) {
                                if (updatedData.data[i].username === data.data[0]['username']) {
                                    latestUser = updatedData.data[i];
                                    break; // Found the latest occurrence, exit the loop
                                }
                            }
        
                            if (latestUser) {
                                console.log("latest user ID:", latestUser.userid);
                                // Set the values for the contactInfo fields using .val()
                                contactInfoEditor
                                    .create()
                                    .val('contactInfo.userid', latestUser.userid)
                                    .val('contactInfo.phone', phoneValue)
                                    .val('contactInfo.email', emailValue)
                                    .submit();
                            } else {
                                // Handle the case where the user wasn't found in the response
                                console.error('Newly created user not found in response.');
                            }
                        },
                        error: function () {
                            // Handle any errors that may occur during the GET request
                            console.error('Failed to fetch updated data.');
                        }
                    });
                } else {
                    // Display an error message for invalid fields
                    if (!phoneIsValid) {
                        alert('Phone number must be 8 to 15 digits and may contain a country code like "+965".');
                    }
                    if (!emailIsValid) {
                        alert('Invalid email address format. Please enter a valid email.');
                    }
                }
            }
        });
    

    I need to run a few more tests to ensure its working properly but it seems to be doing the job, any opinions on this method?

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    The response for an Editor edit request shouldn't be empty - particularly if it was a Generator based project. It should be responding to create and edit requests with data in the format described here.

    Without being able to see it in action and the full server-side code, I can't know for sure why that would be. That said, your code looks fine, as long as you don't have two users submitting data at the same time :)

    Allan

  • FroopleDesignFroopleDesign Posts: 21Questions: 3Answers: 0

    You're right, im looking into the main issue as this is a temporary fix, i did make it so it checks the username rather than just taking the last entry to lessen asynchronous issues but it'll need some further configuration to properly handle multiple users. The payload is sending proper data, the response is simply empty, and even if it wasn't, i don't think the userid will be present as its something that is set after the data is posted by the mysql database. ( auto increment ).

    Thank you for your active support on this forum allan, i truly appreciate it :)

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    i don't think the userid will be present as its something that is set after the data is posted by the mysql database. ( auto increment ).

    The should actually be okay. The way the Editor libraries we publish work is that after writing a new row to the database, they then read the data back from the db. It is done that way for exactly the reason you are seeing - auto increments. It also allows for triggers and other database formatting functions.

    If you are using our PHP libraries, it should be doing all of that automatically. Something has gone wrong somewhere if that isn't the case.

    Allan

  • FroopleDesignFroopleDesign Posts: 21Questions: 3Answers: 0

    The should actually be okay. The way the Editor libraries we publish work is that after writing a new row to the database, they then read the data back from the db. It is done that way for exactly the reason you are seeing - auto increments. It also allows for triggers and other database formatting functions.

    If you are using our PHP libraries, it should be doing all of that automatically. Something has gone wrong somewhere if that isn't the case.

    Allan

    Yes i used the generater to get the files and worked from there, it doesn't seem to be doing that, i kept getting empty POST responses which is why i opted to use the GET responses for now. It seems like i should start looking into the code more deeply.

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    Our libraries should never actually return empty. At the very least there should be a {}.

    What I would suggest doing is adding:

    error_reporting(\E_ALL);
    ini_set('display_errors', '1');
    

    at the top of the server-side PHP files (i.e. where the Ajax call is made to - table.{name}.php - just inside the first <?php). That will cause anything that is causing an error to print the error out - which it sounds like might be happening.

    Allan

Sign In or Register to comment.