I have form action for search service
<div class="search">
<form action="{{ path('app_song_search') }}" metod="POST" class="form-search">
<input type="text" name="search" class="input-medium search-query" />
<input type="submit" class="btn" value="Search"/>
</form>
</div>
DB - Mongo, search for field $name in document song
I create service
class Search {
protected $repository;
public function __construct(SongRepository $repository)
{
$this->repository = $repository;
}
public function search($string)
{
return $this->repository->getIdArrayByName($string);
}
}
and I have action
public function searchAction(Request $request)
{
$searcher = $this->get('searcher');
$result = $searcher->search($request->get('search'));
$repository = $this->get('doctrine_mongodb')->getRepository('AppBundle:Song');
$query = $repository->createQueryBuilder('m')
->where('m.id IN (:ids)')
->setParameter('ids', $result)
->getQuery();
$song = $query->getResult();
if (!$song){
throw $this->createNotFoundException('Opss, dont search');
}
return $this->render('AppBundle::serchSong.html.twig', array('song' => $song));
}
and songRepository
function getIdArrayByName($name)
{
return $this->getDocumentManager()->createQueryBuilder($this->findByName($name))
->setQueryArray('name', '%'.$name.'%');
}
Notice: Undefined offset: 0. what am I doing wrong?
Related
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.
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();
I am new to codeigniter trying out some simple pages. I have successfully connected to the database for inserting and updating. But now I want to populate the fields from the database for updating. That is when the user selects the name from the dropdown the corresponding values should appear in the other fields so that the user can update easily.
I have worked on this to do without ajax or jquery. It worked for me but with some warning message - Use of undefined constant.
I am giving by mvc. Help me clear this.
Controller:
public function update()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Update Type';
$data['product_type'] = $this->editType_model->get_product_type();
$data['row'] = $this->editType_model->get_row();
$this->form_validation->set_rules('productype', 'productype', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('cm/update', $data);
$this->load->view('templates/footer');
}
else
{
$data['title']= 'Updation';
$data['message']= 'Updation succeeded';
$this->editType_model->update_news();
$this->load->view('cm/success', $data);
}
}
Model:
public function get_product_type() {
$data = array();
$this->db->order_by("product_type_name", "desc");
$query = $this->db->get('product_type');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function get_row() {
$data = array();
$id= $_POST[product_type_id];
$query = $this->db->get_where('product_type', array('product_type_id' => $id));
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
public function update_news()
{
$this->load->helper('date');
$Product = $this->input->post('product_type_id');
$data = array(
'product_type_name'=>($_POST['productype']),
'rank'=>($_POST['rank'])
);
$this->db->where('product_type_id',$Product);
return $this->db->update('product_type', $data);
}
View:
<?php $productType = 0;
if(isset($_POST['product_type_id'])){
$productType = $_POST['product_type_id'];
}?>
<div id="Content"><div>
<form action="" method="post" name="f1">
<table ><tr><td>Select Product Type Name:</td>
<td><Select id="product_type_id" name="product_type_id" onChange="document.f1.submit()">
<option value="0">--SELECT</option>
<?php if (count($product_type)) {
foreach ($product_type as $list) { ?>
<option value="<?php echo $list['product_type_id']; ?>"
<?php if($productType==$list['product_type_id']) echo "Selected" ?> >
<?php echo $list['product_type_name']; ?></option>
<?php }} ?></Select></td></tr></table></form>
<?php if($productType){
if (count($row)) {
foreach ($row as $faProductType) { ?>
<div > <form action="" method="post" class="form-Fields" >
<input type="hidden" name="product_type_id" id="product_type_id" value="<?php echo $faProductType['product_type_id']; ?>" >
<table border="0" cellpadding="8" cellspacing="0" >
<tr><td>Product Type <font color="red">*</font></td><td style="width: 10px;"> : </td>
<td><input name="productype" type="text" value="<?php echo $faProductType['product_type_name']; ?>" style=" width:300px;" /></td>
<td><span class="err" id="productTypeDesc1Err"></span></td></tr>
<tr><td >Rank</td><td style="width:10px;"> : </td>
<td ><input type="text" name="rank" id="rank" value="<?php echo $faProductType['rank']; ?>" size="39" /> <span class="err" id="productTypeNameErr"></span></td>
<td ></td></tr><tr><td></td><Td colspan="2" align="center">
<input type="submit" value="Update" class="buttonimg" name='cm/editType/update' style="width:100px"
onClick="return validEditProductType();">
</Td><td></td></tr></table></form></div></div></div>
<?php }}} ?>
you can use Ajax for this purpose
onchange of your select box fill a div with form.
Controller Method
function getUserdata(){
$where['username'] = $this->input->post('username');
$this->load->model('users_model');
$data['user'] = $this->users_model->getUser($where);
$this->load->view('userform',$data);
}
And you model method
function getUser($where){
return $this->db->where($where)->get('usertable')->row()
}
Ajax
$(function(){
$('#selecttion').change(function(){
var username = $(this).val();
$.ajax({
url : '<?php 'echo url to controller method'?>',
type : 'POST' ,
data : 'username='+username,
success : function(data){
$('#dividtofill').html(data);
}
});
});
})
EDIT :
calling ajax is easy
for this include jquery library in your header.
Here is your dropdown
Note : put the above ajax code in your head section in script
<select name="user" id="selecttion">
<option value="John">John</option>
<option value="Sam">Sam</option>
<option value="David">David</option>
</select>
Now when this dropdown value is changed the ajax function defined above will be called.
I have finally cleared the error. I have done this by a simple if isset loop.
Now my get_row() in my model looks like this.
public function get_row() {
$data = array();
$id= 0;
if(isset($_POST['product_type_id'])){
$id = $_POST['product_type_id'];
}
$query = $this->db->get_where('product_type', array('product_type_id' => $id));
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
I just started using CodeIgniter today, and was following the tutorial at the CI website.
When I got to the final step for creating a new news item, I ran into an issue with the form submit. I would expect the URL to be jonhopkins.net/news/create when I press the form's submit button, but it is going to http://jonhopkins.net/news/jonhopkins.net/news/create instead, which is clearly very wrong, and I have no idea why this is happening. Does anyone know how to fix this?
Everything else on my site (the Pages part of the tutorial) works perfectly. This is the only thing that is breaking. All of my code is exactly as it appears in the tutorial, except for a change to what happens when an item is successfully submitted to the database, which currently is never happening.
News Controller
public function create() {
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
} else {
//$success will contain the slug of the created item, or FALSE if database insertion failed
$success = $this->news_model->set_news();
if ($success) {
$this->_doView($success);
} else {
echo "Something went wrong while trying to submit the news item.";
}
}
}
public function view($slug) {
$this->_doView($slug);
}
private function _doView($slug) {
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item'])) {
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
Create View
<h2>Create a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create') ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
And the resulting HTML...
<form action="jonhopkins.net/news/create" method="post" accept-charset="utf-8">
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
News Model I don't think it's ever getting here, but just in case
public function set_news() {
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text'),
'date' => date("Y-m-d H:i:s")
);
if ($this->db->insert('news', $data)) {
return $slug;
} else {
return FALSE;
}
}
Routes
$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
The form_open('news/create') method uses the $CI->Config->site_url() method which, in turn, uses the base_url from your config file.
Make sure your $config['base_url'] is set to your domain (with trailing slash) in the application/config/config.php file.
$config['base_url'] = 'http://jonhopkins.net/';