Laravel: Unable to redirect to get Route - redirect

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();

Related

Symfony mongo. how search document for name?

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?

Laravel 4 RESTful API with Angular.js

I have a RESTful API based application with Laravel 4 and Angular.js.
The application's CRUD processes are handled by angularjs $http service.
The Backend Side (Laravel 4):
Routing : app/routes.php
//.....
Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
{
//....
Route::resource('pages', 'PagesController');
//....
});
//.....
Controller : app/controllers/api/PageController.php
<?php
//.....
class PagesController extends BaseController {
//......
public function update($id) {
$page = Page::find($id);
if ( Request::get('title') )
{
$page->title = Request::get('title');
}
if ( Request::get('slug') )
{
$page->slug = Request::get('slug');
}
$page->save();
return Response::json(array(
'error' => false,
'message' => 'Page Updated'),
200
);
}
//......
}
Calling : cURL
This update function can be accessed using cURL method also.
curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/laravel/index.php/api/v1/pages/2
Front-end : HTML
<!-- Top Code -->
<!-- From to Add/Edit Pages -->
<form class="form-horizontal" role="form" ng-show="edit" ng-submit="updatePage(entry)">
<!-- Page Title -->
<div class="form-group">
<label class="col-lg-2 control-label">Page Title</label>
<div class="col-lg-4">
<input type="text" class="form-control" value="{{entry.title}}" ng-model="entry.title">
</div>
</div>
<!-- Slug -->
<div class="form-group">
<label class="col-lg-2 control-label">Slug</label>
<div class="col-lg-4">
<input type="text" class="form-control" value="{{entry.slug}}" ng-model="entry.slug">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
<!-- Bottom Code -->
Client-side : angularjs
// ......
function pageCtrl($scope, $http, Data) {
//.........
$scope.updatePage = function(entry) {
$http({method: 'PUT', url: Data.root_path + 'api/v1/pages/'+id}).
success(function(data, status, headers, config) {
//
}).
error(function(data, status, headers, config) {
//
});
}
//.........
}
Question:
How can I pass my form data(more than one values) to the $http.put request
here ?
How can I access the PUT request data in Laravel 4 Controller ? Can
I use Input::get() ?
Need some update in your html to get page id to update. Add the following html inside form.
<input type="hidden" ng-model="entry.id" value="entry.id"/>
Then change angular script to,
$scope.updatePage = function(entry) {
$http.put(Data.root_path + 'api/v1/pages/' + entry.id, entry)
.success(function(data, status, headers, config) {
//
})
.error(function(data, status, headers, config) {
//
});
}
And in your Laravel Controller,
public function update($id) {
$page = Page::find($id);
$input = $input = Input::all();
if ( $input['title'] )
{
$page->title = $input['title'];
}
if ( $input['slug'] )
{
$page->slug = $input['slug'];
}
$page->save();
return Response::json(array(
'error' => false,
'message' => 'Page Updated'),
200
);
}

dynamically load form in codeigniter

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;
}

CodeIgniter incorrect URL when submitting form

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/';

Magento Admin form redirects to dashboard on ?post?

