Batch insert in codeigniter - codeigniter

Hi I am quite new to cpdeignoter I just wanted to ask if I am doing the insert batch in ci right because it seemed not to work here is my controller
foreach($dat as $key => $val){
$data[] = array('ModelNumber' => $_POST['txt_model_num'][$key],
'Access' => $_POST['txt_accessories'][$key],
'SerialNumber' => $_POST['txt_snum'][$key],
'Charges' => $_POST['txt_charges'][$key],
'OtherRemarks' => $_POST['txt_rem'][$key],
'RequirementID' => $id1);
}
$cmd3 = $this->Software_model->add_type($data);
if($cmd3){
foreach($sql->result_array() as $row){
$id2 = $row['ID'];
}
$data2s = array();
foreach($dat as $key => $val){
$data2s[] = array('EquipmentName' => $_POST['txt_equipb'][$key],
'EquipmentType' => $_POST['txt_equiptype'][$key],
'RequirementID' => $id2);
}
$cmd2 = $this->Software_model->add_equip($data2s);
and this is the model
public function add_type($data)
{
return $this->db->insert_batch('jobtype', $data);
}
public function add_equip($data2s)
{
return $this->db->insert_batch('equipment', $data2s);
}
and the way I duplicate the textboxes in the views is like this
function second function(){
var etype = document.createElement('input');
etype.type = 'text';
etype.setAttribute("name", "txt_equiptype[]");
etype.setAttribute("class", "form-control");
etype.setAttribute("id", "etype");
etype.setAttribute("placeholder", "Enter Equipment Type");
document.getElementById('third').appendChild(etype);
}
thanks in advance

Hope this will help you :
Try out this alternate method :
foreach($dat as $key => $val)
{
$data[$key]['ModelNumber'] = $_POST['txt_model_num'][$key];
$data[$key]['Access'] = $_POST['txt_accessories'][$key];
$data[$key]['SerialNumber'] = $_POST['txt_snum'][$key];
$data[$key]['Charges'] = $_POST['txt_charges'][$key];
$data[$key]['OtherRemarks'] = $_POST['txt_rem'][$key];
$data[$key]['RequirementID'] = $id1;
}
/* Note : remove auto increment primary key from above array if you are including*/
user it for both the foreach

Related

Display name instead of id in url laravel

I would just like to ask how do I display the name of the business instead of it's id.
It's currently displayed like this, localhost:8000/1/Belen'sChoice and desired output is
localhost:8000/Belen'sChoice. I can get the name however it says 'trying to find id'.
Controller
public function show($id)
{
$categories = Category::all();
$businesses = Business::find($id);
if (Auth::check()) {
$userId = Auth::user()->id;
$users = User::where('id', $userId)->get();
$posts = Post::where('business_id', $businesses->id)->get()->sortByDesc('created_at');
$supporters = Supporter::where('user_id', $userId)->get();
$photos = Image::where('business_id', $businesses->id)->get();
$albums = Album::where('business_id', $businesses->id)->get();
$count = 0;
if ($businesses->user_id != Auth::user()->id) {
$businesses->views = $businesses->views + 1;
$businesses->save();
} else {
$businesses->views = $businesses->views;
}
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
'users' => $users,
'posts' => $posts,
'supporters' => $supporters,
'count' => $count,
'images' => $photos,
'albums' => $albums,
]);
} else {
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
]);
}
}
Blade
<a class="text-center" href='{{ url("/businessprofile/".$business->id."/".str_replace(" ", "" ,$business->name)) }}'><img class="bprof-img" src='{{ asset("storage/$business->logo") }}'>{{ $business->name }}</a>
Web.php
Route::get('/businessprofile/{id?}/{name}', 'BusinessController#show');
TIA
take one Column in your business migration
$table->string('slug')->unique();
and save it like this way in your controller
//use this at the bottom of your controller
use Illuminate\Support\Str;
$business = new Business;
$business->slug = Str::slug($request->name) // whatever you request dring //creating a business row
//and after that save it
$business->save();
then in your controller find the row using slug
public function show($slug)
{
$business = Business::where('slug',$slug)->first();
//and rest of your operation
}
href='{{ url("/".str_replace(" ", "" ,$business->slug))}}'
then in your web
Route::get('/{slug}', 'BusinessController#show');

codeigniter generating multiple pdfs

