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
Related
I have this data structure:
const data = [
{
title: 'title',
description: 'description'
images: [
{ mainImg: 'url' },
{ img1: 'url' },
{ img2: 'url' },
{ img3: 'url' },
],
},
...
]
My question is, how can I render only the mainImg separated from the others? And how can I render the other images without the mainImg.
What I've tied so far is to map through the images like this: (I did mapped through data before)
{data.images.map((img, index) => (
<img
key={`image${index}`}
src={img.mainImg}
className={styles.mainImg}
/>
))
}
This worked, but the issue is that I map through all the images and when I open the consoles, all the images are rendered but they are not visible because they don't have the src tag. (I think).
Simply trying to use data.images.mainImg as the src value doesn't render anything, and also does not throw any errors.
Also, I have an issue trying to render all the other images except the mainImg. This is what I've tried but I get lost and I don't know what the src value should be.
{data.images
.filter((img) => img.mainImg != project.images.mainImg)
.map((img, index) => (
<img src={img} />
))
}
You could use hasOwnProperty : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
data.images.map((e, i) => {
if (e.hasOwnProperty('mainImg')) {
// Do something with mainImg
}
//Do something with the others
})
A JSfiddle with example : https://jsfiddle.net/RyanZee/hu189jxd/12/
Do you always have a mainImg at index 0? If so you can use
const [firstImg, ...imgs] = data.images;
return (
<>
<img src={firstImg.mainImg} ... />
{ imgs.map((img, index) => <img src={img[`img${index + 1}`]} /> }
</>
)
In Yii2 I have ActiveForm with checkbox field. In mysql database it is tinyint(1) column that can be NULL.
I need unchecked checkbox (false value) to be saved as NULL in database. Currently when checkbox is unchecked, it is saved as (int) 0.
What is the proper way to save false value as NULL?
Here is the model:
class ProductToProductCategory extends ActiveRecord {
public function rules()
{
return [
['product_category_id', 'required'],
['product_category_id', 'integer'],
['is_main', 'boolean'],
];
}
}
Here is the view:
<?= $form->field($model, "is_main")->checkbox() ?>
public function rules()
{
return [
['product_category_id', 'required'],
['product_category_id', 'integer'],
['is_main', 'boolean'],
['is_main', 'filter', function ($value) {
// return value you need
return $value ?: null;
}, 'skipOnError' => true],
];
}
Never tried it but you should be able to do it implementing the beforeSave method of the saved model.
public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
return false;
}
if( $this->scenario == "strangeNullScenario" ) {
if( empty( $this->FIELD ) ) {
$this->FIELD = null;
}
}
return true;
}
Just pass uncheck option
<?= $form->field($model, "is_main")->checkbox(['uncheck' => null]) ?>
I have a checkbox in a gridview Yii2 like this,
[
'class' => 'kartik\grid\CheckboxColumn',
'width' => '20px',
'checkboxOptions' => function ($model, $key, $index, $column) {
return [
'value' => trim($model->vessel),
];
}
],
Then to get all the value checkbox in yii2, I use this button
Html::a('<i class="glyphicon glyphicon-print"></i> Print All',
["print-all-based-date"],
[
"class" => "btn btn-success",
'role' => 'modal-remote-bulk',
])
But when in my controller that handle the the action,
public function actionPrintAllBasedTanggal()
{
$request = Yii::$app->request;
$get = $request->get();
print_r($get);
die();
I get :
Array
(
[r] => iwwi/incoming/print-all-based-tanggal
[KMTC_HOCHIMINH,OOCL_NAGOYA] =>
[_] => 1495123320863
)
What it means [KMTC_HOCHIMINH,OOCL_NAGOYA] =>,
I check in html, the checkbox is named selection[] ?
I need this : KMTC_HOCHIMINH,OOCL_NAGOYA
to get continue my app.
Please advise.
Thanks
may be you can use jquery for the solution.
example :
$(document).on('click','#ceklist_all',function(){
if ($(this).is(':checked')) {
$('.ceklist_child').attr('checked',true);
your_variable = [];
$('.ceklist_child:checked').map(function(key,val) {
if(this.checked) {
your_variable[key] = this.value;
}
}).get();
}
});
so,. you can use the your_variable and use the ajax for submit..
$.ajax({
type: 'get',
url: your_url,
data: {
'your_variabel_to_post' : your_variable
},
success: function(data){
// success function
},
error: function(data){
if(data.responseText)
alert(data.responseText);
},
});
CMIIW,.
just the optional solution. heheh
I am trying to group by Year in cakephp3. I am able to get data using
following way, but it's not still grouped by year(The way I want.)
$query = $this->Alerts->query();
$year = $query->func()->year([
'added_on' => 'literal'
]);
$month = $query->func()->monthname(['added_on' => 'literal']);
$monthAlertsCount = $query->func()->count($month);
$data = $query
->select([
'year' => $year,
'month' => $month,
'count' => $monthAlertsCount
])
->group($year)
->group($month);
$status = "success";
$this->set('response', $status);
$this->set('year', $data);
$this->set('_serialize', ['response','year']);
Current output is as follows:
{
"response":"success",
"year":[
{
"year":"2013",
"month":"November",
"count":"1"
},
{
"year":"2014",
"month":"February",
"count":"2"
},
{
"year":"2014",
"month":"January",
"count":"3"
},
{
"year":"2015",
"month":"December",
"count":"6"
},
{
"year":"2015",
"month":"February",
"count":"3"
},
{
"year":"2015",
"month":"January",
"count":"4"
},
{
"year":"2016",
"month":"January",
"count":"83"
}
]
}
Expected Output:
{
"response":"success",
"year":[
{
"2013":[
{
"month":"November",
"count":"1"
}
],
"2014":[
{
"month":"February",
"count":"2"
},
{
"month":"January",
"count":"3"
}
],
"2015":[
{
"month":"December",
"count":"6"
},
{
"month":"February",
"count":"3"
},
{
"month":"January",
"count":"4"
}
],
"2016":[
{
"month":"January",
"count":"83"
}
]
}
]
}
Can anybody help me get the expected output in cakephp3?
Use the collection method groupBy() - remember, queries are collection objects (kind of)!
$data = $query
->select([
'year' => $year,
'month' => $month,
'count' => $monthAlertsCount
])
->group($year)
->group($month)
->groupBy('year');
That will create the desired grouped structure, however it won't remove the year field from the individual rows, if you want them removed, use a mapper, like
// ...
->groupBy('year')
->map(function ($rows) {
foreach ($rows as &$row) {
unset($row['year']);
}
return $rows;
});
See also
Cookbook > Collections > Collection::groupBy()
Cookbook > Collections > Collection::map()
Cookbook > Database Access & ORM > Query Builder > Queries Are Collection Objects
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 }}