I would like to send an array as an argument in a twig command like:
{{ render(controller("AppBundle:Default:Test"), { 'myarray': array }) }}
But I'm not able to figure out the good way. Let's explain the following simple example with the basic AppBundle. In my project, the render will ask for a render from another Bundle. I'm sure the process is the same, whenever it's the same Bundle or not.
In the default Controller, I put this:
/**
* #Route("/test", name="test")
*/
public function testAction()
{
return $this->render('AppBundle:Default:Test.html.twig', array (
'tests' => array("Test 1", "Test 2", "Test 3", "Test 4")
));
}
/**
* #Route("/test2", name="test2")
*/
public function test2Action($tests = array())
{
var_dump($tests);
return $this->render('AppBundle:Default:Test2.html.twig', array(
'tests' => $tests
));
}
I added a var_dump to track the array, and it is not forwarded to the test2Action function.
In the Test.html.twig, I have this code:
{{ render(controller("AppBundle:Default:Test2"), { 'tests': tests }) }}
In the Test2.html.twig, I have this code:
{% for test in tests %}
{{ test }}</br>
{% endfor %}
Finally, I have this in the navigator:
array(0) { }
Nothing about the array I sent to the test2Action function through the render/controller function in twig.
I'm using Symphony 3.0.3, but even in Symphony 2.8, I cannot find any relevant information.
Maybe I'm not using the best way to do this.
Please, could you help me. I really need to send an array from a bundle to another, in order to have both independent from the other.
Thank you so much,
Stef.
Seems a bracket mistake. In the Test.html.twig, try this:
{{ render(controller("AppBundle:Default:Test2", { 'tests': tests }) ) }}
instead of:
{{ render(controller("AppBundle:Default:Test2"), { 'tests': tests }) }}
Hope this help
Related
I have an array and I need to display several random items from this array.
Now the code looks like this, but I think that there simply should be two different services, one in another.
my component looks like this:
items: Item[];
randomItems: Item[];
ngOnInit() {
this.someService.getItems().subscribe((items) => {
this.items = items;
});
this.randomIndex(this.items);
}
randomItems(items: Item[]) {
return this.randomItems = _.sample(items, _.random(9));
}
}
interface Items {
id: number,
title: string,
body: string
}
my html looks like this:
<ul *ngFor="let item of items">
<li>{{ item.id }}</li>
</ul>
How can I make two different services from this code?
First move the call to randomIndex to inside the subscribe callback.
ngOnInit() {
this.someService.getItems().subscribe((items) => {
this.items = items;
this.randomIndex(this.items);
});
}
About your question:
How can I make two different services from this code?
You don't need to based on the code you have shown. If you do it is subjective as to how you refactor it. Your main defect is that you are not waiting on the service to respond to do something with the result and that is easily solved.
what i wants to do is to show the replies that are given to that particular comment on the post.Right now i am able to show the comment to that specific post but the replies are displayed along each comment.
here is the controller part of the code:
public function show($id)
{
$blog = Blog::findOrFail($id);
$comments = Comment::where('blog_id', $id)->get()->all();
$test = Comment::all();
// $comments = Comment::whereIn('blog_id', $id)->get()->all();
$commentReplies = CommentReply::where('comment_id'== $test->id)-
>get();
// $commentReplies = CommentReply::where('comment_id',$blog-
>comment()->id)->get()->all();
return
view('admin/blog/front',compact('blog','comments','commentReplies'));
}
i am saving the refrence to that comment in database in 'comment_id' but when i try to reach the 'comment_id' via $commentReplies it gives me the error of "Property [id] does not exist on this collection instance."
The correct syntax is:
$commentReplies = CommentReply::whereIn('comment_id', $test->pluck('id')->toArray())->get();
You also could use relationships. Define this one in the Comment model:
public function replies()
{
return $this->hasMany(CommentReply::class);
}
Then load comments with replies:
$commentsWithReplies = Comment::with('replies')->get();
And to iterate over comments and replies:
#foreach ($commentsWithReplies as $comment)
{{ $comment->text }}
#foreach ($comment->replies as $reply)
{{ $reply->text }}
#endforeach
#endforeach
You also shouldn't chain ->get()->all(), just use ->get().
And finally, the correct syntax for returning a view is (thanks to #Nikola Gavric):
return view('admin.blog.front', compact('blog', 'comments', 'commentReplies'))
I've got a model called 'Block', which has multiple fields:
type. This is a dropdown where you can select 3 options.
URL
Search
Based on the type field, the URL or Search must be shown.
The search field needs to preform a search using a variable: API_HOST.
I've written JS to do make the form dynamic and I've extended the wagtailadmin/pages/edit.html template to inject the JS.
However, I'm not sure how to pass the API_HOST (defined in dev.py) down to the template.
dev.py
API_HOST = "http://localhost:8000/"
wagtailadmin/pages/edit.html:
{% extends "wagtailadmin/pages/edit.html" %}
{% block extra_js %}
{{ block.super }}
<script>
var api_host = "{{api_url}}";
console.log("api_host:", api_host);
</script>
<script src="/static/js/blocks_hook.js">
</script>
{% endblock %}
blocks_hook.js
$(function () {
var $type = $('#id_type');
var $search = $('#id_search');
var $url = $('#id_url');
var api = new API(api_host);
hide($search);
hide($url);
$type.on('change', function(){
if ($type.val() == 'search') {
show($search);
hide($url);
api.getProduct(function(product){
// .. do something with the product
});
} else if($type.val() == 'url') {
show($url);
hide($search);
}
});
How should I approach this situation?
I managed to fix this using the insert_editor_js hook mechanism, provided by Wagtail.
Make sure the variable you're passing in the method (#hooks.register) is actually present in your configuration file or else the hooks system crashes without any actionable debug information.
I am very to new to laravel 5.4 and don't know about much about the blade template.
The issue is I am passing the array to the views and trying to get the first index of array element through the provided first() function of blade template but it's giving me error Call to a member function first() on array
Here is my controller code
public function authenticate(Request $request )
{
if (Auth::attempt(['email' => $request->input('email'), 'password' =>
$request->input('password'), 'Status' => 0]))
{
// Authentication passed...
return redirect()->intended('Users');
}
else
{
$json=array('email'=>'You cant leave Email field empty');
return View::make('Auth/login')->with('error',($json));
}
}
Here is my View Code
#if($errors->any())
{{ $errors->first('email') }}
#endif
I am looking for the solution which can exactly suit my needs. If am doing something wrong please correct me.
Thanks...
In your approach you are not using Laravel validations. You just passing an array and basic php arrays does not have methods such as any or first. they belong to Laravel collections.
It is just an array and you can reach array elements as I explained below
so if you wanna keep your code you can do this
#if(isset($error))
{{$error['email'] }}
#endif
But correct way to do is for validation part;
$this->validate($request, [
'email' => 'required| email',
]);
please read documentation deeply about validations and authentication https://laravel.com/docs/5.4/validation
You may use
#foreach ($errors as $error)
{{ $error }}
#endforeach
So you can see the list of the error returned
I'm attempting to build a form from an array of form fields where each form field looks like this:
{
"name": "state",
"resource": "customer",
"type": "TextBox",
"assetId": "State",
"label": {
"text": "State",
"assetId": "Label"
}
}
However, when I attempt to map it using JSX, the fields don't get successfully displayed if I access certain properties of the object. Take the following code, which functions correctly:
formfields.map(function (formfield, i) {
var returnfield = <div key={i}>{formfield.name}</div>;
switch (formfield.type) {
case "TextBox":
console.log(formfield.label);
returnfield = (
<div key={i}>
<label htmlFor="theinput">{formfield.name}</label>
<input id="theinput" type="text" value={formfield.name} />
</div>
);
break;
}
return returnfield;
});
And compare it with the code that fails:
formfields.map(function (formfield, i) {
var returnfield = <div key={i}>{formfield.name}</div>;
switch (formfield.type) {
case "TextBox":
console.log(formfield.label.text);
returnfield = (
<div key={i}>
<label htmlFor="theinput">{formfield.name}</label>
<input id="theinput" type="text" value={formfield.name} />
</div>
);
break;
}
return returnfield;
});
The astute observer will notice that the only difference between the two is that, in the second, we are logging formfield.label.text instead of formfield.label
I'm totally stumped why simply logging an object's grandchild attribute should cause the form to appear empty (i.e., with no fields). Perhaps I'm running into reserved names or something? Any ideas appreciated.
why didn't I see a javascript error in my developer console? Is there some weird thing where .map() doesn't allow errors to be raised?
After recognizing that checking for null is needed in your project well I suggest you use some concepts of javascript functional programming to compose a function that checks for falsely values before applying them in your logic.
You can use Maybe functor that returns a Maybe(null) which stops immediately. Before returning a null value to your logic and cause a boom!
You can also use Either, this is cool because it's just like maybe but you can also gve some logic to run if the value is falsely.
I have two examples for these suggestions (Copied from jsbin)
//Key container == Something map can iterate over like an object or an array.
//And am talking about the lodash / ramda.js curried map that can iterate over object not the js native one.
//Using Maybe
//Url http://jsbin.com/yumog/edit?js,console
var safeGet = _.curry(function(x,o){
return Maybe(o[x]);
//This will return Maybe(null)
//if it's some property in a container is not found
//which you can check before breaking something
});
var user = {id: 2, name: "Albert"}
var ex3 = compose(map(_.head), safeGet('name'));
assertDeepEqual(Maybe('A'), ex3(user))
console.log("exercise 3...ok!")
//Using Either.io
//url http://output.jsbin.com/bexuc/
// Write a function that uses checkActive()
//and showWelcome() to grant access or return the error
var showWelcome = compose(_.add( "Welcome "), _.get('name'))
//Here either returns a function you give it on the right if it's truthy
//and left if it's falsey (or falsy i don't know english .. )
// So you get to do something if the property in your container is not present.
var checkActive = function(user) {
return user.active ? Right(user) : Left('Your account is not active')
}
var ex1 = compose(map(showWelcome), checkActive);
assertDeepEqual(Left('Your account is not active'), ex1({active: false, name: 'Gary'}))
assertDeepEqual(Right('Welcome Theresa'), ex1({active: true, name: 'Theresa'}))
Links to the libraries.
Maybe: https://github.com/chrissrogers/maybe
Either: https://github.com/fantasyland/fantasy-eithers
You might also need to check on lodash / ramda to have a full idea on these functional concepts.