Cakephp update or add new record - php

I have an image upload that adds the filename to a table called attachments. If the id already exists then I want it to update and if not then create a new record. At the moment it creates a new record so I have multiple records forthe one id. The id's are from a table called Addon's.
I am not sure how to do this in cakephp.
if (!empty($this->data)) {
$this->layout = null;
//if(empty($this->data['AddOn']['id'])){unset($this->data['AddOn']);}
// restructure data for uploader plugin // NEED TO GET RID OF THIS ? MOVE IT
$tmp_file = $this->data['Attachment'][0]['file'];
$tmp_file['extension'] = array_reverse(explode('.', $tmp_file['name']));
$tmp_file['extension'] = $tmp_file['extension'][0];
$tmp_file['title'] = strtolower(substr($tmp_file['name'],0,(0-strlen('.'.$tmp_file['extension']))));
$this->data['Attachment'][0]['alternative'] = ucwords(str_replace('_',' ', $tmp_file['title']));
$previous = $this->AddOn->Attachment->find('first', array('conditions'=> array('model'=>'AddOn', 'foreign_key'=>$id)));
if( !empty( $previous ) ) {
$this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ];
}
if ($this->AddOn->save($this->data, array('validate' => 'first'))) {
$id = $this->AddOn->Attachment->getLastInsertID();
$att = $this->AddOn->Attachment->query("SELECT * from attachments WHERE id = ".$id);
$this->set('attachment',$att[0]['attachments']);
} else {
$tmp_file['name'] = 'INVALID FILE TYPE';
}
//debug($this->data);
$this->set('file', $tmp_file);
$this->RequestHandler->renderAs($this, 'ajax');
$this->render('../elements/ajax');
}

save() and saveAll() automatically update an existing row if the id has been set. You can do something like:
$previous = $this->AddOn->Attachment->find( /* whatever conditions you need */ );
if( !empty( $previous ) ) {
$this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ];
}
Now the old record will be updated if it exists.
As a side note, the code after a successful saveAll() doesn't make much sense: first you're saving data to the database, then immediately retrieving it again. You can just keep using $this->data that already has the same content.
And another side note: you should use query() only as a last resort when you can't use Cake's other methods. query("SELECT * from attachments WHERE id = ".$id) is a trivial case that can be rewritten as $this->Model->id = $id; $this->Model->read(); or using a simple $this->Model->find() query.

Related

Database error 1452

