Group Events by Week Commencing in Eloquent - grouping

I have the following method in my Event model for my events:
public static function getEvents($perPage = 10)
{
$events = Event::where('active', '=', 1)->paginate($perPage);
return $events;
}
Each event has a start_date and I need to take that start date and group the results in the view by week commencing, as in the Monday of the week each event occurs. I have this in my controller:
public function index()
{
$events = Event::getEvents($perPage = 5);
$this->layout->content = View::make('events.index')->with('events', $events);
}
Can anyone help me out with grouping these events by week commencing? Thanks.
I'm part way there in terms of getting the week commencing date using:
foreach ($events as $event)
{
$start_date = DateTime::createFromFormat('Y-m-d', $event->start_date);
$week = $start_date->format('YW');
$monday = 1;
$day_offset = ($monday - $start_date->format('N'));
$week_commencing = $start_date->modify("$day_offset days");
$week_commencing = $week_commencing->format('jS F Y');
}
Now I just need to use that to group the events but I'm not sure how to.
EDIT: I feel I'm getting closer to a solution but still need a little help. I now have the below in my controller, and it does print out 1 week commencing then all the events but when var_dump(ing) the $events->weeks_commencing there is only 1 date in the object, so I'm nearly there. Any pointers guys?:
foreach ($events as $event)
{
$start_date = DateTime::createFromFormat('Y-m-d', $event->start_date);
$week = $start_date->format('YW');
$monday = 1;
$day_offset = ($monday - $start_date->format('N'));
$week_commencing = $start_date->modify("$day_offset days");
if (!array_key_exists($week, $events))
{
$events->weeks_commencing = (object) array(
'week' => $week_commencing->format('jS F Y')
);
}
}
EDIT: OK I now have this in my controller. It's getting closer but not quite right yet.
foreach ($events as $event)
{
$start_date = DateTime::createFromFormat('Y-m-d', $event->start_date);
$week = $start_date->format('YW');
$monday = 1;
$day_offset = ($monday - $start_date->format('N'));
$week_commencing = $start_date->modify("$day_offset days");
if (array_key_exists($week, $events))
{
$events = (object) array(
'week' => $week_commencing->format('jS F Y'),
'events' => array()
);
}
$events->events[] = $event;
}

OK, so I've solved my issue now, with the following code:
public function index()
{
$events = Event::getEvents($perPage = 10);
$events_by_week = array();
foreach ($events as $event)
{
$start_date = DateTime::createFromFormat('Y-m-d', $event->start_date);
$week = $start_date->format('YW');
$monday = 1;
$day_offset = ($monday - $start_date->format('N'));
$week_commencing = $start_date->modify("$day_offset days");
if (!array_key_exists($week, $events_by_week))
{
$events_by_week[$week] = (object) array(
'week' => $week_commencing->format('jS F Y'),
'events' => array()
);
}
$events_by_week[$week]->events[] = $event;
}
$this->layout->content = View::make('events.index')->with(array('events_by_week' => $events_by_week, 'events' => $events));
}

Related

Symfony get className object from String class declaration

I have this code that returns column names of the className declared in the 2nd line :
public function listColumns(EntityManagerInterface $em ) {
$class = $em->getClassMetadata(Assure::class);
$fields = [];
if (!empty($class->discriminatorColumn)) {
$fields[] = $class->discriminatorColumn['name'];
}
$fields = array_merge($class->getColumnNames(), $fields);
foreach ($fields as $index => $field) {
if ($class->isInheritedField($field)) {
unset($fields[$index]);
}
}
foreach ($class->getAssociationMappings() as $name => $relation) {
if (!$class->isInheritedAssociation($name)){
foreach ($relation['joinColumns'] as $joinColumn) {
$fields[] = $joinColumn['name'];
}
}
}
return $fields;
}
I am trying to make this function parametrable so I can give it every time which table/className I am trying to get its columns
This is a possible solution to do what I want (extracting table column names ) differently :
public function listColumns2(EntityManagerInterface $em ) {
$conn = $this->getEntityManager()->getConnection();
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =
N'Assure' ";
$stmt = $conn->prepare($sql);
$stmt->execute();
return $stmt->fetchAllAssociative();
}

