Magento 2 - Multiline content for static block installer - magento

What is best practice on Magento 2 for having multiline html in content?
On Magento 1 if I remember right you would use some thing <<<'EOT'
$cmsBlockData = [
'title' => "About Us",
'identifier' => "aboutus",
'content' => "
<div class="intro-block" style="background-image: url({{view url='images/content/about-us-img1.jpg'}})">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit.</p>
</div>
",
]

actually there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD') and heredoc(<<<EOD) strings. reference
You can use here document operator (<<<) then use a word like HTML, EOD, EOT or any string you want!
Some handy notes when you wanna use heredoc : here
Sample :
$html = <<<HTML
<div class="intro-block" style="background-image: url({{view url='images/content/about-us-img1.jpg'}})">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit.</p>
</div>
HTML;
$cmsBlockData = [
'title' => "About Us",
'identifier' => "aboutus",
'content' => $html
",
]

Related

Trying to get property 'id' of non-object in laravel session foreach

Im practicing laravel and right now Im in the session topic
this is my controller
public function set(Request $request){
$product = Product::findOrFail($request->input('id'));
session()->put('product', $product);
return redirect()->route('cart');
}
when i tried to echo the{{session()->get('product')}} on my blade it produce an output of
{
"id":9,
"name":"Lorem ipsum dolor sit amet",
"description":"Proin pretium, mauris id convallis tempus, lorem enim tincidunt nulla, vel pharetra sapien odio eget ligula. Sed maximus, massa sit amet condimentum bibendum, nisi ante vestibulum ipsum, ut ornare justo lorem mollis justo.",
"price":"22.21",
"cover_image":"JRwg9TSKTvUTvuij.jpg",
"created_at":"2018-07-20 03:47:57",
"updated_at":"2018-07-20 03:47:57"
}
but when i tried to use foreach on it by using
#foreach(session()->get('product') as $key)
{{$key->id}}
#endforeach
it shows an error of Trying to get property 'id' of non-object
can someone guide me why I'm I getting this error thanks.
You are iterating through your single object but what you seem to need to do is:
{{ session()->get('product')->id }}
If you want to loop then you can do:
#foreach (session()->get('product')->toArray() as $key => $value)
{{ $key }}: {{ $value }}
#endforeach
This will result in:
id: 9
name: Lorem ipsum dolor sit amet
description: Proin pretium, mauris id convallis tempus, lorem enim tincidunt nulla, vel pharetra sapien odio eget ligula. Sed maximus, massa sit amet condimentum bibendum, nisi ante vestibulum ipsum, ut ornare justo lorem mollis justo.
price: 22.21
cover_image: JRwg9TSKTvUTvuij.jpg
created_at: 2018-07-20 03:47:57
updated_at: 2018-07-20 03:47:57
However, just as a sidenote this is bad practice because your coupling your view with a session entry. Ideally your view would just take a product object as a view parameters and use that directly. That way you can pass it that object either from the session or from a database query.
If you are trying to get single value from an object you can get like this.
{{ session()->get('product')->id }}
Or If you wish to print all data, First you have to convert object into an array then use foreach.
#foreach (session()->get('product')->toArray() as $key => $value)
{{ $key }}: {{ $value }} </br>
#endforeach
Try it this way :
#foreach(session()->get('product') as $key)
{{$key['id']}}
#endforeach
You are trying to iterate an object. When you try to do this you get the public properties from the object. In your example $key is one of those properties, not the model itself.
When you echo {{ }} a Model __toString gets called which returns the serialized model as json.
If you want that model's id you can just grab it like normal. session('product')->id
If you want you can serialize the Model to an array:
foreach ($model->toArray() as $key => $value) {
...
}

Laravel check if Request has collection

