Access a single element of the array within twig - mysql

I'm using symfony2 and twig in my view. I'm sending an array to the view which has been created using from a mysql query, not using the symfony entity framework:
$claims_summary_table = $statement->fetchAll();
I can dump this in the view...
{{ dump(claims_summary_table) }}
array:1 [▼
0 => array:11 [▼
"claim_status" => "Open"
"claim_id" => "101"
"claim_reference" => "BALLINGM"
"loss_date_from" => "2015-06-02"
"loss_catastrophe_name" => "Fire"
"loss_value" => "2000.00"
"total_payments" => "300.00"
"total_reserve" => "2000.00"
"claim_file_closed" => null
"last_seen_date" => "2016-04-20 11:20:25"
"last_seen_by" => "2"
]
]
but I just want to access one element, I just want to access "Open".
I have tried {{ claims_summary_table.claim_status }}
The only way I can access the single element is if I use a { for.....}.
How can I just get one element?

If you need to access the first element of the sub-array you can use the following.
{{ claims_summary_table[0][0]. claim_status }}
and
{{ claims_summary_table[0][0]. claim_id }}
Otherwise you need to iterate and looking for the record with the claim_stauts open

You can access the values by array key, in your case:
{{ claims_summary_table[0]. claim_status }}

Related

Pass Data Directly to yii2-tree-manager

I have a tree node in my form. I am using kartik-v's Tree Manager.
This is my view code:
echo TreeViewInput::widget([
'query' => Tree::find()->addOrderBy('root, lft'),
'headingOptions' => ['label' => 'Set Permission'],
'name' => 'name',
'value' => '1,2,3',
'asDropdown' => false,
'multiple' => true,
'fontAwesome' => true,
'rootOptions' => [
'label' => '<i class="fa fa-tree"></i>',
'class' => 'text-success'
]);
But, in this I have to follow the same table structure as mentioned in the widget. I have some extra fields and more permissions. So it is a bit complicated to use the same structure.
Is it possible to pass the value in an array directly to this widget? If possible let me know the array format.
Now I am stuck with this tree node implementation.
You can do this by doing some tricks, or by using another way:
1) you can add a condition to your query like this:
Tree::find()->andWhere(['not in','id',[2,3,4]])->addOrderBy('root, lft'),
by this solution you can ignore unwanted rows like you send data direct in array...
2) you can use another solution by using js lib/plugin direct like jsTree, in this case you can create and pass custom array direct...look at this example: jsTree Example

How to work with JSON coming from api-platform

