CMultiFileUpload class not inserting image names on the database yii - php

I'm working on multi file(images) uploading functionality.
I've tried everything I got.
It's not working.
It's uploading images on the path I specified but not inserting image's names on the table column.
The table's column name is "sample"
Here's the snippet of the view:
$this->widget('CMultiFileUpload', array(
'model' => $model,
'name' => 'sample',
'attribute' => 'sample',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',
'remove' => '[x]',
'max' => 20,
));
This is the controller's code the(the function that dealing with the part):
public function actionCreate($project_id) {
$model = new Bid();
$project = $this->loadModel('Project', $project_id);
if (count($project->bids) == 5) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'This project has already reached its maximum number of bids, so you cannot post a new bid.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
if (!empty($project->bid)) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'This project has a selected bid already, so you cannot post a new bid.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
if ($project->closed) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'You cannot add bids as this project has been closed.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
$model->project = $project;
if (isset($_POST['Bid'])) {
$model->attributes = $_POST['Bid'];
$photos = CUploadedFile::getInstancesByName('sample');
if (isset($photos) && count($photos) > 0) {
foreach ($photos as $image => $pic) {
$pic->name;
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/'.$pic->name)) {
// add it to the main model now
$img_add = new Bid();
$img_add->filename = $pic->name;
$img_add->save();
}
else {
}
}
}
$model->project_id = $project->id;
$model->freelancer_id = $this->currentUser->id;
if ($model->save()) {
$this->redirect(array('project/view', 'id' => $project->id, '#' => 'bidslist'));
}
}
$this->render('create', array(
'model' => $model,
));
}
Thanks in Advance.
Please let me know if anyone needs anything else for better understanding.

If i underssot you correctly when you saving the model
$img_add = new Bid();
$img_add->sample = $pic->name;
$img_add->save();

Related

Create new record using 2amigos SelectizeDropDownList in Yii2

I am trying to implement the 2amigos SelectizeDropDownList widget in a form to add new values to a table directly within the dropdown.
I am using the model Book and the Model Author so basically want to be able to add a new author in the book form.
This is the book controller at the update function:
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
'categories' => BookCategory::find()->active()->all(),
'publishers' => Publisher::find()->all(),
'copirights' => Copiright::find()->all(),
'authors' => Author::find()->all(),
]);
}
}
This is the form:
<?=
$form->field($model, 'author_id')->widget(SelectizeDropDownList::className(), [
// calls an action that returns a JSON object with matched
// tags
'loadUrl' => ['author/list'],
'value' => $authors,
'items' => \yii\helpers\ArrayHelper::map(\common\models\author::find()->orderBy('name')->asArray()->all(), 'id', 'name'),
'options' => [
'class' => 'form-control',
'id' => 'id'
],
'clientOptions' => [
'valueField' => 'id',
'labelField' => 'name',
'searchField' => ['name'],
'autosearch' => ['on'],
'create' => true,
'maxItems' => 1,
],
])
?>
And this is the function author controller:
public function actionList($query) {
$models = Author::findAllByName($query);
$items = [];
foreach ($models as $model) {
$items[] = ['id' => $model->id, 'name' => $model->name];
}
Yii::$app->response->format = \Yii::$app->response->format = 'json';
return $items;
}
The form works fine to load, filter, search and add new items.
But it is not inserting the new typed attribute in the author table.
Do I need to add something in the book controller?
How can I check if it is a new value or a change of an existing author?
Thanks a lot
I made it work with the following code, not sure the most elegant because i am checking the if the author_id is a number or a string.
In my case the author won't be a number anyway.
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$x = Yii::$app->request->post('Book');
$new_author = $x['author_id'];
if (!is_numeric($new_author)) {
$author = new Author();
$author->name = $new_author;
$author->save();
$model->author_id = $author->id;
}
if ($model->save()) {
return $this->redirect(['index']);
}
} else {
return $this->render('update', [
'model' => $model,
'categories' => BookCategory::find()->active()->all(),
'publishers' => Publisher::find()->all(),
'copirights' => Copiright::find()->all(),
'authors' => Author::find()->all(),
]);
}
}

Cakephp redirection after submission