i'm trying to generates pdfs in loop against member id, but every time i got only the first one, i addedd code in foreach so it runs multiple times, but it gives me only one pdf.please someone help me.
public function pdf($ids){
$k = 0;
foreach ($ids as $key => $id) {
$data[$k]['academics'] = $this->Utility_model->get_all_from_table_where('member_academics', array('member_id' => $id));
$data[$k]['member_employment'] = $this->Utility_model->get_all_from_table_where('member_employment', array('member_id' => $id));
$data[$k]['member_data'] = $this->Utility_model->get_all_from_table_where('members',array('member_id' => $id));
$data[$k]['disclosure'] = $this->Utility_model->get_all_from_table('generalsettings',array('key'=>'disclosure'));
$data[$k]['enrollment_fee'] = $this->Utility_model->get_all_from_table('member_invoices',array('user_id' => $id,'paymentFor'=>'Enrollment Fee'));
$data[$k]['enrollment_fee']['payment'] = $this->Utility_model->get_all_from_table('member_payments',array('invoice_id'=>$data[$k]['enrollment_fee']['id']));
$j=0;
if (!empty($data[$k]['member_data'])) {
foreach ($data[$k]['member_data'] as $member) {
$data[$k]['member_data'][$j]['term'] = $this->Utility_model->get_all_from_table('term', array('term_id' => $member['term_id']));
$data[$k]['member_data'][$j]['degree'] = $this->Utility_model->get_all_from_table('degree', array('degree_id' => $member['degree_id']));
$data[$k]['member_data'][$j]['year'] = $this->Utility_model->get_all_from_table('year', array('year_id' => $member['year_id']));
$data[$k]['member_data'][$j]['address'] = $this->Utility_model->get_all_from_table('member_addresses', array('id' => $member['address_id']));
$j++;
}
}
$this->load->view('admin/reports_management/applications_pdf/pdf_output',$data[$k],false);
$html = $this->output->get_output();
$this->load->library('dompdf_gen');
$this->dompdf->load_html($html);
$this->dompdf->render();
$this->dompdf->stream($k."file".".pdf");
$k++;
}
// echo "<pre>";
// print_r($data);
// die;
}
As long as you only request the page once you cannot get the controller method to output more than one file. You could either try to instead make a multiple page PDF or you need to change how the controller is called, and call it multiple times.
See this answer for some input about making multiple page PDF: How to create several pages with dompdf

how to get data from database throught model using codeigniter with for each loop

http error occured while calling data from model using function
model
public function getProductCombo() {
$q = $this->db->get_where('products', array('type' => 'combo'));
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}
controller
function sets() {
$this->sma->checkPermissions();
$this->load->helper('security');
$this->data['error'] = (validation_errors() ? validation_errors() :
$this->session->flashdata('error'));
// problem in this line also
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
$bc = array(array('link' => base_url(),
'page' => lang('home')),
array('link' => site_url('sales'),
'page' => lang('products')),
array('link' => '#', 'page' => "sets")
);
$meta = array('page_title' => "Add Sets", 'bc' => $bc);
$this->page_construct('sales/sets', $meta, $this->data);
}
First of all, No need to include the curly braces for $q->result
foreach ($q->result as $row)
{
$data[] = $row;
}
No need to use validation_errors in your php file.You can directly load your form page.Use validation_errors() in view page.
In your Controller, do this
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
Then in your formpage you can echo
<?php echo validation_errors(); ?>
change this line to
$this->data['showcombo'] = $this->load->sales_model->getComboProduct();
this
$this->data['showcombo'] = $this->load->sales_model->getProductCombo();
Because your
model name is
public function getProductCombo()
{
}
Firstly you load model in controller. And then called function, which you have defined in model..
$this->load->model('sales_model','sales'); // sales is alias name of model name
$this->data['showcombo'] = $this->sales->getComboProduct();

Incorrect Signature in facebook stream_publish call

