How to save new row with ID is auto increment in CakePHP - php

Hi i'm a new user with cakePHP version 2.x.x and i'm trying add new Book into table Books in Database but i can't
Please check my code below
class Book extends AppModel{
var $name = "Book";
var $primaryKey = 'ID';
var $validate = array();
public function vaildInput()
{
$this->validate = array(
// Thiet lap validate cho form
"title" => array(
"rule1" => array(
"rule" => "notempty",
"message" => "Không được để trống."
),
"rule2" => array(
"rule" => array("minlength", 5),
"message" => "Vui lòng nhập tối thiểu 5 kí tự."
),
),
"description" => array(
"rule" => "notempty",
"message" => "Không được để trống."
)
);
if($this->validates($this->validate))
return true;
return false;
}}
And Controller
public function form()
{
$this->Book->set($this->data);
if(!$this->Book->vaildInput())
{
$this->set("data", "Data không hợp lệ");
}
else
{
// Every thing is ok
if($this->request->is("post"))
{
if($this->Book->save($this->data))
{
$this->set("data", "Insert Book Success.");
}
else
$this->set("data", $this->data);
}
}
}
View
if(!empty($data))
var_dump($data);
echo $this->form->create("Book", array("action" => ""));
echo $this->form->input('ID',array('type'=>'hidden') );
echo $this->form->input("title");
echo $this->form->input("description");
echo $this->form->end("Add");
with Table Books have column ID is Primary Key with Auto_Increment, so i have a question how i can save new row Book to database ? I tried but didn't success :(

This my mistake because case insensitive. I have use title but in database is Title.

Related

How to load all rows in codeigniter-base-model? REST api