I want to run an if statement over each of my posted requests and if any are a collection do something different.
When I die dump $request->all I have an array that looks like this;
"_token" => "MMRFBAgyThsIHzITzT26Qwdp4L6HDV0JTPGs6h"
"page_name" => "Travel"
"heading" => "Travel Europe"
"textarea" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostru ▶"
"seo_title" => "travel"
"seo_description" => "travel"
"attribute_1" => "Food"
"attribute_2" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor."
"attribute_3" => "Hotels"
"attribute_6" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor."
"attribute_5" => "Events"
"attribute_4" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor."
"attribute_7" => null
"attribute_8" => null
"attribute_9" => UploadedFile {#233 ▶}
The data will be different so I can't write anything static e.g.$request->input('attribute_9')
This is how I'm currently handling the attributes which are the unknown requests.
$input = $request->all();
foreach($input as $key=>$value) {
if(strstr($key,'attribute_')) {
$i = str_replace("attribute_", "", $key);
if (!empty($value)) {
if ($value instanceof Illuminate\Http\UploadedFile) {
dd('lets have a collection...');
}
Attribute::where('id', $i)->update(['value' => $value]);
} else{
Attribute::where('id', $i)->update(['value' => '']);
}
}
}
You can see I've tried to check the $value using instanceOf but that hasn't worked. The if statement is never true and the page just returns.
Example of attribute input submission -
#if($comp_attr['data_type'] == 'file')
<div class="form-grp img-form" style="width: {{ $comp_attr['width'] }}%;">
<label>Banner Image</label>
<span class="img-hold">
{{ $banner }}
</span>
<input type="{{ $comp_attr['field_type'] }}" name="attribute_{{ $comp_attr['id'] }}" />
</div>
#else
<div class="form-grp" style="width: {{ $comp_attr['width'] }}%;">
<label>{{ $comp_attr['label'] }}</label>
<input type="{{ $comp_attr['field_type'] }}" name="attribute_{{ $comp_attr['id'] }}" value="{{ $comp_attr['value'] }}" />
</div>
#endif
I believe you are trying to get the $_FILES
So you can get all the files using
$request->allFiles();
This will return you all the files in the request. then you can perform any action on it.
Hope this helps
Instead of
name="attribute_{{ $comp_attr['id'] }}"
Try
name="attributes[{{ $comp_attr['id'] }}]"
Notice the new 's' ^ , and the brackets on either side of the {{ }}
By using brackets we convert it to an associative array, keyed by the blade variable.
Then on the php side you can do something like this:
foreach($request->get('attributes') as $i => $value)
{
...
}

Error: JSON.parse: expected ',' or ']' after array element

Am newbie to Json am getting this error while call json my json file expected ',' or ']'
[
{
"modules":
[
{
"title":"name of module1",
"description":"description of module1",
"weeks":[{"id":1, "title":"Week 01"}]
},
{
"title":"name of module2",
"description":"description of module2",
"weeks":[{"id":2, "title":"Week 02"},{"id":3,"title":"Week 03"}]
}
]
},
{
"products":
[
{
"url":"http://dummyimage.com/242x200/f3f3f3/2d2d2d.png",
"description":"Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.",
"viewurl" : "/",
"savebtn" : "save"
},
{
"url":"http://dummyimage.com/242x200/f3f3f3/2d2d2d.png",
"description":"Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.",
"viewurl" : "/",
"savebtn" : "save"
}
]
}
]
hope i did correct i dont know what is happening its getting Error: JSON.parse: expected ',' or ']' after array element am attempting to use in angular js controller
app.controller('settingsController', function($scope, $http){
$http.get('assets/javascripts/datas.json').then(function(result){
$scope.employe = result.data;
$scope.prod = result
})
});
and in view
<div class="col-sm-6 col-md-4" ng-repeat="datas in prod.products">
<div class="thumbnail">
<img ng-src="{{ datas.url }}" alt="product">
<div class="caption">
<h3>{{ datas.caption}} </h3>
<p>{{ datas.description}}</p>
<p><a role="button" class="btn btn-primary" ng-href="{{datas.viewurl}}">Button</a> <a role="button" class="btn btn-default" href="#">{{datas.savebtn}}</a></p>
</div>
</div>
</div>
and the error in console
Error: JSON.parse: expected ',' or ']' after array element at line 76 column 9 of the JSON data cc#/test/assets/javascripts/vendors/angular.js:14:289 Ud/this.defaults.transformResponse<#/test/assets/javascripts/vendors/angular.js:69:58 xc/<#/test/assets/javascripts/vendors/angular.js:68:352 r#/test/assets/javascripts/vendors/angular.js:7:288 xc#/test/assets/javascripts/vendors/angular.js:68:336 b#/test/assets/javascripts/vendors/angular.js:70:65 ye/e/l.promise.then/K#/test/assets/javascripts/vendors/angular.js:100:59 ye/f/<.then/<#/test/assets/javascripts/vendors/angular.js:101:235 Zd/this.$get
This error occurred for me when I parsed JSON from a string literal. When I copied in the JSON, I forgot that the escape sequences would need to be double escaped.
Example of the problem:
var data = JSON.parse('[{"key": "This value has \"a quoted\" string"}]');
While the string value is valid JSON, the escape sequences are lost. Then need to be double escaped:
Corrected version:
var data = JSON.parse('[{"key": "This value has \\\"a quoted\\\" string"}]');
Well for me the problem occurs if I have a :// (e.g. http://) inside my json stirng for this reason I replaced it and it worked.

wordpress get_posts() returns empty the_ID()

I've got a problem with loading a list of posts in a certain category via AJAX. the funny part is, that I get a right amount of posts, I get the excerpts right for each post, but ID, and title are empty, plus the date is wrong (1.1.1970). this is my function within functions.php:
function ajax_cat(){
if( isset($_GET['action'])&& $_GET['action'] == 'ajax_cat'){
$my_id = htmlspecialchars($_GET["id"]);
$args = array(
'offset' => 0,
'category' => $my_id,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish' );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<div class="nadpis1" id="<?php the_ID(); ?>" >
<?php the_title(); ?>
<span class="sipka"><?php the_date("d.m. Y"); ?></span>
</div>
<div class="vnutro" ><?php echo the_excerpt();?></div>
<?php endforeach;
die();
}
}
originally this code was inside the loop and worked well. this is what i get now:
<div class="nadpis1" id="" >
<span class="sipka">01.01. 1970</span>
</div>
<div class="vnutro" ><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p></div>
<div class="nadpis1" id="" >
<span class="sipka"></span>
</div>
<div class="vnutro" ><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec adipiscing ultrices posuere. Aenean et egestas enim. Phasellus sit amet nisl elit. Sed pulvinar, purus nec commodo condimentum, lectus risus lacinia urna, sed ultrices magna est vitae turpis. Sed convallis pulvinar gravida. Sed non sem sem, at lobortis tellus. Etiam commodo risus vitae diam cursus volutpat. [...]</p></div>
<div class="nadpis1" id="" >
<span class="sipka"></span>
</div>
<div class="vnutro" ><p>gfdgdfsgngfjty ty jghj ty jtyhjghj dh gfdj5 fgjfdthbkdfgxhjsrgv ,f xfhbtyj dc rtjdtxhvcntydxvhctr shxfc</p></div>
<div class="nadpis1" id="" >
<span class="sipka">01.01. 1970</span>
</div>
<div class="vnutro" ><p>Vitajte vo WordPress. Toto je váš prvý článok. Môžete ho upraviť alebo vymazať a potom už len začať písať!</p></div
>
thanks for any suggestions!
You can't use the_ functions outside of The Loop. Try using get_the_title($postid); and similar get_ functions. Note that the get_ functions don't display the value, they return it, so you'll have to use echo get_the_title($postid);.
Edit: Nevermind, I see that you're using setup_postdata(). However, it could still be worthwhile to use the functions which pass in the ID instead of the ones that change global settings. Try inspecting $post with print_r to see which data you already have in your foreach loop without calling a whole bunch of other database queries.

YUI Datatable: custom column definitions and data

I am trying to use the YUI datatable to display data from a JSON object which looks like this:
{"results":[{"label":"Column 1","notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. "},{"label":"Column 2","notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."},{"label":"Column 3","notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. "},{"label":"Column 4","notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."},{"label":"Column 5","notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."},{"label":"Column 6","notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. "}]}
I can do this fine with the standard implementation. However, the column names (labels in above object) are dynamic so I will not know them until the data reaches the page. I therefore want to define the column definitions from the datasource which I am doing in doBeforeParseData().
From reading / IRC, it has been suggested that I should be able to add columns to the data table. I want the table to look like this:
Column 1 Column 2.......
note note.....
so the above data should produce one row of data. Here's what I have so far:
function loadTable() {
YAHOO.example.Basic = function() {
var myColumnDefs = [];
var myDataSource = new YAHOO.util.DataSource("/index/testajax");
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.doBeforeParseData = function (oRequest, oFullResponse, oCallback) {
// alert(oFullResponse);
var colDefs = [];
var len = oFullResponse.results.length;
for (var i = 0; i < len; i++) {
var obj = {
key: oFullResponse.results[i].label,
sortable: true,
resizeable: true
};
myColumnDefs.push(obj);
}
console.log(myColumnDefs);
return oFullResponse;
};
myDataSource.responseSchema = {
resultsList:"results",
fields: ["label","notes"]
};
var myDataTable = new YAHOO.widget.DataTable("json",
myColumnDefs, myDataSource, {caption:"DataTable Caption"});
return {
oDS: myDataSource,
oDT: myDataTable
};
}();
}
Would be grateful for on any input on HOW to do this rather than why I shouldn't ;-)
thanks,
codecowboy
I spent a bit of my lunch hour on this, but I got something working for you. I looked at your JSON and the way you did it would not work in the data table. results is a list, every entry is a row, and every attribute is a column. Here is the json that I came up with that I hope works for you.
{
"resultSet":{
"columnList":[
{"key":"Column1","label":"My Col 1"},
{"key":"Column2","label":"My Col 2"},
{"key":"Column3","label":"My Col 3"}
],
"results":[
{
"Column1":"Row 1 value",
"Column2":"Row 1 value",
"Column3":"Row 1 value"
},
{
"Column1":"Row 2 value",
"Column2":"Row 2 value",
"Column3":"Row 2 value"
}
]
}
}
I made a small javascript object for handling what you need to do. What needs to be done is you need to make an ajax call to the server for the data. This is so you can define the columns in the datasource before you MAKE the datasource.
function DataProvider(url){
this.url = url;
}
DataProvider.prototype = {
url:null,
data:null,
ds:null,
getData:function() {return this.data},
initialize:function(){
YAHOO.util.Connect.asyncRequest('GET', this.url, this);
},
success:function(response){
var responseVal = YAHOO.lang.JSON.parse(response.responseText);
var columnList = responseVal.resultSet.columnList;
this.data = responseVal.resultSet.results;
this.ds = new YAHOO.util.FunctionDataSource(function(){return this.dataProvider.getData()});
this.ds.responseSchema = {
resultsList:"resultSet.results",
fields:columnList
}
this.ds.dataProvider = this;
/* make call to initialize your table using the data set */
var myDataTable = new YAHOO.widget.DataTable("basic", columnList, this.ds, {caption:"DataTable Caption"});
//console.debug(columnList);
//console.debug(this.data);
}
}
So when the page loads do the following
function init(){
var dataProvider = new DataProvider('testjson.json');
dataProvider.initialize();
}
And your html should look like this
<body onload="init()" class="yui-skin-sam">
<div id="basic"></div>
</body>
And you should have the following scripts included
<!-- css -->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/datatable/assets/skins/sam/datatable.css">
<!-- js -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/connection/connection-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/datasource/datasource-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/element/element-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/datatable/datatable-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/json/json-min.js"></script>
That should work, works for me in both IE and firefox.

Resources