I am having a facebook error on stream_publish call. I actually used an extension for Magento for Fconnect. Fconnect & Flogin is working fine. But it is requirement that when user place an order it should be posted on user's wall. For that I have implemented like this
document.observe('click', function(e){
if (e.element().match('a[rel^=facebook-connect]') || e.element().match('button[rel^=facebook-connect]')) {
e.stop();
FB.login(function(response){
if(response.status=='connected') setLocation('http://staging.mystore.com/facebook/customer_account/connect/');
}, {perms:"email,publish_stream"});
}
});
in Facebook Client file generateSignature method is like this
private function _generateSig($params_array)
{
Mage::log($params_array);
$str = '';
ksort($params_array);
foreach ($params_array as $k=>$v) {
$str .= "$k=$v";
}
$str .= $this->_secret;
Mage::log($str);
Mage::log('md5 sigs:: ' . md5($str));
return md5($str);
}
& My code that is calling the API is like this
$message = 'just placed an order on mystore.com';
$attachment = array(
'name' => "mystore",
'href' => 'http://www.mystore.com/',
'description' => 'New order on mystore.com',
'media' => array(array('type' => 'image',
'src' => 'http://www.mystore.com/skin/frontend/default/mystore/images/logo.png',
'href' => 'http://www.mystore.com/')));
$action_links = array( array('text' => 'Buy#mystore', 'href' => 'http://www.mystore.com/'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
try{
// if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id))
if($this->_getClient()->call( 'facebook.stream.publish',
array($message, $attachment, $action_links,
$this->_getClient()->users->getLoggedInUser(),
Mage::getSingleton('facebook/config')->getApiKey() )
) )
{
Mage::log( "Added on FB Wall" );
}
} catch(Exception $e)
{
Mage::log( "Exception in wall write" );
Mage::log($e);
}
After logging the Signature I found in log is
api_key=XXXXXXXXmethod=facebook.stream.publishsession_key=2.AQCm5fABfobInAS5.3600.1309352400.1-1000025660978090=just placed an order on mystore.comcall_id=1309345883.3068format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
I have never done any development on Facebook SO I have no Idea what to do? Please help me with solution. & let me know if u guys need any other info to understand this.
Oh yeah One more thing the Client File code that is calling Api (call method) its like this
private function _prepareParams($method, $params)
{
$defaultParams = array(
'api_key' => $this->_apiKey,
'call_id' => microtime(true),
'format' => 'JSON',
'v' => '1.0'
);
if($this->_sessionKey){
$defaultParams['session_key'] = $this->_sessionKey;
}
$params = array_merge($defaultParams, $params);
foreach ($params as $key => &$val) {
if (!is_array($val)) continue;
$val = Zend_Json::encode($val);
}
$params['method'] = $method;
if(isset($params['sig'])) {
unset($params['sig']);
}
$params['sig'] = $this->_generateSig($params);
return $params;
}
public function call($method, $args=array())
{
Mage::log($args);
$params = $this->_prepareParams($method, $args);
$client = self::_getHttpClient()
->setUri(self::FACEBOOK_REST_URI)
->setMethod(Zend_Http_Client::POST)
->resetParameters()
->setParameterPost($params);
try {
$response = $client->request();
} catch(Exception $e) {
throw new Mage_Core_Exception('Service unavaliable');
}
if(!$response->isSuccessful()) {
throw new Mage_Core_Exception('Service unavaliable');
}
$result = Zend_Json::decode($response->getBody());
//json decode returns float on long uid number? is_json check? old php?
if(is_float($result)){
$result = $response->getBody();
}
if(is_array($result) && isset($result['error_code'])) {
throw new Mage_Core_Exception($result['error_msg'], $result['error_code']);
}
return $result;
}
For calling API I used two ways $this->_getClient()->call( 'facebook.stream.publish',
& $this->_getClient()->call( 'stream_publish',
None of them are working
ok GUys I figure out the mistake
look at my code
format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
where u can see format=JSONv=1.01={....}2=[{.....}] the problem was I used numeric arrays for parameters. they should be associated arrays
like message={new order}attachment={....}
Once I fixed the associative array problem my code start working correctly
here is a link that'll give u detail about parameters to pass to stream.publish
http://schoolout.net/en/developers/view/39
Hope this will help somebody else too.

Display multi-option customer attribute within customer management admin grid

Okay so with Customer Attributes I have a multi-option selection that I have added to the Manage Customers Grid.
$prodCode = Mage::getSingleton('eav/config')->getAttribute('customer','prod_codes');
$prodCodeOptions = $prodCode->getSource()->getAllOptions(false);
$prodOptions = array();
foreach($prodCodeOptions as $k)
$prodOptions[$k['value']] = $k['label'];
$this->addColumn('prod_codes', array(
'header' => Mage::helper('customer')->__('Product Code'),
'width' => '100',
'index' => 'prod_codes',
'type' => 'options',
'options' => $prodOptions,
'filter_condition_callback'
=> array($this, '_filterProdOptionsCondition'),
));
I do have my attribute added to the collection at the top of my Grid.php:
->addAttributeToSelect('prod_codes')
Here is my _filterProdOptionsCondition method:
protected function _filterProdOptionsCondition($collection, $column) {
if(!$value = $column->getFilter()->getValue()) {
return;
}
$this->getCollection()->addFieldToFilter('prod_codes', array('finset' => $value));
#print($collection->getSelectSql());
}
Now this work fine and dandy if I only have ONE of the options selected, once I apply more than one option to the customers attribute I will get a blank results within the admin grid, however it IS still searchable.
A close look with the print($collection->getSelectSql()); uncommented I see that the attribute ID values are being returned in an comma delimited list.
Now onto my question with that background laid out, is there a method or "Magento" way to display these multi-options within the admin grid I'm just unaware of? Or do I need to simply get the comma values exploded and call for a new collection to build out the display values? Any help appreciated!
Appears I had to extend the Column renderer to anticipate comma values and simply render them, I'm amazed this isn't built in since the functionality exists to create the multioptions attributes but no grid display option for it.
app/code/local/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Options.php
public function render(Varien_Object $row)
{
$options = $this->getColumn()->getOptions();
$showMissingOptionValues = (bool)$this->getColumn()->getShowMissingOptionValues();
if (!empty($options) && is_array($options)) {
$value = $row->getData($this->getColumn()->getIndex());
if (is_array($value)) {
$res = array();
foreach ($value as $item) {
if (isset($options[$item])) {
$res[] = $options[$item];
}
elseif ($showMissingOptionValues) {
$res[] = $item;
}
}
return implode(', ', $res);
}
elseif (isset($options[$value])) {
return $options[$value];
} elseif (is_string($value)) { // <--- MY CHANGES HERE
$values = explode(',', $value);
$returnOptions = "";
foreach($values as $k=>$v) {
$returnOptions .= $options[$v]. ", ";
}
return substr($returnOptions, 0, -2);
}
return '';
}
}

Resources