I am trying to load all rows for my REST API through Postman.
I am using codeigniter-base-model MY_Model.php.
https://github.com/jamierumbelow/codeigniter-base-model
This is how my code currently looks like both in my controller/model:
Controller(api_news.php):
class Api_News extends REST_Controller {
function __construct()
{
parent::__construct();
}
function index_get()
{
$id = $this->uri->segment(3);
$this->load->model('News_model');
$news = $this->News_model->get_by(array('id' => $id));
if(isset($news['id'])) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
}
Model(news_model.php):
class News_model extends MY_Model{
protected $_table = 'news';
protected $primary_key = 'id';
protected $return_type = 'array';
}
At the moment if I access:
localhost/my_api/api_news/id/1, 2, 3, etc...
I can access any record by its individual ID and it shows up which is great.
BUT I also want to be able to see all rows by doing this:
localhost/my_api/api_news/id/
and have all rows showing at once.
But I am not sure how to do this...and am getting an unsuccess/false if I try.
Can you please show me how? I am new to PHP in general and I appreciate any help.
Thank you so much!!
Make some changes in your Controller function as below -
function index_get(){
$id = $this->uri->segment(3);
$this->load->model('News_model');
// pass $id to model
$news = $this->News_model->get_by( $id );
if( !empty( $news ) ) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
And in your model make id parameter optional and then check that if id is passed get data based on id otherwise return all data as below -
// $id variable is optional here
function get_by( $id = '' ) {
if ( $id == '' ) {
$news = $this->db->get( 'news' );
}
else {
$news = $this->db->get_where( 'news', array( 'id' => $id ) );
}
// return data to controller
return $news->result();
}
So if you enter id in API then data will be based on that id otherwise all data will be returned.

how to Insert Multiple data with insert_batch in codeigneitor

i want to insert records of fifty persons to the database at one time(this can be increase).when user click the save button data should be save at the database.what is the best way to do it?
Here is my controller
function month_end_data()
{
$data_save = array(
'employee_id' => $emp,
"annual" => $annual,
"casual" => $casual
);
$id = $this->monthend_mod->savemonthenddata($data_save);
echo json_encode(array("status" => TRUE, "id" => $id));
}
Model
class monthend_mod extends CI_Model
{
public function savemonthenddata($data_save = array())
{
if ($this->db->insert_batch('pay_monthend', $data_save)) {
return true;
} else {
return false;
}
}
}
view
<button onclick="month_end_data()" class="btn btn-danger">Save</button>
Try to send in a multidimensional array:
$data = array(
array(
'employee_id' => 'xx',
//... more fields
),
array(
'employee_id' => 'yy',
//... more fields
),
array(
//... and so on
),
);
...and then send that to your savemonthenddata()-method.

Magento Admin Edit Form Fields - Custom Model Field(s)

Wanting to add a custom Model to be rendered in a custom Magento admin form. Just cant seem to get the source model to render any of the options. Couldn't really find anything on google as it was mostly to do with system/config source model examples. See code below
Model File (My/Module/Model/MyModel.php)
<?php
class My_Module_Model_MyModel extends Mage_Core_Model_Abstract
{
static public function getOptionArray()
{
$allow = array(
array('value' => '1', 'label' => 'Enable'),
array('value' => '0', 'label' => 'Disable'),
);
return $allow;
}
}
and my form tab file - Tab shows up with multiselect field, but its blank (My/Module/Block/Adminhtml/Module/Edit/Tab/Data.php)
<?php
class My_Module_Block_Adminhtml_Module_Edit_Tab_Data extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm(){
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('module_form', array('legend'=>Mage::helper('module')->__('Module Information')));
$object = Mage::getModel('module/module')->load( $this->getRequest()->getParam('module_id') );
echo $object;
$fieldset->addField('module_enabled', 'multiselect', array(
'label' => Mage::helper('module')->__('Allowed Module'),
'class' => 'required-entry',
'required' => true,
'name' => 'module_enabled',
'source_model' => 'My_Module_Model_MyModel',
'after_element_html' => '<small>Select Enable to Allow</small>',
'tabindex' => 1
));
if ( Mage::getSingleton('adminhtml/session')->getModuleData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getModuleData());
Mage::getSingleton('adminhtml/session')->setModuleData(null);
} elseif ( Mage::registry('module_data') ) {
$form->setValues(Mage::registry('module_data')->getData());
}
return parent::_prepareForm();
}
}
So I have other fields, tabs that all save the data etc but just cant get the values to render using a custom model inside the multiselect field.
Looks like method name in the source model is incorrect. Also, you probably don't need to extend Mage_Core_Model_Abstract in source models.
Try this:
<?php
class My_Module_Model_MyModel
{
public function toOptionArray()
{
return array(
array('value' => '1', 'label' => Mage::helper('module')->__('Enable')),
array('value' => '0', 'label' => Mage::helper('module')->__('Disable')),
);
}
}
OP's solution migrated from the question to an answer:
updated the MyModel.php to get a foreach in a collection (CMS Pages
for example)
<?php
class My_Module_Model_MyModel
{
public function toOptionArray($withEmpty = false)
{
$options = array();
$cms_pages = Mage::getModel('cms/page')->getCollection();
foreach ($cms_pages as $value) {
$data = $value->getData();
$options[] = array(
'label' => ''.$data['title'].'('.$data['identifier'].')',
'value' => ''.$data['identifier'].''
);
}
if ($withEmpty) {
array_unshift($options, array('value'=>'', 'label'=>Mage::helper('module')->__('-- Please Select --')));
}
return $options;
}
and within My/Module/Block/Adminhtml/Module/Edit/Tab/Data.php I just
removed "source_model" and replaced it with
'values' => Mage::getModel('module/mymodel')->toOptionArray(),
Just to add, also had the issue of multiselect values not
saving/updating the multiselect field on refresh/save on the edit
page. To get this working, I edited the admin controller under the
saveAction (or the action name to save the form data). See below my
saveAction in the controller for the admin/backend located in
My/Module/controllers/Adminhtml/ModuleController.php
public function saveAction() {
$model = Mage::getModel('module/module');
if ($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('module/module');
$model->setData($data)
->setModuleId($this->getRequest()->getParam('module_id'));
try {
if ($model->getCreatedTime() == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$ModuleEnabled = $this->getRequest()->getParam('module_enabled');
if (is_array($ModuleEnabled))
{
$ModuleEnabledSave = implode(',',$this->getRequest()->getParam('module_enabled'));
}
$model->setModuleEnabled($ModuleEnabledSave);
//save form data/values per field
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('module')->__('Item
was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('module_id' => $model->getModuleId()));
return;
}
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('module_id' => $this->getRequest()->getParam('module_id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('module')->__('Unable
to find item to save'));
$this->_redirect('*/*/');
}
This saves an imploded array (ie 2, 3 ,6, 23, 28,) into the database
value and renders the selected multiselect fields on the corresponding
tab on refresh/update/save

CMultiFileUpload class not inserting image names on the database yii

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();

cakephp insert data on database of linked models

I have two models "Ficha" and "Perigo":
class Ficha extends AppModel {
var $primaryKey = 'id_ficha';
public $validate = array(
'nome_produto' => array(
'rule' => 'notEmpty'
),
'versao' => array(
'rule' => 'notEmpty'
),
'data_ficha' => array(
'rule' => 'notEmpty'
)
);
}
class Perigo extends AppModel {
var $belongsTo = array(
'Ficha' => array(
'className' => 'Ficha',
'foreignKey' => 'id_fichas'
)
);
}
As you can see they are "linked". Now, in the code i have a form for Ficha that the method "add()" of FichasController redirects to my Perigo Model:
add() (of FichaController)
public function add() {
//pr($this->request->data); // to get the data from the form
if ($this->request->is('post')) {
$this->Ficha->create();
if ($this->Ficha->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
//$last_id=$this->Ficha->getLastInsertID();
//$this->redirect(array('action' => 'preencher_ficha'),$last_id);
$this->redirect(array('controller'=>'perigos', 'action' => 'add'),$last_id);
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
The redirection is made to a form that exists in PerigosController.
add.ctp (of Perigo)
echo $this->Form->create('Perigo');
echo $this->Form->input('class_subst', array('label' => 'Classificação da substância ou mistura:'));
echo $this->Form->input('simbolos_perigo', array('label' => 'Símbolos de Perigo:'));
echo $this->Form->input('frases_r', array('label' => 'Frases R:'));
echo $this->Form->end('Avançar');
add() (of PerigoController)
public function add() {
if ($this->request->is('post')) {
$this->Perigo->create();
if ($this->Perigo->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('controller'=>'perigos', 'action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
but there's something i don't know how to do it. Since the models are relational, and the same happens with the two tables on the database (the table perigos has a foreignkey that is the primary key of the table "fichas", how can i insert the data on table perigos in database? I mean, how can i get the key of the Ficha inserted in the first form and insert her in the foreign key of "perigos" when i submit this second form?
As #mark says, your redirection is bad, it should include the id in the URL array:
$this->redirect(array('controller'=>'perigos', 'action' => 'add', $last_id));
Like this you are passing the parameter by URL.
In the add action of your PerigosController you should have an $idFicha param at the method:
//PerigosController.php
public function add($idFicha){
//here you can use $idFicha
...
//when submiting the Perigos form, we add the foreign key.
if($this->request->is('post')){
//adding the foreign key to the Perigo's array to add in the DB.
$this->request->data['Perigo']['ficha_id'] = $idFicha;
if ($this->Ticket->save($this->request->data)) {
//...
}
}
}
Data submitted by POST method in a form will be always contained in an array of this type: $this->request->data['Model_name']. In your case:
$this->request->data['Perigo']
Another way to do this, is using sessions if you prefer to hide the id value:
http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#sessions

Categories