I build a registration form with CodeIgniter. I have a question.
As an example, one of the field from my form
<input type="text" name="username">
But in database, I will use another name instead of username such as user. How do I do it?
So, on the form it will be username, but in the database its name will be user.
Will clear the whole flow (comments may help to understand better)
View:
<form action="/user/register" method="post">
<input name="username" type="text" />
<input name="pass" type="password" />
<input name="age" type="text" />
<input type="submit" />
</form>
Controller:
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function register()
{
if($this->input->server('REQUEST_METHOD') == 'POST')
{
// if validation success
if($validation)
{
/*
Mapping form fields with DB fields
Assuming below as fields in DB
user, password, age
*/
$data['user'] = $this->input->post('username');
$data['password'] = $this->input->post('pass');
$data['age'] = $this->input->post('age');
// Add user
$this->user_mode->add_user($data);
}
}
}
}
Model:
<?php
class User_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->db = $this->load->database('default',true);
}
public function add_user($data)
{
$this->db->insert('users', $data);
}
}
To understand please read the Active Record section of CI User manual.
Related
I have following model:
class HomePageModel
{
public User user { get; set; }
public ResultHistory resultHistory { get; set; }
public Option option { get; set; }
public HomePageModel()
{
}
}
Code from controller when passing it into view:
[FacebookAuthorize]
public async Task<ActionResult> Index(Context context)
{
ViewBag.AppUrl = GlobalFacebookConfiguration.Configuration.AppUrl;
if (ModelState.IsValid)
{
var user = await context.Client.GetCurrentUserAsync<MyAppUser>();
var option = new Option();
//CODE for reading user from db, simpified
Users dbUser = db.Get(context);
var resultHistory = new ResultHistory(dbUser.NSPGW, dbUser.NSPGL,
dbUser.NMPGW,dbUser.NMPGL,dbUser.NDPGW, dbUser.NDPGL);
HomepageModel homepageModel = new HomepageModel();
homepageModel.option = option;
homepageModel.resultHistory = resultHistory;
homepageModel.user = user;
return View(homepageModel);
}
}
Code from controller
#using (Html.BeginForm("Start", "Home", FormMethod.Post, new { id="opcijeForm"}))
{
<div class="row">
<div class="col-md-4">
<div class="radio">
<label>
<input type="radio" name="radio" value="sp" />SP
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="radio" value="mp" />MP
</label>
</div>
<div>
<input type="submit" value="start" />
</div>
</div>
<div class="col-md-8">
<div id="spoption">
#Html.DropDownListFor(m => m.option.sl, Model.option.slSelectList)
<label style="padding-left:10px">
<input type="checkbox" id="bb" /> BB
</label>
#Html.DropDownListFor(m => m.option.swt, Model.option.swtSelectList, new {id="bbdd" })
<label style="padding-left:10px">
<input type="checkbox" id="ziv" /> ziv
</label>
#* #Html.DropDownListFor(m => m.gameOption.sln, Model.option.slnSelectList, new { id="zivdd"})*#
</div>
<div id="mpoption">
<label>Numer of oppointment</label>
#Html.DropDownListFor(m=>m.option.spn, Model.option.spnSelectList)
#Html.DropDownListFor(m=>m.option.smv, Model.option.smvSelectList)
</div>
</div>
</div>
}
and receiving model on post
[FacebookAuthorize]
[HttpPost]
public ActionResult Start(HomepageModel model)
{
//Some code
//here is for example model.option null
}
When I submit form with above model, in my controller action where I receive same model, all it's properties are null.Each class that is within HomePage has only string and int as properties. If I move something, for example from class Option and put it in HomePageModel direct, then properties I have moved are not null. Is there a way to post model as above, or should I just copy properties from these three class into HomePageModel class?
[EDIT]
It is because of meta-data FacebookAuthorize, when I remove it everything is working
MVC app facebook passing object from view to controller at submit
I am devoloping a web application using J2EE and Spring Roo as framework.
I want to create a form with two submit buttons:
One for save and continue
Another for save and finish
<form action="mycontroller" method="post">
<input type="submit" value="Save and continue"/>
<input type="submit" value="Save and finish"/>
</form>
So I can choose to either store the data in the database and add more entries or to store the data and finish the process.
How can I check what submit button was clicked in the method of the controller that processes the action?
public class MyController {
void actionMethod(...) {
// check which submit was clicked
}
}
You should add a name field to both buttons:
<input type="submit" name="button" value="Save and continue"/>
<input type="submit" name="button" value="Save and finish"/>
Once in the controller, you can recover the element by this name field and check its value field:
String field = request.getParameter("button");
if ("Save and continue".equals(button)){
// Do stuff
}
else if ("Save and finish".equals(button)){
// Do a different stuff
}
else {
// None of them were pressed
}
Or also you can use a different name value for both buttons:
<input type="submit" name="button1" value="Save and continue"/>
<input type="submit" name="button2" value="Save and finish"/>
In your controller:
String button1 = request.getParameter("button1");
String button2 = request.getParameter("button2");
if (button1 != null){
// Do stuff
}
else if (button2 != null){
// Do a different stuff
}
else {
// None of them were pressed
}
Second solution is preferred because it doesn't depend on the value of the elements
To reduce if-else if you can, and benefit from Spring framework to handle these mapping, try the following solution (if you don't have many meta parameters to send in the form):
<form action="AddToCartListController" method="post">
<input type="submit" value="Save and continue"/>
</form>
<form action="CommitCartListController" method="post">
<input type="submit" value="Save and finish"/>
</form>
...
public class CartListController {
void AddToCartListController(...) {
// business code
}
void CommitCartListController(...) {
// business code
}
}
// ... or ...
public class AddToCartListController {
void actionMethod(...) {
// business code
}
}
public class CommitCartListController {
void actionMethod(...) {
// business code
}
}
and define a proper mapping in Spring configuration.
I wana create a front-end joomla component and this is my first experience.
here is important things:
1-component/controller.php
class TestController extends JControllerLegacy
{
public function display($cachable = false, $urlparams = false)
{
$view= JFactory::getApplication()->input->getCmd('view','items');
JFactory::getApplication()->input->set('view', $view);
parent::display($cachable, $urlparams);
}
}
2: com_test/model/items.php
<?php
defined('_JEXEC') or die();
jimport( 'joomla.application.component.modellist' );
class TestModelItems extends JModelList
{
public function __construct($config = array())
{
if (empty($config['filter_fields']))
$config['filter_fields'] = array('id', 'title', 'catid');
parent::__construct($config);
}
function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(...)
return $query;
}
}
I can print the query result on default.php on view folder!
but I wana another thing.
I have a form like this in the front page of my site in a custom module:
<form action="" method="post">
<input type="text" name="wordsearch" value="search">
.
.
<input type="submit" />
</form>
Now!
I do not know how can I send this form (with post method) to getListQuery() function in model folder...how can do it?
i wana when sb click submit form, the component filter query sql according to values of form and then show new result to user!
i googled for hourse but no chance to solve. thanks for your help.
You can submit Form from module to component as follows.
Suppose your component name is com_helloworld The in your module form should have the following things.
<form action="" method="post">
<input type="text" name="wordsearch" value="search">
.
.
<input type="hidden" name="option" value="com_helloworld" />
<input type="hidden" name="view" value="yourview" />
<input type="hidden" name="task" value="my_controller_fun" />
<input type="hidden" value="your_controller_file_name" name="controller">
<input type="submit" />
</form>
In this example your controller file should have my_controller_fun method from controller to model you can use regular method. This methods will get all the form data in your controller , then you can pass that to model.
Detailed :
In your controller file.
function my_controller_fun(){
$post_array = $_POST;
$model = $this->getModel('Profile', 'UsersModel');//example for including profile model you can specify your model file name
$model->function_inyourmodel($post_array);//this function should be in model
}
Hope its help..
I'm calling a REST service developed in serviceStack, I'm using angularJs as a client but my problem is that for some reason I can't bind my json model with my requestDTO.
my angularJs code:
I have a AngularJs Service
angular.module('mseApp.services', ['ngResource']).
factory('loginService',
function ($resource) {
return $resource('/Api/User/login', '',
{
query: {
method: 'POST',
params:{ }
}
});
});
controller:
function loginCtrl($scope, loginService) {
$scope.submit = function () {
var user = loginService.query({loginRequest:$scope.loginRequest});
};
}
View:
<div>
<div ng-model="loginRequest">
<form ng-submit="submit()" ng-controller="loginCtrl">
<input id="username" ng-model="loginRequest.Username" type="text" name="text" />
<input id="password" ng-model="loginRequest.Password" type="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<span ng-model="Username"></span>
</form>
</div>
</div>
on the dot net side
my DTO
public class LoginRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
public UserResponse Post(LoginRequest loginRequest)
{
}
everything if fine the only problem is that LoginRequest is null on my service method.
Any ideas???
Just send
query($scope.loginRequest)
instead of
query({loginRequest:$scope.loginRequest})
that will solve your issue.
You can also utilize the $promise object of your query to defer processing of your binding to $scope
function loginCtrl($scope, loginService) {
$scope.submit = function () {
var user = loginService.query.$promise.then(function (promise) {
$scope.userResponse = promise.d;
});
};
}
then bind to (assuming your Username is at UserResponse.Username) like this
<span ng-model="UserResponse.Username"></span>
Routes.php
Route::get("/", "MasterController#home");
Route::get("add/a/category", "MasterController#add_a_category");
Route::post("add/a/category", "MasterController#add_a_category_post");
MasterController.php
<?php
class MasterController extends BaseController {
public function add_a_category()
{
// titling
$data['title'] = "Price Soldier - Add a Category";
// viewing
return View::make("pages.add_a_category", $data);
}
public function add_a_category_post()
{
// titling
$data['title'] = "Price Soldier - Add a Category";
// controlling
CategoryModel::add();
}
}
?>
CategoryModel.php
<?php
class CategoryModel {
protected $fillable = array("category_name", "updated_at", "created_at");
public static function add()
{
// Validation
$rules = array("category_name" => "required|min:3|max:20");
$validation = Validator::make(Input::except("submit"), $rules);
if ( $validation->fails() )
{
return Redirect::to("add/a/category")->withErrors($validation);
}
else
{
$result = DB::table("categories")
->insert(
array(Input::except("submit"))
);
return Redirect::to("add/a/category");
}
}
}
?>
add_a_category.blade.php
#extends("layouts.master")
#section("content")
<h1>Add a Category</h1>
<form action="{{ URL::to("/") }}/add/a/category" method="POST">
<label for="category_name">Category Name</label>
<input type="text" name="category_name" value="">
{{ $errors->first("email", "<span class='error'>:error</span>") }}
<div style="clear: both;"></div>
<div class="submit">
<input type="submit" name="submit" value="Add">
</div>
</form>
#stop
Now when the validation passes or fails, I'm redirecting to add/a/category route. But I don't see anyhting except a blank page while the category_name field is getting added to the database.
You need to return the response of the model's add method to the Controller's response. Instead of:
ControllerModel::add():
Try
return ControllerModel:add();