data not saving in database with fileupload in yii2 - yii2

File uploading to uploads folder but not saving in the database, getting below error
Unknown Method – yii\base\UnknownMethodException Calling unknown
method: app\models\UploadForm::save()
Below is my controller code
$name = $model->file->baseName . '.' .$model->file->extension;
$file = new UploadForm();
$file->image_name = $name;
$file->image_path = $name;
$file->save();
This is my model code
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
public function rules()
{
//echo "in";
return [
[['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg'],
['image_path','string'],
];
}
Can anyone help me? I am new to yii2

Related

How to save data from a request to mysql in laravel

I would like to save the information that I am receiving in the response of a request, in this case the "access_token" field, to my mysql database, here is the code:
My controller,
here I make a post request to have the access token:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class AuthsController extends Controller
{
public function SocialAuth(Request $request)
{
$a = $request->input('auth_code');
// URL
$apiURL = 'https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/';
// POST Data
$postInput = [
'app_id' => '7112335319877287',
'secret' => '18f52730856f43ed821187bfa9283794ca360e',
'auth_code' => $a
];
// Headers
$headers = [
//...
];
$response = Http::withHeaders($headers)->post($apiURL, $postInput);
$statusCode = $response->getStatusCode();
$responseBody = json_decode($response->getBody(), true);
echo $statusCode; // status code
dd($responseBody); // body response
}
}
Response of my request, the value that I want to save to mysql is the access token
^ array:4 [▼
"code" => 0
"message" => "OK"
"request_id" => "202211281314430102451411010AF4AA0A"
"data" => array:3 [▼
"access_token" => "fbcaa610339b7aeb39eabf29346d06a4e7fe9"
"advertiser_ids" => array:1 [▶]
"scope" => array:18 [▶]
]
]
How can I save the access token in mysql?
create a table with the following columns, for storage:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTokenTableTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('token_table', function (Blueprint $table) {
$table->integer('id_token')->primary();
$table->string('token')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('token_table');
}
}
Use your token Model and save the data
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
// call your token Model class
use App\Models\TokenTable
class AuthsController extends Controller
{
public function SocialAuth(Request $request)
{
$a = $request->input('auth_code');
// URL
$apiURL = 'https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/';
// POST Data
$postInput = [
'app_id' => '7112335319877287',
'secret' => '18f52730856f43ed821187bfa9283794ca360e',
'auth_code' => $a
];
// Headers
$headers = [
//...
];
$response = Http::withHeaders($headers)->post($apiURL, $postInput);
$statusCode = $response->getStatusCode();
$responseBody = json_decode($response->getBody(), true);
echo $statusCode; // status code
//check if status code is 200
if($statusCode == 200){
TokenTable::create([
'token' => $responseBody['data']->access_token
]);
echo 'ok';
}
}
}
or this
if($statusCode == 200){
TokenTable::create([
'token' => $responseBody['data']['access_token']
]);
echo 'ok';
}

Call to a member function saveAs() on a non-object

I am trying to upload image and database table.
on database table basic_info field name 'photo' that i want to store file name.
here is model
public function rules()
{
return [
[['photo'], 'string', 'max' => 255],
[['image'], 'safe'],
[['image'], 'file', 'extensions'=>'jpg, gif, png'],
];
}
here is controller
public function actionCreate()
{
$model = new BasicInfo();
if ($model->load(Yii::$app->request->post()))
{
$model->image = UploadedFile::getInstance($model, 'image');
$filename = pathinfo($model->image , PATHINFO_FILENAME);
$ext = pathinfo($model->image , PATHINFO_EXTENSION);
$newFname = $filename.'.'.$ext;
$path=Yii::getAlias('#membersImgPath');
if(!empty($newFname)){
$model->image->saveAs($path.$newFname);
$model->image = $newFname;
if($model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
}
}
return $this->render('create', [
'model' => $model,
]);
}
here is view
echo FileInput::widget([
'name' => 'photo',
'options' => ['accept' => 'image/*'],
]);
from your comment here,
$form = ActiveForm::begin(['type'=>ActiveForm::TYPE_VERTICAL],['opti‌​ons'=>['enctype'=>'m‌​ultipart/form-data']‌​]);
ActiveForm::begin does not have a second parameter. you need to use a single options array.
$form = ActiveForm::begin([
'type' => ActiveForm::TYPE_VERTICAL,
'opti‌​ons' => [
'enctype' => 'm‌​ultipart/form-data'
]‌
​]);
First of all, you have to check if there's a file. To do it try:
if(UploadedFile::getInstance($model, 'image')) {
// here should go your code with $model->image
}
Youre using pathinfo to get filename and extension. Remember, that youre using powerfull framework, you just initialized class UploadedFile which can do everything for you:
if(UploadedFile::getInstance($model, 'image')) {
$model->image = UploadedFile::getInstance($model, 'image');
$newFname = $model->image->name; // UploadedFile have properties like `name`, `tempName`, even `size`!
}
After doing this small fixes to your code (you should always check if something is set) - we can go to main problem.
Your input field name is photo, but youre trying to get image with name image.
Change this:
UploadedFile::getInstance($model, 'image');
To this:
UploadedFile::getInstance($model, 'photo'); // remeber to change it in `if` statement aswell!!
Theres also posibility that youre trying to upload file bigger than your post_max_size and upload_max_filesize allows. Change this properties in your php.ini, restart server and try again. If still something is not right, try to debug this thing, for start by doing var_dump($_FILES);die; in your controller.

How to get configuration params in Controller Console in Yii2 Framework

How to get configuration params in Console Controller in Yii2 Framework
I try below code but its not working
Yii::$app->params['params_1']
Try This:
Code in config/params.php
<?php
return array(
'apptitle' => 'stackOverlfow',
//Define PARAMS as you need.
);
?>
You can use PARAM as below:
\Yii::$app->params['apptitle'];
Example:
echo "App title is:". \Yii::$app->params['apptitle'];
As you mentioned Basic Template Of Yii.
config/web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
.
.
.
],
'params' => $params,
];
return $config;
?>
config/params.php
<?php
$params = [
'params_1' => 'YourValue'
];
return $params;
?>
SomeWhere.php
<?=Yii::$app->params['params_1'];?>
Seems that you insert your param to other conf params.php.
My helper function:
/**
* Get param value from config file.
* Получение параметра из конфигурационного файла
*
* #param string $param_name название пареметра
*
* #return string|ApicoServerErrorHttpException Значение параметра
* #throws \Exception
*/
public static function yiiparam($param_name)
{
if (isset(\Yii::$app->params[$param_name])) {
return \Yii::$app->params[$param_name];
} else {
$msg = "Can not find param in configuration file. have been search by param = " . VarDumper::export($param_name);
\Yii::error($msg, __METHOD__);
throw new ServerErrorHttpException();
}
}

