Image in Code Igniter anchor() function - codeigniter

I have a model to fetch data from mysql database. I am using the table and pagination library to display data. When displaying the data there is a column called "DELETE", which is used for deleting each rows. Instead of using the text "DELETE" I want to use an image. I have tried a lot to add it in the model but it is not working. Would you please kindly help me?
Thanks in Advance :)
function batch_list()
{
$config['per_page'] = 15;
$this->db->select('batchname, class, batchinstructor');
$this->db->order_by("batchid", "desc");
$rows = $this->db->get('batch',$config['per_page'],$this->uri->segment(3))->result_array();
$sl = $this->uri->segment(3) + 1; // so that it begins from 1 not 0
foreach ($rows as $count => $row)
{
array_unshift($rows[$count], $sl.'.');
$sl = $sl + 1;
$rows[$count]['batchname'] = anchor('batch_list/get/'.$row['batchname'],$row['batchname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['batchname'],'Edit');
$rows[$count]['Delete'] = anchor('report/'.$row['batchname'],'<img src="base_url().support/images/icons /cross.png" alt="Delete" />"'); //<<< This is where I actually tried/want to add the image
}
return $rows;
}

Please clarify what you mean by not working.
Anyway,
for now I am guessing your problem is your escaping, try:
anchor('report/'.$row['batchname'], '<img src="'.base_url().'support/images/icons/cross.png" alt="Delete" />');
or if you are using the html helper you can use
anchor('report/'.$row['batchname'], img('support/images/icons/cross.png'));
(if you want the alt attribute you will need to use the array form)
$img = array(
'src' => 'support/images/icons/cross.png',
'alt' => 'Delete'
);
anchor('report/'.$row['batchname'], img($img));

Related

Magento Attribute Values - add description field

Looking for a way to add a description field to invididual attribute values in Magento. Please note I'm referring to Attribute Value options, not the actual Attribute itself.
As an example:
Attribute = colour
Attribute values:
Red, Green, Blue
I want to add a description field for each of the 3 colours (1 for Red, 1 for Green, 1 for Blue). The purpose of this is to show a tooltip on the frontend to give more information about each colour option.
Does anyone know how to do this? There are lots of solutions round which apply to the Attribute itself (colour) but not the individual options (Red, Green, Blue).
The descriptions should be editable from within the Admin panel. I don't want a solution which relies on editing these straight in the database using, for example, phpMyAdmin.
I understand that the values are stored in the 'eav_attribute_option_value' table and that a further column may be needed to store the Description. No idea how to get all that set up in the Admin panel. Ideas?
EDIT: I've added a screenshot of where the Description text would need adding. So next to each colour (on the screenshot: Black, Blue, Green, Grey, Red, White, etc) - each one needs to have a description next to it.
This maybe 11 months out of date, but for anyone else having this problem then perhaps this can assist you. I hope it will save you from the hours of head banging against a wall like myself and my colleague experienced. For my purpose, I was trying to create an Image URL field for Magento version 1.9 to support a product migration from an older platform.
This answer has been partially answered here - Creating new options for Magento attributes but there are some extra things I had to figure out:
1.) This answer assumes you have created your own module (if you do not know how then start here: http://www.smashingmagazine.com/2012/03/01/basics-creating-magento-module/)
2.) It also leaves you to create the extra fields in catalog/product/attribute/options.phtml yourself. But to save you time here are the amendments I made to to get it to appear in the admin. Create a new table head option on line 88:
<th><?php echo Mage::helper('catalog')->__('YOUR_ATTRIBUTE_NAME_HERE') ?></th>
Next create a new td on line 101:
<td class="a-left"><input class="input-text" type="text" name="option[YOUR_ATTRIBUTE_NAME_HERE][{{id}}]" value="{{TABLE_COLUMN_NAME_HERE}}" <?php if ($this->getReadOnly()):?> disabled="disabled"<?php endif;?>/></td>
And also, most of the logic is done in Javascript so we need to replicate the field here on line 126:
'<td><input class="input-text" type="text" name="option[YOUR_ATTRIBUTE_NAME_HERE][{{id}}]" value="{{TABLE_COLUMN_NAME_HERE}}" <?php if ($this->getReadOnly()):?> disabled="disabled"<?php endif;?>/><\/td>'+
3.) The longest part for me was creating the custom logic for _saveOption method. I overrode the parent class, but to save you the trouble here is my logic:
protected function _saveOption(Mage_Core_Model_Abstract $object)
{
$option = $object->getOption();
if (is_array($option)) {
$adapter = $this->_getWriteAdapter();
$optionTable = $this->getTable('eav/attribute_option');
$optionValueTable = $this->getTable('eav/attribute_option_value');
$stores = Mage::app()->getStores(true);
if (isset($option['value'])) {
$attributeDefaultValue = array();
if (!is_array($object->getDefault())) {
$object->setDefault(array());
}
foreach ($option['value'] as $optionId => $values) {
$intOptionId = (int) $optionId;
if (!empty($option['delete'][$optionId])) {
if ($intOptionId) {
$adapter->delete($optionTable, array('option_id = ?' => $intOptionId));
}
continue;
}
$sortOrder = !empty($option['order'][$optionId]) ? $option['order'][$optionId] : 0;
$imgUrl = !empty($option['image_url'][$optionId]) ? $option['image_url'][$optionId] : 0;
if (!$intOptionId) {
$data = array(
'attribute_id' => $object->getId(),
'sort_order' => $sortOrder,
'image_url' => $imgUrl
);
$adapter->insert($optionTable, $data);
$intOptionId = $adapter->lastInsertId($optionTable);
} else {
$data = array('sort_order' => $sortOrder, 'image_url' => $imgUrl);
$where = array('option_id =?' => $intOptionId);
$adapter->update($optionTable, $data, $where);
}
if (in_array($optionId, $object->getDefault())) {
if ($object->getFrontendInput() == 'multiselect') {
$attributeDefaultValue[] = $intOptionId;
} elseif ($object->getFrontendInput() == 'select') {
$attributeDefaultValue = array($intOptionId);
}
}
// Default value
if (!isset($values[0])) {
Mage::throwException(Mage::helper('eav')->__('Default option value is not defined'));
}
$adapter->delete($optionValueTable, array('option_id =?' => $intOptionId));
foreach ($stores as $store) {
if (isset($values[$store->getId()])
&& (!empty($values[$store->getId()])
|| $values[$store->getId()] == "0")
) {
$data = array(
'option_id' => $intOptionId,
'store_id' => $store->getId(),
'value' => $values[$store->getId()]
);
$adapter->insert($optionValueTable, $data);
}
}
}
$bind = array('default_value' => implode(',', $attributeDefaultValue));
$where = array('attribute_id =?' => $object->getId());
$adapter->update($this->getMainTable(), $bind, $where);
}
}
return $this;
}
My custom field was named image_url so I added it to the $data variable to be inserted. This will insert values into the column "image_url" of the eav_attribute_option table, but you can manipulate it to store in eav_attribute_option_value in the same method.
4.) For some reason that stack overflow post stated that this _saveOption method would be fired on save but mine was not, therefore I also overrode the _afterSave method in the same class which looks like this:
protected function _afterSave(Mage_Core_Model_Abstract $object)
{
$this->_clearUselessAttributeValues($object);
$this->_saveStoreLabels($object)
->_saveAdditionalAttributeData($object)
->saveInSetIncluding($object)
->_saveOption($object);
return $this;
}
5.) Now it will attempt to save your new value. But it will cause an error since your custom table column most likely doesn't exist yet. You are welcome to create this manually if it is appropriate for you. Unfortunately I needed to create this programmatically for my situation, so for those of you in the same boat (this is a slightly unclean approach) but for speed I re-routed the app/code/core/Mage/Core/Model/Resource/Setup.php by creating the local revision here: app/code/local/Mage/Core/Model/Resource/Setup.php and add this to line 154 in the constructor class:
$installer = $this;
$installer->getConnection()->addColumn($installer->getTable('eav/attribute_option'), 'YOUR_COLUMN_NAME_HERE', 'VARCHAR(256) NULL');
$installer->endSetup();
6.) Okay, everything should now be saving to the database, but we still need to read the value into our <td> - this had me stumped for a while, but figured out that the Javascript is responsible for replacing the {{id}} and {{sort_order}} tags in the HTML on line 230. Therefore we need to add our new column to this getOptionsValues() method. I added the following code in on line 70 of catalog/product/attribute/options.phtml:
<?php foreach ($this->getOptionValues() as &$val) {
$imgUrl = $this->getImageUrl($val->id);
if ($imgUrl != "0") {
$val->_data["YOUR_TABLE_COLUMN_NAME_HERE"] = $imgUrl;
}
} ?>
Then, in your YOUR_MODULE_Block_Adminhtml_Options class add the method getImageUrl() that the above calls:
/**
* Retrieve results from custom column
*
* #return Mage_Core_Model_Mysql4_Store_Collection
*/
public function getImageUrl($option_id)
{
//Get the resource model
$resource = Mage::getSingleton('core/resource');
//Retrieve the read connection
$readConnection = $resource->getConnection('core_read');
//Retrieve our table name
$table = $resource->getTableName('eav/attribute_option');
$query = 'SELECT ' . $this->custom_col . ' FROM ' . $table . ' WHERE option_id = '
. (int)$option_id . ' LIMIT 1';
//Execute the query and store the result
$imgUrl = $readConnection->fetchOne($query);
return $imgUrl;
}
And there you have it. I really hope that this helps anyone in a similar situation.
Try this out
By default Magneto only provide custom options without any description, if you want to customize with description then you must change in following files:
Step 1:-
In File
app\design\adminhtml\default\default\template\catalog\product\edit\option\type\select.phtml
Find the below code:
'<th class="type-sku"><?php echo Mage::helper('catalog')->__('SKU') ?></th>'+
Add these after just after
'<th class="type-description"><?php echo Mage::helper('catalog')->__('Description') ?></th>'+
Find the below code:
'<td><input type="text" class="input-text" name="product[options][{{id}}][values][{{select_id}}][sku]" value="{{sku}}"></td>'+
Add these after just after
'<td><input type="text" class="input-text" name="product[options][{{id}}][values][{{select_id}}][description]" value="{{description}}"></td>'+
Step 2:-
In File
app\code\core\Mage\Adminhtml\Block\Catalog\Product\Edit\Tab\Options\Option.php
Find the below code:
$value['sku'] = $this->htmlEscape($option->getSku());
Add these code just after
$value['description'] = $this->htmlEscape($option->getDescription());
Find the below code:
'sku' => $this->htmlEscape($_value->getSku()),
Add these code just after
'description' => $this->htmlEscape($_value->getDescription()),
Step 3:-
Add field in “catalog_product_option_type_value” table description.
Let me know if you have some query.