Magento 1.7.0.2:
I'm trying to get a form (in the backend) to upload a file(picture) to Post to itself if incomplete, or the adminhtml controller if complete. My JavaScript validation is working well, but when/if my form is POSTed I'm redirected to the dashboard. I've got a form key included and my url's are created with the special key, but still I can't get a POST through. Can anyone help me?
The phtml template file:
<script type="text/javascript">
function postSelf(){
form=document.getElementById('imgSel');
form.action='<?php Mage::helper("adminhtml")->getUrl("*/*/")?>';
form.submit();
}
function validateForm(){
var name=document.forms["imgSel"]["iName"].value;
var file=document.forms["imgSel"]["file_upload"].value;
if (!name){
alert("You must have an Image Name!");
postSelf();
}
else if (!file){
alert("You must have a File to upload");
postSelf();
}
else{
form=document.getElementById('imgSel');
form.submit();
}
}
</script>
<?php Mage::log(Mage::helper("adminhtml")->getUrl("*/*/"), null, ‘layout.log’ );?>
<h3 class="icon-head head-adminhtml-imagegrid">Add an Image:</h3>
<form name="imgSel" id="imgSel" action="<?php Mage::helper("adminhtml")->getUrl("*/*/insert")?>"
enctype="multipart/form-data" method="POST">
<!--Form key-->
<input type="hidden" name="form_key" value="<? echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
<?php Mage::log(Mage::getSingleton('core/session')->getFormKey(), null, ‘layout.log’ );?>
<label for="iName">Image Name:</label>
<input type="text" name="iName">
<label for="style">Associated Style Name:</label>
<select name="style">
<?php
echo '<option value="-1">None</option>';
$styles = Mage::getModel('cartonplugin/cartonstyle')->getCollection();
foreach($styles as $style){
echo '<option value="'.$style->getId().'"';
echo '>'.$style->getData('style_name').'</option> ';
}
echo '</select><br />';
?>
<input type="hidden" name="MAX_FILE_SIZE" value="40" />
Upload Image: <input type="file" name="file_upload" />
<br>
<!--<input type="submit" value="submit">-->
<button onClick="validateForm()" class="UploadButton" >Upload</button>
</form>
Controller: Only the insertAction() function is for this form. The rest is gridview stuff for dealing with any already-uploaded images.
<?php
class Nationwide_Newcart_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()->_setActiveMenu('igrid/set_time7')
->_addBreadcrumb('image Manager','image Manager');
return $this;
}
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
//var_dump(Mage::getSingleton('core/layout')->getUpdate()->getHandles());
}
public function newAction()
{
$this->_forward('edit');
}
public function editAction()
{
$stId = $this->getRequest()->getParam('id');
$model = Mage::getModel('newcart/imagemodel')->load($stId);
if ($model->getId() || $stId == 0)
{
Mage::register('image_data', $model);
$this->loadLayout();
$this->_setActiveMenu('igrid/set_time7');
$this->_addBreadcrumb('image Manager', 'image Manager');
$this->_addBreadcrumb('Image Description', 'Image Description');
$this->getLayout()->getBlock('head')
->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()
->createBlock('newcart/adminhtml_imagegrid_edit'))
->_addLeft($this->getLayout()
->createBlock('newcart/adminhtml_imagegrid_edit_tabs')
);
$this->renderLayout();
}
else
{
Mage::getSingleton('adminhtml/session')
->addError('That Image does not exist');
$this->_redirect('*/*/');
}
}
public function saveAction()
{
if ($this->getRequest()->getPost())
{
try {
$postData = $this->getRequest()->getPost();
$model = Mage::getModel('');
//Mage::log($this->getRequest()->getParam('id'), null, ‘layout.log’ );
if( $this->getRequest()->getParam('id') <= 0 )
$model->setCreatedTime(
Mage::getSingleton('core/date')
->gmtDate()
);
$model
//->addData($postData) //DO NOT! Includes a form key!
->setUpdateTime(
Mage::getSingleton('core/date')
->gmtDate())
->setId($this->getRequest()->getParam('id'));
$model->setData('image_name', $postData['image_name']);
$model->setData('style_name', $postData['style_name']);
$model->save();
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')
->settestData(false);
$this->_redirect('*/*/');
return;
} catch (Exception $e){
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')
->settestData($this->getRequest()
->getPost()
);
$this->_redirect('*/*/edit',
array('id' => $this->getRequest()
->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
public function deleteAction()
{
if($this->getRequest()->getParam('id') > 0)
{
try
{
$model = Mage::getModel('newcart/imagemodel');
$model->setId($this->getRequest()
->getParam('id'))
->delete();
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully deleted');
$this->_redirect('*/*/');
}
catch (Exception $e)
{
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
public function insertAction(){
$postData = $this->getRequest()->getPost();
Mage::log($postData, null, ‘layout.log’ );
//post checking
if(empty($postData)){
}
$this->_redirect('*/*/');
}
}
There are few things you need to check:
You have echo missing here:
action="<?php Mage::helper("adminhtml")->getUrl("*/*/insert")?>"
Should be
action="<?php echo Mage::helper("adminhtml")->getUrl("*/*/insert")?>"
Make sure you're using only normal PHP tags (<?php ?>). Short tags have proven to be a bad practice, so change
<input type="hidden" name="form_key" value="<? echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
to
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Along with that make sure you have all data correctly populated in your HTML using browse source feature in your browser.
Try to add this string to your form.
<input type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey()?>" name="form_key"/>
This creates a hidden parameter for the request, which contains the form_key used by Magento. This form_key is used to make sure the submitted form originated from your magento-instance (as a security measure). Without supplying this form_key, your form will not work.
Eric, your .phtml look fine....
Now you need see if the action url of your form are pointing to the right place, and do your controller like this one:
class controller_name extends Mage_Core_Controller_Front_Action{ // must extends this one for frontend controllers and Mage_Adminhtml_Controller_Action to backend controller.
public function insertAction(){
$_POST['elementName']; //to this to get post information.
$this->getRequest()->getPost('elementName'); //or this way.
}
}