freesoftwarefactory / smartform
自动构建表单。高级控件。Yii2
1.0.0004
2017-11-13 22:13 UTC
Requires
- php: >=5.3.2
This package is auto-updated.
Last update: 2024-09-17 21:21:33 UTC
README
-
将此类安装以使其可见
cd /your/app/components; ln -s ../vendor/freesoftwarefactory/smartform/SmartformWidget.php .
-
通过在您的 'params' 部分安装它来设置配置文件
// copy the template from ./template/smartform.php to: 'field-groups'=>require(__DIR__.'/my-smart-form-settings.php'),
用法
[php]
use yii\widgets\ActiveForm;
$form = ActiveForm::begin();
echo \app\components\SmartformWidget::widget([
'config_entry'=>'field-groups',
'form_id'=>'form-1',
'active_form'=>$form,
'model'=>$model,
]);
ActiveForm::end();
回调示例
有时需要回调来获取值。
回调示例:从数据库读取选择选项。
[php]
<?php
function _somecallback($_call,$_model,$_field_name){
if('select-options' == $_call){
if('some_custom_field_name'==$_field_name){
$options = [''=>'--Choose--'];
foreach(\app\models\Options::all() as $item)
$options[$item->id] = $item->text;
return $options;
}
}
}
?>
...html...
<?=\app\components\SmartformWidget::widget([
...
'callback'=>'_somecallback',
...
]);?>
如何上传文件
- 在您的配置文件中,以这种方式定义一个名为 "product_image" 的字段
"product_image"=>"upload_one_picture",
- 在部件定义中,添加一个内联回调。这用于告诉部件放置 $_POST 和 $_FILES 的位置。
echo \app\components\SmartformWidget::widget([
'config_entry'=>'field-groups',
'form_id'=>'some-form-id',
'active_form'=>$form,
'model'=>$model,
'callback' => function($_call,$_model,$_fieldname){
if('get_file_upload_url'==$_call){
return \yii\helpers\Url::toRoute(['ajax-upload-product-image']);
}
if('instance_files' == $_call){
$list = [];
if('product_image'==$_fieldname) $list[] = [
'id'=>1, 'file_name'=>'', 'file_path'=>'',
'preview_url'=>'/media/landingpage/product/thumb/'.$_model->id,
'delete_url'=>'',
];
return $list;
}
}
]);
- 将接收 $_POST 和 $_FILES 的控制器应声明一个动作和一些 CSRF 异常
// methods required in the controller:
public function beforeAction($action) {
if($action->id == 'ajax-upload-product-image')
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
public function actionAjaxUploadProductImage(){
if(!Yii::$app->request->isAjax) die('invalid ajax request');
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model_id=filter_input(INPUT_POST,"model_id",FILTER_SANITIZE_STRING);
// this will help you to get more information:
Yii::info("UPLOAD_INFO\n", print_r(["POST"=>$_POST,"FILES"=>$_FILES],true));
$model = $this->findModel($model_id);
$tmp_file = $_FILES['Landingpage']['tmp_name']['product_image'];
$binary_data = file_get_contents($tmp_file);
return [];
}
- 仅作参考,注入到动作中的 LOG 会告诉您以下内容,因此请使用此信息以获取您的文件
$_POST = [
'file_id' => '0'
'model_id' => '1'
'field_name' => 'product_image'
]
$_FILES = [
'Landingpage' => [
'name' => [
'product_image' => 'foto_1_verde.jpg'
]
'type' => [
'product_image' => 'image/jpeg'
]
'tmp_name' => [
'product_image' => '/tmp/phppQhABh'
]
'error' => [
'product_image' => 0
]
'size' => [
'product_image' => 2597
]
]
]