I need to do default sorting by id, we don't show id in grid that's why default sorting is not working here is my code for sorting
public function search($params)
{
$this->load($params);
$query = new \yii\db\Query;
$expression = new \yii\db\Expression('CASE WHEN b.status = 1 THEN "Active" WHEN b.status = 2 THEN "Inactive" END AS status');
$query->select(['b.image','bl.name',$expression,'b.brand_id'])
->from('brand AS b')
->join('INNER JOIN',
'brand_lang AS bl',
'bl.brand_id = b.brand_id AND lang_id = 1');
$query->andFilterWhere([
'status' => $this->status,
]);
$query->andFilterWhere(['like', 'name', $this->name]);
$command = $query->createCommand();
$data = $command->queryAll();
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => $query,
'totalCount' => count($data),
'sort' => [
'attributes' => [
'name' => [
'asc' => ['name' => SORT_ASC, 'name' => SORT_ASC],
'desc' => ['name' => SORT_DESC, 'name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
'status' => [
'asc' => ['status' => SORT_ASC, 'status' => SORT_ASC],
'desc' => ['status' => SORT_DESC, 'status' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Status',
],
'brand_id' => [
'asc' => ['brand_id' => SORT_ASC, 'brand_id' => SORT_ASC],
'desc' => ['brand_id' => SORT_DESC, 'brand_id' => SORT_DESC],
'default' => SORT_ASC,
'label' => 'Brand',
],
'defaultOrder' => ['brand_id' => SORT_ASC]
],
],
'pagination' => [
'pageSize' => 20,
],
]);
return $dataProvider;
}
Can anyone please tell me what is solution for this ? I did lots of googling but didn't success
Your defaultOrder param should be in sort, not in attributes :
'sort' => [
'attributes' => [...],
'defaultOrder' => ['brand_id' => SORT_ASC],
],
Use $dataProvider->sort->attributes['attribute_name']:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => ['brand_id' => SORT_ASC]
],
]);
$dataProvider->sort->attributes['name'] = [
'asc' => ['name' => SORT_ASC],
'desc' => ['name' => SORT_DESC],
];
Related
I want order by proyecto_id who is in my ProyectosCategoraisTareas and also order by my categoria id, this is my contain Tareas.Categorias.
I try this but not work.
$proyectostareas = $this->ProyectosCategoriasTareas
->find('all', [
'contain' => [
'Proyectos',
'Tareas',
'Tareas.Categorias' => [
'order' => [
'Tarea.Categoria.id' => 'DESC'
]
]
]
])
->where([
'activa' => '1'
])
->order([
'proyecto_id' => 'DESC'
]);
Try this:
$proyectostareas = $this->ProyectosCategoriasTareas
->find('all')
->where([
'activa' => '1'
])
->join([
'Proyectos',
'Tareas'])
->order([
'proyecto_id DESC',
'Tarea.Categoria.id DESC'
]);
hello I want to get results from multiple tables using the keyword which user has typed. The problem I am having is I don't know how can I do search on that table which is getting through contain
Here's my query
public function getGigPostBasedOnSearch($keyword){
$this->Behaviors->attach('Containable');
return $this->find('all', array(
'contain' => array(
'User','UserInfo', 'GigPostAndCategory.Category','Location','GigPostAndCalender'
),
'conditions' => array(
'AND' => array(
'GigPost.active' => 1,
'OR' => array(
array('GigPost.title LIKE' => '%'.$keyword.'%'),
array('GigPost.description LIKE' => '%'.$keyword.'%'),
array('Location.location_string LIKE' => '%'.$keyword.'%'),
)
)
//'OrderGigPost.request' => 0
),
'order' => 'GigPost.gig_post_id DESC',
'recursive' => 0
));
}
This query works fine. I want to search keyword in category table also.I want to do something like this
array('Category.cat_name LIKE' => '%'.$keyword.'%')
Please help me how can I search in Category table as well
Thank you
Model GigPost.php
<?php
class GigPost extends AppModel
{
public $useTable = 'gig_post';
public $primaryKey = 'gig_post_id';
public $hasAndBelongsToMany = array(
'Category' =>
array(
'className' => 'Category',
'joinTable' => 'gigpost_category',
'foreignKey' => 'gig_post_id',
'associationForeignKey' => 'cat_id',
'unique' => true,
)
);
public $hasOne = array(
'Location' => array(
'className' => 'Location',
'foreignKey' => 'gig_post_id',
'conditions' => array('GigPost.gig_post_id = Location.gig_post_id')
));
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'fields' => array('User.user_id','User.email','User.active')
),
'UserInfo' => array(
'className' => 'UserInfo',
'foreignKey' => 'user_id',
)
);
public function getGigPostBasedOnSearch($keyword){
$this->Behaviors->attach('Containable');
return $this->find('all', array(
'contain' => array(
'User','UserInfo', 'GigPostAndCategory.Category'=>array(
'conditions'=>array(
'OR' => array(
array('Category.cat_name' => '%'.$keyword.'%'),
),
)
),'Location','GigPostAndCalender'
),
'conditions' => array(
'AND' => array(
'GigPost.active' => 1,
'OR' => array(
array('GigPost.title LIKE' => '%'.$keyword.'%'),
array('GigPost.description LIKE' => '%'.$keyword.'%'),
array('Location.location_string LIKE' => '%'.$keyword.'%'),
// array('Category.cat_name LIKE' => '%'.$keyword.'%'),
)
)
//'OrderGigPost.request' => 0
),
'order' => 'GigPost.gig_post_id DESC',
'recursive' => 0
));
}
}
Your issue is that the relationship between GigPost and Category is HABTM, so when you use contain Cake has to do a separate query to retrieve the related categories as there is not a one-on-one association. To get round this you need to manually perform a join rather than contain the categories:-
$this->find('all', array(
'contain' => array(
'User', 'UserInfo', 'GigPostAndCategory.Category', 'Location', 'GigPostAndCalender'
),
'joins' => array(
array(
'table' => 'gigpost_category',
'alias' => 'GigPostCategory',
'type' => 'INNER',
'conditions' => 'GigPost.id = GigPostCategory.gig_post_id'
),
array(
'table' => 'categories',
'alias' => 'Category',
'type' => 'INNER',
'conditions' => 'Category.id = GigPostCategory.cat_id'
)
),
'conditions' => array(
'AND' => array(
'GigPost.active' => 1,
'OR' => array(
array('GigPost.title LIKE' => '%'.$keyword.'%'),
array('GigPost.description LIKE' => '%'.$keyword.'%'),
array('Location.location_string LIKE' => '%'.$keyword.'%'),
array('Category.cat_name LIKE' => '%'.$keyword.'%'),
)
)
),
'order' => 'GigPost.gig_post_id DESC',
'group' => 'GigPost.id',
'recursive' => 0
));
This ensures that the categories will be included with the data returned by the primary query.
You will probably need to modify the joins array a bit as you don't appear to be using Cake naming conventions for your table so I am not sure what you have named things. However, this should put you on the right track.
I've added product with custom options programmatically. When I edit the product & save the added custom options deleted from saved product.
Below is my code to insert product with custom options:
$p = array(
'sku_type' => 0,
'sku' => 'SKU00'.$row['Pid'],
'name' => $row['ProductName'],
'description' => $row['Description'],
'short_description' => $row['Description'],
'type_id' => 'simple',
'attribute_set_id' => 4,
'weight' => 0.00,
'visibility' => 4,
'price_type' => 0,
'price_view' => 0,
'price' => $row['SPrice'],
'status' => 1,
'created_at' => strtotime('now'),
'category_ids' => 2,
'store_id' => 1,
'website_ids' => 1,
'tax_class_id' => 0,
);
$product->setData($p);
$optionRawData = array();
$optionRawData[0] = array(
'required' => 1,
'option_id' => '',
'position' => 0,
'type' => 'select',
'title' => $row['ProductName'],
'default_title' => $row['ProductName'],
'delete' => '',
);
$selectionRawData = array();
$selectionRawData[0] = array();
$selectionRawData[0][] = array(
'product_id' => $row['Product_Id'],
'selection_qty' => 1,
'selection_can_change_qty' => 100,
'position' => 0,
'is_default' => 1,
'selection_id' => '',
'selection_price_type' => 0,
'selection_price_value' => $row['SPrice'],
'option_id' => '',
'delete' => ''
);
$product->setCanSaveConfigurableAttributes(false);
$product->setCanSaveCustomOptions(true);
// Set the Bundle Options & Selection Data
$product->setBundleOptionsData($optionRawData);
$product->setBundleSelectionsData($selectionRawData);
$product->setCanSaveBundleSelections(true);
$product->setAffectBundleProductSelections(true);
$product->getResource()->save($product);
$productID = $product->getId();
$product = Mage::getModel('catalog/product')->load($productID);
$optionsArray = array(
array(
'title' => 'Standard',
'price' => 0.0,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => 0,
),
array(
'title' => 'Premium',
'price' => 10,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => 1,
),
array(
'title' => 'Deluxe',
'price' => 20,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => 2,
)
);
$options = array(
'title' => $product->getName(),
'type' => 'radio',
'is_required' => 1,
'sort_order' => 0,
'values' => $optionsArray,
);
$optionInstance = $product->getOptionInstance()->unsetOptions();
$product->setHasOptions(1);
$optionInstance->addOption($options);
$optionInstance->setProduct($product);
$product->save();
I update an entity (so same id) and I get a validation error on a field which has a 'unique' rule.
I verified in the db that there is no an existing identical field and so I don't understand why I have this error as I update the record so obviously the field exists already because it's itself!
Is it a problem to have a 'unique' rule on patchEntity()?
[
'site_name' => '...',
'datas' => object(App\Model\Entity\User) {
'id' => (int) 653,
'owner_id' => (int) 611,
'extraemails' => [
],
'owner' => object(App\Model\Entity\Owner) {
'id' => (int) 611,
'company' => 'This is the Company name',
'created' => object(Cake\I18n\Time) {
'time' => '2015-06-06T18:07:17+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2015-06-17T02:44:36+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'[new]' => false,
'[accessible]' => [
'email' => true,
'phone' => true,
'phone2' => true,
'fax' => true,
'company' => true,
'tva_number' => true,
'address' => true,
'postcode' => true,
'city' => true,
'country_id' => true,
'users' => true,
'username' => true,
'origin' => true
],
'[dirty]' => [
'email' => true,
'phone' => true,
'postcode' => true,
'city' => true
],
'[original]' => [
'email' => '...',
'phone' => '...',
'postcode' => '...',
'city' => '...'
],
'[virtual]' => [],
'[errors]' => [
'company' => [
'unique' => 'This company name exists already.'
]
],
'[repository]' => 'Owners'
},
....
EDIT patchEntity() call added
$user = $this->Users->patchEntity($site->users[0], [
'email' => $this->siteDatas['userEmail'],
'phone' => $this->siteDatas['ownerPhone'],
'role' => 'owner',
'active' => 1,
'extraemails' => $this->siteDatas['extraemails'],
'owner' => [
'company' => $this->siteDatas['ownerName'],
'email' => $this->siteDatas['ownerEmail'],
'phone' => $this->siteDatas['ownerPhone'],
'address' => $this->siteDatas['ownerAddress'],
'postcode' => $this->siteDatas['ownerPostcode'],
'city' => $this->siteDatas['ownerCity'],
'country_id' => $this->siteDatas['countryId'],
'web' => $this->siteDatas['ownerWeb'],
'origin' => 'sitra',
],
],
[
'validate' => 'import',
'associated' => [
'Extraemails',
'Owners' => [
'validate' => 'import'
]
]
]);
if ($user->errors()) {
// Here is where I get the 'unique' error
}
So again I verified that no other record in the table have the same 'company' name.
and as you can see in the debug() at the begining of my post, I have a owner->id and it's really the one I want to modify.
Here is the validator
public function validationImport(Validator $validator) {
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create')
->notEmpty('company')
->add('company', 'unique', ['rule' => 'validateUnique', 'provider' => 'table', 'message' => __("This company exists already.")])
...
])
;
return $validator;
}
I can get my find to work any other way, but I cannot get this working with pagination. What am I doing wrong?
Output in view:
SQL Error: 1054: Unknown column 'fields' in 'where clause'
Warning (2):** Cannot modify header information - headers already sent by (output started at...
Controller Action:
...
$cond = array(
'fields' => array('id', 'name', 'provider_network_url', 'application_url'),
'conditions' => array('PlanDetail.id' => $id),
'contain' => array(
'Company' => array('fields' => array(
'id',
'name',
'company_logo_url',
'plan_detail_by_company_landing')),
'Plan' => array('fields' => array('id', 'monthly_cost'),
'Applicant' => array('fields' => array('id', 'name')),
'Age' => array('fields' => array('id', 'name')),
'State' => array('fields' => array('id', 'name')),
'Zip' => array('fields' => array('id', 'title')),
'PlanDetail' => array('fields' => array('id', 'name')),
)));
$planDetails = $this->paginate('PlanDetail', $cond);
$this->set(compact('planDetails', $planDetails));
...
$this->paginate = array(
'fields' => ....,
'conditions' => ....,
'contain' => array(
'Company' => ...,
'Plan' => ....));
$this->set('planDetails', $this->paginate()));