I've installed the api-platform demo on a server and I did a client app (working with Symfony 3.3) and I want to display the response in a classic view (Twig).
Everything's working fine : I can request and retrieve the response.
But here's where i'm stuck : when I dump the response in my view I got this
{"#context":"\/contexts\/Book","#id":"\/books","#type":"hydra:Collection","hydra:member":[{"#id":"\/books\/1","#type":"Book","id":1,"isbn":"9783161484100","title":"1st Book","description":"This is my first book synopsis","author":"Hemingroad","publicationDate":"2018-02-16T14:15:58+00:00","reviews":[]}],"hydra:totalItems":1}
Here's my controller's method :
//...
use GuzzleHttp\Client;
public function newAction(Request $request)
{
//initialize client API
$client = new Client([
'base_uri' => 'http://my.apidomain.com/',
'timeout' => 2.0,
]);
//request to API
$dataBooks = $client->request('GET', 'books', ['auth' => ['login', 'p#$$w0rd']]);
$listBooks = $dataBooks->getBody()->getContents();
return $this->render('book/new.html.twig', array(
'listBooks' => $listBooks
));
}
I've also tried to json_decode and using JMSSerializer on $listBooks.
I got a beautiful object but I still cant access the JSON attribute's like ISBN, title by doing something like
{% for book in listBooks %}
{{ dump(book.title) }}
<!-- .... -->
{% endfor %}
Here's what I got when I json_decode $listBooks :
{{ dump(listBooks) }}
I got an error when I try to access every field like this
{{ dump(listBooks.#id) }}
{{ dump(listBooks['hydra:member']) }}
....
Am I missing something ?
Thanks
$dataBooks->getBody()->getContents(); returns a string, as described in Guzzle's documentation, so you need to use json_decode.
$listBooks = json_decode($listBooks); returns an object. In Twig you can use the dot notation to access methods and properties of an object, e.g. {{ listBooks.myProp }}. But because hydra:member includes a special character (:), you need to use Twig's attribute function, as described in Twig's documentation:
{{ attribute(listBooks, 'hydra:member') }}
Another approach is to do $listBooks = json_decode($listBooks, true); so that you get an associative array instead of an object. Then you can use the bracket notation in Twig:
{{ listBooks['hydra:member'] }}
I would prefer this second approach, because in my opinion {{ listBooks['hydra:member'] }} is much clearer and cleaner than {{ attribute(listBooks, 'hydra:member') }}.

Yii2: Kartik Select2: Initial Value from Model Attribute

I have a Model who has a column (attribute) that stored a comma separated value of IDs.
For Example,
Movie has a column "Genre" that includes more than one genre, e.g.: 40,20,1,3
How can I use Select2 widget to show these values separated when 'multiple' => true
And how can I save them back into comma-separated value as a string. I want a solution that will allow for quick flexibility. I know you can implode and explode the string but seems too much.
Any help appreciated
If I remember correctly pass the default option as part of the $options configuration for the widget:
echo $form->field($model, 'model_attribute_name')->widget(Select2::className(), [
'data' => $data
'options' => [
'class' => 'form-control',
'placeholder' => 'Choose Option...',
'selected' => 40
],
'pluginOptions' => [
'allowClear' => true,
],
])->label('Select2 Form Field');
This is from memory for grain fo salt here. The documentation at http://demos.krajee.com/widget-details/select2 is not very specific about how to do this.
I don't believe you can do that. Select2 sends the data in post as an array, so you would still need to use implode before saving. What i would do instead is in your model class:
class MyModel extends \yii\db\ActiveRecord {
$public myArrayAttribute;
...
public function beforeSave($insert) {
if (parent::beforeSave($insert)) {
$this->myAttribute = implode(',', $this->myArrayAttribute);
return true;
}
return false;
}
public function afterFind() {
parent::afterFind();
$this->myArrayAttribute = explode(',', $this->myAttribute);
}
}
This way myArrayAttribute will hold the values from the comma separated field as an array. Of course you will need to add validation rules for it and use it instead of your other attribute in create and update forms.
if you're displaying a form with already populated fields, maybe you want to update an already existing object, and you want to display the already saved value for the Select2 field, use 'data' => [ 1 => 'Some value' ], where 1 is the value, associated to the value displayed in the form. You can retrieve stuff to put in data from DB beforehand.
Source: https://github.com/kartik-v/yii2-widget-select2/issues/37

Pass dynamic params in the ajax call of yii2-grid EditableColum widget

the \kartik\grid\EditableColumn widget has a parameter called ajaxSettings where you may override the parameters passed with the ajax request to the server. What i want to do is to dynamically pass the selected rows ids together with the value coming from the popover to the server. I manage to do that passing static parameter coming from a php array in compile time like so
Editable::widget(['name' => 'publishDate', 'ajaxSettings' => ['ids' => [1,2,3]]])
but It seems that i cannot use a jquery selector there to grab the ids of the selected columns like so
Editable::widget([
'name' => 'publishDate',
'ajaxSettings' => [
'ids' => '$("#books-grid").yiiGridView("getSelectedRows")'
]
])
Maybe you want to try creating a variable outside the Editable::widget([ like this:
var arrayIds = $("#books-grid").yiiGridView("getSelectedRows");
And then assign it to the widget:
Editable::widget([
'name' => 'publishDate',
'ajaxSettings' => [
'ids' => arrayIds
]
])
Hope this helps,
Leo.

Yii2 render database content

There is a textarea where user can edit some templates and can use variables like:
{{model.user.name}}
Application need to replace this variables with data and display HTML output.
We can write a small function that will replace variables from template with data but we need to use a template engine like Twig or Smarty.
https://github.com/yiisoft/yii2-twig
https://github.com/yiisoft/yii2-smarty
Now we can use ViewRenderer from Smarty or Twig.
$render = new ViewRenderer();
$content = $render->render($this->view,'template.twig',[
'model' => $model,
]);
But I see this error:
Unable to find template "template.twig" (looked into: .).
How can I use Smarty or Twig to render a template with the content from database in Yii2 ?
I found Mustache ( https://github.com/bobthecow/mustache.php ) and I'm using like this:
$m = new \Mustache_Engine();
echo $m->render("Hello {{model.client.firma}}",['model' => $model]);
You don't create a renderer manually, you configure your application components, like this:
[
'components' => [
'view' => [
'class' => 'yii\web\View',
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'cachePath' => '#runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
],
'globals' => ['html' => '\yii\helpers\Html'],
'uses' => ['yii\bootstrap'],
],
// ...
],
],
],
]
You are telling Yii that there is a renderer to handle templates with the .twig extension.
Then, all you need to do is add the .twigextension when calling render in your controller actions:
public function actionIndex()
{
return $this->render('index.twig');
Then put your twig templates in the view folders where the views normally go.
Read the documentation for the twig extension: Twig Extension for Yii 2
If you want to only use twig templates, you can avoid specifying the extension (.twig) if you set the default extension:
'components' => [
'view' => [
'defaultExtension' => 'twig',
You should create a twig component which will wrap around Twig_Environment. You can add yii\twig\Extension extension if you need. Then you should use it like this:
$renderedTemplate = Yii::$app->twig->render($template, $context);
If you really need to render a template from a string variable you may implement your own Twig_LoaderInterface. There is a Twig_Loader_String, but it's deprecated and you should not use it.