Jump to content

Marc

Members
  • Posts

    103
  • Joined

  • Last visited

Posts posted by Marc

  1. I am developing a module called 'callcenter', which adds custom menu items to the admin panel. In ProcessCallcenter.info.php a have my navigation setup as follows:

    	'nav' => array(
    		array(
    			'url' => 'enterorder/',
    			'label' => __('Enter order'),
    			'icon' => 'glass',
    			'permission' => 'call-prepare',
    		),array(
    			'url' => 'enteruser/',
    			'label' => __('Enter user'),
    			'icon' => 'glass',
    			'permission' => 'call-prepare',
    		),
    		array(
    			'url' => 'entercall/',
    			'label' => __('Enter call'),
    			'icon' => 'glass',
    			'permission' => 'call-prepare',
    		),
    		array(
    			'url' => 'calloverview/',
    			'label' => __('Call overview'),
    			'icon' => 'glass',
    		),
    	)
    

    The labels should be translated, but it does not work. I went to 'languages' in the admin, added ProcessCallcenter.info.php to my language, which found the four label strings, but after translating only the original English labels are displayed in the custom dropdown menu. Other files of my module are translated correctly using this method. Am I doing something wrong? I tried refreshing the modules a few times but it does not help.

    I attached a screenshot to show what I mean. I have my profile language set to Dutch, so the admin is Dutch except for my module menu (called 'callcenter') which is in English for a reason I don't understand.

    post-2762-0-66467200-1446626844_thumb.jp

  2. Searching around on the forum, I've come up with the following:

    // Add template's fields to the form.
    $p = new Page;
    $template = $templates->get("call");
    $fields = $template->fieldgroup;
    
    foreach($fields as $field) {
    
        $inputfield = $field->getInputfield($p);
    
        $inputfield->label = $template->fieldgroup->getField($field, true)->label;
        $inputfield->description = $template->fieldgroup->getField($field, true)->description;
        $inputfield->required = $template->fieldgroup->getField($field, true)->required;
    
        $form->add($inputfield);
    }

    I'm overriding the fieldgroup properties with template field properties for 'label', 'description' and 'required'. Which works so that solves my initial problem. The way this works raises another question though: is there a way to override all properties instead of setting them individually like I did above for label, description and required? I tried something like this, but there must be a more efficient way?

    // Add the template's fields to the form.
    $p = new Page;
    $template = $templates->get("call");
    $fields = $template->fieldgroup;
    foreach($fields as $field) {
    
        $inputfield = $field->getInputfield($p); 
       
        foreach ($inputfield->data as $key => $value) {
         $inputfield->$key = $fields->getField($field, true)->$key;
        }
        
        $form->add($inputfield);
    }
  3. I could really use another hint... I'm having the same issue with saving a regular page: when a field is set to 'required' in the template but not in the field properties itself, the custom form won't treat it as a required field. Probably because of the missing inputfield context Soma mentioned, which probably means the form is looking at the fields without the context of the template in which I set the fields as required. 

    How should I modify this example for the above?

    $p = new Page; // create new page object
    $p->template = 'order'; // set template
    $p->parent = wire('pages')->get('/Orders/'); // set the parent
    $p->of(false); // turn off output formatting before setting values
    $p->save(); // create the page
    
    foreach ($p->fields as $f) {
    $inputval = $formOrder->get($f->name)->value;
    
    // Attach fields to page.
    $p->set($f->name, $inputval);
    }
    
    $p->set('title', $p->order_number);
    
    $p->save(); // Create the page.
  4. // "new user()" needs to be "new User", because classes do begin with uppercase char
    // Also do you really want to create a new user object for each field?
    $inputfield = $fields->get($field->name)->getInputfield(new user());
    

    Is using the $user variable a valid alternative for a new user object in this context?

    You don't need to get the field every time as you already get it in the loop. Your getting the inputfield without context.

    I think I understand so I modified the code a bit, but this does not solve the problem:

    // Make a form.
    $form = $modules->get('InputfieldForm');
    $form->method = 'post';
    $form->action = './';
    
    // Add the user template's fields to the form.
    $fields = $templates->get("user")->fieldgroup;
    foreach($fields as $field) {
    	// Do not display certain system fields.
    	$skip = array('admin_theme', 'language', 'roles', 'pass');
    	if (in_array($field->name, $skip)) continue;
    
        $inputfield = $field->getInputfield($user);
        $form->add($inputfield);
    }
    
  5. I am building a simple admin module with a custom user registration form. The form displays fields from the user template. In the user template, I have set the 'email' field to required. This is an override, because the field itself is not required. So the field is only required in the context of the user template. However, when creating a new user form with the API, this override seems to be ignored and the email field is not required. Am I missing something? This is my code:

    // Make a form.
    $form = $modules->get('InputfieldForm');
    $form->method = 'post';
    $form->action = './';
    
    // Add the user template's fields to the form.
    $fields = $templates->get("user")->fieldgroup;
    foreach($fields as $field) {
    	// Do not display certain system fields.
    	$skip = array('admin_theme', 'language', 'roles', 'pass');
    	if (in_array($field->name, $skip)) continue;
    
        $inputfield = $fields->get($field->name)->getInputfield(new user());
        $form->add($inputfield);
    }
    
  6. Got it working. Here's my working code in case anybody is interesting (suggestions on improving it are welcome as I'm a ProcessWire newbie):

    $page_id = (int) $input->post->select_product; // page ID
    
    // Set a temporary upload folder where the files are stored during form processing
    // RC: precede temp dir with a period to ensure it remains non-web accessible
    //$upload_path = $config->paths->assets . "files/.temp/";
    $upload_path = "/Applications/MAMP/htdocs/ProcessWire/site/assets/files/.temp/";
    
    // RC: create temp path if it isn't there already
    if(!is_dir($upload_path)) {
        if(!wireMkdir($upload_path)) throw new WireException("No upload path"); 
    }
    
    // show empty form
    if ($page_id) {
        $p = $pages->get($page_id);
        $template = $p->template->name; // this is the template where we will get the fields from
    
        // make a form
        $form = $modules->get('InputfieldForm');
        $form->method = 'post';
        $form->action = './';
        $form->attr("id+name",'aanvraag-form');
    
        // add the page's fields to the form
        $fields = $p->fieldgroup;
        foreach ($fields as $field) {
            $inputfield = $fields->{$field->name}->getInputfield($p);
            $form->append($inputfield);
        }
    
        // add template name field to the form
        $field = $modules->get("InputfieldHidden");
        $field->attr('id', 'Inputfield_template_name');
        $field->attr('name', 'template_name');
        $field->value = $template;
        $form->append($field); // append the field
    
        // add select_product to the form
        $field = $modules->get("InputfieldHidden");
        $field->attr('id', 'select_product');
        $field->attr('name', 'select_product');
        $field->value = $page_id;
        $form->append($field); // append the field
    
        // add a submit button to the form
        $submit = $modules->get('InputfieldSubmit');
        $submit->name = 'save_new_aanvraag';
        $submit->attr("value", "Go");
        $form->append($submit);
    
        // only show the form if it was not just submitted/processed
        if (!$input->post->save_new_aanvraag)
            echo $form->render();
    }
    
    // process the form if it was submitted
    if ($input->post->save_new_aanvraag) {
        
        // new wire upload
        $u = new WireUpload('images');
        $u->setMaxFiles(2);
        $u->setMaxFileSize(200*1024);
        // tell it to rename rather than overwrite existing files
        $u->setOverwrite(false);
        $u->setDestinationPath($upload_path);
        $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png'));
    
        // execute upload and check for errors
        $files = $u->execute();
    
        if(!$u->getErrors()) {
            // now we assume the form has been submitted.
            // tell the form to process input from the post vars.
            $form->processInput($input->post);
    
            // validation
            $email = $form->get("email");
            if ($email && (strpos($email->value,'@hotmail') !== FALSE)) { 
                // attach an error and it will get displayed along the field
                $email->error("Sorry we don't accept hotmail addresses for now.");
            }
    
            // see if any errors occurred
            if (count( $form->getErrors() )) {
                // re-render the form, it will include the error messages
                echo $form->render();
            } else {
                // successful form submission
                $np = new Page(); // create new page object
                $np->template = $form->get("template_name")->value; // set template
                $np->parent = $pages->get('/aanvraag/'); // set the parent
                $np->of(false); // turn off output formatting before setting values
                $np->save();
    
                foreach ($np->fields as $f) {
                    // do not sanitize or set Image and File fields here, because that will happen at the next step which will break if we do not skip images and files here
                    if ($f->type == 'FieldtypeImage' || $f->type == 'FieldtypeFile') continue;
    
                    echo $inputval = $form->get($f->name)->value;
                    // sanitize fields
                    if ($f->type == 'FieldtypePageTitle') {
                        $sanitizer->text($inputval);
                        // also set page name based on title
                        $np->set('name', $sanitizer->pageName($inputval, true));
                    }
                   
                    if ($f->type == 'FieldtypeEmail') $sanitizer->email($inputval);
                    if ($f->type == 'FieldtypeText') $sanitizer->text($inputval);
                    if ($f->type == 'FieldtypeTextarea') $sanitizer->textarea($inputval);
                    if ($f->type == 'FieldtypeInteger') $inputval = (int) $inputval;
    
                    // attach fields to page
                    $np->set($f->name, $inputval);
                }
    
                // add images upload
                foreach($files as $filename) {
                    $np->images = $upload_path . $filename;
                }
    
                $np->save(); //create the page
    
                // remove all tmp files uploaded
                foreach($files as $filename) unlink($upload_path . $filename);
    
                echo "<p>Page saved.</p>";
            }
        }
        else {
            // remove files
            foreach($files as $filename) unlink($upload_path . $filename);
    
            // get the errors
            foreach($u->getErrors() as $error) echo "<p class='error'>$error</p>";
        }
    } else {
        //echo $form->render();
    }
    
    • Like 1
    • Confused 1
  7. I've wasted many hours trying to get file uploads working on my front-end form, trying different ways of doing it by following examples on the forum and finally by stripping my form and adding some debug features. Looks like ProcessWire is not able write to my temp directory. The form below gets its template via POST. The template includes a file upload field called "sm_files". I have manually set the upload directory and even let ProcessWire write that directory itself by deleting the directory. Folder permissions should be in order. Writing a test.txt file to the upload folder works just fine. Running the code below returns this error:

    Unable to move uploaded file to: /Applications/MAMP/htdocs/ProcessWire/site/assets/files/.temp/test.png

    The test.png file that is being copied is already in the assets/files folder. Suggestions are more than welcome at this point...

    $page_id = (int) $input->post->select_product; // page ID
    
    // Set a temporary upload folder where the files are stored during form processing
    // RC: precede temp dir with a period to ensure it remains non-web accessible
    //$upload_path = $config->paths->assets . "files/.temp/";
    $upload_path = "/Applications/MAMP/htdocs/ProcessWire/site/assets/files/.temp/";
    
    // test if the upload folder is writable
    file_put_contents ($upload_path.'/test.txt', 'Hello File');
    
    // RC: create temp path if it isn't there already
    if(!is_dir($upload_path)) {
        if(!wireMkdir($upload_path)) throw new WireException("No upload path"); 
    }
    
    // show empty form
    if ($page_id) {
        $p = $pages->get($page_id);
        $template = $p->template->name; // this is the template where we will get the fields from
    
        // make a form
        $form = $modules->get('InputfieldForm');
        $form->method = 'post';
        $form->action = './';
        $form->attr("id+name",'aanvraag-form');
    
        // add the page's fields to the form
        $fields = $p->fieldgroup;
        foreach ($fields as $field) {
            $inputfield = $fields->{$field->name}->getInputfield($p);
            $form->append($inputfield);
        }
    
        // add select_product to the form
        $field = $modules->get("InputfieldHidden");
        $field->attr('id', 'select_product');
        $field->attr('name', 'select_product');
        $field->value = $page_id;
        $form->append($field); // append the field
    
        // add a submit button to the form
        $submit = $modules->get('InputfieldSubmit');
        $submit->name = 'save_new_aanvraag';
        $submit->attr("value", "Go");
        $form->append($submit);
    
        // only show the form if it was not just submitted/processed
        if (!$input->post->save_new_aanvraag)
            echo $form->render();
    }
    
    // process the form if it was submitted
    if ($input->post->save_new_aanvraag) {
        // now we assume the form has been submitted.
        // tell the form to process input from the post vars.
        $form->processInput($input->post);
        
        // new wire upload
        $u = new WireUpload('sm_files');
        $u->setMaxFiles(2);
        $u->setMaxFileSize(200*1024);
        // tell it to rename rather than overwrite existing files
        $u->setOverwrite(false);
        $u->setDestinationPath($upload_path);
        $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png'));
    
        // execute upload and check for errors
        $files = $u->execute();
    
        if(!$u->getErrors()) {
    
            echo "<p>No errors!</p>";
        }
        else {
            // remove files
            foreach($files as $filename) unlink($upload_path . $filename);
    
            // get the errors
            foreach($u->getErrors() as $error) echo "<p class='error'>$error</p>";
        }
    }
    
  8. So I restructured the code a bit and also added some validation and sanitising, and the part that did not work before ($np->set($f->name, $form->get($f->name)->value);) started working  ^-^

    Did I do the validation and sanitising parts correctly? Or are there more efficient/better ways of doing this? Here's the fully working code:

    $page_id = (int) $input->post->select_product; // page ID
    
    if ($page_id) {
        $p = $pages->get($page_id);
        $template = $p->template->name; // this is the template where we will get the fields from
    
        // make a form
        $form = $modules->get('InputfieldForm');
        $form->method = 'post';
        $form->action = './';
        $form->attr("id+name",'subscribe-form');
    
        // add the page's fields to the form
        $fields = $p->fieldgroup;
        foreach ($fields as $field) {
            $inputfield = $fields->{$field->name}->getInputfield($p);
            $form->append($inputfield);
        }
    
        // add template name field to the form
        $field = $modules->get("InputfieldHidden");
        $field->attr('id', 'Inputfield_template_name');
        $field->attr('name', 'template_name');
        $field->value = $template;
        $form->append($field); // append the field
    
        // add select_product to the form
        $field = $modules->get("InputfieldHidden");
        $field->attr('id', 'select_product');
        $field->attr('name', 'select_product');
        $field->value = 1156;
        $form->append($field); // append the field
    
        // add a submit button to the form
        $submit = $modules->get('InputfieldSubmit');
        $submit->name = 'save_new_aanvraag';
        $submit->attr("value", "Go");
        $form->append($submit);
    
        // only show the form if it was not just submitted/processed
        if (!$input->post->save_new_aanvraag)
            echo $form->render();
    }
    
    // process the form if it was submitted
    if ($input->post->save_new_aanvraag) {
        // now we assume the form has been submitted.
        // tell the form to process input from the post vars.
        $form->processInput($input->post);
    
        // validation
        $email = $form->get("email");
        if ($email && (strpos($email->value,'@hotmail') !== FALSE)) { 
            // attach an error and it will get displayed along the field
            $email->error("Sorry we don't accept hotmail addresses for now.");
        }
    
        // see if any errors occurred
        if (count( $form->getErrors() )) {
            // re-render the form, it will include the error messages
            echo $form->render();
        } else {
            // successful form submission
            $np = new Page(); // create new page object
            $np->template = $form->get("template_name")->value; // set template
            $np->parent = $pages->get('/aanvraag/'); // set the parent
            $np->of(false); // turn off output formatting before setting values
            $np->save();
    
            foreach ($np->fields as $f) {
                $inputval = $form->get($f->name)->value;
                // sanitize fields
                if ($f->type == 'FieldtypePageTitle') {
                    $sanitizer->text($inputval);
                    // also set page name based on title
                    $np->set('name', $sanitizer->pageName($inputval));
                }
                if ($f->type == 'Email') $sanitizer->email($inputval);
                if ($f->type == 'Text') $sanitizer->text($inputval);
                if ($f->type == 'Textarea') $sanitizer->textarea($inputval);
                if ($f->type == 'Integer') $inputval = (int) $inputval;
    
                // attach fields to page
                $np->set($f->name, $inputval);
            }
    
            $np->save(); //create the page
    
            echo "<p>Page saved.</p>";
        }
    } else {
        //echo $form->render();
    }
    
    • Like 2
  9. Yes my template has a title field, in fact it only has 2 fields, 'title' and 'email'. I tried with the basic page template as well, same error. I also tried your suggestion about debugging the line that the error refers to, and it's $form->get($f->name)->value that seems to be the problem. If I replace it with a simple string, the page title is set to the string value instead of the current date/time.

    I did not know about the automatic page name option before now, but I think that's not it. 

    I really do appreciate your help and patience by the way, what a helpful community this is  :)

  10. Sorry about all that - shouldn't try offering advise with browser written code. This works fine for me:

    Are you sure? I copy-pasted your code and I get the same error: "trying to get property of non-object", referring to $np->set($f->name, $form->get($f->name)->value);

    I noticed you added an extra $np->save, which makes sense, I reckon you are supposed to save the new page before added the field values to it. Strange how it is still not working for me, a new page is created with the correct parent and template, but the fields are empty and the page title is a date/time...

  11. I think the building of the form the way you are doing should work, and I think it is, correct? 

    Well it is saving a new page, but it's empty still, no fields. I made the edits you suggested:

    $page_id = (int) $_POST['select_product']; // page ID
    $p = $pages->get($page_id);
    $template = $p->template->name; // this is the template where we will get the fields from
    
    // make a form
    $form = $modules->get('InputfieldForm');
    $form->method = 'post';
    $form->action = './';
    $form->attr("id+name",'subscribe-form');
    
    // add the page's fields to the form
    $fields = $p->getInputfields();
    foreach($fields as $field) {
        $form->append($field);
    }
    
    // add template name field to the form
    $field = $modules->get("InputfieldHidden");
    $field->label = "Template";
    $field->attr('id+name','template_name');
    $field->required = 1;
    $field->value = $template;
    $form->append($field); // append the field
    
    // add a submit button to the form
    $submit = $modules->get('InputfieldSubmit'); 
    $submit->name = 'save_new_aanvraag';
    $submit->attr("value", "Go");
    $form->append($submit); 
    
    // process the form if it was submitted
    if($this->input->post->save_new_aanvraag) {
    	// now we assume the form has been submitted.
        // tell the form to process input from the post vars.
        $form->processInput($this->input->post);
    
        // see if any errors occurred
        if( count( $form->getErrors() )) {
            // re-render the form, it will include the error messages
            echo $form->render();
        } else {
            // successful form submission
            $np = new Page(); // create new page object
       		$np->template = $form->get("template_name")->value; // set template
        	$np->parent = $pages->get('/aanvraag/'); // set the parent
            $np->of(false); // turn off output formatting before setting values
    
            foreach($np->fields as $f) {
                $np->set($f->name, $form->get($f->name)->value);
            }
        	$np->save(); //create the page
    
            echo "<p>Page saved.</p>";
        }
    } else {
        echo $form->render();
    }
    

    When saving the page, I get this error: "Trying to get property of non-object". That refers to line 49. Also, the way you suggested doing this part:

    // add the page's fields to the form
    $fields = $p->getInputfields();
    foreach($fields as $field) {
        $form->append($field);
    }
    

    it's filling out the fields with the values of the $page_id that I'm requesting, but I don't want its values, just its empty fields?

  12. Hi Marc

    Here a few things I see that need fixing:

    First, thank you for your help, much appreciated. I did the changed you mentioned, but it is still not quite working. Here's what I've got right now:

    $page_id = (int) $_POST['select_product']; // page ID
    $p = $pages->get($page_id);
    $template = $p->template->name; // this is the template where we will get the fields from
    
    // make a form
    $form = $modules->get('InputfieldForm');
    $form->method = 'post';
    $form->action = './';
    $form->attr("id+name",'subscribe-form');
    
    // add the page's fields to the form
    $fields = $p->fieldgroup;
    foreach($fields as $field) {
        $inputfield = $fields->get("$field->name")->getInputfield($page);
        $form->append($inputfield);
    }
    
    // add template name field to the form
    $field = $modules->get("InputfieldHidden");
    $field->label = "Template";
    $field->attr('id+name','template_name');
    $field->required = 1;
    $field->value = $template;
    $form->append($field); // append the field
    
    // add a submit button to the form
    $submit = $modules->get('InputfieldSubmit'); 
    $submit->name = 'save_new_aanvraag';
    $submit->attr("value", "Go");
    $form->append($submit); 
    
    // process the form if it was submitted
    if($this->input->post->save_new_aanvraag) {
    	// now we assume the form has been submitted.
        // tell the form to process input from the post vars.
        $form->processInput($this->input->post);
    
        // see if any errors occurred
        if( count( $form->getErrors() )) {
            // re-render the form, it will include the error messages
            echo $form->render();
        } else {
            // successful form submission
            $p = new Page(); // create new page object
       		$p->template = $form->get("template_name")->value; // set template
        	$p->parent = $pages->get('/aanvraag/'); // set the parent
    
            foreach($form as $field) {
                $p->set($field->name, $field->value);
            }
        	$p->save(); //create the page
    
            echo "<p>Page saved.</p>";
        }
    } else {
        echo $form->render();
    }
    

    I renamed $page to $p, and as an addition to your suggestions I also changed this line:

    // add the page's fields to the form
    $fields = $p->fieldgroup;
    

    That is because I need the fields from $p, not $page. However, the fields are not added to $form and so they are not saved. So I'm guessing this part needs to change:

     
    // add the page's fields to the form
    $fields = $p->fieldgroup;
    foreach($fields as $field) {
        $inputfield = $fields->get("$field->name")->getInputfield($p);
        $form->append($inputfield);
    }
    
  13. I am trying to do the following: create a frontend form that generates a new page that has the fields from a template that a specific page uses. I send the page ID to the form and get the correct template and its fields from there. The presentation part of this form works, but as soon as it is trying to save, the $form variable does not contain the fields from the specified template so it saves a new page without any fields. Here's what I've got so far, hopefully anybody can tell me what I'm doing wrong (I've got most of this code from examples found on this forum):

    $page_id = htmlspecialchars($_POST['select_product']); // page ID
    $page = $pages->get($page_id);
    $template = $page->template; // this is the template where we will get the fields from
    
    // make a form
    $form = $modules->get('InputfieldForm');
    $form->method = 'post';
    $form->action = './';
    $form->attr("id+name",'subscribe-form');
    
    // add the page's fields to the form
    $fields = $page->fieldgroup;
    foreach($fields as $field) {
        $inputfield = $fields->get("$field->name")->getInputfield($page);
        $form->append($inputfield);
    }
    
    // add template name field to the form
    $field = $modules->get("InputfieldHidden");
    $field->label = "Template";
    $field->attr('id+name','template_name');
    $field->required = 1;
    $field->value = $template;
    $form->append($field); // append the field
    
    // add a submit button to the form
    $submit = $modules->get('InputfieldSubmit'); 
    $submit->name = 'save_new_aanvraag';
    $submit->attr("value", "Go");
    $form->append($submit); 
    
    // process the form if it was submitted
    if($this->input->post->save_new_aanvraag) {
    	// now we assume the form has been submitted.
        // tell the form to process input from the post vars.
        $form->processInput($this->input->post);
    
        // see if any errors occurred
        if( count( $form->getErrors() )) {
            // re-render the form, it will include the error messages
            echo $form->render();
        } else {
            // successful form submission
            $p = new Page(); // create new page object
       		$p->template = $input->post->template_name; // set template
        	$p->parent = $pages->get('/aanvraag/'); // set the parent
    
            foreach($form as $field) {
                $p->set($field->name, $field->value);
            }
        	$p->save(); //create the page
    
            echo "<p>Page saved.</p>";
        }
    } else {
        echo $form->render();
    }
    
  14. I am trying to do frontend page creation via AJAX but when the form is loaded into an element, things like CKeditor and proper image uploading do not work. It seems javascript should be re-initialized on the elements that got added to the DOM after the initial page has loaded, but I don't know how to do this (if that is even what should be done in the first place)?

    I got it working fine without AJAX, via a regular template. But when I move the code to a file that is called by AJAX, javascript breaks on the form hence things like CKeditor don't work.

    Here's what's in HEAD of the main template:

      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title><?php echo $headline; ?></title>
        <link rel="stylesheet" href="<?php echo $config->urls->templates;?>css/foundation.css" />
        <script src="<?php echo $config->urls->templates;?>js/vendor/modernizr.js"></script>
    
        <!-- Somatonic page edit script -->
        <script>
          <?php
          $jsConfig = $config->js();
          $jsConfig['urls'] = array(
            'root' => $config->urls->root,
            'admin' => $config->urls->admin,
            'modules' => $config->urls->modules,
            'core' => $config->urls->core,
            'files' => $config->urls->files,
            'templates' => $config->urls->templates,
            'adminTemplates' => $config->urls->adminTemplates,
            'adminTemplates' => $config->urls->adminTemplates,
          );
          ?>
          var config = <?php echo json_encode($jsConfig); ?>;
        </script>
        <?php
        //$config->styles->prepend($config->urls->adminTemplates . "styles/main.css?v=2");
        //$config->styles->append($config->urls->adminTemplates . "styles/inputfields.css");
        //$config->styles->append($config->urls->adminTemplates . "styles/ui.css?v=2");
         
        $config->scripts->append($config->urls->JqueryUI . "JqueryUI.js");
        $config->scripts->prepend($config->urls->JqueryCore . "JqueryCore.js");
        $config->scripts->append($config->urls->adminTemplates . "scripts/inputfields.js");
         
        foreach($config->styles->unique() as $file) echo "\n\t<link type='text/css' href='$file' rel='stylesheet' />";
        foreach($config->scripts->unique() as $file) echo "\n\t<script type='text/javascript' src='$file'></script>";
        ?>
        
      </head>
    

    It loads all the necessary script for frontend page creation. And here is the template that does the form processing:

    if ($command == "template_selection") {
    
    	// Selected template ID
    	$id = htmlspecialchars($_POST['template_id']);
    
    	$page = $pages->get($id);
    	$template = $page->template; 
    
    	foreach($template->fields as $field){
    	    echo $field->label . ": ";
    	    //echo $field->type . "<br/>";
    	    echo $page->get($field->name) . "<br/>";
    	}
    
    	// make a form
    	$form = $modules->get('InputfieldForm');
    	$form->method = 'post';
    	$form->action = './';
    
    	// add the page's fields to the form
    	$form->add($page->getInputfields()); 
    
    	// add a submit button to the form
    	$submit = $modules->get('InputfieldSubmit'); 
    	$submit->name = 'submit';
    	$form->add($submit); 
    
    	// process the form if it was submitted
    	if($input->post->submit) {
    	    $form->processInput($input->post);
    	    $page->save();
    	    echo '<p>saved</p>';
    	}
    
    	// render the form output
    	echo $form->render(); 
    
    	die;
    }
    

    This template works properly when not called by AJAX, but, again, when I call it with an AJAX request, the javascripts don't work. Is there any way I can make this work?

  15. I assume you have a special template for /functions/ and you have set up your config.php to autp-append _main.php. You can exclude templates from auto-appending and auto-prepending in the “files” tab of the template settings. If autp-append is active, there will be a checkbox called “Disable automatic append of file: _main.php”.

    Regardless, it’s always a good idea to die() as soon as possible. In your case, I would advocate putting a die() at the end of each if ($command ...) block, unless there’s something you need to do afterwards. Probably a good idea to use a switch, too, then.

    Your assumptions are correct, and so is your answer. Problem solved  :)

  16. I'm using the delayed output template structure the way Ryan recommends. That means I have a _main.php file with all of my HTML markup and each page has a template that outputs to a variable that is echo'd in _main.php. Now I doing some very basic ajax testing, to figure out how this fits into the Processwire workflow. I'm already running into an issue: the file that handles the ajax request is not only outputting the data I'm requesting, but it's also outputting the complete _main.php markup into the ajax container where only the result of my ajax request should be going. Here what I've got:

    _main.php (greatly simplified)

    <html>
    <body>
    
    <!-- template output goes here -->
    <p><?php echo $bodycopy; ?></p>
    
    <p>This line will unfortunately also be output to the ajax container</p>
    
    </body>
    </html>
    

    ajax_test.php template

    <?php
    ob_start();
    ?>
    
    <?php 
    
    ?>
    <form method="post" enctype="multipart/form-data">
    	<div id="enter_template_container">
    		<input type="text" name="select_template" id="select_template"/>
    	</div>
    	<p>
    		<a href="#" class="button" id="button_select_template">Search</a>
    	</p>
    </form>
    
    <div id="placeholder_template"></div>
    <?php
    $bodycopy .= ob_get_clean();
    

    front.js

    /**
    	Simple ajax test: search templates
    **/
    	
    	var show_template = function(template) {
    
    		// Ajax
    		data = {
    			template_search: template,
    			command: 'show_template' // add a unique command value to every ajax call so we can identify what function to call in function.php
    		};
    		  
    		$.post("../functions/", data, function (response) {
    			// Add form
    			$('#placeholder_template').html(response);
    		}).fail(function() {
             
                // Just in case posting your form failed
                alert( "Posting failed." );
                 
            });
    		
    	}
    
    	$('#button_select_template').on('click', function() {
    		var template = $('#select_template').val();
    
    	    show_template(template);
    	});
    

    functions.php template (yes I have a Wordpress background ;-))

    /**
    	Simple ajax test: search templates
    **/
    
    if ($command == "show_template") {
    
    	$template = $templates->get(htmlspecialchars($_POST['template_search']));
    
    	foreach($template->fields as $field){
    	    echo $field->name . "<br/>";
    	}
    
    }
    

    Functions.php does the ajax output which is placed in a div with "placeholder_template" ID in a template called ajax_test.php. The problem is that all the contents of _main.php are also put into that div, not just the output generated by functions.php. What is the best way to counter this behavior? Is it a good idea to add "die;" at the end of the functions.php template for instance? What's the best way to deal with this?

  17. I unfortunately don't have an answer to your specific question (I'm rather new to ProcessWire myself), but have you seen the "Fredi" module: http://modules.processwire.com/modules/fredi/

    It will handle the front-end editing for you.

    Yeah I looked at that, it's a nice solution but not quite what I had in mind. Thanks for the suggestion though.

    Take a look at Soma's gist.

    It loops through all the fields of your page and displays a form.

    Then on Submit of the form it again loops through each field and saves the value.

    It also includes all styles and scripts that you need for your form to work on the frontend.

    This is working great for my frontend form.

    If you need help implementing it, let us know.

    Looks like there's a lot of cool stuff to find down there, thanks for the link!

    • Like 1
  18. I'm just getting started and have looked for ways to update a page including its fields via a front-end form, but I'm missing a few pieces of the puzzle. Here's what I have, mostly borrowed from posts on this forum:

    $page = $pages->get('1015'); // get some page
    
    // make a form
    $form = $modules->get('InputfieldForm');
    $form->method = 'post';
    $form->action = './';
    
    // add the page's fields to the form
    $form->add($page->getInputfields()); 
    
    // add a submit button to the form
    $submit = $modules->get('InputfieldSubmit'); 
    $submit->name = 'submit';
    $form->add($submit); 
    
    // process the form if it was submitted
    if($input->post->submit) {
        $form->processInput($input->post);
        $page->save();
        echo '<p>saved</p>';
    }
    
    // render the form output
    echo $form->render(); 

    I think the problem is that I have to loop through the form inputs and save them individually? How would I do this?

    • Like 1
×
×
  • Create New...