I'm working on this project that have foreign keys on two tables. By using a form I'm trying to insert a new record to the database. And there's also an image path in the db and I'm inserting the image path via the form. I'm using codeigniter file upload library. Other fields of the database table get updated when i submit the form even the foreign key field. But the image path is not updating. When I submit the form it shows this error.
A Database Error Occurred
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`bfh`.`products`, CONSTRAINT `category_fk` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`))
INSERT INTO `products` (`img`) VALUES ('assets/img//sakya.PNG')
Filename: C:/xampp/htdocs/CI-skeleton/system/database/DB_driver.php
Line Number: 691
Controller
public function add_product()
{
$result = 0;
$cat_id = $this->input->post("category_id");
$type_id = $this->input->post("type_id");
$pname = $this->input->post("p_name");
$images = $this->input->post("images");
$images = $_FILES['images']['name'];
$price = $this->input->post("price");
$this->load->model("Products_Model");
$product_id = $this->Products_Model->add_product( $cat_id, $type_id, $pname, $price);
if ($product_id != 0) {
$result = $this->Products_Model->add_product_images($images);
}
if ($result && $_FILES['images']['name'][0] != "") {
$this->load->model('Image_Upload');
$result = $this->Image_Upload->upload("assets/img");
}
$this->session->set_flashdata('result', $result);
redirect('Products');
}
Model
public function add_product( $cat_id, $type_id, $pname, $price)
{
$result = $this->db->get_where("products", array('name' => $pname));
if ($result->num_rows() != 0) {
return 0; // record already exists
} else {
$data = array(
'category_id' => $cat_id,
'type_id' => $type_id,
'name' => $pname,
'price' => $price
);
if( !$this->db->insert('products', $data)) {
return -1; // error
}else{
return $this->db->insert_id();
}
return 1; // success
}
}
public function add_product_images($images)
{
$path = "assets/img/";
foreach ($images as $image) {
// if no images were given for the item
if ($image == "") {
return 1;
}
$data = array(
'img' => $path."/".$image
);
if ( ! $this->db->insert('products', $data)) {
return 0; // if something goes wrong
}
}
return 1;
}
You should use "update" query on the behalf of insert in add_product_images().
Because "insert" will add a new record of the product and there is no any category id(Foreign Key) with this that's why shows this error.
So try to update image.
you have two variables with the same name and thats the problem.
You need have different variable name.
I hope this will help you.
there are some problems in this script
if model you wrote, function add product. if your query failed, returns -1 otherwise return product Id
but if product was in database it returns 0, then in controller: you check if product_id != 0 then insert images. so you don't care if product didn't exists in database, you failed you insert that in table or not
in add_product_images you check if ($image == "") . I don't understand how you get that image array ($images) is empty if this statement is true. you can check if (sizeof($images) == 0) before foreach to check emptiness of image array ($images)

Entry in database not being overwritten when looking at ID

I'm currently looking at a script that a previous developer made that is meant to look a table, if the id does not exist then create the new code, if it does exist, overwrite the existing one.
Sounds fairly simple, but I can't get my head around how Yii manages the overwrite and new verification code. It is only adding new records, not over writing.
$invitingUser = User::model()->findByPk(Yii::app()->user->id);
if ($invitingUser->isAttending($eventId)) {
// Event attending
$event = Event::model()->findByPk($eventId);
//
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation(array($guestInviteForm));
if (isset($_POST['GuestInviteForm'])) {
$guestInviteForm->attributes = $_POST['GuestInviteForm'];
// Perform Validation
$valid = $guestInviteForm->validate();
if ($valid) {
// Check if a Verification Code entry for this user already exists
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
//THE CODE ONLY SEEMS TO RUN THIS.
if (is_null($existingVerificationCode)) {
// Create Verification Code instance
$verificationCode = new VerificationCode();
$verificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$verificationCode->user_id = $invitingUser->id;
$verificationCode->verification_code = VerificationCode::generateVerificationCode();
$verificationCode->forename = $guestInviteForm->forename;
$verificationCode->surname = $guestInviteForm->surname;
$verificationCode->event_id = $eventId;
$verificationCode->save(false);
} else {
// Update existing Verification Code enty
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
}
The code never seems to enter the else here
//THE CODE ONLY SEEMS TO RUN THIS.
if (is_null($existingVerificationCode)) {
// Create Verification Code instance
$verificationCode = new VerificationCode();
$verificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$verificationCode->user_id = $invitingUser->id;
$verificationCode->verification_code = VerificationCode::generateVerificationCode();
$verificationCode->forename = $guestInviteForm->forename;
$verificationCode->surname = $guestInviteForm->surname;
$verificationCode->event_id = $eventId;
$verificationCode->save(false);
} else {
// Update existing Verification Code enty
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
}
1st. After form validation:
if ($valid) {
Verification code select done:
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
If you translate it to SQL it will be something like this:
SELECT * FROM verification_code WHERE user_id=x AND type=x
2nd. Check if record exists
if (is_null($existingVerificationCode)) {
If its not - creating new, populating, saving.
Else updating:
$existingVerificationCode->type = VerificationCode::TYPE_GUEST_INVITE;
$existingVerificationCode->user_id = $invitingUser->id;
$existingVerificationCode->forename = $guestInviteForm->forename;
$existingVerificationCode->surname = $guestInviteForm->surname;
$code = $existingVerificationCode->verification_code = VerificationCode::generateVerificationCode();
$existingVerificationCode->save(false);
save(false) means save without validation. Consider model attributes - fields in your database table.
Seems like it ever goes in the ELSE because it never finds $existingVerificationCode.
We don't have the whole code, but from what I see, I suspect you're checking the wrong user, because it's weird to search for an event for $user, and if that doesn't exist, to create one related to $invitingUser.
$existingVerificationCode = VerificationCode::model()->findByAttributes(array('user_id' => $user->user_id, 'type' => VerificationCode::TYPE_GUEST_INVITE));
// ...
$verificationCode->user_id = $invitingUser->id;

Passing parameters to a function in yii

I am new to yii. I've created a custom in button in CGridView that has a class of CButtonColumn. I'm just wondering how can I pass parameters that I can add to my php function in my model.
This is my custom button in the table
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
'click'=>$model->approveRegistrants("$user_id, $category", array("id"=>$data->user_id , "category"=>$data->category),
)
)
)
and this is my function is
public function approveRegistrants($user_id, $category){
$db = new PDO('mysql:host=localhost; dbname=secret; charset=utf8', 'Andy', '*****');
$getCounter = "SELECT registrants FROM counter order by registrants desc limit 1;";
$bool = false;
$show = '0';
do{
$result = $db->query($getCounter);
// $registrants = $db->query($getCounter);
// $result->setFetchMode(PDO::FETCH_ASSOC);
// $registrants = '1';
foreach ($result as $value){
$registrants = $value['registrants'];
echo 'hello'.$registrants.'</br>';
}
// $registrants = $result['registrants'];
// print_r($registrants);
$max_registrants = '3400';
if($max_registrants > $registrants){
// pdo that will use $updateCounterByOne
$updateCounterByOne = "UPDATE counter set registrants = registrants + 1 WHERE registrants = ". $registrants .";";
$updateCounter = $db->prepare($updateCounterByOne);
$updateCounter->execute();
// return affected rows
$returnAffectedRows = $updateCounter->rowCount();
$bool = true;
// break;
}
else{
echo "No more slot Available";
// break;
}
}while($returnAffectedRows == '0');
if($bool = true){
//sql syntax
$selectApprovedUser = "SELECT user_id FROM registrants WHERE user_id = '". $user_id ."';";
//pdo that will use $selectApprovedUser
$updateApprovedUser = "UPDATE registrants set approved = 'YES' where user_id = ". $selectApprovedUser .";";
$updateApproved = $db->prepare($updateApprovedUser);
$updateApproved->execute();
//pdo that will use $insertApprovedUser
$insertApprovedUser = "INSERT INTO approved_registrants (user_id, category, approved_date) VALUES ('".$user_id."', '".$category."', 'curdate()');";
$insertApproved = $db->prepare($insertApprovedUser);
$insertApproved->execute();
//execute trial
$selectSomething = "SELECT registrants from counter where tandem = '0'";
$doSelect = $db->prepare($selectSomething);
$doSelect->execute();
$hello = $doSelect->fetchAll();
echo $hello[0]['registrants'];
}
}
your issue is that you are bypassing the controller fully here.
buttons column is configured with the following parameters
'buttonID' => array(
'label'=>'...', // text label of the button
'url'=>'...', // a PHP expression for generating the URL of the button
'imageUrl'=>'...', // image URL of the button. If not set or false, a text link is used
'options'=>array(...), // HTML options for the button tag
'click'=>'...', // a JS function to be invoked when the button is clicked
'visible'=>'...', // a PHP expression for determining whether the button is visible
)
See CButtonColumn for details.
As you can see click has to be a js function that will be called on clicking the button. You can rewrite your button like this
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
// Alternative -1 Url Method -> will cause page to change to approve/id
'url'=>'array("approve","id"=>$data->id)',
// Alternative -2 Js method -> use 1,2 not both
'click'=>'js:approve()',
)
)
)
in your CGridView configuration you add
array(
....
'id'=>'gridViewID', //Unique ID for grid view
'rowHtmlOptionsExpression'=> 'array("id"=>$data->id)',
)
so that each row has the unique ID, ( you can do the same to a button, but it slightly more difficult as $data is not available there)
in your js function you can do this.
<script type="text/javascript">
function approve(){
id = $(this).parent().parent().attr("id");
<?php echo CHtml::ajax(array( // You also can directly write your ajax
'url'=>array('approve'),
'type'=>'GET',
'dataType'=>'json',
'data'=>array('id'=>'js:id'),
'success'=>'js:function(json){
$.fn.yiiGridView.update("gridViewID",{});
// this will refresh the view, you do some other logic here like a confirmation box etc
}'
));?>
}
</script>
Finally your approve action
class YourController extend CController {
......
public function actionApprove(){
id = Yii::app()->request->getQuery('id');
$dataModel = MyModel::model()->findByPk($id); // This is the model has the $user_id, and $category
....
$OtherModel->approve($dataModel->user_id,$dataModel->category) // if approve is in the same model you can self reference the values of category and user_id directly no need to pass as parameters.
// Do some logic based on returned value of $otherModel->approve()
// return the values from the approve() function and echo from here if required back to the view, directly echoing output makes it difficult to debug which function and where values are coming from .
Yii::app()->end();
}

get unique slug in codeigniter

I want to get unique slug for my articles. I am using codeigniter. I was wondering to have some thing like sample-title-1 and sample-title-2 if there are two articles that have the same title like codeignier does with file upload filename(:num) . I could not figure out a way to do it. I am not an expert on codeigniter. I am learning it.
I prepared a function, when passed a string $str it checks if the slug exists, if it does, it adds the ID of that article to the end of that slug and returns it, if not, it returns the slug.
It is working fine and serving the purpose of unique slug. But what I wanted was to have something like sample-title-1 and sample-title-2 . Is there any way to do so?
$data['slug'] = $this->get_slug($data['title']);
public function get_slug ($str)
{
$slug = url_title($str, 'dash', true);
// Do NOT validate if slug already exists
// UNLESS it's the slug for the current page
$id = $this->uri->segment(4);
$this->db->where('slug', $slug);
! $id || $this->db->where('id !=', $id);
$category = $this->category_m->get();
if (count($category)) {
return $slug.$id;
}
return $slug;
}
easy to use and really helpful to create unique slugs have look on CI slug library
read its documentation to implement it.
what i used to do is to make slug db field UNIQUE.
Then easly do all with the CI helpers Url Helper and Text Helper
$last_id_inserted = //get from db the last post's ID;
$post_title = "My slug would be";
$slug = mb_strtolower(url_title(convert_accented_characters($post_title))).'-'.$last_id_inserted;
echo $slug;
//outputting my-slug-would-be-123
//insert the new post with slug
So ID will be unique and slug too.
I think you need something like that:
//Database loaded
//Text helper loaded
function post_uniq_slug($slug, $separator='-', $increment_number_at_end=FALSE) {
//check if the last char is a number
//that could break this script if we don't handle it
$last_char_is_number = is_numeric($slug[strlen($slug)-1]);
//add a point to this slug if needed to prevent number collision..
$slug = $slug. ($last_char_is_number && $increment_number_at_end? '.':'');
//if slug exists already, increment it
$i=0;
$limit = 20; //for security reason
while( get_instance()->db->where('slug', $slug)->count_all_results('posts') != 0) {
//increment the slug
$slug = increment_string($slug, $separator);
if($i > $limit) {
//break;
return FALSE;
}
$i++;
}
//so now we have unique slug
//remove the dot create because number collision
if($last_char_is_number && $increment_number_at_end) $slug = str_replace('.','', $slug);
return $slug;
}
Examples:
post_uniq_slug('sample'); //"sample" exists
//sample-1
post_uniq_slug('sample-2013'); //"sample-2013" exists
//sample-2013-2
post_uniq_slug('sample-2013', '-', TRUE); //increment "sample-2013"
//sample-2014
*NOT TESTED
public function create_slug($name)
{
$table='tradeshow'; //Write table name
$field='slug'; //Write field name
$slug = $name; //Write title for slug
$slug = url_title($name);
$key=NULL;
$value=NULL;
$i = 0;
$params = array ();
$params[$field] = $slug;
if($key)$params["$key !="] = $value;
while ($this->db->from($table)->where($params)->get()->num_rows())
{
if (!preg_match ('/-{1}[0-9]+$/', $slug ))
$slug .= '-' . ++$i;
else
$slug = preg_replace ('/[0-9]+$/', ++$i, $slug );
$params [$field] = $slug;
}
return $alias=$slug;}

Add new values to a attribute option in Magento

I am trying to add new values to an attribute option in Magento using a script to speed up the process since I have over 2,000 manufacturers.
Here is a piece of code that I used to perform exactly this task. Create a custom module (using ModuleCreator as a tool) and then create a mysql4-install-0.1.0.php under the sql/modulename_setup folder. It should contain the following (adapted to your own data, of course!).
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$aManufacturers = array('Sony','Philips','Samsung','LG','Panasonic','Fujitsu','Daewoo','Grundig','Hitachi','JVC','Pioneer','Teac','Bose','Toshiba','Denon','Onkyo','Sharp','Yamaha','Jamo');
$iProductEntityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
$aOption = array();
$aOption['attribute_id'] = $installer->getAttributeId($iProductEntityTypeId, 'manufacturer');
for($iCount=0;$iCount<sizeof($aManufacturers);$iCount++){
$aOption['value']['option'.$iCount][0] = $aManufacturers[$iCount];
}
$installer->addAttributeOption($aOption);
$installer->endSetup();
More documentation on the Magento wiki if you want.
If you don't want to do it in a custom module, you could just create a php file that starts with:
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
Answer of Jonathan is correct. But if you want to perform it without installer i.e in any other code, then you might find this helpful:
$arg_attribute = 'manufacturer';
$manufacturers = array('Sony','Philips','Samsung','LG','Panasonic','Fujitsu','Daewoo','Grundig','Hitachi','JVC','Pioneer','Teac','Bose','Toshiba','Denon','Onkyo','Sharp','Yamaha','Jamo');
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
$option['attribute_id'] = $attr_id;
foreach ($manufacturers as $key=>$manufacturer) {
$option['value'][$key.'_'.$manufacturer][0] = $manufacturer;
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
More information can be found here.
I have created a function to dynamically add option to attribute
public function addAttributeOptions($attributeCode, $argValue)
{
$attribute = Mage::getModel('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
if ($attribute->usesSource()) {
$id = $attribute->getSource()->getOptionId($argValue);
if ($id)
return $id;
}
$value = array('value' => array(
'option' => array(
ucfirst($argValue),
ucfirst($argValue)
)
)
);
$attribute->setData('option', $value);
$attribute->save();
//return newly created option id
$attribute = Mage::getModel('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
if ($attribute->usesSource()) {
return $attribute->getSource()->getOptionId($argValue);
}
}
You can add an option to your attribute by providing code and option value
$this->addAttributeOptions('unfiorm_type', 'leotartd')
Important! (Hopefully this helps somebody, cause I was stuck like 2h with this issue)
If you are using special characters (such as ä, ö, ü, ß, ×, ...) make sure to encode them properly!
array_walk($manufacturers , create_function('&$val', '$val = utf8_encode($val);'));
Here a simple and very fast way....
Delete an option
/* My option value */
$value = 'A value';
/* Delete an option */
$options = array();
$entity_type_id = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId(); // Product Entity Type ID
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type_id, $attribute_code); // Load attribute by code
if ($attribute && $attribute->usesSource()) {
$option_id = $attribute->getSource()->getOptionId($value); // Check Option ID from value...
if ($option_id) {
$options['delete'][$option_id] = true;
$attribute->setOption($options)->save();
}
}
/* END ! */
Add or update an option
/* Add/Update an option */
$options = array();
$entity_type_id = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId(); // Product Entity Type ID
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type_id, $attribute_code); // Load attribute by code
if ($attribute && $attribute->usesSource()) {
$option_id = $attribute->getSource()->getOptionId($value); // Check Option ID...
$options['order'][$option_id] = 10; // Can be removed... Set option order...
$options['value'][$option_id] = array(
0 => $value, // Admin Store - Required !
1 => $value, // Store id 1 - If U want ! Can be removed
);
$attribute->setDefault(array($option_id)); /* If you want set option as default value */
$attribute->setOption($options)->save(); /* That's all */
}
/* END ! */
In my tutorial I am explaining how to read the options from the CSV and create the options pro grammatically.
http://www.pearlbells.co.uk/add-attribute-options-magento-scripts/
please click the tutorial for further explanation
function createAttribute($options) {
$option = array('attribute_id' =>
Mage::getModel('eav/entity_attribute')->getIdByCode(
Mage_Catalog_Model_Product::ENTITY,
'color'
)
);
for ($i = 0; $i < count($options); $i++) {
$option['value']['option'.$i][0] = $options[ $i ]; // Store View
$option['value']['option'.$i][1] = $options[ $i ]; // Default store view
$option['order']['option'.$i] = $i; // Sort Order
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
}
Answer of Arvind Bhardwaj enter code here is correct. But if you want to perform it without installer i.e in any other code, then you might find this helpful:
Agree with Arvind but it's only works for insert the single option value and if you want to perform insert multiple option value then you just needs to replace the code from "$option['value'][$key.''.$manufacturer] = $manufacturer;" to "$option['values'][$key.''.$manufacturer] = $manufacturer;" to this.
below is the final code
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
$arg_attribute = 'manufacturer';
$manufacturers = array('Sony', 'Philips', 'Samsung', 'LG', 'Panasonic', 'Fujitsu', 'Daewoo', 'Grundig', 'Hitachi', 'JVC', 'Pioneer', 'Teac', 'Bose', 'Toshiba', 'Denon', 'Onkyo', 'Sharp', 'Yamaha', 'Jamo');
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
$option['attribute_id'] = $attr_id;
foreach ($manufacturers as $key => $manufacturer) {
$option['values'][$key . '_' . $manufacturer] = $manufacturer;
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
I hope its works for insertion multiple option.

Categories