Hot to use variable in query in Drupal 8?

I have this code:
function my_module_test($key_make = '') {
$db = new mysqli('xxx', 'xxx', 'xxx', "xxx");
mysqli_set_charset($db, "UTF8");
if ($key_make) {
$sql_model = "SELECT * FROM `car_model` WHERE `id_car_make` = ('$key_make')";
$res_model = $db->query($sql_model) or die(mysqli_error($db));
while ($row = mysqli_fetch_object($res_model)) {
$Key_model = $row->id_car_model;
$Model_value = $row->name;
$dropdown_model[$Key_model] = $Model_value;
}
}
return $dropdown_model;
}
How can I pass the value of the variable $key_make in WHERE clausole ?
The query function takes a second parameter with an array of replacement values, so you would do it like this:
$sql_model = "SELECT * FROM {car_model} WHERE id_car_make = :make";
$res_model = $db->query($sql_model, [':make' => $key_make]);
Static queries are documented here
You could also use a dynamic query (documented here):
$query = $db->select('car_model', 'cm');
$query->fields('cm');
$query->condition('cm.id_car_make', $key_make);
$res_model = $query->execute();
But...
if your "car_model"s are custom entities (which they should be as you will get many benefits like views integration), you should probably use an entityQuery
First you need to use the Drupal Database API to connect to a database. So my final code is the following and it works.
function car2db_model_dropdown_options($key_make) {
$connection = Database::getConnection('default', 'migrate');
$dropdown_model = ['_none'=>'Select'];
$key_make = (int)$key_make;
$sql_model = "SELECT * FROM car_model WHERE id_car_make = :make";
$query = $connection->query($sql_model, [':make' => $key_make]);
$result = $query->fetchAll();
foreach ($result as $row) {
$Key_model = $row->id_car_model;
$Model_value = $row->name;
$dropdown_model[$Key_model] = $Model_value;
}
return $dropdown_model;
}

How to edit a list of object c# linq to xml

<Team Side="Home" TeamRef="ref123">
<Goal PlayerRef="p1111" Time="10" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p4444" Time="11" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="13" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="17" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
</Team>
public void GetScorer(string side, string OCompetition, string OSeason, string OGameId)
{
try
{
var xDoc = XDocument.Load(test);
var query = from q in xDoc.Descendants("Team")
where (string)q.Attribute("Side") == side
from d in q.Elements("Goal")
select new
{
TeamRef = q.Attribute("TeamRef").Value,
PlayerRef = d.Attribute("PlayerRef").Value,
Time = d.Attribute("Time").Value
};
var count = 0;
foreach (var qq in query)
{
if (side == "Home")
{
if (HomeSlateScorerList[count].PlayerRef != qq.PlayerRef)
{
HomeSlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OSeason, OCompetition, OGameId) });
}
else
{
HomeSlateScorerList[count].Time = HomeSlateScorerList[count].Time + "' ";
}
}
if (side == "Away")
{
AwaySlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OCompetition, OSeason, OGameId) });
}
count++;
}
}
catch (Exception)
{
// ignored
}
}
I would like to edit a player in a list of players
HomeSlateScorerList = new List<Scorer>();
AwaySlateScorerList = new List<Scorer>();
what I would like to achieve is for e.g. there are two players with the ref of "p7777" so in the list of object I would like to have one player with the playerref of "p7777" so if the player exist the format will be
playerref = "p7777"
Time = 13' 17'
or if one player its
Time = 13'
or if another goal is added to the xml its
Time = 13' 17' 25'
HomeSlateScorerList = HomeSlateScorerList
.GroupBy(s => s.PlayerRef)
.Select(g => new Scorer { PlayerRef = g.Key, Time = string.Join(", ", g.Select(v => v.Time)) })
.ToList();
Thanks to: #SergeyS SergeyS

how to add product to cart in opencart

