Retrieve value from new column - mysql

I am trying to learn opencart structure, and trying to create a new column under the table product. The new column is "test"
Then I try to retrieve the data under this page index.php?route=checkout/cart (replace price with test column)
catalog\controller\checkout\cart.php
...
$this->data['products'][] = array(
'key' => $product['key'],
'thumb' => $image,
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
'reward' => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
'price' => $product['test'], //<-- new column
'total' => $total,
'href' => $this->url->link('product/product', 'product_id=' . $product['product_id']),
'remove' => $this->url->link('checkout/cart', 'remove=' . $product['key'])
);
The problem is I'm not getting any output, and I'm not sure how to work with the model. Which query/function is related with this page ?

The problem is that the $products that are available at cart.php controller are retrieved from the session where they have been stored in previously set structure, so there is no test index and You should get a Notice: undefined index 'test' in .... The $products are retrieved by
foreach ($this->cart->getProducts() as $product) {
//...
}
See /system/library/cart.php and method getProducts() to understand what I am speaking about.
If You would like to use this at catalog/controller/product/category.php or catalog/controller/product/product.php controllers, the code You are trying will work.
If You replace the price within all product lists and product detail, these controllers:
product/
category.php
manufacturer_info.php
product.php
search.php
special.php
module/
bestseller.php
featured.php
latest.php
special.php
with Your value, the final price within cart would be Your test value.

Related

Laravel - Create or Update by defined attributes

I have this this table:
--Votes--
id: Integer
post_id: Integer
user_id: Integer
positive: Boolean
Now I would like to create a record only if it not exists. It is working until someone wants to click on dislike after he clicked on like(on the other side exactly equivalent).
For example someone likes a post a record will be created with positive=true. Now if the user clicks on the same post but this time on dislike, it will be created another record, but i want that it only updates the existing record.
Is there a simple solution?
Here is my Code to create the record:
$vote = Vote::firstOrCreate(array(
'post_id' => $request->input('post_id'),
'user_id' => Auth::user()->id,
'positive' => $request->input('positive')
));
Note: If someone knows how to do that, maybe he could show me how a deletion would be. For example someone clicks on like two times. The record should be created an deleted.
You can use updateOrCreate method:
public static function updateOrCreate(array $attributes, array $values = array())
{
$instance = static::firstOrNew($attributes);
$instance->fill($values)->save();
return $instance;
}
have a look: https://github.com/laravel/framework/blob/5.0/src/Illuminate/Database/Eloquent/Model.php#L605
EDIT:
Example
$attributes = [
'name' => 'Christian',
'email' => 'christian#example.com'
];
$values = [
'name' => 'Christian',
'email' => 'christian#example.com',
'phone' => '123456789'
];
MyModel::updateOrCreate($attributes, $values);
In the example above I will search if in my table I have an entry which match name and email, if it exists I will update the records, otherwise I will insert a new entry with the $values infos

Retrieving and posting static dropdown data into mysql database in Zend 2

I have several fields in my form that i wish to post to the database. All the other fields bar the dropdown field are all working fine
The official documentation for zend 2 is not really clear on how to deal with posting data from a dropdown menu into the database
Here's what i have:
my addAction in the controller
public function addAction()
{
$form = new UsersForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$users = new Users();
$form->setInputFilter($users->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
{
$users->exchangeArray($form->getData());
$this->getUsersTable()->saveUser($users);
// Redirect to list of albums
return $this->redirect()->toRoute('index');
}
}
return array('form' => $form);
}
my form
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('users');
//other form elements...
//the dropdown menu
$this->add(array(
'type' => 'Select',
'name' => 'groupid',
'options' => array(
'label' => 'Group',
'value_options' => array(
'0' => 'Not Selected',
'1' => 'Super Admin',
'2' => 'Company Admin',
),
),
));
//...
}
}
the view
<?php
$form->setAttribute('action', $this->url('user', array('action' => 'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('groupid'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
When i run my application for the addAction, i get an error message:
Statement could not be executed (23000 - 1048 - Column 'GroupID' cannot be null)
where 'GroupID' is the column in my table that takes the value from the dropdown which means the field is not being posted
I need help on this
If the column in your database is GroupID, the form element should also be named that. Yours is groupid (i.e. lowercase). If that doesn't fix the issue, please edit your question to include the DB structure and the code for the saveUser() function.

WordPress Filtering Custom Post Type by Metadata and Search Heirachy

I have a custom Post Type called cptMovie which has two Custom Field (Metadata) "Language" and "Box office" assigned to it.
I also have a Custom Taxonomy called movieTax with 4 tax Terms "Action", "Comedy", "Family" ,and "Horror" .
In a WordPress File structe like below:
index.php
page.php
page-movie.php
taxonomy.php
taxonomy-movieTax.php
I am able to list and display all the Custom Post Types (movie) under Taxonomy (movieTax) using indexed page page-movie.php and custom wp-query and eventually link them to the taxonomy-movieTax.php to have all Post under each tax terms.
Up to here I am Ok and getting the resut BUT I need to add some Filters for users like Filtering the result by Language or Boc office Metadata,
Now my question is Which Part of the WP Template Hierarchy is in charge of displaying the result? Do I have to create the search.php if so how a query like this:
$arg = array(
'meta_query' => array(
array(
'key' => 'language',
'value' => 'english'
)
)
);
$filter-lang = new WP_Query( $arg );
in page-movie.php will end up in search.php?
Thanks,
You don't need to create a "search.php" file.
You can add the below code in "page-movie.php" or "taxonomy-movieTax.php" file, as per your requirement.
$arg = array(
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'language',
'value' => $lang_val,
'compare' => '='
),
array(
'key' => 'box_office',
'value' => $box_office_val,
'compare' => '='
)
)
);
$filter-lang = new WP_Query( $arg );
Here, $lang_val & $box_office_val are values to search for language key & box office key respectively. However, if you want to create separate search file, you also need to specify post type in arguments.

How do I best avoid inserting duplicate records in CakePHP?

I'm pulling data from several remote DataSources, restructuring to fit my models schema and finally passing the array to MyModel::saveAll();
I'd like to avoid importing duplicate records (ie, don't import if MyModel.external_id = 120 & MyModel.external_type = 'basecamp.comment' already exists in db).
What's the most efficient way of going about this?
Sample data:
$data['MyModel'] = [
[
'title' => 'foo',
'created' => '2013-12-18 11:29:06',
'external_id' => 120,
'external_type' => 'github.commit'
],
[
'title' => 'bar',
'created' => '2013-12-18 13:22:06',
'external_id' => 120,
'external_type' => 'basecamp.comment'
]
];
NB: Notice that MyModel.external_id isn't unique on it's own.
This is where validation comes into play. In your MyModel class, add the following:
public $validate = array(
'external_type' => array(
'rule' => 'idAndTypeUnique',
'message' => "Type and ID already exist"
)
);
public function idAndTypeUnique()
{
$existing = $this->find('first', array(
'conditions' => array(
'external_id' => $this->data[$this->name]['external_id'],
'external_type' => $this->data[$this->name]['external_type']
)
));
return (count($existing) == 0);
}
Your saveAll() call would look like:
$this->MyModel->saveAll($data, array('validate' => true));
The easiest way is to make a unique index on those two fields.
alter table my_model add unique index(external_id, external_type);
This forces the constraint in the database level.
If you want to force this constraint in the cake layer, then check this out:
cakephp isUnique for 2 fields?

How can I insert data from a table from sql into a dropdown list in zend framework 2?

I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).