I'm developing an application with Cakephp and I can't find my answer in existing topics...
I have a main menu with several action (Edit/Delete/Add) which is manage sockets. When I edit a socket and I submit my update, my socket is updated correctly BUT my redirection on the main menu doesn't work. The URL stay the same.
For example, I edit socket with id = 2. The application go to '/my/app/sockets/edit/2'. After update and submit, the application should redirect to '/my/app/sockets/index' but it doesn't work.
Below, you can see my code.
SocketsController.php :
public function index($searchCloset = null) {
$this->Paginator->settings = $this->paginate;
if($searchCloset != null) {
$sockets = $this->paginate('Socket', array(
'Closet.name LIKE' => $searchCloset
));
}
else{
$sockets = $this->paginate('Socket');
$searchCloset = '' ;
}
$this->set('sockets',$sockets);
$this->set('closets',$this->Socket->Closet->find('all'));
$this->set('searchCloset',$searchCloset);
}
public function edit($id = null){
// Bad socket management
if (!$id) {
throw new NotFoundException(__('Invalid socket'));
}
$socket = $this->Socket->findByid_socket($id);
if (!$socket) {
throw new NotFoundException(__('Invalid socket'));
}
// if there's a submit
if ($this->request->is(array('post'))) {
$this->Socket->id = $id;
if ($this->Socket->save($this->request->data)) {
// update 'lastchange' column
if($this->updateSocketStatus($this->Socket->id)){
$this->Session->setFlash(__('Your socket has been updated.'));
}
else {
$this->Session->setFlash(__('Unable to create history.'));
}
}
else {
$this->Session->setFlash(__('Unable to update your socket.'));
}
return $this->redirect(array('controller' => 'sockets','action' => 'index'));
}
// send all informations about the socket to the view
$this->set('socket',$socket);
// send closets list to the view (select menu)
$this->set('closets',$this->Socket->Closet->find('list',array(
'fields' => array('Closet.id_closet','Closet.name')
)));
}
edit.ctp :
<h2>Edit socket</h2>
<div><?php
echo $this->Form->create('Socket');
echo $this->Form->input('Socket.name', array(
'label' => 'Socket name :',
'default' => $socket['Socket']['name']
));
echo $this->Form->input('Socket.location', array(
'label' => 'Location :',
'default' => $socket['Socket']['location']
));
echo $this->Form->input('Socket.comment', array(
'label' => 'Comment :',
'default' => $socket['Socket']['comment']
));
echo $this->Form->input('Socket.closet_id',array(
'type' => 'select',
'label' => 'Closet :',
'options' => $closets,
'default' => $socket['Closet']['id_closet']
));
echo $this->Form->end('Save socket');
echo $this->Form->postButton(
'Back',
array('controller' => 'sockets','action' => 'index'),
array(
'id' => 'back_button',
'class' => 'ui-btn ui-btn-inline ui-icon-back ui-btn-icon-left'
)
);
?></div>
I've already search and it could be a cache problem.
Thanks in advance.
Can you force with
$this->redirect($this->referer());
Please, try and comment
Your request checking if-statement is omitted, because is() method accepts param of string type according to documentation.
So you should change line:
if ($this->request->is(array('post'))) { ... }
into:
if ($this->request->is('post')) { ... }

magento saveAction - for beginners

