how to sort cart data in ascending or descending order in codeigniter - codeigniter-3

i want to show the most recent item at the top in $this->cart->contents(); below is my add to cart and show cart functions. its display the contents but i want to show the items as new inserted one at the top.
public function show_cart(){
$output='';
foreach ($this->cart->contents() as $items) {
$output .='
<tr>
<td>'.$items['name'].'</td>
<td> <span class="c_qunt qty" id="qty">'.$items['qty'].'</span> </td>
<td>'.number_format($items['price']).'</td>
<td>'.number_format($items['subtotal']).'</td>
<td>
<span style="font-size:40px; color:red" id="'.$items['rowid'].'" class="remove"></span>
</td>
</tr>
';
}
return $output;
}
public function add_to_cart(){
$data = array(
'id' => $this->input->post('product_id'),
'name' => $this->input->post('product_name'),
'price' => $this->input->post('product_price'),
'qty' => $this->input->post('qty'),
);
$this->cart->insert($data);
echo $this->show_cart();
}

Related

Using Placeholder Viewhelper

I have worked with partials and now I'd like to have something like an info box which shall be filled with additional information.
I'm a bit confused how to give the data to the placeholder.
What I did:
I have an additional layoutfile. layout2.phtml
<?php $this->placeholder('content')->captureStart(); ?>
<div class="row">
<div class="col-md-8">
<?= $this->content; ?>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">additional part info</h3>
</div>
<div class="panel-body">
<strong>Approval Status</strong><p>
<strong>Alerts</strong> <p>
there are
<?= $this->AnzahlAlerts?> Alerts at the moment<p>
<strong>MoM</strong><p>
<p>see MoM here</p>
</div>
</div>
</div>
</div>
<?php
$this->placeholder('content')->captureEnd();
echo $this->partial('layout/layout',
['content'=>$this->placeholder('content')]);
?>
The placeholderbox will be shown like I wanted.
But I won't get the value of $this->AnzahlAlerts. I thought it must be given to the viewmodell, so I tried as follows:
controller/showAction
return new ViewModel([
'unitid' => $unit,
'part' => $part,
'dcls' => $this->table->fetchPartDcl($part,$dclid),
'pads' => $this->padtable->fetchPadPart($part, $unit),
'heritage' => $this->table->getHeritage($part, $projectid), //$this->unitpartTable->fetchHeritage($part)
'AnzahlAlerts' => $this->padtable->countAlert($part)
]);
My **onDispatchAction** here for completion:
public function onDispatch(MvcEvent $e)
{
$response = parent::onDispatch($e);
$this->layout()->setTemplate('layout/layout2');
return $response;
}
My Questions are, what is the error, and where is the postion to give the value AnzahlAlerts?
EDIT: count records
This is my modelfunction:
public function countAlert($partnumber)
{
$statment = "SELECT count(*) as AnzahlAlerts
from t_part_alert
WHERE t_part_alert.Part_Number = '" . $partnumber. "';";
// AND t_unit_part.UnitID =" . $unitid;
return $this->tableGateway->adapter->query($statment, "execute");
}
Just because it my be the problem.
You call and print a partial like so:
<?= $this->partial('partial/file/alias') ?>
This causes a partial to be rendered within the current partial where you called it. The name in the view_manager config is partial/file/alias.
If you wanted to pass variables to the partial file, you would have to pass an array as the second parameter, like so:
<?= $this->partial(
'partial/file/alias',
[
'param1' => 'value1',
'param2' => 'value2',
]
) ?>
The keys of the array become parameters in the called partial. So in the partial you can print a variable like so:
<?= $param1 ?>
When wanting to fill the 2nd partial with data, starting at the controller, you should pass the data you want to the first partial and from there fill the second.
Another option, the more difficult way, is to pre-render the partials in the Controller and then return the rendered whole from the Controller function.
Personally, I'm opposed to this as you would then not be separating concerns (viewing vs handling).
But of course, it's possible ;)
Full example from Controller into 2nd partial
class AwesomeController
{
public function demoAction()
{
// do stuff to create the values
return [
'key1' => 'value1',
'key2' => 'value2',
'fooKey1' => 'barValue1',
'fooKey2' => 'barValue2',
];
}
}
So now there's 4 values. These get passed to demo.phtml. However, the last 2 values are for the sub-partial, so we must call that. We even loop that, because we want to show them more than once!
<div class="row">
<div class="col-8 offset-2">
<table class="table table-striped table-bordered">
<tr>
<th><?= $this->translate('Key 1') ?></th>
<td><?= $this->escapeHtml($key1) // <-- Look, the key from Controller is now a variable! This is ZF magic :) ?></td>
</tr>
<tr>
<th><?= $this->translate('Key 2') ?></th>
<td><?= $this->escapeHtml($key2) ?></td>
</tr>
<?php for ($i = 0; $i < 3; $i++) : ?>
<?= $this->partial(
'custom/partial',
[
'value1' => $fooKey1, // <-- Look, the key from Controller is now a variable! This is ZF magic :)
'value2' => $fooKey2,
]
) ?>
<?php endfor ?>
</table>
</div>
</div>
Now, the above bit calls for the partial with name custom/partial. This must be registered. Example config below (place in module.config.php from your module):
'view_manager' => [
'template_map' => [
'custom/partial' => __DIR__ . '/../view/partials/demo-child.phtml',
// -- ^^ name -- ^^ location
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
File demo-child.phtml
<tr>
<th><?= $this->translate('Value 1') ?></th>
<td><?= $this->escapeHtml($value1) // <-- Look, from above partial - ZF magic :) ?></td>
</tr>
<tr>
<th><?= $this->translate('Value 2') ?></th>
<td><?= $this->escapeHtml($value2) ?></td>
</tr>

Dynamic form input fields in Cakephp 3

I have seen this: https://waltherlalk.com/blog/dynamic-form-input-fields and have been active in this: Dynamically add form field rows - cakePHP. I have reached the stage where the setup is as per the original tutorial with changes made as per the Stackoverflow post from monsur.hoq.
The form is working fine but, upon saving, it only saves the 'student' part of the data: nothing is sent to grades. The add part of my controller currently looks like this:
public function add()
{
$student = $this->Students->newEntity();
if ($this->request->is('post')) {
$student = $this->Students->patchEntity($student, $this->request->data);
if ($this->Students->save($student)) {
$this->Flash->success(__('The student has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The student could not be saved. Please, try again.'));
}
}
$this->set(compact('student'));
$this->set('_serialize', ['student']);
}
All code is as per bake or the tutorial shaped by the monsur.hoq post.
If anyone could help me to arrive at a working Cakephp3 example of the Walther Lalk tutorial I'd be very grateful.
The debugging toolbar shows the following SQL being produced on submitting the form:
INSERT INTO students (name, created, modified)
VALUES
(
'Test Two', '2016-09-13 16:04:07',
'2016-09-13 16:04:07'
)
All that serves to do is confirm the problem. Debugging in PHP Storm on form submission reveals the following:
$_POST = {array} [3]
_method = "POST"
name = "Test Four"
Grade = {array} [1]
0 = {array} [3]
id = ""
subject = "Maths"
grade = "3"
The add.ctp is as follows:
<nav class="large-3 medium-4 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('List Students'), ['action' => 'index']) ?></li>
<li><?= $this->Html->link(__('List Grades'), ['controller' => 'Grades', 'action' => 'index']) ?></li>
<li><?= $this->Html->link(__('New Grade'), ['controller' => 'Grades', 'action' => 'add']) ?></li>
</ul>
</nav>
<div class="students form large-9 medium-8 columns content">
<?= $this->Form->create($student) ?>
<fieldset>
<legend><?= __('Add Student') ?></legend>
<?php
echo $this->Form->input('name');
?>
</fieldset>
<fieldset>
<legend><?php echo __('Grades');?></legend>
<table id="grade-table">
<thead>
<tr>
<th>Subject</th>
<th>Grade achieved</th>
<th> </th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<td colspan="2"></td>
<td class="actions">
Add grade
</td>
</tr>
</tfoot>
</table>
</fieldset>
<script id="grade-template" type="text/x-underscore-template">
<?php echo $this->element('grades');?>
</script>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
<script>
$(document).ready(function() {
//I changed undescore default template settings
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
}
var
gradeTable = $('#grade-table'),
gradeBody = gradeTable.find('tbody'),
gradeTemplate = _.template($('#grade-template').remove().text()),
numberRows = gradeTable.find('tbody > tr').length;
gradeTable
.on('click', 'a.add', function(e) {
e.preventDefault();
$(gradeTemplate({key: numberRows++}))
.hide()
.appendTo(gradeBody)
.fadeIn('fast');
})
.on('click', 'a.remove', function(e) {
e.preventDefault();
$(this)
.closest('tr')
.fadeOut('fast', function() {
$(this).remove();
});
});
if (numberRows === 0) {
gradeTable.find('a.add').click();
}
});
</script>
Change from CakePHP 2 to CakePHP 3 fields name conventions,
Grade.{$key}.grade to grades.{$key}.grade
Create View/Elements/grades.ctp file with the following contents.
https://waltherlalk.com/blog/dynamic-form-input-fields
<?php
$key = isset($key) ? $key : '<%= key %>';
?>
<tr>
<td>
<?= $this->Form->hidden('grades.{$key}.id') ?>
<?= $this->Form->text('grades.{$key}.subject'); ?>
</td>
<td>
<?= $this->Form->select("grades.{$key}.grade",
[
'A+',
'A',
'B+',
'B',
'C+',
'C',
'D',
'E',
'F'
],
[
'empty' => '-- Select grade --'
]); ?>
</td>
<td class="actions">
Remove grade
</td>
</tr>

Facebook Ads API -> Displaying Campaigns

I am trying to show a list of all my facebook ad campaigns for the current day...
This code mostly works, except it only shows 24 of my campaigns... when I have over 100.
I am not sure why this would be... also not sure how to show for the current day stats... thanks for any help
<?php
$app_id='ID';
$app_secret='SECRET';
$access_token = 'TOKEN';
define('SDK_DIR', __DIR__ . '/..'); // Path to the SDK directory
$loader = include SDK_DIR.'/vendor/autoload.php';
use FacebookAds\Api;
// Initialize a new Session and instanciate an Api object
Api::init($app_id, $app_secret, $access_token);
// The Api object is now available trough singleton
$api = Api::instance();
use FacebookAds\Object\AdUser;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\Fields\AdCampaignFields;
use FacebookAds\Object\Fields\AdSetFields;
$me = new AdUser('me');
$accounts = $me->getAdAccounts();
// Output account ID
foreach ($accounts as $account) {
echo $account_id = $account->id;
echo "----";
}
$account = new AdAccount($account_id);
$fields = array(
AdCampaignFields::NAME,
AdCampaignFields::OBJECTIVE,
AdCampaignFields::STATUS,
);
$campaigns = $account->getAdCampaigns($fields);
?>
<table border="1" bordercolor="#6699CC" style="width:100%">
<tr>
<th bgcolor="#336699" style="color:#FFF">Campaign_id</th>
<th bgcolor="#336699" style="color:#FFF">Campaign Name</th>
<th bgcolor="#336699" style="color:#FFF">Status</th>
<th bgcolor="#336699" style="color:#FFF">Impressions</th>
<th bgcolor="#336699" style="color:#FFF">Clicks</th>
<th bgcolor="#336699" style="color:#FFF">Spent</th>
</tr>
<?PHP
foreach ($campaigns as $campaign) {
//---------------------------------
?>
<tr>
<td><?php echo $campaign->id; ?></td>
<td><?php echo $campaign->name; ?></td>
<td><?php echo $campaign->campaign_group_status ?></td>
<?php
$fields = array (
'impressions',
'clicks',
'spent',
);
$params = array (
'date_preset'=>'yesterday',
'data_columns'=>"['adgroup_id','actions','spend']",
);
$campaign = new AdCampaign($campaign->id);
$stats = $campaign->getStats($fields, $params);
foreach ($stats as $stat) {
echo '<td>'.$stat->impressions. '</td>';
echo '<td>'.$stat->clicks. '</td>';
echo '<td>'.$stat->spent. '</td>';
}
//---------------------------------
}
?>
You will need to create a param array to pass in. In the example below I set the limit to 500.
$params = array(
'time_interval' => array(
'day_start' => array('year' =>'2015', 'month'=> '5', 'day'=>'1'),
'day_stop' => array( 'year'=>'2015', 'month'=>'5', 'day'=>'31')
),
'limit' => 500,
);
$fields = array(
AdCampaignFields::NAME,
AdCampaignFields::OBJECTIVE,
AdCampaignFields::STATUS,
);
$campaigns = $account->getAdCampaigns($fields,$params);
I had same issue right now, so I am writing this as help to others.
You need to explicit say that you want to loop through whole result set (all result pages), and you doing it by setting ImplicitFetch to true. Example for you code :
$campaigns = $account->getAdCampaigns($fields);
...
$campaigns->setUseImplicitFetch(true); // set this before loop
...
foreach ($campaigns as $campaign) {
Best regards,
Nikola

Disable or change validation for embedded form fields in Symfony1 form

I am trying to cancel validation in embedded forms based on a value from main form.
By default, embedded forms fields have validator option set to 'required'=>true. So it gets validated like that. If user leave any field blank, the form does not pass validation and blank fields get marked in template (different style).
What I am trying to do is to change option:"required" to false for all fields in embedded form.
I tried to do that in post validator callback method, but it seems that it is not possible that way.
The main form code:
class TestForma extends sfForm
{
public function configure()
{
$this->setWidgets(array(
'validate_items' => new sfWidgetFormChoice(array(
'choices' => array('no' => 'No', 'yes' => 'Yes'),
'multiple' => false,'expanded'=>true,'default' => 'no')),
));
$this->setValidators(array('validate_items' => new sfValidatorPass()));
$this->widgetSchema->setNameFormat('testforma[%s]');
$subForm = new sfForm();
for ($i = 0; $i < 2; $i++)
{
$form = new ItemForma();
$subForm->embedForm($i, $form);
}
$this->embedForm('items', $subForm);
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'postValidate')))
);
}
Post-validator code:
public function postValidate($validator,$values)
{
$validatorSchema = $this->getValidatorSchema();
if($values['validate_items']=='no')
{
$itemsValidatorSchema = $validatorSchema['items'];
$itemsFieldsValidatorSchemes = $itemsValidatorSchema->getFields();
foreach($itemsFieldsValidatorSchemes as $itemValidatorScheme)
{
$itemValidatorScheme['color']->setOption('required',false);
$itemValidatorScheme['shape']->setOption('required',false);
}
}
return $values;
}
Embedded form class:
class ItemForma extends sfForm
{
public function configure()
{
$this->setWidgets(array(
'color' => new sfWidgetFormInputText(),
'shape' => new sfWidgetFormInput(),
));
$this->setValidators(array(
'color' => new sfValidatorString(array('required'=>true)),
'shape' => new sfValidatorEmail(array('required'=>true)),
));
$this->widgetSchema->setNameFormat('items[%s]');
}
}
Template code:
<form action="<?php echo url_for('weather/formiranje')?>" method="post">
<?php
foreach($form->getErrorSchema()->getErrors() as $e)
{
echo $e->__toString();
}
?>
<table>
<tfoot>
<tr>
<td colspan="2">
<input type="submit" value="OK" />
</td>
</tr>
</tfoot>
<tbody>
<tr><th>Main form</th></tr>
<tr><td><?php echo $form['validate_items']->renderLabel() ?>
<span class="<?php echo $form['validate_items']->hasError() ? 'rowError' : ''?>">
<?php echo $form['validate_items'] ?></span>
</td></tr>
<tr><td> </td></tr>
<tr><th>Embedded forms</th></tr>
<?php
foreach($form['items'] as $item)
{
?>
<tr>
<td><span class="<?php echo $item['color']->hasError() ? 'rowError' : ''?>">
<?php echo $item['color']->renderLabel() ?>
<?php echo $item['color'] ?></span>
</td>
</tr>
<tr>
<td><span class="<?php echo $item['shape']->hasError() ? 'rowError' : ''?>">
<?php echo $item['shape']->renderLabel() ?>
<?php echo $item['shape'] ?></span>
</td></tr>
<?php
}
echo $form['_csrf_token'];
?>
</tbody>
</table>
</form>
The way you organised it won't work because the post validator is run after all the field validators, so they've already been checked and marked as failed. (because the fields were required).
You could try the same approach you have here but with setting a preValidator instead of a postValidator. I think it should work then.
If it still won't work as expected what I would do is to change the default settings on the embedded form's fields to 'required' = false and use the postValidator. In the validator you could check whether or not you need to validate the embedded fields. If you need to validate them you can check if their values are set and if not you can throw errors for those fields. (I hope this is explained clearly)
Another thing you could try is to re-run the validation for the chosen fields. So something like that in your postValidator:
$itemValidatorScheme['color']->setOption('required',false);
$itemValidatorScheme['color']->clean($values['name_of_the_field']);

