I have a form where images can be submitted, this isn't originally my code, I'm inheriting it and I'm trying to figure it out and fix the problem.
When editing the datas from this form, the input file is empty as opposed to the other inputs. So saving actually replaces the current file to "array" in database.
I would like to be able to keep the current one if it is unchanged ?
Form edit :
<h1>Edit</h1>
<?php
echo $this->Form->create($template,['enctype' => 'multipart/form-data']);
echo $this->Form->input('title');
echo $this->Form->input('works_id');
echo $this->Form->input('photo',['type' => 'file']);
echo $this->Form->input('text', ['rows' => '4']);
echo $this->Form->input('url');
echo $this->Form->button(__('Save'));
echo $this->Form->end();
?>
edit function from controller :
public function edit($id = null){
$template = $this->Templates->get($id);
if ($this->request->is(['post', 'put'])) {
$template = $this->Templates->patchEntity($template, $this->request->data,['associated' => ['Works']]);
if ($this->Templates->save($template)) {
$this->Flash->success(__('Your template has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your template.'));
}
$this->set('template', $template);
$works = $this->Templates->Works->find('list');
$this->set(compact('works'));
}
In my database it saves on two colomns :
file_dir and filename, so it confuses me even more on how to get the file in the edit form.
edit : adding TemplatesTable :
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class TemplatesTable extends Table
{
protected function _initializeSchema(\Cake\Database\Schema\Table $table){
$table->columnType('photo', 'proffer.file');
return $table;
}
public function initialize(array $config){
$this->addBehavior('Timestamp');
$this->addBehavior('Proffer.Proffer', [
'photo' => [
'root' => WWW_ROOT.'files',
'dir' => 'photo_dir',
'thumbnailSizes' => [
'square' => ['w' => 200, 'h' => 200],
'portrait' => ['w' => 100, 'h' => 300, 'crop' => true],
],
'thumbnailMethod' => 'gd' // Options are Imagick, Gd or Gmagick
]
]);
$this->belongsTo(
'Works',
[
'foreignKey' => 'work_id',
]
);
}
public function validationDefault(Validator $validator){
$validator
->notEmpty('work_id')
->notEmpty('title');
return $validator;
}
}
According to the docs, the Proffer behavior can handle empty uploads out of the box, and you just have to configure the validation rules for the field accordingly to allow it to be empty on update:
If you want your users to submit a file when creating a record, but
not when updating it, you can configure this using the basic Cake
rules.
$validator
->requirePresence('image', 'create')
->allowEmpty('image', 'update');
So now your users do not need to upload a file every time they update
a record.
https://github.com/davidyell/CakePHP3-Proffer/blob/0.8.2/docs/validation.md
https://github.com/davidyell/CakePHP3-Proffer/blob/0.8.2/src/Model/Behavior/ProfferBehavior.php#L56
So in your case that would be:
->requirePresence('photo', 'create')
->allowEmpty('photo', 'update')
Related
I've got very big trouble with custom operations in Laravel backpack.
The documentated setup is clear but lack a real exemple with a form.
In my case I wanted to use the form engine to create a form for a relationship.
First step I did this :
public function getProtocoleForm($id)
{
// Config base
$this->crud->hasAccessOrFail('update');
$this->crud->setOperation('protocole');
//
$this->crud->addFields([
[ 'name' => 'codeCim',
'type' => 'text',
'label' => 'Code CIM',
],
]);
$this->crud->addSaveAction([
'name' => 'save_action_protocole',
'visible' => function($crud) {
return true;
},
'button_text' => 'Ajouter le procotole',
'redirect' => function($crud, $request, $itemId) {
return $crud->route;
},
]);
// get the info for that entry
$this->data['entry'] = $this->crud->getEntry($id);
$this->data['crud'] = $this->crud;
$this->data['saveAction'] = $this->crud->getSaveAction();
$this->data['title'] = 'Protocole ' . $this->crud->entity_name;
return view('vendor.backpack.crud.protocoleform', $this->data);
}
This is working fine, the form appears on the screen, then I did a setup for a post route like this :
Route::post($segment . '/{id}/protocolestore', [
'as' => $routeName . '.protocolestore',
'uses' => $controller . '#storeProtocole',
'operation' => 'protocole',
]);
The route appears correctly when I execute the artisan command but the storeProtocole function is never called. I checked the generated HTML and the form action is correct and checking in the "network" panel of the browser is also targeting the correct route.
Can you help me and tell me where I missed something ?
[Quick update] I made a mistake, the form route is not good in the HTML, it takes the route of the main controller.
I do my project in yii2.
I have form which get data from db to dropdown list(using kartik depdtop widget).
First field is "type_of_goods", depending on "type_of_goods" customer receive "goods".
After they are two text input field with "goods_amount" and "total_cost" of goods depends on "goods_amount" (goods_amount * price).
Customer inputs goods amount he wants to buy, or money amount to which he wants to buy and js script shows him value in another field in both cases.
Price value is in goods table in DB.
Can I get goods_id or some information about goods from "goods"-field(to perform db query and get price and put it into js function), or maybe even price to put it into js script which do things that I wrote above.
How can I realize it? Is it right way to do it?
Code:
View
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'form-horizontal col-lg-11',
'enctype' => 'multipart/form-data'
],
]); ?>
<?= $form->field($type_of_goods, 'id')
->dropDownList(
ArrayHelper::map(Type_of_goods::find()->all(), 'id', 'name'),
['id'=>'type_of_goods_id']
);
?>
<?= $form->field($goods, 'id')->widget(DepDrop::classname(), [
'options' => ['id' => 'id'],
'pluginOptions' => [
'depends' => ['type_of_goods_id'],
'placeholder' => 'Choose your goods',
'url' => \yii\helpers\Url::to(['goods/goods-dep-type'])
]
]);
?>
<?= $form->field($goods, 'price')->textInput();
?>
<?= $form->field($order, 'amount')->textInput();
?>
<?php ActiveForm::end(); ?>
Controller:
public function actionGoodsDepType()
{
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$game_id = $parents[0];
$out = \app\models\Goods::gelGoodsList($goods_type_id);
echo Json::encode(['output' => $out, 'selected' => '']);
return;
}
}
echo Json::encode(['output' => '', 'selected' => '']);
}
Model:
public static function gelGoodsList($type_id)
{
$query = self::find()
->where(['type_id' => $type_id])
->select(['id', 'name'])->asArray()->all();
return $query;
}
public static function getPrice($id)
{
$query = self::find()
->where(['id' => $id])
->select(['price'])->asArray()->one();
return $query;
}
You would need to create an AJAX request each time user inputs new value. This might work well (place at the bottom of the view file):
$this->registerJs("
$('#Type_of_goods-price').on('change', function() { // Should be ID of a field where user writes something
$.post('index.php?r=controller/get-price', { // Controller name and action
input_price: $('#Type_of_goods-price').val() // We need to pass parameter 'input_price'
}, function(data) {
total_price = $.parseJSON(data)['result']; // Let's say, controller returns: json_encode(['result' => $totalPrice]);
$('#Type_of_goods-total').value = total_price; // Assign returned value to a different field that displays total amount of price
}
});
");
You only need to set correct elements' correct IDs and write a method in controller (using this example, it would be controller controller name and actionGetPrice method name).
my controller file inside api/v1/controller/
class ProfileController extends ActiveController
{
public $modelClass = 'app\models\Profile';
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' =>
['index', 'view', 'createnew','update','search'],
'formats' =>
['application/json' => Response::FORMAT_JSON,],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
'view' => ['get'],
'createnew' => ['post'],
'update' => ['put'],
'delete' => ['delete'],
'deleteall' => ['post'],
'search' => ['get']
],
]
];
}
public function actionCreatenew() {
$model = new Profile();
$model->load(Yii::$app->request->post());
$model->asset = UploadedFile::getInstance($model, 'asset');
$name = $model->user_id;
if($model->asset) {
$model->asset->saveAs('uploads/'.$name.'.
'.$model->asset->extension);
$model->asset = $model->asset->name.'.'.
$model->asset->extension;
}
if($model->save()) {
echo json_encode(array('status'=>"Success",
'data'=>$model->attributes),JSON_PRETTY_PRINT);
} else {
echo json_encode(array('status'=>"Failure",
'error_code'=>400,
'errors'=>$model->errors),JSON_PRETTY_PRINT);
}
}
}
When I try to use access this from Postman like:
POST http://localhost/myapp/api/v1/profiles
I get Invalid Parameter – yii\base\InvalidParamException
Response content must not be an array.
What is the issue?? help would be grateful!! Thanks
You can easily receive single / multi-uploaded files using HTTP POST with form-data encoding in Yii2, directly in your Yii2 Controller / action.
Use this code:
$uploads = UploadedFile::getInstancesByName("upfile");
if (empty($uploads)){
return "Must upload at least 1 file in upfile form-data POST";
}
// $uploads now contains 1 or more UploadedFile instances
$savedfiles = [];
foreach ($uploads as $file){
$path = //Generate your save file path here;
$file->saveAs($path); //Your uploaded file is saved, you can process it further from here
}
If you use Postman API client to test how your API is working, you can configure the upload endpoint to work like this for multi-file uploads:
Note: The upfile[] square brackets are important! Postman will happily let you select multiple files for upload in one slot, but this will not actually work. Doing it the way shown in the screenshot makes an array of files available to the Yii2 action, through the UploadedFile mechanism. This is roughly equivalent to the standard PHP $_FILES superglobal variable but with easier handling.
Single files can be uploaded with or without the [] square brackets after the key name. And of course you can name upfile whatever you like, for your convention.
You should use \yii\web\UploadedFile::getInstanceByName('asset'); instead of getInstance() checkout this Link
I use an ActiveForm in Yii2 for my SearchModel. After click on search button the form fields remember previous values but SorterDropdown is refreshed.
<?php echo SorterDropdown::widget(['sort' => $dataProvider->sort,
'label' => $model->sortedBy($dataProvider->sort->attributes),])
?>
SorterDropdown is just a wrapper of ButtonDropdown.
How can I forse the SorterDropdown to remember sort order (and show it) after the form submition?
class SorterDropdown extends LinkSorter
{
public $label;
protected function renderSortLinks()
{
$attributes = empty($this->attributes) ? array_keys($this->sort->attributes) : $this->attributes;
$links = [];
foreach ($attributes as $name) {
$links[] = Html::tag('li', $this->sort->link($name, ['tabindex' => '-1']));
}
if (empty($this->label))
$this->label = 'Sort';
return \yii\bootstrap\ButtonDropdown::widget([
'encodeLabel' => false,
'label' => $this->label,
'dropdown' => [
'items' => $links,
],
]);
}
You should add some class to li element, which indicate active state of it and special style in CSS file.
I have successfully added my own form (from the same module) into my custom template, but now I wish to load the taxonomy add term form (used by ubercart I think for product categories in the catalog vocab) into my template.
I have gotten this far with my module - filename simpleadmin.module
/**
* #file
* A module to simplify the admin by replacing add/edit node pages
*/
function simpleadmin_menu() {
$items['admin/products/categories/add'] = array(
'title' => 'Add Category',
'page callback' => 'simpleadmin_category_add',
'access arguments' => array('access administration pages'),
'menu_name' => 'menu-store',
);
return $items;
}
function simpleadmin_category_add() {
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
$output = drupal_get_form('taxonomy_form_term');
return theme('simpleadmin_category_add', array('categoryform' => $output));
}
function simpleadmin_theme() {
return array(
'simpleadmin_category_add' => array(
'template' => 'simpleadmin-template',
'variables' => array('categoryform' => NULL),
'render element' => 'form',
),
);
}
?>
And as for the theme file itself - filename simpleadmin-template.tpl.php, only very simple at the moment until I get the form to load into it:
<div>
This is the form template ABOVE the form
</div>
<?php
dpm($categoryform);
print drupal_render($categoryform);
?>
<div>
This is the form template BELOW the form
</div>
Its telling me that it is
Trying to get property of non-object in taxonomy_form_term()
and throwing up an error. Should I be using node_add() and passing the nodetype?
To render a taxonomy term form, the function should be able to know the vocabulary to which it belongs to. Otherwise how would it know which form to show? I think this is the proper way to do it.
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
if ($vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_name')) {
$form = drupal_get_form('taxonomy_form_term', $vocabulary);
return theme('simpleadmin_category_add', array('categoryform' => $form));
}
To redirect your form use hook_form_alter
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
//get your vocabulary id or use print_r or dpm for proper validation
if($form_id == 'taxonomy_form_term' && $form['#vocabulary']['vid'] = '7' ){
$form['#submit'][] = 'onix_sections_form_submit';
}
}
function yourmodule_form_submit($form, &$form_state) {
$form_state['redirect'] = 'user';
}