I am a Magento beginner so please bear with me...
I am creating a simple extension for my site to add a custom field to my Tags in adminhtml. The custom field is just a number which I need to identify a specific Z-block (cms block extension) so that I can access it as a widget and show it on the frontend in the Tag "category".
I have created a custom module which is working: I set a field in the form using $fieldset and have extended TagController.php, both of which are being used (I made a simple trial to see whether or not they had been recognized). However, I do not know how to go about saving my custom field to DB (whether amending saveAction is enough, and I haven't done it properly, or if I need to add a custom Model or sql install).
Sorry for the "basic" question but I'm new at this, and have mostly done frontend dev (so my extension knowledge is simply limited).
Thank you to anyone who can help...
Claudia
NEW TAG FORM:
public function __construct()
{
parent::__construct();
$this->setId('tag_form');
$this->setTitle(Mage::helper('tag')->__('Block Information'));
}
/**
* Prepare form
*
* #return Mage_Adminhtml_Block_Widget_Form
*/
protected function _prepareForm()
{
$model = Mage::registry('tag_tag');
$form = new Varien_Data_Form(
array('id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post')
);
$fieldset = $form->addFieldset('base_fieldset',
array('legend'=>Mage::helper('tag')->__('General Information')));
if ($model->getTagId()) {
$fieldset->addField('tag_id', 'hidden', array(
'name' => 'tag_id',
));
}
$fieldset->addField('form_key', 'hidden', array(
'name' => 'form_key',
'value' => Mage::getSingleton('core/session')->getFormKey(),
));
$fieldset->addField('store_id', 'hidden', array(
'name' => 'store_id',
'value' => (int)$this->getRequest()->getParam('store')
));
$fieldset->addField('name', 'text', array(
'name' => 'tag_name',
'label' => Mage::helper('tag')->__('Tag Name'),
'title' => Mage::helper('tag')->__('Tag Name'),
'required' => true,
'after_element_html' => ' ' . Mage::helper('adminhtml')->__('[GLOBAL]'),
));
$fieldset->addField('zblock', 'text', array(
'name' => 'zblock_id',
'label' => Mage::helper('tag')->__('Z-Block Id'),
'title' => Mage::helper('tag')->__('Z-Block Id'),
'required' => true,
'after_element_html' => ' ' . Mage::helper('adminhtml')->__('[GLOBAL]'),
));
$fieldset->addField('status', 'select', array(
'label' => Mage::helper('tag')->__('Status'),
'title' => Mage::helper('tag')->__('Status'),
'name' => 'tag_status',
'required' => true,
'options' => array(
Mage_Tag_Model_Tag::STATUS_DISABLED => Mage::helper('tag')->__('Disabled'),
Mage_Tag_Model_Tag::STATUS_PENDING => Mage::helper('tag')->__('Pending'),
Mage_Tag_Model_Tag::STATUS_APPROVED => Mage::helper('tag')->__('Approved'),
),
'after_element_html' => ' ' . Mage::helper('adminhtml')->__('[GLOBAL]'),
));
$fieldset->addField('base_popularity', 'text', array(
'name' => 'base_popularity',
'label' => Mage::helper('tag')->__('Base Popularity'),
'title' => Mage::helper('tag')->__('Base Popularity'),
'after_element_html' => ' ' . Mage::helper('tag')->__('[STORE VIEW]'),
));
if (!$model->getId() && !Mage::getSingleton('adminhtml/session')->getTagData() ) {
$model->setStatus(Mage_Tag_Model_Tag::STATUS_APPROVED);
}
if ( Mage::getSingleton('adminhtml/session')->getTagData() ) {
$form->addValues(Mage::getSingleton('adminhtml/session')->getTagData());
Mage::getSingleton('adminhtml/session')->setTagData(null);
} else {
$form->addValues($model->getData());
}
$this->setForm($form);
return parent::_prepareForm();
}
NEW CONTROLLER:
public function saveAction()
{
if ($postData = $this->getRequest()->getPost()) {
if (isset($postData['tag_id'])) {
$data['tag_id'] = $postData['tag_id'];
}
$data['name'] = trim($postData['tag_name']);
$data['zblock'] = $postData['zblock_id'];
$data['status'] = $postData['tag_status'];
$data['base_popularity'] = (isset($postData['base_popularity'])) ? $postData['base_popularity'] : 0;
$data['store'] = $postData['store_id'];
if (!$model = $this->_initTag()) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Wrong tag was specified.'));
return $this->_redirect('*/*/index', array('store' => $data['store']));
}
$model->addData($data);
if (isset($postData['tag_assigned_products'])) {
$productIds = Mage::helper('adminhtml/js')->decodeGridSerializedInput(
$postData['tag_assigned_products']
);
$model->setData('tag_assigned_products', $productIds);
}
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('The tag has been saved.'));
Mage::getSingleton('adminhtml/session')->setTagData(false);
if (($continue = $this->getRequest()->getParam('continue'))) {
return $this->_redirect('*/tag/edit', array('tag_id' => $model->getId(), 'store' => $model->getStoreId(), 'ret' => $continue));
} else {
return $this->_redirect('*/tag/' . $this->getRequest()->getParam('ret', 'index'));
}
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setTagData($data);
return $this->_redirect('*/*/edit', array('tag_id' => $model->getId(), 'store' => $model->getStoreId()));
}
}
return $this->_redirect('*/tag/index', array('_current' => true));
}
The custom field I'm trying to add is "zblock"...thanks and, again, bear with me! :)
First add the field in database table.
For example if you want to add in your custom table.
ALTER TABLE myCustomModuleTable ADD COLUMN 'myCustomField' int(10);
Thenafter, In your controller action take the model object of that table and set the field.
If you are adding data in existing table row:
$value = 6;
$rowInWhichIWantToSave = Mage:getModel('companyname/modulename')->load($rowId);
$rowInWhichIWantToSave->setData('myCustomField',$value)->save();
If you are adding a new row:
$value = 6;
$rowInWhichIWantToSave = Mage:getModel('companyname/modulename');
$rowInWhichIWantToSave->setData('myCustomField',$value)->save();
Hope this helps!!

