I'm try to save multiple files (manual: http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html)
Here is my controller code:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$model->thumb = UploadedFile::getInstance($model, 'thumb');
$model->gallery = UploadedFile::getInstances($model, 'gallery');
$model->thumb->saveAs('uploads/' . $model->thumb->baseName . '.' . $model->thumb->extension);
foreach ($model->gallery as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
if($model->validate() && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
But it gives me this exception:
Database Exception – yii\db\Exception
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
The SQL being executed was: UPDATE `project` SET `thumb`='deliver.png', `gallery`=:qp1, `total_square`=221.4, `living_square`=133.6, `price`=150000, `floor`=1 WHERE `id`=1
Error Info: Array
(
[0] => HY093
[1] => 0
)
↵
Caused by: PDOException
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
in /var/www/map.dev/vendor/yiisoft/yii2/db/Command.php at line 846
Can anyone help?
Related
currently i have base 64 value in
$model->test
and i want to decode the base 64 value in controller and save it to database through API here some of my code in controller
i try to decode and cant figure out how to upload it to server and create path
however i try to to pass the $data to getinstance which is not working
public function doSaveStudent(StudentLoanForm $model)
{
$url = API_URL . 'web/apply/student';
$data1 = $model->test;
$decode = base64_decode($data);
$img = file_put_contents('webcam.jpg', $data);
$model->doUploads();
$ktpdetail = UploadedFile::getInstance($model, 'image_ktp');
$data = null;
$data = [
[
'name' => 'univ_name',
'contents' => $model->univ_name
],
[
'name' => 'test',
'contents' =>$model->test
],
];
// dd($model->test);
if ($ktpdetail != null) {
$data[] = [
'name' => 'image_ktp',
'contents' => fopen(Yii::getAlias('#frontend/web/') . $model->image_ktp, 'r'),
'filename' => $ktpdetail->getBaseName() . '.' . $ktpdetail->getExtension()
];
}
if($ktpayahdetail != null){
$data[] = [
'name' => 'foto_ktp_ayah',
'contents' => fopen(Yii::getAlias('#frontend/web/') . $model->foto_ktp_ayah, 'r'),
'filename' => $ktpayahdetail->getBaseName() . '.' . $ktpayahdetail->getExtension()
];
}
if ($kkdetail != null) {
$data[] = [
'name' => 'image_kk',
'contents' => fopen(Yii::getAlias('#frontend/web/') . $model->image_kk, 'r'),
'filename' => $kkdetail->getBaseName() . '.' . $kkdetail->getExtension()
];
i expect to decode the base 64 and upload all the value using yii2 best practice
The yii\web\UploadedFile is used only for files uploaded using file input in forms.
In your case base64_decode($model->test) should give you binary data of image.
Then you have two options what to do with them.
1) You can store them directly into BLOB attribute in database.
$imageModel = new MyImageModel();
$imageModel->data = base64_decode($model->test);
if(!$imageModel->save()) {
throw new \yii\base\Exception("Couldn't save file to db");
}
2) You can save the file with file_put_contents and then store the path to file in your model.
$imageData = base64_decode($model->test);
//the used alias in path is only example.
//The datetime and random string are used to avoid conflicts
$filename = Yii::getAlias(
'#frontend/web/' . date('Y-m-d-H-i-s') .
Yii::$app->security->generateRandomString(5) . '.jpg'
);
if (file_put_contents($filename, $imageDate === false) {
throw new \yii\base\Exception("Couldn't save image to $filename");
}
$imageModel = new MyImageModel();
$imageModel->path = $filename;
if(!$imageModel->save()) {
//delete file if we couldn't save path into db to prevent creating an orphan
unlink($filename);
throw new \yii\base\Exception("Couldn't add $filename to database");
}
I've created a list which is fully populated with records from database. I'd like to add a button 'delete' in order to delete records on demand. The button appears, but whenever it makes a request, it does not have an ID of the record I want to delete. The URL looks like this:
controller=AdminModules&configure=estimateddelivery&=&deleteestimateddelivery&token=6d1625ddf520e0bf8d2c43bea84f21d3
There is a &=& which if I understand correctly should be populated with something like &id=10&. I am not sure what the problem is or where to look at. I've check code examples of similar functionalities and it looks like I am doing everything the same way.
public function renderList()
{
$this->$fields_list = [
'id_estimateddelivery' => [
'title' => $this->l('ID'),
'type' =>'text',
],
'from' => [
'title' => $this->l('Delivery period from')
],
'to' => [
'title' => $this->l('Delivery period to')
],
'countries' => [
'title' => $this->l('Countries applicable'),
'type' => 'text'
]
];
$helper = new HelperList();
$helper->module = $this;
$helper->shopLinkType = '';
$helper->simple_header = true;
$helper->idientifier = 'id_estimateddelivery';
$helper->actions = [
'delete'
];
$helper->show_toolbar = false;
$helper->title = $this->l('List of created estimated deliveries');
$helper->table = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex . '&configure=' . $this->name;
return $helper->generateList($this->getEstimatedDeliveries(), $this->$fields_list);
}
public function deleteEstimatedDelivery()
{
return Db::getInstance()->execute('DELETE FROM '. _DB_PREFIX_ .'estimateddelivery WHERE `id_estimateddelivery` = '. (int)Tools::getValue('id_estimateddelivery'));
}
else if(Tools::isSubmit('delete' . $this->name))
{
if(!$this->deleteEstimatedDelivery())
$output . $this->displayError($this->l('An error occured during link deletion'));
else
$output . $this->displayConfirmation($this->l('The estimated delivery has been deleted'));
}
Even though there was no error message, the code line: $helper->idientifier = 'id_estimateddelivery'; had a typo. Should have been identifier.
I'm using the data from telegrams received Webhook but I am faced with this error
Webhook tested properly set.
In your opinion, what is the problem?
This is my code:
Route :
Route::post('setwebhook','BotController#setWebhook');
Route::post('updates','BotController#updates');
BotController :
public function setWebhook()
{
$res = Telegram::setWebhook([
'url' => 'https://example.com/telegram-sdk/public/updates'
]);
return $res;
}
public function updates()
{
$update = Telegram::getWebhookUpdates();
$chat_id = $update->getMessage()->getChat()->getId();
$text = $update->getMessage()->getText();
$name = $update->getMessage()->getChat()->getFirstName();
if ($text == '/start') {
Telegram::sendMessage([
'chat_id' => $chat_id,
'text' => 'Hello World'
]);
}
}
I have a provision to upload logo for companies in my application. Uploading and saving on creating profile works fine. But on update, logo goes empty if I am not uploading it again!
Here's my update form
<?php $form = ActiveForm::begin([
'options' => ['enctype'=>'multipart/form-data']
]); ?>
.....
<?= $form->field($model, 'logo')->fileInput() ?>
...
My Controller action
if ($model->load($_POST) ) {
$file = \yii\web\UploadedFile::getInstance($model, 'logo');
if($file){
$model->logo=$file; }
if($model->save()){
if($file)
$file->saveAs(\Yii::$app->basePath . '/web/images/'.$file);
}
return $this->redirect(['profile']);
} else {
return $this->renderPartial('update', [
'model' => $model,
]);
}
My Rules:
public function rules()
{
return [
[['logo'], 'image', 'extensions' => 'jpg,png', 'skipOnEmpty' => true],
[['name'], 'required'],
[['name', 'description'], 'string'],
];
}
Any ideas????
skipOnEmpty does not apply here because in the update action the $model->logo attribute will not be empty, it will be a string with the file name.$file is still an array with only keys, but not values if not uploaded again. So checked the $file->size instead of checking !empty($file). Fixed the issue by modifying the controller code as follows!
$model = $this->findModel($id);
$current_image = $model->featured_image;
if ($model->load(Yii::$app->request->post())) {
$image= UploadedFile::getInstance($model, 'featured_image');
if(!empty($image) && $image->size !== 0) {
//print_R($image);die;
$image->saveAs('uploads/' . $image->baseName . '.' .$image->extension);
$model->featured_image = 'uploads/'.$image->baseName.'.'.$image->extension;
}
else
$model->featured_image = $current_image;
$model->save();
return $this->redirect(['update', 'id' => $model->module_id]);
} else {
return $this->render('add', [
'model' => $model,
]);
}
'skipOnEmpty' => !$this->isNewRecord
For update it can be skipped.
I have been looking into select2 and yii and have managed to load data via json request/response.
The issue I'm faced with is when I try to select an entry of the returned data, I can not.
Where am I going wrong ? The data returnd by the action is json formatted as CustomerCode and Name
Widget code in form
$this->widget('bootstrap.widgets.TbSelect2', array(
'asDropDownList' => false,
'name' => 'CustomerCode',
'options' => array(
'placeholder' => 'Type a Customer Code',
'minimumInputLength' => '2',
'width' => '40%',
'ajax' => array(
//'url'=> 'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
'url'=> Yii::app()->getBaseUrl(true).'/customer/SearchCustomer',
'dataType' => 'jsonp',
'data' => 'js: function (term,page) {
return {
term: term, // Add all the query string elements here seperated by ,
page_limit: 10,
};
}',
'results' => 'js: function (data,page) {return {results: data};}',
),
'formatResult' => 'js:function(data){
var markup = data.CustomerCode + " - ";
markup += data.Name;
return markup;
}',
'formatSelection' => 'js: function(data) {
return data.CustomerCode;
}',
)));
code snipped from controller action SearchCustomer
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderJSON(Customer::model()->searchByCustomer($term));
renderJSON function from base controller class
protected function renderJSON($data)
{
header('Content-type: application/json');
echo $_GET['callback'] . "(";
echo CJSON::encode($data);
echo ")";
foreach (Yii::app()->log->routes as $route) {
if($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
Appreciate any help on this
i try.
change
'dataType' => 'jsonp' to 'dataType' => 'json'
and check json format
https://github.com/ivaynberg/select2/issues/920