Is it possible to get a record of my model by another field of my model?
The normal way
$model = Mage::getModel('foo_bar/baz');
$model->load($id);
// do something with the loaded record
But i need something like this
$model = Mage::getModel('foo_bar/baz');
$model->loadByAnotherFieldOfModel($value)
// do something with the loaded record
is that possible?
$model = Mage::getModel('foo_bar/baz');
$model->load('field_value', 'field_name');
use this
$_category = Mage::getModel('catalog/category')->loadByAttribute('name', 'computer');
$_product = Mage::getModel('catalog/product')->loadByAttribute('name', 'hp2312');
// Load by SKU
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', 'computer123');
Goto model file
NameSpace/Yourmodule/Model/YourModel.php
add below code
public function loadByField($fieldvalue)
{
$this->_getResource()->loadByField($this, $fieldvalue);
return $this;
}
AND
NameSpace/YourModule/Model/Resource/YourModel.php
and code is
public function loadByField(NameSpace_YourModule_Model_YourModel $Object, $fieldvalue)
{
$adapter = $this->_getReadAdapter();
$bind = array('fieldname' => $fieldvalue);
$select = $adapter->select()
->from($this->getMainTable(), 'tablePrimaryKey')
->where('fieldname = :fieldname');
$modelId = $adapter->fetchOne($select, $bind);
if ($modelId) {
$this->load($Object, $modelId );
} else {
$Object->setData(array());
}
return $this;
}
Related
i am a newbie having difficulty in this. i did not getting a value of ID In A box for Update Inside A Box.
update code
<?php
require_once (__DIR__ . '/../../config.php');
require_once($CFG->dirroot.'/local/message/classes/form/edit.php');
global $DB;
$PAGE->set_url(new moodle_url('/local/message/update.php'));
$PAGE->set_context(\context_system::instance());
$PAGE->set_title('Edit');
//here display form
$mform=new edit();
$table='local_message';
$id=required_param('id', PARAM_INT);
$info=$DB->get_records($table,array('id' => $id));
if ($mform->is_cancelled()) {
print_r("1");
redirect($CFG->wwwroot.'/local/message/manage.php', 'You Cancelled The Form');
} else if ($fromform = $mform->get_data()) {
print_r("2");
$record = new stdClass();
$record->id=$id;
$record->messagetext = $fromform->messagetext;
$record->messagetype = $fromform->messagetype;
$DB->update_record($table, $record);
redirect($CFG->wwwroot . '/local/message/manage.php', 'you created a message with a title ' . $fromform->messagetext);
}
echo $OUTPUT->header();
$mform->display();
echo $OUTPUT->footer();
Form/moodle/Code
<?php
require_once("$CFG->libdir/formslib.php");
class edit extends moodleform {
public function definition() {
global $CFG;
$mform = $this->_form; // Don't forget the underscore!
$mform->addElement('text', 'id');
$mform->setType('id', PARAM_INT);
$mform->addElement('text', 'messagetext', get_string('message_text', 'local_message')); // Add elements to your form
$mform->setType('messagetext', PARAM_NOTAGS); //Set type of element
$mform->setDefault('messagetext', get_string('enter_message', 'local_message')); //Default value
$choices = array();
$choices['0'] = \core\output\notification::NOTIFY_WARNING;
$choices['1'] = \core\output\notification::NOTIFY_SUCCESS;
$choices['2'] = \core\output\notification::NOTIFY_ERROR;
$[enter image description here][1]choices['3'] = \core\output\notification::NOTIFY_INFO;
$mform->addElement('select', 'messagetype', get_string('message_type', 'local_message'), $choices);
$mform->setDefault('messagetype', '3');
$this->add_action_buttons();
}
//Custom validation should be added here
function validation($data, $files) {
return array();
}
}
You need to pass the id to the form before displaying the form
$mform->set_data($info);
$mform->display();
Also, you should use the single get_record function not the multiple get_records function
$info = $DB->get_record($table, array('id' => $id));
Also, you might want to use the hidden element for the id
$mform->addElement('hidden', 'id');
I have a code on Save.php of Module Invoice:
public function saveRecord($request) {
...
$received = $request->get('received');
$balance = $request->get('balance');
$relProject = $request->get('relProject');
$project = Project_Record_Model::getInstanceById($relProject);
$fields = $project->getField('cf_938');
$fieldInstance = Vtiger_Field::getInstance($fields->id);
if ($fieldInstance) {
$fieldInstance->value = $received;
$fieldInstance->save();
}
}
Why save() is not work? When I save Invoice my field is not update on project.. I need fix it.
You should use the Record Model object to edit the record, not the Field Model. Try something like this:
public function saveRecord($request) {
...
$received = $request->get('received');
$balance = $request->get('balance');
$relProject = $request->get('relProject');
$project = Project_Record_Model::getInstanceById($relProject);
$project->set('mode', 'edit');
$project->set('cf_938', $received);
$project->save();
}
I want to delete record Photo and Photo_list from Database but give me error
This is my Code in Controller
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
Product::select('photo','photo_list')->delete($product->id);
return redirect(route('stores.index'));
}
I don't think you can delete specific data with delete.
Delete is used to remove a row.
You will need to update your table with a request like that :
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
Product::where('id', 100)->update(['photo' => NULL, 'photo_list' => NULL]);
return redirect(route('stores.index'));
}
You can see more here :
https://laravel.com/docs/5.3/eloquent#updates
https://laravel.com/docs/5.3/eloquent#deleting-models
You can try this :
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
if($product){
$product->photo= null;
$product->photo_list= null;
$product->save();
}
return redirect(route('stores.index'));
}
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
Product::Where('id','=',$product->id)->delete();
return redirect(route('stores.index'));
}
Or you can directly do this
Product::find($id)->delete();
Try this
Product::WhereProductId($product->id)->delete();
guys sorry for bad English.
I am using in Magento enterprise I am working in wishlist there is a function in core at path
C:\xampp\htdocs\projects\baab.bh\app\code\core\Mage\Wishlist\Helper\Data.php
getWishlist()
When I am calling this function to get wishlist from front-end phtml file it's giving me correct wishlist but when I am calling this function from controller it's giving me default wishlist only not the current wishlist here is the code of this function
public function getWishlist()
{
if (is_null($this->_wishlist)) {
if (Mage::registry('shared_wishlist')) {
$this->_wishlist = Mage::registry('shared_wishlist');
} elseif (Mage::registry('wishlist')) {
$this->_wishlist = Mage::registry('wishlist');
} else {
$this->_wishlist = Mage::getModel('wishlist/wishlist');
if ($this->getCustomer()) {
$this->_wishlist->loadByCustomer($this->getCustomer());
}
}
}
return $this->_wishlist;
}
I am calling it with the same code but it behaves differently from front-end phtml file and from controller. How can I get current wishlist from the controller as well?
For this, you will get all customers wishlist:
public function getWishlist()
{
$customer = Mage::getModel('customer/customer')->getCollection()->addAttributeToSelect('*');
$wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer);
$wishListAllItem = $wishList->getItemCollection();
if (count($wishListAllItem)) {
$arrOfProductIds = array();
foreach ($wishListAllItem as $item) {
$arrOfProductIds[] = $item->getProductId();
}
}
return $arrOfProductIds;
}
For this, you can get current user wishlist:
$wishList = Mage::getSingleton('wishlist/wishlist')->loadByCustomer($customer)
$wishListAllItem = $wishList->getItemCollection();
if (count($wishListAllItem)) {
$arrOfProductIds = array();
foreach ($wishListAllItem as $item) {
$product = $item->getProduct();
$arrOfProductIds[] = $product->getId();
}
}
Actually,
as you see below code,
in model two functions are calling
$this->sendMailtoTutor(),$this->sendMailtoLearner()
i want to check a condition in model that if that condition will true then only these both function will call otherwise not. Is there any way to pass attributes or variable so that i can check condition in aftersave().
my code is as below
in controller
public function actionBooking()
{
$booking_temp = new BookingTemp();
$this->performAjaxValidation($booking_temp);
if (Yii::app()->request->isPostRequest && Yii::app()->request->getPost('BookingTemp'))
{
$booking_temp->attributes = Yii::app()->request->getPost('BookingTemp');
//echo '<pre>';print_r($booking_temp->attributes);exit;
if ($booking_temp->validate())
{
$extra_price = 0;
$post_data = Yii::app()->request->getPost('BookingTemp');
$cam = Cam::model()->findByPk($post_data['temp_cam_id']);
$data = array();
$data = $post_data;
$data['temp_book_user_id'] = Yii::app()->user->id;
$data['temp_book_cam_price'] = $cam->cam_price;
$data['temp_book_duration'] = $cam->cam_duration;
if ($post_data['temp_book_session'] == 2) {
$data['temp_book_cam_price'] = 2 * $cam->cam_price;
$data['temp_book_duration'] = 2 * $cam->cam_duration;
}
if ($post_data['temp_book_is_extra'] == "Y") {
$extra_price = $cam->camExtras->extra_price;
$data['temp_book_extra_price'] = $extra_price;
}
$price_calculation = CamBooking::price_calculation(Yii::app()->user->country_id, $data['temp_book_cam_price'], $extra_price);
$data['temp_book_processing_fees'] = $price_calculation['processing_fees'];
$data['temp_book_service_tax'] = $price_calculation['service_tax'];
$data['temp_book_total_price'] = $price_calculation['total_price'];
$booking_temp->temp_value = serialize($data);
$booking_temp->user_id = Yii::app()->user->id;
$booking_temp->tutor_id = $cam->tutor_id;
$booking_temp_variable = 'check_aftersave';
$booking_temp->save(false, $booking_temp_variable);
//$booking_temp->saveAttributes(array('tutor_id', 'user_id', 'temp_value'));
$created_at = Yii::app()->localtime->fromUTC($booking_temp->created_at);
$created_at_time = strtotime($created_at);
$end_time = $created_at_time + (60 * 3); // 3 min greater from created
$end_time_format = date("Y/m/d H:i:s", $end_time);
echo json_encode(array(
'status' => 'success',
'temp_guid' => $booking_temp->temp_guid,
'end_time_format' => $end_time_format,
), JSON_UNESCAPED_SLASHES);
Yii::app()->end();
} else {
$error = CActiveForm::validate($booking_temp);
if ($error != '[]')
echo $error;
Yii::app()->end();
}
}
}
in model
protected function afterSave()
{
if ($this->isNewRecord)
{
$this->sendMailtoTutor();
$this->sendMailtoLearner();
if ($this->is_message == 'Y' && !empty($this->book_message))
{
Message::insertMessage($this->book_message, $this->book_user_id, $this->cam->tutor_id, $this->cam_id);
}
$user_profile_link = CHtml::link($this->bookUser->fullname, array("/site/user/profile", "slug" => $this->bookUser->slug));
$cam_link = CHtml::link($this->cam->cam_title, array("/site/cam/view", "slug" => $this->cam->slug));
$message = "You have a new booking from {$user_profile_link} for your {$cam_link}";
Notification::insertNotification($this->cam->tutor_id, $message, 'book', $this->book_id);
}
return parent::afterSave();
}
How can I perform this?
Hi See if you want to do it in the afterSave() of BookingTemp Model;. Then you can define a variable in that model like
like
class BookingTemp extends CActiveRecord
{
public $booking_temp_variable;
............
}
now assign this variable before saving your model in actionBooking();
as
$booking_temp->booking_temp_variable = 'check_aftersave';
$booking_temp->save(false);// no need to pass a varible
now in your aftersave function you can easily get it like
protected function afterSave()
{
if ($this->isNewRecord)
{
$this->booking_temp_variable; // this has your value
}
return parent::afterSave();
}
Don't forget to keep it in rules as safe
public function rules(){
// your rules
array('booking_temp_variable','safe');
}
What exacly you want to do?
At first you have to know, that when you are calling save() method and u pass there two args - false and, $booking_temp_variable . The first arg says that you do not run validation, the second one is (should be) array of attributes.
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail