Jump to content

want to show data from Form fields in XML document


Pravin
 Share

Recommended Posts

On 14/11/2016 at 8:18 PM, Pravin said:

I want the data inserted in the forms to be fetched into a XML document is it possible

Pretty much anything is possible with PW. Make a start by yourself and if you have any specific problems just ask in the forums.

  • Like 2
Link to comment
Share on other sites

You say you you are using form-upload.php and form-process.php from Soma, ok, lets simplify a bit the code for our example. Also we are going to create a template and a page.

First step: we create a new file form-xml.php in the templates folder and copypasta the following code into this file :

Spoiler

<?php namespace ProcessWire;
// ------------------------------ FORM Configuration ---------------------------------------
// --- Some default variables ---
$success_message   = "<p class='message'>XML file generated successfully.</p>";
// --- All form fields as nested array ---
// using html form field name => template field nam, from the page you're going to create
$form_fields = array(
    'username' => array('type' => 'text', 'value' => '', 'required' => true),
    'email'    => array('type' => 'email', 'value' => '', 'required' => true)
);

// ------------------------------ FORM Processing ---------------------------------------
include("./_form-process.php");
?>

<!-- ========================= FORM HTML markup  ================================== -->


<div class="content">

    <h2>Generate XML from form</h2>

    <?php if(!$success) : ?>

        <?php if(!empty($errors)) echo showError("Form contains errors"); ?>
        <?php if(!empty($errors['csrf'])) echo showError($errors['csrf']); ?>

        <form name="myform" class="myform" id="myform" method="post" action="./" enctype="multipart/form-data">

            <input type="hidden" name="<?php echo $session->CSRF->getTokenName(); ?>" value="<?php echo $session->CSRF->getTokenValue(); ?>"/>

            <div class="row <?php if(isset($errors['username'])) echo "error";?>">
                <label for="username">Name* </label><br/>
                <input type="text" name="username" id="username" value="<?php echo $sanitizer->entities($form_fields['username']['value']); ?>"/>
                <?php if(isset($errors['username'])) echo showError($errors['username']); ?>
            </div>

            <div class="row <?php if(isset($errors['email'])) echo "error";?>">
                <label for="email">Email* </label><br/>
                <input type="text" name="email" id="email" value="<?php echo $sanitizer->entities($form_fields['email']['value']); ?>"/>
                <?php if(isset($errors['email'])) echo showError($errors['email']); ?>
            </div>

            <div class="row">
                <input type="hidden" name="action" id="action" value="send"/>
                <input type="submit" name="submit" id="submit" value="Submit"/>
            </div>
        </form>

    <?php else: ?>

        <p><?php echo $success_message; ?></p>

    <?php endif; ?>

</div>

 

 

Second step: we create another new file _form-process.php in our templates folder (note: the underscore is here to avoid the file being listed as template found) and again we copypasta the following code into this file :

Spoiler

<?php namespace ProcessWire;
// ------------------------------ FORM Processing ---------------------------------------
$errors            = null;
$success           = false;
// helper function to format form errors
function showError($e){
    return "<p class='error'>$e</p>";
}

/**
 * Cast and save field values in array $form_fields
 * this is also done even form not submited to make populating the form later easier.
 *
 * Also used for pupulating page when form was valid
 */
$required_fields = array();
foreach($form_fields as $key => $f){
    if($f['type'] == 'text'){
        $form_fields[$key]['value'] = $sanitizer->text($input->post->$key);
    }
    if($f['type'] == 'email'){
        $form_fields[$key]['value'] = $sanitizer->email($input->post->$key);
    }
    // store required fields in array
    if($f['required']) $required_fields[] = $key;
}

/**
 * form was submitted, start processing the form
 */
if($input->post->action == 'send'){
    // validate CSRF token first to check if it's a valid request
    if(!$session->CSRF->hasValidToken()){
        $errors['csrf'] = "Form submit was not valid, please try again.";
    }
    /**
     * Check for required fields and make sure they have a value
     */
    foreach($required_fields as $req){

        // reqired text fields
        if($form_fields[$req]['type'] == 'text' || $form_fields[$req]['type'] == 'email')
        {
            if(!strlen($form_fields[$req]['value'])){
                $errors[$req] = "Field required";
            }
            // reqired email fields
            if($form_fields[$req]['type'] == 'email'){
                if($form_fields[$req]['value'] != $input->post->$req){
                    $errors[$req] = "Please enter a valid Email address.";
                }
            }
        }
    }
    /**
     * if no required errors found yet continue creating the XML document
     */
    if(empty($errors))
    {
        // path where we save the document (site/assets is arbitrary)
        $pathofxmlfiles = $config->paths->assets . 'XMLFILES' . DIRECTORY_SEPARATOR;
        // name of the document
        $xmlfilename = 'Users.xml';

        // create an XML document object
        $doc = new \DOMDocument('1.0');
        // we want a nice output
        $doc->formatOutput = true;

        // root node
        $root = $doc->createElement('user_profil');
        $root = $doc->appendChild($root);

        // first child node : field username
        $username = $doc->createElement('username');
        $username = $root->appendChild($username);
        $text = $doc->createTextNode(($form_fields ["username"]["value"]));
        $text = $username->appendChild($text);

        // second chield node : field email
        $email = $doc->createElement('email');
        $email = $root->appendChild($email);
        $text = $doc->createTextNode(($form_fields ["email"]["value"]));
        $text = $email->appendChild($text);

        // save the document
        $doc->save($pathofxmlfiles . $xmlfilename);

        $success = true;
    }
}

 

 

Third step: we go in the backend, create a new template and choose (check) form-xml.php from the template found listing. Then we go to the page tree, create a page under root page, give the new page a title and we assign form-xml as template.

The final step is to create the folder which hold our XML generated files. I set as arbitrary path - site/assets/XMLFILES - so we go in site/assets and create a folder with the following name: XMLFILES

Now we can open our new page in the browser and play with the form generating XML file.

Result:

<?xml version="1.0"?>
<user_profil>
  <username>root</username>
  <email>root@foo.bar</email>
</user_profil>

 

Edited by flydev
result
  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...