Kohana 3.3 & Kostache - Unable to display ORM Validation Errors in Form - kohana-3

I'm trying to create a user registration page for my site using Kohana 3.3 and Kostache as my template system.
I'm having a hard time getting to work the Form Validation to display validation errors on the same page. Right now when i click on the form submit button and sending all empty values in the form (username, email and password) all i get is the form to refresh, when I should be getting validation errors such as username is empty, email is empty etc (im using Model_Auth_User).
I have no clue what am I doing wrong.
Model:
class Model_User extends Model_Auth_User
{
public function rules()
{
return array(
'username' => array(
array('not_empty'),
array('alpha_dash'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 20)),
array(array($this, 'unique'), array('username', ':value')),
),
'email' => array(
array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 127)),
array('email'),
),
);
}
}
Controller:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_User extends Controller {
public function action_index()
{
}
public function action_login()
{
$renderer = Kostache_Layout::factory();
$this->response->body($renderer->render(new View_FrontEnd_User, 'frontend/login'));
}
public function action_signup()
{
$renderer = Kostache_Layout::factory();
$this->response->body($renderer->render(new View_FrontEnd_User, 'frontend/signup'));
}
public function action_createuser()
{
$signupView = new View_FrontEnd_User();
try {
$user = ORM::factory('User');
$user->username = $this->request->post('username');
$user->password = $this->request->post('password');
$user->email = $this->request->post('email');
$user->save();
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors();
$signupView->errors = $errors;
}
$renderer = Kostache_Layout::factory();
$this->response->body($renderer->render(new View_FrontEnd_User, 'frontend/signup'));
}
}
View
<?php defined('SYSPATH') or die('No direct script access.');
class View_FrontEnd_User extends View_Main
{
public $errors = array();
}
signup.mustache
<p>
<form action="user/createuser" method="post">
<fieldset style="width: 20em;">
<legend>User Registration</legend>
<label>Enter your username</label>
<input type="text" name="username" />
    <label for="username" class="error">
{{#errors}}{{username}}{{/errors}}
</label>
<label>Enter your password</label>
<input type="password" name="password" />
<label for="password" class="error">
{{#errors}}{{password}}{{/errors}}
</label>
<label>Email</label>
<input type="text" name="email" />
<input type="submit" value="Submit" class="nice blue radius button" />
</fieldset>
</form>
{{#errors}}{{.}}{{/errors}}
</p>
Thanks a lot in advance for any pointers you can give me.
I've spent hours on this and still can't get it working :(

Change
$this->response->body($renderer->render(new View_FrontEnd_User, 'frontend/signup'));
to
$this->response->body($renderer->render($signupView, 'frontend/signup'));

Related

I'm using modal and I just want to use dropdown select method in laravel 7

This is my code in my Controller but I already try this method without using modal and it works.
public function create()
{
$department = Department::pluck('department', 'id');
return view('positions.create',compact('department'));
}
public function store()
{
$validator = Validator::make(Request::all(), [
'dep_id' => 'required',
'position' => 'required',
],
[
'dep_id.required' => 'Department Required',
'position.required' => 'Position Required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
Position::create(Request::all());
Session::flash('message', 'Position Created Successfully');
return redirect()->back();
}
This is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Position extends Model
{
protected $guarded = [];
public function department(){
return $this->belongsTo('App\Department','dep_id','id');
}
}
This is my code in my create modal form, but I get this error:
Undefined variable: department
I want to use the modal form for my project.
<div class="modal-body">
#include('alert')
{!! Form::open(['method'=>'POST','action'=>'PositionController#store']) !!}
<div class="form-group">
<label>Department</label>
{!! Form::select('dep_id',$department,null,['class'=>'form-control','placeholder'=>'PLEASE SELECT']) !!}
</div>
<div class="form-group">
<label>Position</label>
{!! Form::text('position',null,['class'=>'form-control']) !!}
</div>
<div class="text-end">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
{!! Form::close() !!}
</div>

How to get form data as a object in reactjs

I'm trying to create a google form with react,
I have been creating all the questions as a components
if (props.type == "text") {
return (
<div className="box">
<h3 className="">{props.qustion}</h3>
<input className="short-text" placeholder="Your answer" id={"text"+props.id} name={"q"+props.id} type="text" onChange={updateField}/>
</div>
)
}
else if (props.type == "choice") {
return (
<div className="box">
<h3 className="">{props.qustion}{props.requre? <label className="requir">*</label>:""}</h3>
{props.answer.map(ans=>(
<div key={ans}>
<input className="radio" type="radio" id={ans} name={"radio"+props.id} value={ans} required={props.requre} onChange={updateField}/>
<label htmlFor={ans}>{ans}</label>
</div>
))
}
</div>
)
and I have been creating a form on the app file and put the components inside him,
return (
<div className="App">
<FormTitle/>
<form>
{
error? <h1>the sorce not found</h1>:data.map((item) =>(<Qustion qustion={item.question} type={item.type} requre={item.requre} id={item.id} answer={item.answares} key={item.id} />))
}
<div className="submit-right">
<input className="submit-button" type="submit" value="Submit" />
</div>
</form>
</div>
);
how to get all the form data as an object to create a post request ??
Try this function at start of the file where the form is
const formSubmit = (event) => {
event.preventDefault();
var data = new FormData(event.target);
let formObject = Object.fromEntries(data.entries());
console.log(formObject);
}
and in the form use this onSubmit={formSubmit}
<form onSubmit={formSubmit}>
<any element or components>
</form>
entries is not a function you can just reach it
const formSubmit = (event) => {
event.preventDefault();
var data = new FormData(event.target);
let formObject = Object.fromEntries(data.entries);
console.log(formObject);
}

Force preact-router to reload a page completely

I have a page that contains a link to a secondary page that creates a record. Here is the problem I'm running into: If I fill out the fields on the secondary page, and return back to create another item, the previous data is still inside my text boxes.
I don't know if this is just how preact works. I thought that by calling route it would unmount the component, thus clearing state. I even tried adding unique keys to my routes (which I heard forces them to unmount).
I really am at wits end.
app.jsx
const App = () => (
<div>
<Header/>
<Router history={createHashHistory()}>
<Home path="/" />
<DisplayUsers key="displayUsers" path="/display-users"/>
<CreateUser key="createUser" path="/create-user"/>
</Router>
</div>
);
create-item.jsx
import { h, Component } from "preact";
import { route } from 'preact-router';
import { $post } from "app/services/ajax.jsx";
import Section from "app/components/section/section.jsx";
import UserList from "app/components/user-list/user-list.jsx";
class CreateUser extends Component {
constructor(props) {
super(props);
this.state = {
userName: "",
route: ""
};
}
handleSubmit = (event) => {
event.preventDefault();
$post("/api/users", this.state, () =>
{
route('/display-users');
}
);
}
handleChange = (event) => {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
return (
<Section title="New User">
<form onSubmit={this.handleSubmit}>
<div className="mat-field">
<label
htmlFor="userName"
className="mat-field__label">
User Name:
</label>
<input
type="text"
id="userName"
name="userName"
className="mat-field__input"
autoComplete="off"
autoFocus="autoFocus"
maxlength="30"
required
onChange={this.handleChange}/>
</div>
<div className="mat-field">
<label
htmlFor="route"
className="mat-field__label">
Route To:
</label>
<UserList
name="route"
onChange={this.handleChange}/>
</div>
{/* Buttons */ }
<div>
<input
type="submit"
value="Create"
className="mat-button mat-button--secondary mat-button--raised"/>
<a
href="/display-users"
className="mat-button">Cancel</a>
</div>
</form>
</Section>
);
}
}
export default CreateUser;

How to pass csrf token to an upload component from antd?

In a form when passing csrf tokens I use a hidden input to pass the value a long.
<Form method="post" action="/account/user" onSubmit={this.onSubmit}>
<Input name="_csrf" type="hidden" value={this.state.session.csrfToken} onChange={()=>{}}/>
<FormGroup row>
<Label sm={2}>Name:</Label>
<Col sm={10} md={8}>
<Input name="name" value={this.state.name} onChange={this.handleChange}/>
</Col>
</FormGroup>
</Form>
How do you do that when you have a component like this? It's the upload component from antd.
render() {
const props = {
name: 'file',
action: '//localhost/file/upload',
onChange(info) {
}
};
return (
<Dragger {...props}>
// drag and drop area
</Dragger>
)
}
Ended up being a prop that was available called headers that I could include. Hope that helps someone else along the way.
render() {
const props = {
name: 'file',
action: '//localhost/file/upload',
headers: {
'X-CSRF-Token': 'somelongtokenstring'
}
onChange(info) {
}
};
return (
<Dragger {...props}>
// drag and drop area
</Dragger>
)
}

How to Localize Custom Module Content in Orchard CMS?

I had made some modules in my Orchard site using MVC 3 and EFW .I had also made contents using Orchard Cms like I made some static pages using CMS . But my module has dynamic data which user can add and change them using site admin area.But my question is that I had to localize my app but how ? I made enable Culture picker module and added po files of my desire language and added translations of every content of my site but when I change culture only my CMS content changes.my custom module which I made using MVC 3 and EntityFrameWork does not have any offect of site Culture how to localize my custom module contents ?
public class ContactUsController : Controller
{
DbEntities context = new DbEntities();
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SaveContacts(FormCollection frmData) {
try
{
using (new TransactionScope(TransactionScopeOption.Suppress))
{
if (ModelState.IsValid == true)
{
Imidus_ContactUs ob = new Imidus_ContactUs();
ob.UserName = frmData["UserName"];
ob.Subject = frmData["Subject"];
ob.Message = frmData["Message"];
ob.Email = frmData["Email"];
context.Imidus_ContactUs.Add(ob);
context.SaveChanges();
return RedirectToAction("Success", "ContactUs");
}
}
}
catch (Exception ex) {
throw ex;
}
return View("Index");
}
public ActionResult Success()
{
return View();
}
}
<fieldset class="contact-form">
#using (Html.BeginForm("SaveContacts", "ContactUs", FormMethod.Post, new { id = "frmContact" }))
{
#Html.ValidationSummary(true)
<span class="errormsg"></span>
<label for="cname">
Name</label>
<div class="editor-field">
<input id="cname" name="UserName" minlength="2" type="text" required />
</div>
<div class="editor-label">
<label for="cemail">
E-Mail</label>
</div>
<div class="editor-field">
<input id="cemail" type="email" name="Email" required />
#* #Html.EditorFor(model => model.Email, new { Class = "input-xlarge" })
*#
</div>
<div class="editor-label">
<label for="csubject">
Subject</label>
</div>
<div class="editor-field">
<input id="csubject" name="Subject" minlength="2" type="text" required />
#* #Html.EditorFor(model => model.Subject, new { Class = "input-xlarge" })
#Html.ValidationMessageFor(model => model.Subject)*#
</div>
<div class="editor-label">
<label for="cMessage">
Message</label>
</div>
<div class="editor-field">
<input id="cMessage" name="Message" minlength="15" type="text" required />
#* #Html.TextAreaFor(model => model.Message)
#Html.ValidationMessageFor(model => model.Message)*#
</div>
<p>
<input type="submit" value="Submit" class="btn btn-primary block my-btn" />
</p>
}
</fieldset>

Resources