How to add images in Photo Album using different Models

hello guys i want to create a gallery using two tables
album table and photo table
'album' holds the (album_name) and 'photo' holds the (pictures)
this is my form
//this is for my album name to album table
<?php echo $form->labelEx($model,'album_name'); ?>
<?php echo $form->textField($model,'album_name'); ?>
<?php echo $form->error($model,'album_name'); ?>
//this is for the pictures to the photo table
<?php $this->widget('CMultiFileUpload', array(
'name' => 'photo_name',
'model' => $model,
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'File is already added!',
'remove'=>Yii::t('ui','Remove'),
'denied' => 'Not images', // useful,
'htmlOptions'=>array(
'multiple' => 'multiple',
'class' => 'btn btn-success fileinput-button',),
)); ?>
this is my controller
public function actionCreate()
{
$model = new Album;
$model2 = new Photo;
if (isset($_POST['Album'])) {
$model->attributes = $_POST['Album'];
$model2->attributes = $_POST['Photo'];
$photos = CUploadedFile::getInstancesByName('photo_name');
if (isset($photos) && count($photos) > 0) {
foreach ($photos as $pic) {
echo $pic->name.'<br />';
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/assets/photos/'.$pic->name)) {
$model2 = new Photo();
$model2->attributes = $_POST['Photo'];
$model2->photo_name = $pic->name;
$model2->photo_id = NULL;
$model2->isNewRecord= true;
$model2->save();
} else {
echo 'Cannot upload!';
}
}
}
if ($model->save())
$this->redirect(array('index'));
}
$this->render('create', array(
'model' => $model,
));
}
am i doing it the right way? because when i run this code its only adding the album_id and album_name in the album table
the photo table is empty. Also the actionCreate is in the AlbumController

yii load data from database base on $_GET

I have a controller that has a display data from a database depending on the ?id=, it works correctly. However, if you do not give any value id gets error
error 400
Your request is invalid.
My code:
public function actionIndex($id)
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->pageTitle = 'Page';
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => $id),
//if $id is not defined then error
)
);
}
$ModelPages = Pages::model()->findAll($criteria);
$this->render('index',
array(
'Model' => $ModelPages,
)
);
}
I tried this out in such a way, but it did not help.
public function actionIndex($id)
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->pageTitle = 'Page';
if(empty($id)){
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => 'index'),
)
);
}
else {
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => $id),
)
);
}
$ModelPages = Pages::model()->findAll($criteria);
$this->render('index',
array(
'Model' => $ModelPages,
)
);
}
Is my solution is correct (safe) when it comes to displaying the content according to the site?
You solution is correct but better use getQuery() method for fetching GET parameters and handle the error if no pages found:
public function actionIndex($id='index') //Notice the default parameter value
{
$id = Yii::app()->request->getQuery('id', 'index') //if id GET parameter does not exist $id will be 'index'
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => $id),
)
);
$ModelPages = Pages::model()->findAll($criteria);
if (empty($ModelPages)) {
throw new CHttpExeption(404,'page not found');
}
$this->render('index',
array(
'Model' => $ModelPages,
)
);
}
Also if your action can not receive id parameter you should set default value for it (actionIndex($id='index'))
Try simply this way
public function actionIndex($id)
{
if(isset($id) && $id>0)
{
$this->pageTitle = 'Page';
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => $id),
)
);
$ModelPages = Pages::model()->findAll($criteria);
$this->render('index',
array(
'Model' => $ModelPages,
)
);
}else
throw new CHttpException(404,'invalid request');
}

Categories