Save default values in Yii2 not working - yii2

I want to save the this following datetime while update or create so I wrote this in rules()
['createdon','default','value'=>date('Y-m-d H:i:s'),'on'=>'insert' ],
['updatedon','default','value'=>date('Y-m-d H:i:s'),'on'=>'update' ],
and I declare scenario in create and update functions as
public function actionCreate()
{
$model = new JobFunctionRole();
$model->scenario = 'insert';
....
....
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update';
...
...
}
While create datetime stores perfectly.but in update its not stores.Whats the issue??Anybody?

You directly use _form
<?= $form->field($model, 'createdon')->hiddenInput('value'=>date("Y-m-d")])->label(false) ?>

These are validators for user input. You probably are looking for TimestampBehavior:
http://www.yiiframework.com/doc-2.0/yii-behaviors-timestampbehavior.html
The TimestampBehavior config should be added to an ActiveRecord model. Not the controller.

Related

(1/1) FatalErrorException Call to a member function all() on null in laravel 5.4

4 and i have a form when submitted i want to validate its fields, what happened is when i submit the form this is what it gets
(1/1) FatalErrorException
Call to a member function all() on null
This is my code below
$validator = app('validator')->make($this->request->all(),[
'postTitle' => 'required',
'postContent' =>'required']);
In laravel 5.2 this validator works well but in laravel 5.4 it returns null
can someone help me figured this thing out?
Any help is muchly appreciated. TIA
this is my full code
<?php
namespace App\Repositories;
use App\Repositories\Contracts\addPostRepositoryInterface;
use Validator;
use Illuminate\Http\Request;
use DB;
use Session;
use Hash;
class addPostRepository implements addPostRepositoryInterface{
protected $request;
// Intialize request instance
public function __contruct(Request $request){
$this->request = $request;
}
public function addPosts(Request $request){
//validate posts
echo "test";
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
//if validation fails return error response
if($validator->fails())
return redirect()->route('get.addPost')->withErrors($validator)->withInput();
try{
}catch(\Exception $e){
return redirect()->route('get.addPost')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
public function postCreate($screen){
switch($screen){
case 'add':
return $this->addPosts($screen);
break;
}
}
//getAddPost View
public function getAddPost(){
return view('addPost');
}
}
Seems an issue with the method injection (in the constructor) or something.
You may try creating the request object on the local(addPosts()) function.
Please try below alternative solution.
<?php
namespace App\Repositories;
use App\Repositories\Contracts\addPostRepositoryInterface;
use Validator;
use DB;
use Session;
use Hash;
class addPostRepository implements addPostRepositoryInterface{
public function addPosts(Request $request){
//validate posts
$reqeust = new \Illuminate\Http\Request;
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
//if validation fails return error response
if($validator->fails())
return redirect()->route('get.addPost')->withErrors($validator)->withInput();
try{
}catch(\Exception $e){
return redirect()->route('get.addPost')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
public function postCreate($screen){
switch($screen){
case 'add':
return $this->addPosts($screen);
break;
}
}
//getAddPost View
public function getAddPost(){
return view('addPost');
}
// REST OF THE CODE GOES HERE...
}
Given the information you gave, I will demonstrate you how to validate a request properly in Laravel 5.4
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
if ($validator->fails()) {
return redirect('your.view')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
This will successfully validate the request for you wherever need be. If the validation fails, you will be forwarded to your view with the according errors.
Make sure you use Validator; on top of your file.
For more information, you can read up on https://laravel.com/docs/5.4/validation

Yii2 model save returns true but there is no change in MySQL

Actually, If I update my model in the action of controller(in this case it is actionTest) it gets updated. Here is my code:
public function actionTest()
{
$model = ProviderOrder::find()->where(['is_used' => 0,'type' => Transaction::COD])->orderBy(['id' => SORT_ASC])->one();//const COD = 0
$model->is_used = 1;
$model->save();
}
But in my case I defined afterSave function to my Booking model. There I call getTrackNumber function which has Transaction Class in its body.
class Booking extends ActiveRecord
{
public function afterSave($insert, $changedAttributes)
{
$this->getTrackNumber($this->id);
parent::afterSave($insert, $changedAttributes);
}
public static function getTrackNumber($bookingId){
$transaction = new Transaction();
....
}
}
Inside of Transaction class there is the same code like in actionTest.
But the problem is $model->save() returns true but when I look through phpmyadmin there is no any change is_used is still 0.
But in the first case, i.e. in actionTest everything is fine. Please help me!

Laravel Eloquent when save or delete

public function destroy(Request $request){
$customer = customer::find($request->ID);
$customer->delete();
}
Back Query
"delete from `customer` where `id` is null"
when using Laravel's eloquent, it returns back the query but why is id showing as null?
Change it to $request->id. So, do this:
public function destroy(Request $request){
Customer::destroy($request->id);
}
Or:
public function destroy(Request $request){
Customer::where('id', $request->id)->delete();
}
let's try this
it will work
customer::where('id', $request->ID)->delete();
You need to code like this.
public function destroy(Request $request){
Customer::where('id', $request->input('ID'))->delete();
}
fix the problem edit Primary key on model because on database is primary key is "ID" not "id"
protected $primaryKey = 'ID';

Finding where values come to the $model

I changed the login page layout and got error that $model is undefined variable in Yii.
How can I find where values come to the $model?
Where is the model variable declared?
Error page:
Inside the controllers directory you can find the SiteController.php controller file. In this controller class you can find the below index method. For example
public function actionIndex() {
$model = new YourModelClassName(); //your model file class name replace here
return $this->render('index', ['model' => $model]);
}

professional way add data in database laravel 5.2

what is the professional way insert record in database.
i am using laravel 5.2.
i'm new in laravel.
class students extends Controller
{
public function index()
{
$insertData = array(
"name" => Input::get("name"),
"detail" => Input::get("detail"),
"token_key" => Input::get("_token")
);
return view('student');
}
public function fees()
{
$record = array(
"p_name" => Input::get("name"),
"p_fees" => Input::get("fees"),
"p_detail" => Input::get("detail")
);
return view('fee');
}
}
stander able way?
You should use mass assignment. Fill $fillable array inside your model and use this:
Model::create($insertData);
public function store_student(Request $request)
{
$student = new Student;
$student->name = $request->name;
$student->detail = $request->details
$student->save();
return view('student');
}
public function store_fee(Request $request)
{
$fee = new Fee;
$fee->p_name = $request->name;
$fee->p_fee = $request->fees;
$fee->p_detail = $request->details
$fee->save();
return view('fee');
}
I suggest you to read this from Laravel official guide.
However you can do it like this:
DB::table('tablename')->insert($insertData);