Update data to related tables yii2 - php

I have table USR and ORGANIZATION :
USR table
|ID | ID_APP | NAMA_APP|
ORGANIZATION table
|ID | NAMA |
I tried to insert data to USR table (ID_APP and NAMA_APP) from ORGANIZATION by ID (relationship). This my code :
UsersController :
public function actionUpdate($id)
{
$model = $this->findModel($id);
if (Yii::$app->request->post()) {
try {
$state = true;
$data = Yii::$app->request->post();
$transaction = Yii::$app->db->beginTransaction();
$model->ID_APP = $data['USR']['ID_APP'];
$model->NAMA_APP = $data['USR']['NAMA_APP'];
if (!$model->save()) {
$ErrorMessage = $model->getErrorMessage($model->getErrors());
throw new Exception($ErrorMessage);
}
$transaction->commit();
$message = "Success update Application ";
} catch (Exception $e) {
$state = false;
$transaction->rollback();
$message = $e->getMessage();
}
if ($state) {
Yii::$app->session->setFlash('successApplication', $message);
return $this->redirect(['view', 'id' => $model->ID]);
} else {
Yii::$app->session->setFlash('errorApplication', $message);
return $this->render('view', ['id' => $model->ID]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
My View :
<?php $org = \app\models\ORGANIZATION::find()->all(); ?>
<?= $form->field($model, 'ID_APP')->dropDownList(
ArrayHelper::map($org,'ID', 'NAMA'))->label('ID APP') ?>
I'm still beginner on php and yii2 framework How to get NAMA_APP (USR table) from NAMA (ORGANIZATION)?

Based on you view assumuning that you post the ID_APP and need to retrive the NAMA_APP for a separated store in USR
// make accessible your ORGANIZAZTION model with use eg:
// use common\models\ORGANIZATION; or
use yourapp\models\ORGANIZATION;
public function actionUpdate($id)
{
$model = $this->findModel($id);
if (Yii::$app->request->post()) {
try {
$state = true;
$data = Yii::$app->request->post();
$transaction = Yii::$app->db->beginTransaction();
$model->ID_APP = $data['USR']['ID_APP'];
// then you can use eg: the find method
// related to ORGANIZAZTION active record
$modelOrg = ORGANIZATION::find()->where(['ID_APP']=> $data['USR']['ID_APP'])->one();
$model->NAMA_APP = $modelOrg->NAMA_APP
....

Related

Unable to update data by Eloquent in Laravel, phpunit

I am developing an application using Laravel, Eloquent as ORM, phpunit for unit testing. But i am not able to update data in database. Though there is no exception, warning or error. If the object of the model class checked in laravel, before update and after update, it is showing that data has been changed in the model class but when checking the database, found that data is not being changed.
Model Class
class Post extends Model
{
protected $table = "posts";
protected $fillable = [
'id',
'user_id',
'title',
'description',
'total_needed',
'total_collected',
'total_expanse',
'start_date',
'end_date',
'active',
'updated_at',
'created_at',
];
}//class
Repository Code
class Post_Repo_Impl implements Post_Repo_I
{
public function update(Post $postUpdate)
{
$raedOld = false;
$updateStatus = false;
try {
$psot_id = $postUpdate->id;
$postOrgin = Post::find($psot_id);
$raedOld = true;
} catch (Exception $e) {
error_log("Post Update : failed to read existig post.");
}
if ($raedOld) {
try {
//line 1
echo "\n" . $postOrgin->title . "\n";
$this->setPostValues($postOrgin, $postUpdate)->update();
//line 2
echo "\n" . $postOrgin->title . "\n";
$updateStatus = true;
} catch (Exception $e) {
error_log("Post Update : Failed to save updated post." . "\n\n" . $e);
}
}
return $updateStatus;
} //update
}
Line 1 and Line 2, not printing same value. Line 2 printing the changed value.
Unit Test code
class RepoPost extends TestCase
{
public function testMain()
{
echo "\n >----------- Test Main : ---------> \n";
$this->postUpdate();
} //mother test
public function postUpdate()
{
$postDummyUpdate = new Post();
$postDummyUpdate->id = '2';
$postDummyUpdate->user_id = 'Tst';
$postDummyUpdate->title = 'Post Updated Repo Test........';
$postDummyUpdate->description = 'UnitTesting of URLs';
$postDummyUpdate->total_needed = '2000';
$postDummyUpdate->total_collected = '1000';
$postDummyUpdate->total_expanse = '500';
$postDummyUpdate->start_date = '22-09-2019';
$postDummyUpdate->end_date = '22-10-2019';
$postDummyUpdate->active = '1';
$postDummyUpdate->updated_at = '2019-09-24';
$postDummyUpdate->created_at = '2019-09-22';
echo '\n----PostUpdate----\n';
$postRepoSave = $this->getRepoPostImpl();
dd($postRepoSave->update($postDummyUpdate));
if ($postRepoSave == false) {
error_log("\n\nTest : Data Save Failed.");
} else {
error_log("Saved Post ID : " . $postRepoSave);
}
}
public function getRepoPostImpl()
{
return new Post_Repo_Impl();
}
}
In the test code it is returning true.

getting error &#039 in yii2 advance

Exception 'yii\base\InvalidArgumentException' with message 'Response content must not be an array.'
in C:\xampp1\htdocs\advanced\vendor\yiisoft\yii2\web\Response.php:1054
Stack trace:
0 C:\xampp1\htdocs\advanced\vendor\yiisoft\yii2\web\Response.php(337): yii\web\Response->prepare()
1 C:\xampp1\htdocs\advanced\vendor\yiisoft\yii2\base\Application.php(392): yii\web\Response->send()
2 C:\xampp1\htdocs\advanced\frontend\web\index.php(17): yii\base\Application->run()
3 {main}
SiteController.php
public function actionGetuser()
{
$model = new UsersData();
if(Yii::$app->request->isAjax){
$id = Yii::$app->request->post();
return $model->get($id);
}
}
model:-
function get($id)
{
$model = Yii::$app->db->createCommand("SELECT * FROM user where id=$id");
return $user = $model->queryOne();
}
I got the solution :-
model:-
function get($id)
{
$userid = json_decode($id);
$uid = $userid->id;
$model = Yii::$app->db->createCommand("SELECT * FROM user where id = $uid");
$user = $model->queryOne();
//return $user;
return json_encode($user);
}
controller:-
public function actionGetuser()
{
$model = new UsersData();
//return "Dfasdafsd";
if(Yii::$app->request->isAjax){
$data = Yii::$app->request->post();
$id = json_encode($data);
return $model->get($id);
}
}
You need to change format of your response :
You can modify its configuration by adding an array to your application config under components as it is shown in the following example:
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
// ...
]
Check This Link For More info
OR
function get($id)
$result = user::find()->where(['id' => $id])->all();
return Json::encode($result);
}

Unique key validation showing error while updating data in laravel

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

How to edit Zend form with edit button next to each field

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!

Why is Zend DB Update not posting?

Other modules in the application are updating, besides this one.
Here, I am using a model mapper in attempts to update a row set, as found in http://framework.zend.com/manual/en/learning.quickstart.create-model.html
public function SomeAction()
{
$mapper = new Application_Model_SomeMapper();
$model = new Application_Model_SomeModel(); //getters and setters
// action body
$request = $this->getRequest();
$data = $this->_request->getParams();
$someId = $data['someid'];
$get = $mapper->find($someId, new Application_Model_SomeModel, true); //find the row by id, and return array
/*
instantiating a form object and adding "submit"
*/
$form = new Module_Form_FormName();
$form->setAction("/module/controller/action/params/$someId");
$form->setMethod('post');
$form->setName('some_edit');
$submit = $form->createElement('button', 'submit');
$submit->setAttrib('ignore',true);
$submit->setLabel('Edit Something');
$form->addElement($submit);
if ($this->_request->isPost())
{
if($form->isValid($request->getPost()))
{
$data = $this->_request->getPost();
if(empty($data['some_id' ]))
{
$data['tier_models_id'] = NULL;
}
unset($data['submit']);
$setters = $model->setId($data['id'])
->setField1($data['field_1']);
if ($mapper->save($someId, $setters))
{
$this->_redirect("/index/");
}
}
}
$form->populate($tier);
$this->view->form = $get;
}
Here is an example of the save mapper function, except I've included an additional $id parameter
public function save(Application_Model_Guestbook $guestbook)
{
$data = array(
'email' => $guestbook->getEmail(),
'comment' => $guestbook->getComment(),
'created' => date('Y-m-d H:i:s'),
);
if (null === ($id = $guestbook->getId())) {
unset($data['id']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('id = ?' => $id)); //not happening, although the 'id' is passed as a param
}
}
Is there something missing?
Try this instead
$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
$this->getDbTable()->update($data, $where);

Categories