show custom attributes of type yes/no whose value is yes in list.phtml in magento

I made some attributes of type yes/no. Now I want to show those attributes whose value is yes in list.phtml
I try many codes but failed to solve this problem. This is my most recent code:
<?php $attributes = $_product->getAttributes();
foreach ($attributes as $attribute) {
$excludeAttr = array();echo $attribute->getIsVisibleOnFront() ;
if ( !in_array($attribute->getAttributeCode(), $excludeAttr)) {
$value = $attribute->getFrontend()->getValue($_product);echo $value;
if (!$_product->hasData($attribute->getAttributeCode())) {
$value = Mage::helper('catalog')->__('N/A');
} elseif ((string)$value == '') {
$value = Mage::helper('catalog')->__('No');
} elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
$value = Mage::app()->getStore()->convertPrice($value, true);
}
if (is_string($value) && strlen($value)) {
$data[$attribute->getAttributeCode()] = array(
'label' => $attribute->getStoreLabel(),
'value' => $value,
'code' => $attribute->getAttributeCode()
);
}
}
}
if($_additional = $data): ?>
<h2><?php echo $this->__('Additional Information') ?></h2>
<table class="data-table" id="product-attribute-specs-table">
<col width="25%" />
<col />
<tbody>
<?php foreach ($_additional as $_data): ?>
<tr>
<th class="label"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table')</script>
But it shows all attributes but I want to show only yes/no type of attributes whose value is yes. I have one more problem that when I use this code :
if ($attribute->getIsVisibleOnFront() && !in_array($attribute->getAttributeCode(), $excludeAttr)) {
It returns false. It did not understand why this statement returns false.
At last I got solution. Basically I add this condition
<?php if ($_product->getAttributeText($_data['code']) == "Yes"): ?>
it start working