To fetch data from mysql table using hooks codeigniter

I am new for hooks in codeigniter. I have enabled the hooks in config file.
$config['enable_hooks'] = TRUE;
and then in hooks.php I have written my hook that is like below
$hook['pre_controller'] = array(
'class' => 'MyClass',
'function' => 'Myfunction',
'filename' => 'Myclass.php',
'filepath' => 'hooks',
'params' => '');
AND the class having function is as below
class MyClass {
function MyClass() {
$this->CI = &get_instance();
require_once(APPPATH . 'config/database.php');
}
function Myfunction() {
$record = $this->CI->db->SELECT('*')
->FROM('currency')
->get()
->result();
echo "<pre>";
print_r($record);
die;
}}
but i am getting a blank page. please tell me what is wrong with me.
I think your main problem was in this area.
function MyClass() {
$this->CI = &get_instance();
require_once(APPPATH . 'config/database.php');
}
Try
Note: codeigniter 3 versions are case sensitive should be first letter upper case only on class and file name.
application > hooks > My_class.php
<?php
class My_class {
public function __construct() {
$this->CI = &get_instance();
// Auto load database
// require_once(APPPATH . 'config/database.php');
}
public function my_function() {
$query = $this->CI->db->get('currency');
$record = $query->result_array();
echo "<pre>";
print_r($record);
echo "</pre>";
}
}
Config Hook
$hook['pre_controller'] = array(
'class' => 'My_class',
'function' => 'my_function',
'filename' => 'My_class.php',
'filepath' => 'hooks',
);
Autoload the database better option
$autoload['libraries'] = array('database');
Codeigniter Hooks

Namespaces not working with Codeception (Yii2)

Im using Codeception in Yii2 to make acceptance tests and there's no way to access my models because namespaces are not working into these tests.
I have this in my tests/_bootstrap.php
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../console/config/main.php');
//
$application = new yii\console\Application( $config );
## Added (#vitalik_74)
Yii::setAlias('#tests', dirname(__DIR__));
This in my console/config/main
<?php
$params = array_merge(
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params,
];
<?php
return [
'adminEmail' => 'admin#example.com',
'supportEmail' => 'support#example.com',
'user.passwordResetTokenExpire' => 3600,
];
And this is one of the wannabe-tests:
<?php namespace tests\acceptance;
use \AcceptanceTester;
use backend\models\User; ## I have tried writing it with a / at the beggining
class ListUserCest
{
public function _before(AcceptanceTester $I)
{
}
public function _after(AcceptanceTester $I)
{
}
public function init(AcceptanceTester $I)
{
$this->login($I);
if( User::find()->exists() )
$I->amGoingTo('List Users having at least one');
else
$I->amGoingTo('List Users having any');
}
...
I get this error when running the tests:
PHP Fatal error: Class 'backend\models\User' not found in /var/www/project/tests/acceptance/ListUserCest.php on line 21
Error: Class 'backend\models\User' not found
Please, help me, I have tried everything I know
EDIT
Now (after adding the line recommended by vitalik_74) I can use for example, \Yii methods into the tests but witout the web application configuration, just the console configuration.
I mean, I still can't use \backend\models\User and I can't neither access the Yii::$app->user status (to check if user is logged, for example).
The User model is just a common ActiveRecord model with his tableName, rules, attributeLabels, and some relational methods like getProfile().
It works out of the tests
<?php
namespace backend\models;
use common\helpers\MathHelper;
use backend\models\AntropometricData;
use Yii;
class User extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
...
Put the next code to tests/_bootstrap.php:
require('vendor/autoload.php');
require('vendor/yiisoft/yii2/Yii.php');
$config = require('config/web.php');
(new yii\web\Application($config));