Automatically create pages in phpfox

I have an array of information of places and I wanna use them to create multiple pages in a phpfox site.
First I tried to manually insert data in phpfox database (in tables of phpfox_pages and phpfox_pages_text).
The page is shown up in the site but when opening it's link, the site says:
The page you are looking for cannot be found.
Do you know what other tables should I manipulate to make it work?
Or do you know any plugin for phpfox to do the same?
Thanks,
Solved ( With #Purefan Guide):
"Pages" also has a user
If you take a look at phpfox_user table, you'll found out how to fetch new records on that. But there are two ambiguous fields in that table ( password & password_salt). You can use this script to create values for the fields:
<?php
function generateRandomString()
{
$length = 164;
$characters = '-_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$sSalt = '';
for ($i = 0; $i < 3; $i++)
{
$sSalt .= chr(rand(33, 91));
}
$sPossible = generateRandomString();
$sPassword = '';
$i = 0;
while ($i < 10)
{
$sPassword .= substr($sPossible, mt_rand(0, strlen($sPossible)-1), 1);
$i++;
}
$password_Salt_Field = $sSalt;
$password_Field = md5(md5($sPassword) . md5($sSalt));
Phpfox has 2 very similar modules: "Pages" and "Page", you create "Pages" if you want people to "like" them, post in them, add photos... a "Page" is static so I think this is what you want, in that case I would add to phpfox_page and phpfox_page_text
Edit: Ok then you are probably forgetting to insert into phpfox_user, a "Pages" also has a user, the following should shed some light:
$iUserId = $this->database()->insert(Phpfox::getT('user'), array(
'profile_page_id' => $iId,
'user_group_id' => NORMAL_USER_ID,
'view_id' => '7',
'full_name' => $this->preParse()->clean($aVals['title']),
'joined' => PHPFOX_TIME,
'password' => Phpfox::getLib('hash')->setHash($sPassword, $sSalt),
'password_salt' => $sSalt
)
);
Look in the file /module/pages/include/service/process.class.add around line 338 (depending on your version).

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

Displaying database value

I am trying to display data from database using Codeigniter's table and pagination library. In my model, apart from other column I want to fetch information of column "batchid" from my table "batch" ,but don't want to show it in the view file when I am displaying the other data.
But since I have included the "batchid" in this-(in the following)
$this->db->select('batchname, class, batchid, batchinstructor');
It is showing all the information of the column "batchid" in the view, which I don't want. I just want to retrieve the value of batchid to use it for anchoring "batchname".
I have tried a lot but it won't work. Would you please kindly help me?
Thanks in Advance
Here is my model
//Function To Create All Student List
function batch_list()
{
$config['per_page'] = 15;
$this->db->select('batchname, class,batchid, batchinstructor');
$this->db->order_by("batchid", "desc");
$rows = $this->db->get('batch',$config['per_page'],$this->uri->segment(3))->result_array();
$sl = $this->uri->segment(3) + 1; // so that it begins from 1 not 0
foreach ($rows as $count => $row)
{
array_unshift($rows[$count], $sl.'.');
$sl = $sl + 1;
$rows[$count]['batchname'] = anchor('batch_list/get/'.$row['batchid'],$row['batchname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['batchname'],img(base_url().'/support/images/icons/edit.png'));
$rows[$count]['Delete'] = anchor('report/'.$row['batchname'],img(base_url().'/support/images/icons/cross.png'));
}
return $rows;
}
//End of Function To Create All Student List
Here is my controller
function index(){
$this->load->helper('html');
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('Serial Number','Batch Name','Class','Batch Instructor','Edit','Delete');
$config['base_url'] = base_url().'batchlist/index';
$config['total_rows'] = $this->db->get('batch')->num_rows();
$config['per_page'] = 15;
$config['num_links'] = 5;
$config['full_tag_open'] = '<div class="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['tab'] = "Batch List";
$this->load->model('mod_batchlist');
$data['records']= $this->mod_batchlist->batch_list();
$data['main_content']='view_batchlist';
$this->load->view('includes/template',$data);
}
I'm not sure what you're doing in your view, but you can add rows manually by looping through your dataset:
foreach ($records->result() as $r)
{
$this->table->add_row($r->serial,
$r->batchname,
$r->class,
$r->batchinstructor,
$r->edit,
$r->delete
);
}
echo $this->table->generate();
In this way, you control what data goes to your table.

How to display Serial Numbers in a table that has been created using table library in codeigniter?

I know how to create pagination and generate a table containing information from database in codeigniter, but I don't how to display the serial numbers for each row in the table. Example:
SL. Name Email
1. Srijon example#yahoo.com
2. Jake jake#yahoo.com
Would you please kindly show me how to do that? Thanks in advance
Here is the controller for how I create pagination and generate table (without serial numbers)
function index(){
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('Student ID','Student Name','Batch','Edit','Delete');
$config['base_url'] = 'http://localhost/coaching/index.php/student_list/index';
$config['total_rows'] = $this->db->get('student')->num_rows();
$config['per_page'] = 15;
$config['num_links'] = 20;
$config['full_tag_open'] = '<div id="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['tab'] = "Student List";
$this->load->model('mod_studentlist');
$data['records']= $this->mod_studentlist->student_list();
$data['main_content']='studentlist';
$this->load->view('includes/template',$data);
}
Here's my model
function student_list()
{
$config['per_page'] = 10;
$this->db->select('studentid, studentname, batch');
$this->db->order_by("studentid", "desc");
$rows = $this->db->get('student',$config['per_page'],$this->uri->segment(3))->result_array();
foreach ($rows as $count => $row)
{
$rows[$count]['studentname'] = anchor('student_list/get/'.$row['studentid'],$row['studentname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['studentid'],'Update');
$rows[$count]['Delete'] = anchor('report/'.$row['studentid'],'Delete');
}
return $rows;
}
Here's my view file
<?php echo $this->table->generate($records);?>
<?php echo $this->pagination->create_links();?>
<script type="text/javascript" charset="utf-8">
$('tr:odd').css('background','#EAEAEA');
</script>
You should create a variable inside your model function:
<?php
function student_list()
{
$config['per_page'] = 10;
$this->db->select('studentid, studentname, batch');
$this->db->order_by("studentid", "desc");
$rows = $this->db->get('student',$config['per_page'],$this->uri->segment(3))->result_array();
$sl = $this->uri->segment(3) + 1; // so that it begins from 1 not 0
foreach ($rows as $count => $row)
{
array_unshift($rows[$count], $sl.'.');
$sl = $sl + 1;
$rows[$count]['studentname'] = anchor('student_list/get/'.$row['studentid'],$row['studentname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['studentid'],'Update');
$rows[$count]['Delete'] = anchor('report/'.$row['studentid'],'Delete');
}
return $rows;
}
and modify your controller:
<?php
function index() {
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('SL.', 'Student ID','Student Name','Batch','Edit','Delete');
....
Codeigniter has a great Table library to display data in html table format. Adding a Serial No is sometime required to a table, but Row num is not easily provided by MySQL hence while using Table library this function is added to do the job.
Here goes the code:
/**
* Set the serial no
*
* Add serial no to left of table
*
* #access public
* #param mixed
* #return mixed
*/
function add_sr_no(&$arr)
{ if (!is_array($arr)) return $arr;
$i=1;
foreach ($arr as &$values) {
if (!is_array($values))
break;
else
array_unshift($values, $i++);
}
return $arr;
}
Just add these lines to table.php in library.
Usage:
$rows = $query->result_array();
$this->table->add_sr_no($rows);
Don't forget to add first column 'Sr No' in set_heading.
Read the post here.
Hope this helps.
Have you thought about doing this on the client? the javascript library datatables is brilliant. it can handle the sorting for you at the user side, and can be made to dynamically retrieve information using ajax, so load times are fast on large tables. for under < 100 rows or so there probably isn't a need though. i have it sorting/filtering tables with >100 000 rows with no problems at all (using ajax)
unless the serial numbers have semantic meaning don't show them to the client. it just more stuff for them to filter. if they are required for your code, but not for the user to see, just hide them away in a data attribute or something.

Resources