如何在 yii2 中使用单个操作更新将存储在不同 table 中的多个图像
how to update multiple image that will store in different table using single action in yii2
在此更新操作代码中,仅更新文件夹中的数据和更新图像,但不更新另一个 table tabl4e 图像
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if ($model->validate()) {
$model->save();
$cid = $model->id;
if (isset($_FILES['attr_name']['tmp_name'])) {
$photos = UploadedFile::getInstancesByName('attr_name');
$imgName = array();
if (isset($photos) && count($photos) > 0) {
$DD = 0 ;
foreach ($photos as $image => $pic) {
$imagepath = Yii::getAlias('@image').'/';
$imageFileName = rand(10, 100).$pic->name;
$imageFile = $imagepath.$imageFileName;
if ($pic->saveAs($imageFile)) {
$imgName[] = $imageFileName;
} else {
//echo 'Cannot upload!';
}
$Image = new Image();
$Image->c_id = $cid;
$Image->image = $imageFileName;
$img = $Image->image;
if (isset($_POST['deletedImg'])) {
$pics = $_POST['deletedImg'];
foreach ($pics as $img1) {
$image = $img1;
unlink(Yii::getAlias('@image').'/'.$image);
}
} else {
$Image->image = $img;
}
if ($Image->validate()) {
$Image->save();
} else {
print '<pre>';
print_r($Image->errors);
exit;
}
unset($Image);
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
jQuery
在此代码中将获取多个文件按钮并存储和删除多个图像,我正在获取删除图像 ID,如何在更新操作中使用此 ID,我不知道。
$(".removeBtn").click(function(event){
var img =$(this).attr("data-id");
var id = $(this).attr('id');
var hiddenfield= '<input type="hidden" value="'+img+'" name="deletedImg[]" id=""/>';
$("#deleted-img").append(hiddenfield);
$(this).parent().parent().remove();
});
$(".btnAddRec").click(function(){
var clonedHTML = $( "#fieldsRow" ).html();
clonedHTML = clonedHTML.replace("<!--BUTTON-->",'<button type="button" class="removeBtn btn btn-xs btn-danger"><i class="glyphicon glyphicon-trash"></i> Delete</button>');
$("#cloned").append('<div class="row" id="fieldsRow">'+clonedHTML+'</div>');
$(".removeBtn").click(function(event){
$(this).parent().parent().remove();
});
$("#cloned #fieldsRow:last-child input ").val('');
});
你真的应该先开始重构你的代码。
例如,您尝试在每次迭代上传图片的循环中删除图片;将图像文件名多次分配给图像模型属性,反之亦然,未使用的变量($DD
?)可能还有更多。
但我建议您首先开始查看官方文档。这个用例甚至还有一个代码示例:
高级方法:创建专用的多图上传表单(模型)并在此处添加所有上传逻辑。
从示例中复制:
模型上传表单
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* @var UploadedFile[]
*/
public $imageFiles;
public function rules()
{
return [
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4],
];
}
public function upload()
{
if ($this->validate()) {
foreach ($this->imageFiles as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}
}
查看(HTML 表格)
编辑此内容以添加您的 jQuery 脚本
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
你在控制器中上传的动作:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class SiteController extends Controller
{
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
if($model->validate())
{
$model->save();
$cid = $model->id;
$Image = Image::find()->where(['c_id' => $cid])->asArray()->all();
if(!empty($Image)){
if(isset($_FILES['attr_name']['tmp_name']) > 0){
if(isset($_POST['deletedImg']))
{
$pics = $_POST['deletedImg'];
// echo "<pre>";print_r($pics);exit;
foreach($pics as $img1)
{
$image = $img1;
unlink(Yii::getAlias('@image').'/'.$image);
}
$connection = \Yii::$app->db;
$delRec = $connection->createCommand(" delete image FROM image WHERE image='$image'");
$delRecExec = $delRec->query();
}
$photos = UploadedFile::getInstancesByName('attr_name');
$imgName = array();
if(isset($photos) && count($photos) > 0)
{
foreach ($photos as $image => $pic) {
$imagepath = Yii::getAlias('@image').'/';
$imageFileName = rand(10,100).$pic->name;
$imageFile = $imagepath.$imageFileName;
if ($pic->saveAs($imageFile))
{
$imgName[] = $imageFileName;
}
else
{
//echo 'Cannot upload!';
}
$Image = new Image();
// print_r($Image);exit;
$Image->c_id = $cid;
$Image->image = $imageFileName;
$img = $Image->image;
if($Image->validate()){
$Image->save();
}else{
print '<pre>';print_r($Image->errors);
exit;
}
unset($Image);
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
在此更新操作代码中,仅更新文件夹中的数据和更新图像,但不更新另一个 table tabl4e 图像
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if ($model->validate()) {
$model->save();
$cid = $model->id;
if (isset($_FILES['attr_name']['tmp_name'])) {
$photos = UploadedFile::getInstancesByName('attr_name');
$imgName = array();
if (isset($photos) && count($photos) > 0) {
$DD = 0 ;
foreach ($photos as $image => $pic) {
$imagepath = Yii::getAlias('@image').'/';
$imageFileName = rand(10, 100).$pic->name;
$imageFile = $imagepath.$imageFileName;
if ($pic->saveAs($imageFile)) {
$imgName[] = $imageFileName;
} else {
//echo 'Cannot upload!';
}
$Image = new Image();
$Image->c_id = $cid;
$Image->image = $imageFileName;
$img = $Image->image;
if (isset($_POST['deletedImg'])) {
$pics = $_POST['deletedImg'];
foreach ($pics as $img1) {
$image = $img1;
unlink(Yii::getAlias('@image').'/'.$image);
}
} else {
$Image->image = $img;
}
if ($Image->validate()) {
$Image->save();
} else {
print '<pre>';
print_r($Image->errors);
exit;
}
unset($Image);
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
jQuery
在此代码中将获取多个文件按钮并存储和删除多个图像,我正在获取删除图像 ID,如何在更新操作中使用此 ID,我不知道。
$(".removeBtn").click(function(event){
var img =$(this).attr("data-id");
var id = $(this).attr('id');
var hiddenfield= '<input type="hidden" value="'+img+'" name="deletedImg[]" id=""/>';
$("#deleted-img").append(hiddenfield);
$(this).parent().parent().remove();
});
$(".btnAddRec").click(function(){
var clonedHTML = $( "#fieldsRow" ).html();
clonedHTML = clonedHTML.replace("<!--BUTTON-->",'<button type="button" class="removeBtn btn btn-xs btn-danger"><i class="glyphicon glyphicon-trash"></i> Delete</button>');
$("#cloned").append('<div class="row" id="fieldsRow">'+clonedHTML+'</div>');
$(".removeBtn").click(function(event){
$(this).parent().parent().remove();
});
$("#cloned #fieldsRow:last-child input ").val('');
});
你真的应该先开始重构你的代码。
例如,您尝试在每次迭代上传图片的循环中删除图片;将图像文件名多次分配给图像模型属性,反之亦然,未使用的变量($DD
?)可能还有更多。
但我建议您首先开始查看官方文档。这个用例甚至还有一个代码示例:
高级方法:创建专用的多图上传表单(模型)并在此处添加所有上传逻辑。
从示例中复制:
模型上传表单
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* @var UploadedFile[]
*/
public $imageFiles;
public function rules()
{
return [
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4],
];
}
public function upload()
{
if ($this->validate()) {
foreach ($this->imageFiles as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}
}
查看(HTML 表格) 编辑此内容以添加您的 jQuery 脚本
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
你在控制器中上传的动作:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class SiteController extends Controller
{
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
if($model->validate())
{
$model->save();
$cid = $model->id;
$Image = Image::find()->where(['c_id' => $cid])->asArray()->all();
if(!empty($Image)){
if(isset($_FILES['attr_name']['tmp_name']) > 0){
if(isset($_POST['deletedImg']))
{
$pics = $_POST['deletedImg'];
// echo "<pre>";print_r($pics);exit;
foreach($pics as $img1)
{
$image = $img1;
unlink(Yii::getAlias('@image').'/'.$image);
}
$connection = \Yii::$app->db;
$delRec = $connection->createCommand(" delete image FROM image WHERE image='$image'");
$delRecExec = $delRec->query();
}
$photos = UploadedFile::getInstancesByName('attr_name');
$imgName = array();
if(isset($photos) && count($photos) > 0)
{
foreach ($photos as $image => $pic) {
$imagepath = Yii::getAlias('@image').'/';
$imageFileName = rand(10,100).$pic->name;
$imageFile = $imagepath.$imageFileName;
if ($pic->saveAs($imageFile))
{
$imgName[] = $imageFileName;
}
else
{
//echo 'Cannot upload!';
}
$Image = new Image();
// print_r($Image);exit;
$Image->c_id = $cid;
$Image->image = $imageFileName;
$img = $Image->image;
if($Image->validate()){
$Image->save();
}else{
print '<pre>';print_r($Image->errors);
exit;
}
unset($Image);
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}