Hi I am creating an application using laravel and i have a model where asset_number field is unique and the validation rules are as follows
MODEL
protected $rules = array
(
'asset_number' => 'required|alpha_dash|min:2|max:12|unique:asset_details,asset_number,{id}',
'asset_name' => 'alpha_space',
'asset_type_id' => 'required',
'shift' => 'required',
);
Here is my controller code for create and edit
CONTROLLER
public function postCreate()
{
// get the POST data
$new = Input::all();
// create a new Assetdetail instance
$assetdetail = new Assetdetail();
// attempt validation
if ($assetdetail->validate($new))
{
// Save the location data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail ->save())
{
// Redirect to the new location page
return Redirect::to("admin/settings/assetdetails")->with('success', Lang::get('admin/assetdetails/message.create.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the location create page
return Redirect::to('admin/settings/assetdetails/create')->with('error', Lang::get('admin/assetdetails/message.create.error'));
}
public function getEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
//$assetlife = DB::table('asset_details')->where('id', '=', $assetdetailId)->lists('asset_life');
$location_list = array('' => '') + Location::lists('name', 'id');
$assettype_list = array('' => '') + Assettype::lists('asset_type', 'id');
$assignTo_list = array('' => 'Select a User') + User::select(DB::raw('CONCAT(first_name, " ", last_name) AS full_name'), 'id') ->lists('full_name', 'id');
$assetdetail_options = array('' => 'Top Level') + DB::table('asset_details')->where('id', '!=', $assetdetailId)->lists('asset_number', 'id');
return View::make('backend/assetdetails/edit', compact('assetdetail'))->with('assetdetail_options',$assetdetail_options)->with('location_list',$location_list)->with('assettype_list',$assettype_list)->with('assignTo_list',$assignTo_list);
}
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
$new = Input::all();
/*if ($assetdetail ->asset_number == Input::old('asset_number') &&
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
}*/
if ($assetdetail->validate($new))
{
// Update the asset data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the asset management page with error
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
My Route.php
Route::post('create', array('as' => 'savenew/assetdetail','uses' => 'Controllers\Admin\AssetdetailsController#postCreate'));
Route::get('{assetdetailId}/edit', array('as' => 'update/assetdetail', 'uses' => 'Controllers\Admin\AssetdetailsController#getEdit'));
Route::post('{assetdetailId}/edit', 'Controllers\Admin\AssetdetailsController#postEdit');
Now the problem is whenever i try to update my form my asset_number field throws an Error: The asset_number has already been taken.How do i pass the id in my controller while updating my form so that it throws error only if an already existing asset_number is used and not while editing the form with current asset_number.
I tried the following with no luck
Model
'asset_number' => 'mobileNumber' => 'required|min:5|numeric|unique:asset_details,asset_number,' . $id
Controller
Assetdetail::$rules['mobileNumber'] = 'required|min:5|numeric|unique:asset_details,asset_number,' . $id
Hi i finally found a working solution myself here is what i did please take a look
Controller
class AssetdetailsController extends AdminController
{
protected $validationRules = array
(
'asset_number' => 'required|alpha_dash|min:2|max:12|unique:asset_details,asset_number',
'asset_name' => 'alpha_space',
'asset_type_id' => 'required',
'shift' => 'required',
);
public function postCreate()
{
$validator = Validator::make(Input::all(), $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
// attempt validation
else
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail ->save())
{
// Redirect to the new location page
return Redirect::to("admin/settings/assetdetails")->with('success', Lang::get('admin/assetdetails/message.create.success'));
}
}
// Redirect to the location create page
return Redirect::to('admin/settings/assetdetails/create')->with('error', Lang::get('admin/assetdetails/message.create.error'));
}
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.assetdetail_not_exist'));
}
$this->validationRules['asset_number'] = "required|alpha_dash|min:2|max:12|unique:asset_details,asset_number,{$assetdetail->asset_number},asset_number";
$validator = Validator::make(Input::all(), $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
else
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
// Redirect to the asset management page with error
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
}
Related
I create a menu table and menu seeder inside my database. However when I tried to click on the company menu on my website it saying that $menu is undefined but when I tried to change to jobs.index(this the one which is working fine) for my route it works but it will goes to the job.blade.php not company.blade.php I do not know which part is wrong inside my code.
companycontroller.php
class CompanyController extends Controller
{
public function index()
{
$data = Company::latest()->paginate(5);
return view('company.index', compact('data'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function insert_logo(Request $request)
{
$request->validate([
'company_logo' => 'required|image|max:2048',
'company_name' => 'required'
]);
$image_file = $request->company_logo;
$image = Company::make($image_file);
Response::make($image->encode('jpeg'));
$form_data = array(
'company_logo' => $image,
'company_name' => $request->company_name,
);
Company::create($form_data);
return redirect()->back();
}
public function fetch_logo($image_id)
{
$image = Company::findOrFail($image_id);
$image_file = Company::make($image->company_logo);
$response = Response::make($image_file->encode('jpeg'));
$response->header('Content-Type', 'image/jpeg');
return $response;
}
is there a way to pass a URL variable to a form action? I've got it working on a user details form, but when I'm trying to do it with a user file upload it won't work.
As you will see below, I have a form and a save action for saving user details. That works fine.
When I try to pass the URL variable to the User File Upload form, it doesn't work. It says that I'm trying to get a value of a non-object.
// Get Client ID from URL Parameters
public function getUser() {
if( isset($this->urlParams['ID']) && is_numeric($this->urlParams['ID']) ) {
return $user = Member::get()->byID($this->urlParams['ID']);
} else {
return $user = $this->request->postVars();
}
}
// Edit/Save a User's details
public function EditUserDetails() {
//Include JS for updating details
Requirements::javascript('module-memberprofiles/javascript/MemberProfileUpdate.js');
Requirements::set_force_js_to_bottom(true);
$fields = new FieldList(
$leftCol = CompositeField::create(
TextField::create('FirstName', 'First Name')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
TextField::create('Surname', 'Surname')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
CompositeField::create(
TextField::create('Address', ''),
TextField::create('Suburb', ''),
CompositeField::create(
DropdownField::create('State', '', singleton('Member')->dbObject('State')->enumValues())->setFieldHolderTemplate('UserDetails_StatePostCode'),
TextField::create('PostCode', '')->setFieldHolderTemplate('UserDetails_StatePostCode')
)->addExtraClass('row')
)
->addExtraClass('userdetails-address wrap')
->setFieldHolderTemplate('UserDetails_AddressHolder'),
TextField::create('Phone', 'Phone')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
TextField::create('Email', 'Email')
->setFieldHolderTemplate('UserDetails_FieldHolder')
)->setFieldHolderTemplate('UserDetails_CompositeField')
);
$actions = new FieldList(new FormAction('SaveUserDetails', 'Save Profile'));
$validation = new RequiredFields(array('FirstName','Surname','Email'));
$form = new Form ( $this, 'EditUserDetails', $fields, $actions, $validation);
$form->loadDataFrom($this->getUser());
$form->setTemplate('MemberProfilePage_UserDetailsForm');
return $form;
}
public function SaveUserDetails($data, $form) {
$table = Member::get()->byID($this->getUser());
$members = Member::get();
$emailExists = $members->filter(array(
'Email' => $data['Email'],
'ID:not' => $table->ID
));
if( $emailExists->count() > 0 ) {
$form->sessionMessage('Sorry, that email address already exists. Please try again','bad');
return $this->redirectBack();
} else {
$form->sessionMessage('You have successfully updated this user\'s details.','good');
}
$form->saveInto($table);
$table->write();
$this->redirectBack();
return $this;
}
//User file upload function
public function UploadUserFile() {
$fields = FieldList::create(
FileField::create('UserFiles', 'Upload files')
);
$actions = FieldList::create(FormAction::create('SaveUserFile', 'Upload files'));
$form = Form::create($this, __FUNCTION__, $fields, $actions, null);
$form->loadDataFrom($this->getUser());
return $form;
}
//Refresh files function
public function SaveUserFile($data, $form) {
$up = new Upload();
$file = Object::create('File');
$file->setFileName('newname');
$up->loadIntoFile($data['UserFiles'], $file, 'User-Files');
if($up->isError()) {
//handle error here
//var_dump($up->getErrors());
}else {
//file uploaded
//$file->OwnerID = 3;
//$file->write();
//$this->redirectBack();
return $this;
}
}
OK, I managed to figure this one out...
I had to set a form action to direct the upload function to the correct URL. It appears that the ID was being removed from the URL when I clicked submit, so the "getUser" function couldn't see the value.
Here's the working code for the Upload Form function:
public function UploadUserFile() {
$fields = FieldList::create(
FileField::create('UserFiles', 'Upload files'),
HiddenField::create('ID','',$this->getUser()->ID)
);
$actions = FieldList::create(
FormAction::create('SaveUserFile', 'Upload files')
->addExtraClass('button rounded solid')
);
$form = Form::create($this, 'UploadUserFile', $fields, $actions);
$form->setFormAction($this->Link().'UploadUserFile/'.$this->getUser()->ID);
return $form;
}
In Laravel 4.2, I have declared a session:
session_start();
$code=rand(100000,999999);
$_SESSION["captcha"]=$code;
Then I want to get the data that I have stored, and use it in a Laravel controller to check if the user entered the right code before I enter it inside the database.
Here is my code:
public function store2()
{
// i was trying to get the value
// session_start();
// $getsCapt = $_SESSION["captcha"];
$rules = array(
'username' => 'required|min:2|max:50|regex:/^[a-zA-Z0-9\-\s]+$/',
'description' => 'required|min:1|max:100|regex:/^[a-zA-Z0-9\-\s]+$/',
'usertype' => 'required|numeric'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails())
{
return Redirect::to('createsu')
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
// store
$su = new SystUser;
$su->SystemUserTypeID = Input::get('usertype');
$su->SystemUserName = Input::get('username');
$su->SystemUserPassword = 'changeme';
$su->SystemUserDescription = Input::get('description');
$su->timestamps = false;
$su->save();
// redirect
Session::flash('message', 'Successfully created system user!');
return Redirect::to('createsu');
}
}
In Laravel you don't have to start session explicitly.
You can do something like:
To Set In Session
$captcha='whatever';
Session::put('captcha', $captcha);
To Get From Session
if(Session::has('captcha'){
$captcha = Session::get('captcha');
}
Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}
I have file (ProfileController.php) which contains the following code:
public function editAction() {
if (Zend_Auth::getInstance()->hasIdentity()) {
try {
$form = new Application_Form_NewStory();
$request = $this->getRequest();
$story = new Application_Model_DbTable_Story();
$result = $story->find($request->getParam('id'));
// $values = array(
// 'names' => $result->names,
// 'password' => $result->password,
// );
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$data = array(
'names' => $form->getValue("names"),
'password' => $form->getValue("password"),
);
$form->populate($data->toArray());
$where = array(
'id' => $request->getParam('id'),
);
$story->update($data, $where);
}
}
$this->view->form = $form;
$this->view->titleS= $result->title;
$this->view->storyS= $result->story;
} catch (Exception $e) {
echo $e;
}
} else {
$this->_helper->redirector->goToRoute(array(
'controller' => 'auth',
'action' => 'index'
));
}
}
and another file (edit.phtml) with following code:
<?php
try
{
$tmp = $this->form->setAction($this->url());
//$tmp->titleS=$this->title;
//$tmp->storyS=$this->story;
//echo $tmp->title = "aaaaa";
}
catch(Exception $e)
{
echo $e;
}
?>
I would like the users to be able to edit their Username and password. How do I go about it?
First: move the Zend_Auth stuff up to init() or preDispatch(), that way Auth will run against any or all actions in the controller.
The trick in getting more then one submit button to work is to give the buttons different names so that getParam('') has something to work with.
Normally I only do this sort of thing when doing deletes, for edit's or update's I just submit the whole array back to the database. I typically use the Zend_Db_Table_Row save() method instead of Zend_Db_Table's insert() or update() so the mechanism is a little different.
I just use a simple form to perform an update, here is the controller code (the view just echo's the form):
//update album information
public function updatealbumAction()
{ //get page number from session
$session = new Zend_Session_Namespace('page');
//get album id
$id = $this->getRequest()->getParam('id');
$model = new Music_Model_Mapper_Album();
//fetch the album database record
$album = $model->findById($id);
$form = new Admin_Form_Album();
//this form is used elsewhere so set the form action to this action
$form->setAction('/admin/music/updatealbum/');
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();//get valid and filtered form values
$newAlbum = new Music_Model_Album($data);//create new entity object
$update = $model->saveAlbum($newAlbum);//save/update album info
$this->message->addMessage("Update of Album '$update->name' complete!");//generate flash message
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));//redirect back to the page the request came from
}
} else {
$form->populate($album->toArray());
$this->view->form = $form;
}
}
This is a pretty common update action.
Now here is how you might use different request parameters to perform an action on a record. I use this to delete database records but anything is possible.
public function deleteAction()
{
$session = new Zend_Session_Namespace('page');
$request = $this->getRequest()->getParams();
try {
switch ($request) {
//if
case isset($request['trackId']):
$id = $request['trackId'];
$model = new Music_Model_Mapper_Track();
$model->deleteTrack($id);
$this->message->addMessage("Track Deleted!");
break;
case isset($request['albumId']):
$id = $request['albumId'];
$model = new Music_Model_Mapper_Album();
$model->deletealbum($id);
$this->message->addMessage("Album Deleted!");
break;
case isset($request['artistId']):
$id = $request['artistId'];
$model = new Music_Model_Mapper_Artist();
$model->deleteArtist($id);
$this->message->addMessage("Artist Deleted!");
break;
default:
break;
}
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
} catch (Exception $e) {
$this->message->addMessage($e->getMessage());
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
}
}
you can pass the request parameters as submit button labels or as urls or whatever works for you.
Good Luck!