I have this class:
class Product extends DataObject {
static $db = array(
'Name' => 'Varchar',
'ProductType' => 'Varchar',
'Price' => 'Currency'
);
}
The database table looks as follows:
---------------------------------
| Name | ProductType | Price |
|-----------+-------------+-------|
| Product 1 | Type1 | 100 |
| Product 2 | Type1 | 240 |
| Product 3 | Type2 | 10 |
| Product 4 | Type1 | 100 |
---------------------------------
I would like to have 2 model admins:
class MyFirstModel extends ModelAdmin {
public static $managed_models = array(
Product
);
}
class MySecondModel extends ModelAdmin {
public static $managed_models = array(
Product
);
}
What is the best way to come to this result:
MyFirstModel should show me all entries where ProductType in table is Type1
And
MySecondModel should show me all entries where ProductType in table is Type2
getList() should be the answer. DOC here http://doc.silverstripe.org/framework/en/reference/modeladmin#results-customization
So something like:
public function getList() {
$list = parent::getList();
if($this->modelClass == 'Product') {
$list->exclude('ProductType', 'Type1');
}
return $list;
}
If you have more than 2 ProductType you can use an array to exclude multiple values like
$list->exclude('ProductType', array('Type2', 'Type3'));
Related
I have a word press site with custom fields.
I need to query a repeater field as a table. It looks like that:
| param_1 | param_2 | param_2 | param_4
| 20 | 20 | 20 | 20
| 555 | 680 | 56 | 0
| 5555 | 45 | 56 | 1
| 69 | 0 | 45 | 0
I need to query this repeater to get a result only if it match the query in the same line
My meta query looks like that:
[post_type] => product
[posts_per_page] => -1
[orderby] => title
[order] => ASC
[meta_query] => Array (
[relation] => AND
[0] => Array (
[key] => BBBproduct_params_values_AAA_param_value_0
[value] => 25
[compare] => <=
[type] => NUMERIC
)
[1] => Array (
[key] => BBBproduct_params_values_AAA_param_value_1
[value] => 56
[compare] => >=
[type] => NUMERIC
)
[2] => Array (
[key] => BBBproduct_params_values_AAA_param_value_2
[value] => 56
[compare] => >=
[type] => NUMERIC
)
[3] => Array (
[key] => BBBproduct_params_values_AAA_param_value_3
[value] => 0
[compare] => =
[type] => NUMERIC
)
)
She is created trough this code:
if( $product_search_by_param_active ){
function my_posts_where( $where ){
$where = str_replace("AAA_param_value_", "%_param_value_", $where);
$where = str_replace("meta_key = 'BBBproduct_params_values_", "meta_key LIKE 'product_params_values_", $where);
return $where;
}
add_filter('posts_where', 'my_posts_where');
$range_angine_settings = get_field('param_search_range_settings');
$search_args['meta_query'] = array();
$search_args['meta_query'] ['relation'] = 'AND';
foreach( $range_angine_settings as $rangekey => $search_range ){
${'range-'.$rangekey} = $_GET['range-'.$rangekey]? $_GET['range-'.$rangekey] : '0';
if ( $_GET['range-'.$rangekey] ) $has_range_query = true;
//$pre_prama_value = 'product_params_values_'.strval($rangekey).'_param_value_AAA';
if( isset($_GET['range-'.$rangekey])){
$search_args['meta_query'][] = array(
"key" => 'BBBproduct_params_values_AAA_param_value_'.strval($rangekey),
"value" => $search_range['search_metric_ranges'][${'range-'.$rangekey}]['range_value'],
"compare" => $search_range['product_search_logic'],
'type' => 'NUMERIC'
);
}
}
}
The problem is that this because of the '%' I get result even if the query match not on the same line.
In the example above it is intended not to get any results, but as every condition is met on a different line I do get a result.
Is there a way to create this king of query to give results by line number?
For me I prefer using CMB2 for custom fields
https://github.com/CMB2/CMB2
I have a problem with GroupBy.
I have entity with categories and entity with products. I want to get all the products grouped by category(id).
public function getAll()
{
$qb = $this->createQueryBuilder('p');
$qb->leftJoin('p.categories', 'category');
$qb->where('p.enabled = true');
$qb->andWhere('p.visible = true');
$qb->andWhere('p.quantity >= 1');
$qb->groupBy('category.id');
return $qb->getQuery()->getResult();
}
But this returns just few records(I think 1 from each category).
How can I get all products grouped in categories?
Thanks
So if you have something like this:
Category(id, name) 1-N Products (id, name, enabled, visible, quantity, category_id), and:
categories:
id name
1 category1
2 category2
products:
id name enabled visible quantity category_id
1 prod1 1 1 1 1
2 prod2 1 1 2 1
3 prod3 1 1 3 1
4 prod4 1 1 1 2
5 prod5 1 1 2 2
Then I think you should start from CategoryRepository, and:
public function getAll()
{
$qb = $this->createQueryBuilder('c');
$qb
->select('c.name')
->addSelect("(SELECT GROUP_CONCAT(p.name) FROM AppBundle:Product p WHERE p.category = c.id AND p.enabled = :enabled AND p.visible = :visible AND p.quantity >= :number) AS prods")
->setParameter('enabled', true)
->setParameter('visible', true)
->setParameter('number', 1)
;
return $qb->getQuery()->getResult();
}
The results will look like:
array:2 [▼
0 => array:2 [▼
"name" => "category1"
"prods" => "prod1,prod2,prod3"
]
1 => array:2 [▼
"name" => "category2"
"prods" => "prod4,prod5"
]
]
Also, you'll need to install beberlei's DoctrineExtensions to let doctrine know about GROUP_CONCAT function
I'm trying to get all the list of Users query
$userList = [1,5,2,3,1];
$users = $this->getEntityManager()->getRepository('AppBundle:User')->findBy(['id' => $userList]);
this code is working but the it distinct the user. It display like this
---------------
userid | name
---------------
1 | we
5 | ace
2 | red
3 | ran
but i want to display like this one
---------------
userid | name
---------------
1 | we
5 | ace
2 | red
3 | ran
1 | we
How can i do that in ORM?
Update
I try this one.
public function getUsers($id)
{
$query = $this->createQueryBuilder('u')
->addSelect('u')
->distinct(false)
->where('u.id IN (:ulist)')
->setParameter('ulist', $id)
->getQuery();
$users = $query->getResult(Query::HYDRATE_ARRAY);
return $users;
}
but it display the same
You can try with the query builder.
$repository = $this->getDoctrine()->getRepository('AppBundle:User');
$query = $repository->createQueryBuilder('u')
->select('u')
->where('u.id IN (:ulist)')
->setParameter('ulist', $userList)
->getQuery();
$users = $query->getResult();
if this still gets you distinct results try this
$repository = $this->getDoctrine()->getRepository('AppBundle:User');
$query = $repository->createQueryBuilder('u')
->select('u')
->distinct(false)
->where('u.id IN (:ulist)')
->setParameter('ulist', $userList)
->getQuery();
$users = $query->getResult();
Otherwise you'll have to create an array of objects. You can do it by replacing the last line with
$users = $query->getResult(Query:HYDRATE_ARRAY);
Now you have a multidimensional array with all records, and you can display them as many want as you want just fetching them like $users[0]['username'] for example
I'm new in MVC5.
I have 2 table, tblClient & tblBranch.
The Data Structure are:
tblClient
ID | Name
---------
1 | BCS
2 | LBBI
3 | CARB
tblBranch
ID | cID | BranchName
---------------------
1 | 1 | Savar
2 | 1 | Nobinogor
3 | 2 | Sawrapara
4 | 1 | Mirpur
5 | 3 | Motijheel
6 | 2 | Dhanmondi
7 | 1 | Kazipara
Now I need to show data in index page as like:
BCS
sL | Branch
-----------
1 | Savar
2 | Nobinogor
3 | Mirpur
4 | Kazipara
LBBI
sL | Branch
-----------
1 | Sawrapara
2 | Dhanmondi
CARB
sL | Branch
-----------
1 | Motijheel
How can I do this ?
Write a model class for your index view.
public class MyModel
{
public string GroupName;
public List<string> GroupItems;
}
Specify your model for your view:
#model IEnumurable<MyProject.MyModel>
#foreach (var item in Model)
{
<h2>#item.GroupName</h2>
<ol>
#foreach (var it in item.GroupItems)
{
<li>#it</li>
}
</ol>
}
And finally in the index action of your controller fill the model and pass it to the view:
public ActionResult Index()
{
var model = new List<MyModel>();
var item = new MyModel();
item.GroupName = "Hello World";
item.GroupItems = new List<string>() { "item1", "item2" };
model.Add(item);
return View(model);
}
You can wrap every tblClient in new Object:
tblClient has name and contains List of tblBranch
public Class Client
{
public string clientName {get;set;}
public List<Branch> branches {get;set;}
}
public Class Branch
{
public string branchName
}
and retriere List<Client> and show them to the UI
There is no need in doing something unusual. Especially, groupping by.
You can simply iterate through items and output it.
In ASP.NET Razor:
Dictionary<int, string> clients = // get dictionary from DB like {{1, "BCS"}, {2, "LBBI"} ...}};
List<BranchEntity> branches = // get list of Branch entities just like in DB;
// You can pass these values as ViewBag or together as a Model
#{
foreach (var client in clients)
{
var branchesForClients = branches.Where(x => x.cID == client.Key).ToArray();
<h3>#client.Value</h3>
<table>
for (int i = 0; i < branchesForClients.Length; i++)
{
<tr>
<td>#(i + 1)</td>
<td>#branchesForClients[i].BranchName</td>
</tr>
}
</table>
}
}
Here is an entity:
public class BranchEntity
{
public int Id { get; set; }
public int cId { get; set; }
public string BranchName { get; set; }
}
I'm using drupal_execute to save a node programmatically, and for the most part, it works fine, except when it comes to a multi-value field.
What gets posted is this (I'm just including the portion that isn't working):
[alt] => Array
(
[0] => Array
(
[name] => Sam I. Am
[phone] => (650) 5553131
)
[1] => Array
(
[name] => The Lorax
[phone] => 6505553344
)
[2] => Array
(
[name] =>
[phone] =>
)
)
When I'm setting the $form_state['values'], I'm using:
for($a = 0; $a < count($_REQUEST['alt']); $a++) {
$form_state['values']['field_alternativename'][$a]['value'] = check_plain($_REQUEST['alt'][$a]['name']);
$form_state['values']['field_alternativephone'][$a]['value'] = format_phone($_REQUEST['alt'][$a]['phone']);
}
And to save the node:
drupal_execute('info_node_form', $form_state, $node);
As a test, to make sure that I'm referencing the appropriate fields, I edited an existing node using node/X/edit and printed out the $form_state['values'] upon submission. This is what it printed out:
//output of print '<pre>'; print_r($form_state['values']); print '</pre>';
[field_alternativename] => Array
(
[0] => Array
(
[value] => Sam I. Am
[_error_element] => group_alternative_contacts][0][field_alternativename][value
[_weight] => 0
[_remove] => 0
)
[1] => Array
(
[value] => The Lorax
[_error_element] => group_alternative_contacts][1][field_alternativename][value
[_weight] => 1
[_remove] => 0
)
)
[field_alternativephone] => Array
(
[0] => Array
(
[value] => (650) 5553131
[_error_element] => group_alternative_contacts][0][field_alternativephone][value
[_weight] => 0
[_remove] => 0
)
[1] => Array
(
[value] => (650) 5553344
[_error_element] => group_alternative_contacts][1][field_alternativephone][value
[_weight] => 1
[_remove] => 0
)
)
So, I'm not understanding why it isn't being saved... I'm not setting the delta, but I didn't think I'd have to? In mysql, the data is stored as:
mysql> select * from content_field_alternativename ;
+-------+-------+-------+-----------------------------+
| vid | nid | delta | field_alternativename_value |
+-------+-------+-------+-----------------------------+
| 22433 | 22433 | 0 | Sam I. Am |
+-------+-------+-------+-----------------------------+
mysql> select * from content_field_alternativephone;
+-------+-------+-------+------------------------------+
| vid | nid | delta | field_alternativephone_value |
+-------+-------+-------+------------------------------+
| 22433 | 22433 | 0 | (650) 5553131 |
+-------+-------+-------+------------------------------+
The delta is how cck stores multiple values. nid x, vid x, delta 0 is the first in the multivalue field nid x, vid x, delta 1 is the second etc. It's required so if you add deltas to your multi-values it should work.