Below is add to product code . But I am not getting where the values are storing . Kindly help to find out solution for this . I want to know logic behind this code
public function add($product_id, $qty = 1, $option = array(), $recurring_id = 0) {
$this->data = array();
$product['product_id'] = (int)$product_id;
if ($option) {
$product['option'] = $option;
}
if ($recurring_id) {
$product['recurring_id'] = (int)$recurring_id;
}
$key = base64_encode(serialize($product));
if ((int)$qty && ((int)$qty > 0)) {
if (!isset($this->session->data['cart'][$key])) {
$this->session->data['cart'][$key] = (int)$qty;
} else {
$this->session->data['cart'][$key] += (int)$qty;
}
}
}
The product details with options are stored in $key = base64_encode(serialize($product));. Where $this->session->data['cart'][$key] contains the number of quantity added by the customer.
For more details check the getProducts() function on the same page. Where you can find
foreach ($this->session->data['cart'] as $key => $quantity) {
....
$product = unserialize(base64_decode($key));
....
}

Zend Regex route reverse with paginator

I have following regex route, which allows me to use pagination - to parse URL and also build it:
; route "product-{brand}"
product.type = "Zend_Controller_Router_Route_Regex"
product.route = "product-([a-z\-]+)(?:/page/(\d+)/?)?"
product.defaults.module = "default"
product.defaults.controller = "products"
product.defaults.action = "product"
product.defaults.page = "1"
product.map.1 = "brand"
product.map.2 = "page"
product.reverse = "product-%s/page/%d"
Everything is working fine, however, I need to get the rid of default page. Currently we are migrating old web to the Zend and we need to preserve old links because of current google positions, etc.
With default "page", I'm getting always /page/1, without it Zend "cannot assemble" URL.
How to not display page 1 in URL ?
Finally, I've managed to achieve this, but only by rewriting Regex assemble method.
I'm simply overriding two methods.
Class extension:
class Utils_Router_Regex extends Zend_Controller_Router_Route_Regex
{
// instantiate
public static function getInstance(Zend_Config $config)
{
$defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
$map = ($config->map instanceof Zend_Config) ? $config->map->toArray() : array();
$reverse = (isset($config->reverse)) ? $config->reverse : null;
return new self($config->route, $defs, $map, $reverse);
}
// in this case, we are using $this->_reverse as array from config
public function assemble($data = array(), $reset = false, $encode = false, $partial = false)
{
//// EXTENSION PART !!!
if( !isset( $data[(string) $this->_reverse->pagemap]) ) { // if not set url helper
$reverse = $this->_reverse->base;
} else { // if set in url helper
$reverse = $this->_reverse->paginator;
}
/// end of extension part
if ($reverse === null) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('Cannot assemble. Reversed route is not specified.');
}
$defaultValuesMapped = $this->_getMappedValues($this->_defaults, true, false);
$matchedValuesMapped = $this->_getMappedValues($this->_values, true, false);
$dataValuesMapped = $this->_getMappedValues($data, true, false);
// handle resets, if so requested (By null value) to do so
if (($resetKeys = array_search(null, $dataValuesMapped, true)) !== false) {
foreach ((array) $resetKeys as $resetKey) {
if (isset($matchedValuesMapped[$resetKey])) {
unset($matchedValuesMapped[$resetKey]);
unset($dataValuesMapped[$resetKey]);
}
}
}
// merge all the data together, first defaults, then values matched, then supplied
$mergedData = $defaultValuesMapped;
$mergedData = $this->_arrayMergeNumericKeys($mergedData, $matchedValuesMapped);
$mergedData = $this->_arrayMergeNumericKeys($mergedData, $dataValuesMapped);
if ($encode) {
foreach ($mergedData as $key => &$value) {
$value = urlencode($value);
}
}
ksort($mergedData);
$return = #vsprintf($reverse, $mergedData);
if ($return === false) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('Cannot assemble. Too few arguments?');
}
return $return;
}
}
Then you can define which sprintf string to use:
hodinky.type = "Utils_Router_Regex"
hodinky.route = "hodinky-([a-z\-]+)(?:/page/(\d+)/?)?"
hodinky.defaults.module = "default"
hodinky.defaults.controller = "products"
hodinky.defaults.action = "hodinky"
hodinky.map.1 = "znacka"
hodinky.map.2 = "page"
hodinky.reverse.paginator = "hodinky-%s/page/%d" ; assebmly with paginator
hodinky.reverse.base = "hodinky-%s/" ; assebmly without paginator
hodinky.reverse.pagemap = "page" ; "page" map key
If you have better solution, please let me know.