Where to define static array related to an entity in symfony2 ? - arrays

I have an array contains static data related to an entity Product:
public static $category = array(
1 => 'animal.png',
2 => 'blague.png',
3 => 'devinette.png',
4 => 'enfant.png',
5 => 'h-f.png',
6 => 'nationalite.png',
7 => 'politique.png',
8 => 'sport.png',
9 => 'name',
10 => 'travail.png',
11 => 'vulgaire.png',
12 => 'autre.png',
);
Where i should declare the array ?
And how i can accede to data from the Twig view ?
Thanks

I don't know if that's the best way but I used something similar to your code:
class Product
{
protected static $category = array(
1 => 'animal.png',
2 => 'blague.png',
3 => 'devinette.png',
// ...
)
);
}
Then you can add some functions in this class in order to get data from the array
public function getCategoryImageFromIndex($a)
{
return self::$category[$a];
}
// if you have a getter getCategory() which returns the category of the Product
public function getCategoryImage()
{
return self::$category[$this->getCategory()];
}
Then you can call these functions from Twig:
{{ product.categoryImageFromIndex(1) }}
will display:
animal.png
And
{{ product.categoryImage }}
will display the corresponding image from the category.

I've always used a Twig extension function to access the static array.
For example, in my Order entity, I have something like this:
class Order
{
const ORDER_STATUS_PENDING = 0;
const ORDER_STATUS_AWAITING_PAYMENT = 1;
const ORDER_STATUS_COMPLETE = 2;
public static $ORDER_STATUS_DISPLAY = [
self::ORDER_STATUS_PENDING => 'Pending',
self::ORDER_STATUS_AWAITING_PAYMENT => 'Order placed',
self::ORDER_STATUS_COMPLETE => 'Order completed',
];
then assuming you already have a registered Twig_Extension class, create a new filter function:
public function displayOrderStatus($orderStatus)
{
return Order::$ORDER_STATUS_DISPLAY[$orderStatus];
}
Finally, use the filter in your Twig template:
{{ order.orderStatus|displayOrderStatus }}

Related

Using Carbon in React/Laravel project for localisation (Changing language of dates)

Trying to use Carbon for localisation on my project. Carbon works fine, I have tested it. I have tried to add the code block below to my Model file :
use DateTimeInterface;
protected function serializeDate(DateTimeInterface $date)
{
return $date->translatedFormat('A B M');
}
So my Model file looks like this (the file -> home/username/public_html/app/Models/TransferRecords.php :
<?php
namespace App\Models;
use App\Events\TransferRecordSaved;
use App\Helpers\CoinFormatter;
use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;
class TransferRecord extends Model
{
/**
* The attributes that aren't mass assignable.
*
* #var array
*/
protected $guarded = [];
/**
* The event map for the model.
*
* #var array
*/
protected $dispatchesEvents = [
'saved' => TransferRecordSaved::class,
];
protected $appends = [
'value_price',
'hash',
'formatted_value_price',
'coin',
'confirmed',
];
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = [
'walletAccount',
];
/**
* #return bool
*/
public function getConfirmedAttribute()
{
return $this->confirmations >= $this->required_confirmations;
}
/**
* #return mixed|string
*/
public function getCoinAttribute()
{
return $this->walletAccount->wallet->coin->name;
}
/**
* #param $value
*/
public function setValueAttribute($value)
{
if ($value instanceof CoinFormatter) {
$this->attributes['value'] = $value->getAmount();
} else {
$this->attributes['value'] = (float) $value;
}
}
/**
* #return CoinFormatter|mixed
*/
public function getValueObject()
{
return coin($this->getOriginal('value'), $this->walletAccount->wallet->coin);
}
/**
* Get value converted from base unit
*
* #param $value
* #return float
*/
public function getValueAttribute()
{
return $this->getValueObject()->getValue();
}
/**
* Get the price of the value
*
* #return \HolluwaTosin360\Currency\Currency|string
*/
public function getValuePriceAttribute()
{
return $this->getValueObject()
->getPrice($this->walletAccount->user->currency, $this->dollar_price);
}
/**
* Get formatted price of the value
*
* #return \HolluwaTosin360\Currency\Currency|string
*/
public function getFormattedValuePriceAttribute()
{
return $this->getValueObject()
->getFormattedPrice($this->walletAccount->user->currency, $this->dollar_price);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo|WalletAddress
*/
public function receiverWalletAddress()
{
return $this->belongsTo('App\Models\WalletAddress', 'receiver_wallet_address_id', 'id');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo|WalletTransaction
*/
public function walletTransaction()
{
return $this->belongsTo('App\Models\WalletTransaction', 'wallet_transaction_id', 'id');
}
/**
* Get transaction hash
*
* #return mixed
*/
public function getHashAttribute()
{
return $this->walletTransaction()->value('hash');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo|WalletAccount
*/
public function walletAccount()
{
return $this->belongsTo('App\Models\WalletAccount', 'wallet_account_id', 'id');
}
protected function serializeDate(DateTimeInterface $date)
{
return $date->translatedFormat('A B M');
}
}
Then in resources/routes/wallets/components/RecorsTable/index.js file I am trying to use translatedFormat() function in order to get the date in translated format. The required value is {formatUTC(text)} :
dataIndex : 'created_at',
sorter : (a, b) => sortDate(a.created_at, b.created_at),
render : text => (
<div style={{whiteSpace : 'nowrap'}}>
{formatUTC(text)}
</div>
The full version of resources/routes/wallets/components/RecorsTable/index.js file :
import React, {Component} from 'react';
import {Tag} from "antd";
import Widget from "components/Widget";
import {FormattedMessage, injectIntl} from "react-intl";
import AsyncTable from "components/AsyncTable";
import {route} from "support/Services/Api";
import Auth from "support/Auth";
import {formatUTCDate, pipe, sortDate} from "support/utils/common";
import {connect} from "react-redux";
import {mapValues, values} from "lodash";
class RecordsTable extends Component {
columns = () => {
const {accounts} = this.props;
return [
{
title : (
<FormattedMessage
defaultMessage="Amount"
id="common.amount"/>
),
dataIndex : 'formatted_value_price',
render : (text, record) => (
<span>
{record.type === 'receive' ?
<span className="cp-text-success">
{text}
</span> :
<span className="cp-text-danger">
{text}
</span>
}
</span>
)
},
{
title : (
<FormattedMessage
defaultMessage="Date"
id="widget.marketplace_earnings_chart.date"/>
),
dataIndex : 'created_at',
sorter : (a, b) => sortDate(a.created_at, b.created_at),
render : text => (
<div style={{whiteSpace : 'nowrap'}}>
{translatedFormat(text)}
</div>
),
},
{
title : 'Status',
dataIndex : 'confirmed',
render : (text) => {
const isConfirmed = text === "true" ||
(typeof text === "boolean" && text);
return (
<span>
{isConfirmed ?
<Tag color="green">
<FormattedMessage
defaultMessage="confirmed"
id="wallet.transaction_confirmed"/>
</Tag> :
<Tag color="red">
<FormattedMessage
defaultMessage="unconfirmed"
id="wallet.transaction_unconfirmed"/>
</Tag>
}
</span>
)
},
},
{
title : (
<FormattedMessage
defaultMessage="Amount"
id="common.amount"/>
),
dataIndex : 'value',
},
{
title : 'Hash',
dataIndex : 'hash',
},
{
title : 'Coin',
dataIndex : 'coin',
fixed : 'right',
onFilter : (value, record) => {
return record.coin.includes(value)
},
filters : values(mapValues(accounts, (o) => {
return {
text : o.wallet.coin.name,
value : o.wallet.coin.name
}
})),
},
];
};
render() {
const endpoint = route("user.transfer-records-table");
return (
<Widget styleName="cp-card-table"
title={
<FormattedMessage
defaultMessage="Transfer Records"
id="wallet.transfer_records"/>
}>
<AsyncTable
route={endpoint.url()}
columns={this.columns()}
className="mt-1"
scroll={{x : true, y : false}}
size="middle"/>
</Widget>
);
}
}
const mapStateToProps = ({
wallet : {accounts},
auth
}) => ({
accounts,
auth : new Auth(auth)
});
export default pipe(
injectIntl,
connect(
mapStateToProps
)
)(RecordsTable);
{translatedFormat(text)} - this was formatUtc(text) before and works fine.
Getting an error when I open the webpage after succesfull compilation. It's been 1 week I am trying to figure this out but no success so far. Any help would be highly appreciated.
Anyone who has the project with reactjs/laravel can fix the issue with the localisation by changing the method with utcDateCalendarTime() . So, if i change the code block like below it worked like charm :
dataIndex : 'created_at',
sorter : (a, b) => sortDate(a.created_at, b.created_at),
render : text => (
<div style={{whiteSpace : 'nowrap'}}>
{utcDateCalendarTime(text)}
</div>
),
And need to make sure that you are calling the method at the top of the file : import {formatUTCDate, pipe, sortDate,utcDateCalendarTime} from "support/utils/common";

How to get checkbox checked from database array using Laravel and Ajax

I'm trying to get data from database to checkboxes as checked. The checkbox data in database are as array that have been inserted with json and they are dynamic data based on insert function.
My tasks table:
id |employee_id | startDate | endDate | ...
---|------------|------------|-----------|--------
1 |["1","2"] | .......... | ..........| ....
My TasksController.php
function fetchdata(Request $request)
{
$id = $request->input('id');
$task = Task::find($id);
$output = array(
'employee_id' => $task->employee_id,
'name' => $task->name,
'description' => $task->description,
'startDate' => $task->startDate,
'endDate' => $task->endDate,
'percentage' => $task->percentage
);
echo json_encode($output);
}
public function getEmployeesList()
{
$employeesList = Employee::all();
return view('adminlte::tasks', ['employeesList' => $employeesList]);
}
My tasks.blade.php
#foreach($employeesList as $emplist)
<label class="checkbox-inline">
<input type="checkbox" id="employee_id" name="employee_id[]" class="chck" value="{{$emplist->id}}" >{{ $emplist->name }}</label>
#endforeach
My Ajax function inside blade:
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
$('#form_output').html('');
$.ajax({
url: "{{route('tasks.fetchdata')}}",
method: 'get',
data: {id:id},
dataType: 'json',
success:function(data)
{
$('#id').val(data.id);
$('#employee_id').val(data.employee_id);
$('#name').val(data.name);
.......................
..................
}
})
});
So, how can I retrieve data from database to checkboxes as checked, because for now I'm getting null "employee_id" value when I try to update a record.
Thank you in advance
Since you're encoding the data on the server side, you must decode it in the client side like :
...
success:function(data)
{
console.log( data );
data = JSON.parse(data);
$('#id').val(data.id);
$('#employee_id').val(data.employee_id);
$('#name').val(data.name);
...
}

Listing items from an array via Angular

I just can't work out how to list/loop through items from an array into my component. All the online tutorials and SO answers make sense, but my code won't respond in a like fashion.
My scenario is this: A user selects an option from a menu and...
switch(which){
:
case 'who': {
this.getStaffList('stafflist');
break;
}
:
the database is called and returns an array...
getStaffList(value:string){
this.targetID = value;
this.service.getStuff(this.targetID).subscribe(
items => {
console.log(items[0].fname); <---this yields 'Sue'
this.title = "Your staff list";
}, error => {
}, () => {
}
);
}
The PHP view of the array (before JSON.encode) is:
Array
(
[0] => Array
(
[userID] => 6551
[certID] => SB287
[fname] => Sue
[lname] => Bennett
)
[1] => Array
(
[userID] => 6568
[certID] => MF6568
[fname] => Marion
[lname] => Ferguson
)
:
Back in Angular, the very simple template is:
<div id="stafflist" class="mainbox" *ngIf="bListStaff">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">{{title}}</div>
</div>
<div style="padding-top:25px" class="panel-body">
{{items[0].fname}} <!--This generates a '..._co.items is undefined' error
<ul>
<li *ngFor="let item of items; let i = index">{{i}} {{item}}</li> <--- this yields nothing/zilch
</ul>
</div>
</div>
</div>
The '..._co.items is undefined' error that I'm receiving suggests that the items array isn't known outside of getStaffList, but I don't understand why that is (if it is) and don't understand what's missing in my approach.
You are not assigning items inside the subscribe, create a variable named items of type any and assign the value inside the subscription,
getStaffList(value:string){
this.targetID = value;
this.service.getStuff(this.targetID).subscribe(
items => {
this.items = items;
this.title = "Your staff list";
}, error => {
}, () => {
}
);
}
also since the request is asynchronous use safe navigation operator to check if the value is present before the values are being assigned,
<div style="padding-top:25px" class="panel-body">
{{items[0]?.fname}} <!--This generates a '..._co.items is undefined' error
<ul>
<li *ngFor="let item of items; let i = index">{{i}} {{item}}</li> <--- this yields nothing/zilch
</ul>
</div>
Just define a property items in your component class and set it like this:
getStaffList(value:string){
this.targetID = value;
this.service.getStuff(this.targetID).subscribe(
items => {
console.log(items[0].fname); <---this yields 'Sue'
this.title = "Your staff list";
this.items = items;
}, error => {
}, () => {
}
);
}
The scope of the items in your subscribe is only inside that function so it's not accessible from the outside.

twig array of objects

I'm working on a symfony2 project.
I send from my controller to twig, an array of arrays of objects.
My array is nicely set, and got the values I want.
But when I try to access to these datas on twig, I can't...
My twig looks like {{ myarray.1.0.getFichier() }}
But, twig didn't call getFichier method of myarray.1.0.
Here is what twig responses to me : Item "getFichier" for "Array" does not exist in CDUserBundle:Prof:edit_session.html.twig at line 74
Edit :
dump(myarray.1.0) shows nothing, dump(myarray) shows nothing.
But dump() show a blank page...
Edit² :
Here is my controller
return $this->render('CDUserBundle:Prof:edit_session.html.twig', array(
'erreur' => $erreur,'message' => $message,
'title' => 'C# | Editer session',
'description' => 'keywords description',
'sessionInfo' => $sessionInfo,
'sessionFull' => $sessionFull,
'documents' => $documents,
'videos' => $videos,
'a' => 'showForm',
'vidName' => $videos[0]->getName(),
'vidDMCId'=>$videos[0]->getDMCId(),
'session' => $form->createView(),
'partPath' => $documents[0]->getFichier()
));
My Array is either $documents either $videos
Here is when I create arrays
$videos=array();
if($sessionFull[0]['sess_vid_id']!=NULL) {
if($em->getRepository('CD\ConfigBundle\Entity\Video')->findOneById($sessionFull[0]['sess_vid_id']))
array_push($videos,$em->getRepository('CD\ConfigBundle\Entity\Video')->findOneById($sessionFull[0]['sess_vid_id']));
else
array_push($videos,new Video());
}
else
array_push($videos,new Video());
for($i=0;$i<4;$i++) {
if($sessionFull[$i]['coursVidId']!=NULL) {
$vids=array();
$vidsId=explode(',',$sessionFull[$i]['coursVidId']);
foreach($vidsId as $vidId) {
if($em->getRepository('CD\ConfigBundle\Entity\Video')->findOneById($vidId))
array_push($vids,$em->getRepository('CD\ConfigBundle\Entity\Video')->findOneById($vidId));
else
array_push($vids,new Video());
}
array_push($videos,$vids);
}
else
array_push($videos,array(new Video()));
}
$documents=array();
if($sessionFull[0]['sess_doc_id']!=NULL) {
if($em->getRepository('CD\ConfigBundle\Entity\Document')->findOneById($sessionFull[0]['sess_doc_id']))
array_push($documents,$em->getRepository('CD\ConfigBundle\Entity\Document')->findOneById($sessionFull[0]['sess_doc_id']));
else
array_push(new Document());
}
else
array_push($documents,new Document());
for($i=0;$i<4;$i++) {
if($sessionFull[$i]['coursDocId']!=NULL) {
$docs=array();
$docsId=explode(',',$sessionFull[$i]['coursDocId']);
foreach($docsId as $docId) {
if($em->getRepository('CD\ConfigBundle\Entity\Document')->findOneById($docId))
array_push($docs,$em->getRepository('CD\ConfigBundle\Entity\Document')->findOneById($docId));
else
array_push($docs,new Document());
}
array_push($documents,$docs);
}
else
array_push($documents,array(new Document()));
}
Use {{ myarray.1.0.Fichier }} directly

telerik-mvc grid - how to format footer template?

This is my code in the controller:
[GridAction]
public ActionResult _Select()
{
// Creating dummy data to bind the grid
var data = Enumerable.Range(1, 100)
.Select(index => new Customer
{
ID = index,
Name = "Customer #" + index,
Tax = 1 + index,
Amount = 500 + index
});
return View(new GridModel(data));
}
This is what I have in my view:
<%: Html.Telerik().Grid<GridLoadedWithAjaxInTabStrip.Models.Customer>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.ID).Width(200);
columns.Bound(c => c.Name);
columns.Bound(c => c.Tax);
columns.Bound(p => p.Amount);
})
.DataBinding(dataBinding => dataBinding.Ajax().Select("_Select", "Home"))
.Sortable()
.Pageable()
.Groupable()
.Filterable()
%>
I would like to know how I can put a custom footer template in this format:
Total Tax: XXXXX
Total Amount: XXXXX
Grand Total: XXXXXXX
Please assist me how I can do this. Thanks!
You need to check this demo
http://demos.telerik.com/aspnet-mvc/grid/aggregatesajax

Resources